language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C++ | x64dbg-development/src/gui/Src/Gui/SEHChainView.cpp | #include "SEHChainView.h"
#include "Bridge.h"
SEHChainView::SEHChainView(StdTable* parent) : StdTable(parent)
{
int charWidth = getCharWidth();
addColumnAt(8 + charWidth * sizeof(dsint) * 2, tr("Address"), true); //address in the stack
addColumnAt(8 + charWidth * sizeof(dsint) * 2, tr("Handler"), false); // Exception Handler
addColumnAt(8 + charWidth * 50, tr("Module/Label"), false);
addColumnAt(charWidth * 10, tr("Comment"), false);
connect(Bridge::getBridge(), SIGNAL(updateSEHChain()), this, SLOT(updateSEHChain()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(doubleClickedSlot()));
loadColumnFromConfig("SEH");
setupContextMenu();
}
void SEHChainView::setupContextMenu()
{
QIcon icon = DIcon(ArchValue("processor32", "processor64"));
mFollowAddress = new QAction(icon, tr("Follow &Address"), this);
connect(mFollowAddress, SIGNAL(triggered()), this, SLOT(followAddress()));
mFollowHandler = new QAction(icon, tr("Follow Handler"), this);
mFollowHandler->setShortcutContext(Qt::WidgetShortcut);
mFollowHandler->setShortcut(QKeySequence("enter"));
connect(mFollowHandler, SIGNAL(triggered()), this, SLOT(followHandler()));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followHandler()));
}
void SEHChainView::updateSEHChain()
{
DBGSEHCHAIN sehchain;
memset(&sehchain, 0, sizeof(DBGSEHCHAIN));
if(!DbgFunctions()->GetSEHChain)
return;
DbgFunctions()->GetSEHChain(&sehchain);
setRowCount(sehchain.total);
for(duint i = 0; i < sehchain.total; i++)
{
QString cellText = ToPtrString(sehchain.records[i].addr);
setCellContent(i, 0, cellText);
cellText = ToPtrString(sehchain.records[i].handler);
setCellContent(i, 1, cellText);
char label[MAX_LABEL_SIZE] = "";
char module[MAX_MODULE_SIZE] = "";
DbgGetModuleAt(sehchain.records[i].handler, module);
QString label_text;
if(DbgGetLabelAt(sehchain.records[i].handler, SEG_DEFAULT, label))
label_text = "<" + QString(module) + "." + QString(label) + ">";
else
label_text = QString(module);
setCellContent(i, 2, label_text);
QString comment;
if(GetCommentFormat(sehchain.records[i].handler, comment))
setCellContent(i, 3, comment);
}
if(sehchain.total)
BridgeFree(sehchain.records);
reloadData();
}
void SEHChainView::contextMenuSlot(const QPoint pos)
{
if(!DbgIsDebugging() || this->getRowCount() == 0)
return;
QMenu wMenu(this); //create context menu
wMenu.addAction(mFollowAddress);
wMenu.addAction(mFollowHandler);
QMenu wCopyMenu(tr("&Copy"), this);
wCopyMenu.setIcon(DIcon("copy"));
setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
{
wMenu.addSeparator();
wMenu.addMenu(&wCopyMenu);
}
wMenu.exec(mapToGlobal(pos)); //execute context menu
}
void SEHChainView::doubleClickedSlot()
{
followHandler();
}
void SEHChainView::followAddress()
{
QString addrText = getCellContent(getInitialSelection(), 0);
DbgCmdExecDirect(QString("sdump " + addrText));
}
void SEHChainView::followHandler()
{
QString addrText = getCellContent(getInitialSelection(), 1);
DbgCmdExecDirect(QString("disasm " + addrText));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SEHChainView.h | #pragma once
#include "StdTable.h"
class SEHChainView : public StdTable
{
Q_OBJECT
public:
explicit SEHChainView(StdTable* parent = 0);
void setupContextMenu();
protected slots:
void updateSEHChain();
void contextMenuSlot(const QPoint pos);
void doubleClickedSlot();
void followAddress();
void followHandler();
private:
QAction* mFollowAddress;
QAction* mFollowHandler;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/SelectFields.cpp | #include "selectfields.h"
#include "ui_selectfields.h"
SelectFields::SelectFields(QWidget* parent) :
QDialog(parent),
ui(new Ui::SelectFields)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true);
}
QListWidget* SelectFields::GetList()
{
return ui->listWidget;
}
SelectFields::~SelectFields()
{
delete ui;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SelectFields.h | #pragma once
#include <QDialog>
class QListWidget;
namespace Ui
{
class SelectFields;
}
class SelectFields : public QDialog
{
Q_OBJECT
public:
explicit SelectFields(QWidget* parent = 0);
QListWidget* GetList();
~SelectFields();
private:
Ui::SelectFields* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/SelectFields.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SelectFields</class>
<widget class="QDialog" name="SelectFields">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>213</width>
<height>181</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<property name="windowIcon">
<iconset theme="log" resource="../../resource.qrc">
<normaloff>:/Default/icons/log.png</normaloff>:/Default/icons/log.png</iconset>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListWidget" name="listWidget"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton_2">
<property name="text">
<string>&OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>pushButton_2</sender>
<signal>clicked()</signal>
<receiver>SelectFields</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>19</x>
<y>150</y>
</hint>
<hint type="destinationlabel">
<x>27</x>
<y>176</y>
</hint>
</hints>
</connection>
<connection>
<sender>pushButton</sender>
<signal>clicked()</signal>
<receiver>SelectFields</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>182</x>
<y>153</y>
</hint>
<hint type="destinationlabel">
<x>207</x>
<y>164</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/SettingsDialog.cpp | #include "SettingsDialog.h"
#include "ui_SettingsDialog.h"
#include <QMessageBox>
#include "Configuration.h"
#include "Bridge.h"
#include "ExceptionRangeDialog.h"
#include "MiscUtil.h"
SettingsDialog::SettingsDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::SettingsDialog)
{
ui->setupUi(this);
//set window flags
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true);
adjustSize();
bTokenizerConfigUpdated = false;
bDisableAutoCompleteUpdated = false;
LoadSettings(); //load settings from file
connect(Bridge::getBridge(), SIGNAL(setLastException(uint)), this, SLOT(setLastException(uint)));
lastException = 0;
}
SettingsDialog::~SettingsDialog()
{
disconnect(Bridge::getBridge(), SIGNAL(setLastException(uint)), this, SLOT(setLastException(uint)));
delete ui;
}
void SettingsDialog::GetSettingBool(const char* section, const char* name, bool* set)
{
duint currentSetting;
if(!set || !BridgeSettingGetUint(section, name, ¤tSetting))
return;
if(currentSetting)
*set = true;
else
*set = false;
}
Qt::CheckState SettingsDialog::bool2check(bool checked)
{
if(checked)
return Qt::Checked;
return Qt::Unchecked;
}
void SettingsDialog::LoadSettings()
{
//Flush pending config changes
Config()->save();
//Defaults
settings.exceptionFilters = &realExceptionFilters;
//Events tab
GetSettingBool("Events", "SystemBreakpoint", &settings.eventSystemBreakpoint);
GetSettingBool("Events", "NtTerminateProcess", &settings.eventExitBreakpoint);
GetSettingBool("Events", "TlsCallbacks", &settings.eventTlsCallbacks);
GetSettingBool("Events", "TlsCallbacksSystem", &settings.eventTlsCallbacksSystem);
GetSettingBool("Events", "EntryBreakpoint", &settings.eventEntryBreakpoint);
GetSettingBool("Events", "DllEntry", &settings.eventDllEntry);
GetSettingBool("Events", "DllEntrySystem", &settings.eventDllEntrySystem);
GetSettingBool("Events", "ThreadEntry", &settings.eventThreadEntry);
GetSettingBool("Events", "DllLoad", &settings.eventDllLoad);
GetSettingBool("Events", "DllUnload", &settings.eventDllUnload);
GetSettingBool("Events", "DllLoadSystem", &settings.eventDllLoadSystem);
GetSettingBool("Events", "DllUnloadSystem", &settings.eventDllUnloadSystem);
GetSettingBool("Events", "ThreadStart", &settings.eventThreadStart);
GetSettingBool("Events", "ThreadEnd", &settings.eventThreadEnd);
GetSettingBool("Events", "ThreadNameSet", &settings.eventThreadNameSet);
GetSettingBool("Events", "DebugStrings", &settings.eventDebugStrings);
ui->chkSystemBreakpoint->setCheckState(bool2check(settings.eventSystemBreakpoint));
ui->chkExitBreakpoint->setCheckState(bool2check(settings.eventExitBreakpoint));
ui->chkTlsCallbacks->setCheckState(bool2check(settings.eventTlsCallbacks));
ui->chkTlsCallbacksSystem->setCheckState(bool2check(settings.eventTlsCallbacksSystem));
ui->chkEntryBreakpoint->setCheckState(bool2check(settings.eventEntryBreakpoint));
ui->chkDllEntry->setCheckState(bool2check(settings.eventDllEntry));
ui->chkDllEntrySystem->setCheckState(bool2check(settings.eventDllEntrySystem));
ui->chkThreadEntry->setCheckState(bool2check(settings.eventThreadEntry));
ui->chkDllLoad->setCheckState(bool2check(settings.eventDllLoad));
ui->chkDllUnload->setCheckState(bool2check(settings.eventDllUnload));
ui->chkDllLoadSystem->setCheckState(bool2check(settings.eventDllLoadSystem));
ui->chkDllUnloadSystem->setCheckState(bool2check(settings.eventDllUnloadSystem));
ui->chkThreadStart->setCheckState(bool2check(settings.eventThreadStart));
ui->chkThreadEnd->setCheckState(bool2check(settings.eventThreadEnd));
ui->chkThreadNameSet->setCheckState(bool2check(settings.eventThreadNameSet));
ui->chkDebugStrings->setCheckState(bool2check(settings.eventDebugStrings));
//Engine tab
duint cur;
if(BridgeSettingGetUint("Engine", "CalculationType", &cur))
{
switch(cur)
{
case calc_signed:
case calc_unsigned:
settings.engineCalcType = (CalcType)cur;
break;
}
}
if(BridgeSettingGetUint("Engine", "DebugEngine", &cur))
{
settings.engineType = (DEBUG_ENGINE)cur;
}
if(BridgeSettingGetUint("Engine", "BreakpointType", &cur))
{
switch(cur)
{
case break_int3short:
case break_int3long:
case break_ud2:
settings.engineBreakpointType = (BreakpointType)cur;
break;
}
}
GetSettingBool("Engine", "UndecorateSymbolNames", &settings.engineUndecorateSymbolNames);
GetSettingBool("Engine", "EnableDebugPrivilege", &settings.engineEnableDebugPrivilege);
GetSettingBool("Engine", "EnableSourceDebugging", &settings.engineEnableSourceDebugging);
GetSettingBool("Engine", "SaveDatabaseInProgramDirectory", &settings.engineSaveDatabaseInProgramDirectory);
GetSettingBool("Engine", "DisableDatabaseCompression", &settings.engineDisableDatabaseCompression);
GetSettingBool("Engine", "SkipInt3Stepping", &settings.engineSkipInt3Stepping);
GetSettingBool("Engine", "NoScriptTimeout", &settings.engineNoScriptTimeout);
GetSettingBool("Engine", "IgnoreInconsistentBreakpoints", &settings.engineIgnoreInconsistentBreakpoints);
GetSettingBool("Engine", "HardcoreThreadSwitchWarning", &settings.engineHardcoreThreadSwitchWarning);
GetSettingBool("Engine", "VerboseExceptionLogging", &settings.engineVerboseExceptionLogging);
GetSettingBool("Engine", "NoWow64SingleStepWorkaround", &settings.engineNoWow64SingleStepWorkaround);
GetSettingBool("Engine", "DisableAslr", &settings.engineDisableAslr);
if(BridgeSettingGetUint("Engine", "MaxTraceCount", &cur))
settings.engineMaxTraceCount = int(cur);
if(BridgeSettingGetUint("Engine", "AnimateInterval", &cur))
settings.engineAnimateInterval = int(cur);
switch(settings.engineCalcType)
{
case calc_signed:
ui->radioSigned->setChecked(true);
break;
case calc_unsigned:
ui->radioUnsigned->setChecked(true);
break;
}
switch(settings.engineType)
{
case DebugEngineTitanEngine:
ui->radioTitanEngine->setChecked(true);
break;
case DebugEngineGleeBug:
ui->radioGleeBug->setChecked(true);
break;
}
switch(settings.engineBreakpointType)
{
case break_int3short:
ui->radioInt3Short->setChecked(true);
break;
case break_int3long:
ui->radioInt3Long->setChecked(true);
break;
case break_ud2:
ui->radioUd2->setChecked(true);
break;
}
ui->chkUndecorateSymbolNames->setChecked(settings.engineUndecorateSymbolNames);
ui->chkEnableDebugPrivilege->setChecked(settings.engineEnableDebugPrivilege);
ui->chkEnableSourceDebugging->setChecked(settings.engineEnableSourceDebugging);
ui->chkSaveDatabaseInProgramDirectory->setChecked(settings.engineSaveDatabaseInProgramDirectory);
ui->chkDisableDatabaseCompression->setChecked(settings.engineDisableDatabaseCompression);
ui->chkSkipInt3Stepping->setChecked(settings.engineSkipInt3Stepping);
ui->chkNoScriptTimeout->setChecked(settings.engineNoScriptTimeout);
ui->chkIgnoreInconsistentBreakpoints->setChecked(settings.engineIgnoreInconsistentBreakpoints);
ui->chkHardcoreThreadSwitchWarning->setChecked(settings.engineHardcoreThreadSwitchWarning);
ui->chkVerboseExceptionLogging->setChecked(settings.engineVerboseExceptionLogging);
ui->chkNoWow64SingleStepWorkaround->setChecked(settings.engineNoWow64SingleStepWorkaround);
ui->chkDisableAslr->setChecked(settings.engineDisableAslr);
ui->spinMaxTraceCount->setValue(settings.engineMaxTraceCount);
ui->spinAnimateInterval->setValue(settings.engineAnimateInterval);
//Exceptions tab
char exceptionRange[MAX_SETTING_SIZE] = "";
bool unknownExceptionsFilterAdded = false;
if(BridgeSettingGet("Exceptions", "IgnoreRange", exceptionRange))
{
QStringList ranges = QString(exceptionRange).split(QString(","), QString::SkipEmptyParts);
for(int i = 0; i < ranges.size(); i++)
{
const QString & entry = ranges.at(i);
unsigned long start;
unsigned long end;
if(!entry.contains("debug") && // check for old ignore format
sscanf_s(entry.toUtf8().constData(), "%08X-%08X", &start, &end) == 2 && start <= end)
{
ExceptionFilter newFilter;
newFilter.range.start = start;
newFilter.range.end = end;
// Default settings for an ignore entry
newFilter.breakOn = ExceptionBreakOn::SecondChance;
newFilter.logException = true;
newFilter.handledBy = ExceptionHandledBy::Debuggee;
AddExceptionFilterToList(newFilter);
}
else if(entry.contains("debug") && // new filter format
sscanf_s(entry.toUtf8().constData(), "%08X-%08X", &start, &end) == 2 && start <= end)
{
ExceptionFilter newFilter;
newFilter.range.start = start;
newFilter.range.end = end;
newFilter.breakOn = entry.contains("first") ? ExceptionBreakOn::FirstChance : entry.contains("second") ? ExceptionBreakOn::SecondChance : ExceptionBreakOn::DoNotBreak;
newFilter.logException = !entry.contains("nolog");
newFilter.handledBy = entry.contains("debugger") ? ExceptionHandledBy::Debugger : ExceptionHandledBy::Debuggee;
AddExceptionFilterToList(newFilter);
if(newFilter.range.start == 0 && newFilter.range.start == newFilter.range.end)
unknownExceptionsFilterAdded = true;
}
}
}
if(!unknownExceptionsFilterAdded) // add a default filter for unknown exceptions if it was not yet present in settings
{
ExceptionFilter unknownExceptionsFilter;
unknownExceptionsFilter.range.start = unknownExceptionsFilter.range.end = 0;
unknownExceptionsFilter.breakOn = ExceptionBreakOn::FirstChance;
unknownExceptionsFilter.logException = true;
unknownExceptionsFilter.handledBy = ExceptionHandledBy::Debuggee;
AddExceptionFilterToList(unknownExceptionsFilter);
}
//Disasm tab
GetSettingBool("Disassembler", "ArgumentSpaces", &settings.disasmArgumentSpaces);
GetSettingBool("Disassembler", "HidePointerSizes", &settings.disasmHidePointerSizes);
GetSettingBool("Disassembler", "HideNormalSegments", &settings.disasmHideNormalSegments);
GetSettingBool("Disassembler", "MemorySpaces", &settings.disasmMemorySpaces);
GetSettingBool("Disassembler", "Uppercase", &settings.disasmUppercase);
GetSettingBool("Disassembler", "OnlyCipAutoComments", &settings.disasmOnlyCipAutoComments);
GetSettingBool("Disassembler", "TabbedMnemonic", &settings.disasmTabBetweenMnemonicAndArguments);
GetSettingBool("Disassembler", "NoHighlightOperands", &settings.disasmNoHighlightOperands);
GetSettingBool("Disassembler", "PermanentHighlightingMode", &settings.disasmPermanentHighlightingMode);
GetSettingBool("Disassembler", "NoCurrentModuleText", &settings.disasmNoCurrentModuleText);
GetSettingBool("Disassembler", "0xPrefixValues", &settings.disasm0xPrefixValues);
GetSettingBool("Disassembler", "NoBranchDisasmPreview", &settings.disasmNoBranchDisasmPreview);
GetSettingBool("Disassembler", "NoSourceLineAutoComments", &settings.disasmNoSourceLineAutoComments);
GetSettingBool("Disassembler", "AssembleOnDoubleClick", &settings.disasmAssembleOnDoubleClick);
if(BridgeSettingGetUint("Disassembler", "MaxModuleSize", &cur))
settings.disasmMaxModuleSize = int(cur);
ui->chkArgumentSpaces->setChecked(settings.disasmArgumentSpaces);
ui->chkHidePointerSizes->setChecked(settings.disasmHidePointerSizes);
ui->chkHideNormalSegments->setChecked(settings.disasmHideNormalSegments);
ui->chkMemorySpaces->setChecked(settings.disasmMemorySpaces);
ui->chkUppercase->setChecked(settings.disasmUppercase);
ui->chkOnlyCipAutoComments->setChecked(settings.disasmOnlyCipAutoComments);
ui->chkTabBetweenMnemonicAndArguments->setChecked(settings.disasmTabBetweenMnemonicAndArguments);
ui->chkNoHighlightOperands->setChecked(settings.disasmNoHighlightOperands);
ui->chkPermanentHighlightingMode->setChecked(settings.disasmPermanentHighlightingMode);
ui->chkNoCurrentModuleText->setChecked(settings.disasmNoCurrentModuleText);
ui->chk0xPrefixValues->setChecked(settings.disasm0xPrefixValues);
ui->chkNoBranchDisasmPreview->setChecked(settings.disasmNoBranchDisasmPreview);
ui->chkNoSourceLinesAutoComments->setChecked(settings.disasmNoSourceLineAutoComments);
ui->chkDoubleClickAssemble->setChecked(settings.disasmAssembleOnDoubleClick);
ui->spinMaximumModuleNameSize->setValue(settings.disasmMaxModuleSize);
//Gui tab
GetSettingBool("Gui", "FpuRegistersLittleEndian", &settings.guiFpuRegistersLittleEndian);
GetSettingBool("Gui", "SaveColumnOrder", &settings.guiSaveColumnOrder);
GetSettingBool("Gui", "NoCloseDialog", &settings.guiNoCloseDialog);
GetSettingBool("Gui", "PidTidInHex", &settings.guiPidTidInHex);
GetSettingBool("Gui", "SidebarWatchLabels", &settings.guiSidebarWatchLabels);
GetSettingBool("Gui", "NoForegroundWindow", &settings.guiNoForegroundWindow);
GetSettingBool("Gui", "LoadSaveTabOrder", &settings.guiLoadSaveTabOrder);
GetSettingBool("Gui", "ShowGraphRva", &settings.guiShowGraphRva);
GetSettingBool("Gui", "GraphZoomMode", &settings.guiGraphZoomMode);
GetSettingBool("Gui", "ShowExitConfirmation", &settings.guiShowExitConfirmation);
GetSettingBool("Gui", "DisableAutoComplete", &settings.guiDisableAutoComplete);
GetSettingBool("Gui", "AutoFollowInStack", &settings.guiAutoFollowInStack);
GetSettingBool("Gui", "NoSeasons", &settings.guiHideSeasonalIcons);
GetSettingBool("Gui", "EnableQtHighDpiScaling", &settings.guiEnableQtHighDpiScaling);
GetSettingBool("Gui", "WindowLongPath", &settings.guiEnableWindowLongPath);
GetSettingBool("Gui", "NoIcons", &settings.guiNoIcons);
ui->chkFpuRegistersLittleEndian->setChecked(settings.guiFpuRegistersLittleEndian);
ui->chkSaveColumnOrder->setChecked(settings.guiSaveColumnOrder);
ui->chkNoCloseDialog->setChecked(settings.guiNoCloseDialog);
ui->chkPidTidInHex->setChecked(settings.guiPidTidInHex);
ui->chkSidebarWatchLabels->setChecked(settings.guiSidebarWatchLabels);
ui->chkNoForegroundWindow->setChecked(settings.guiNoForegroundWindow);
ui->chkSaveLoadTabOrder->setChecked(settings.guiLoadSaveTabOrder);
ui->chkShowGraphRva->setChecked(settings.guiShowGraphRva);
ui->chkGraphZoomMode->setChecked(settings.guiGraphZoomMode);
ui->chkShowExitConfirmation->setChecked(settings.guiShowExitConfirmation);
ui->chkDisableAutoComplete->setChecked(settings.guiDisableAutoComplete);
ui->chkAutoFollowInStack->setChecked(settings.guiAutoFollowInStack);
ui->chkHideSeasonalIcons->setChecked(settings.guiHideSeasonalIcons);
ui->chkHideSeasonalIcons->setVisible(isSeasonal());
ui->chkQtHighDpiScaling->setChecked(settings.guiEnableQtHighDpiScaling);
ui->chkWindowLongPath->setChecked(settings.guiEnableWindowLongPath);
ui->chkNoIcons->setChecked(settings.guiNoIcons);
//Misc tab
if(DbgFunctions()->GetJit)
{
char jit_entry[MAX_SETTING_SIZE] = "";
char jit_def_entry[MAX_SETTING_SIZE] = "";
bool isx64 = true;
#ifndef _WIN64
isx64 = false;
#endif
bool get_jit_works;
get_jit_works = DbgFunctions()->GetJit(jit_entry, isx64);
DbgFunctions()->GetDefJit(jit_def_entry);
if(get_jit_works)
{
if(_strcmpi(jit_entry, jit_def_entry) == 0)
settings.miscSetJIT = true;
}
else
settings.miscSetJIT = false;
ui->editJIT->setText(jit_entry);
ui->editJIT->setCursorPosition(0);
ui->chkSetJIT->setCheckState(bool2check(settings.miscSetJIT));
if(!BridgeIsProcessElevated())
{
ui->chkSetJIT->setDisabled(true);
ui->lblAdminWarning->setText(QString(tr("<font color=\"red\"><b>Warning</b></font>: Run the debugger as Admin to enable JIT.")));
}
else
ui->lblAdminWarning->setText("");
}
char setting[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("Symbols", "DefaultStore", setting))
ui->editSymbolStore->setText(QString(setting));
else
{
QString defaultStore("https://msdl.microsoft.com/download/symbols");
ui->editSymbolStore->setText(defaultStore);
BridgeSettingSet("Symbols", "DefaultStore", defaultStore.toUtf8().constData());
}
if(BridgeSettingGet("Symbols", "CachePath", setting))
ui->editSymbolCache->setText(QString(setting));
if(BridgeSettingGet("Misc", "HelpOnSymbolicNameUrl", setting))
ui->editHelpOnSymbolicNameUrl->setText(QString(setting));
bJitOld = settings.miscSetJIT;
GetSettingBool("Misc", "Utf16LogRedirect", &settings.miscUtf16LogRedirect);
GetSettingBool("Misc", "UseLocalHelpFile", &settings.miscUseLocalHelpFile);
GetSettingBool("Misc", "QueryProcessCookie", &settings.miscQueryProcessCookie);
GetSettingBool("Misc", "QueryWorkingSet", &settings.miscQueryWorkingSet);
GetSettingBool("Misc", "TransparentExceptionStepping", &settings.miscTransparentExceptionStepping);
ui->chkUtf16LogRedirect->setChecked(settings.miscUtf16LogRedirect);
ui->chkUseLocalHelpFile->setChecked(settings.miscUseLocalHelpFile);
ui->chkQueryProcessCookie->setChecked(settings.miscQueryProcessCookie);
ui->chkQueryWorkingSet->setChecked(settings.miscQueryWorkingSet);
ui->chkTransparentExceptionStepping->setChecked(settings.miscTransparentExceptionStepping);
}
void SettingsDialog::SaveSettings()
{
//Events tab
BridgeSettingSetUint("Events", "SystemBreakpoint", settings.eventSystemBreakpoint);
BridgeSettingSetUint("Events", "NtTerminateProcess", settings.eventExitBreakpoint);
BridgeSettingSetUint("Events", "TlsCallbacks", settings.eventTlsCallbacks);
BridgeSettingSetUint("Events", "TlsCallbacksSystem", settings.eventTlsCallbacksSystem);
BridgeSettingSetUint("Events", "EntryBreakpoint", settings.eventEntryBreakpoint);
BridgeSettingSetUint("Events", "DllEntry", settings.eventDllEntry);
BridgeSettingSetUint("Events", "DllEntrySystem", settings.eventDllEntrySystem);
BridgeSettingSetUint("Events", "ThreadEntry", settings.eventThreadEntry);
BridgeSettingSetUint("Events", "DllLoad", settings.eventDllLoad);
BridgeSettingSetUint("Events", "DllUnload", settings.eventDllUnload);
BridgeSettingSetUint("Events", "DllLoadSystem", settings.eventDllLoadSystem);
BridgeSettingSetUint("Events", "DllUnloadSystem", settings.eventDllUnloadSystem);
BridgeSettingSetUint("Events", "ThreadStart", settings.eventThreadStart);
BridgeSettingSetUint("Events", "ThreadEnd", settings.eventThreadEnd);
BridgeSettingSetUint("Events", "ThreadNameSet", settings.eventThreadNameSet);
BridgeSettingSetUint("Events", "DebugStrings", settings.eventDebugStrings);
//Engine tab
BridgeSettingSetUint("Engine", "CalculationType", settings.engineCalcType);
BridgeSettingSetUint("Engine", "DebugEngine", settings.engineType);
BridgeSettingSetUint("Engine", "BreakpointType", settings.engineBreakpointType);
BridgeSettingSetUint("Engine", "UndecorateSymbolNames", settings.engineUndecorateSymbolNames);
BridgeSettingSetUint("Engine", "EnableDebugPrivilege", settings.engineEnableDebugPrivilege);
BridgeSettingSetUint("Engine", "EnableSourceDebugging", settings.engineEnableSourceDebugging);
BridgeSettingSetUint("Engine", "SaveDatabaseInProgramDirectory", settings.engineSaveDatabaseInProgramDirectory);
BridgeSettingSetUint("Engine", "DisableDatabaseCompression", settings.engineDisableDatabaseCompression);
BridgeSettingSetUint("Engine", "SkipInt3Stepping", settings.engineSkipInt3Stepping);
BridgeSettingSetUint("Engine", "NoScriptTimeout", settings.engineNoScriptTimeout);
BridgeSettingSetUint("Engine", "IgnoreInconsistentBreakpoints", settings.engineIgnoreInconsistentBreakpoints);
BridgeSettingSetUint("Engine", "MaxTraceCount", settings.engineMaxTraceCount);
BridgeSettingSetUint("Engine", "AnimateInterval", settings.engineAnimateInterval);
BridgeSettingSetUint("Engine", "VerboseExceptionLogging", settings.engineVerboseExceptionLogging);
BridgeSettingSetUint("Engine", "HardcoreThreadSwitchWarning", settings.engineHardcoreThreadSwitchWarning);
BridgeSettingSetUint("Engine", "NoWow64SingleStepWorkaround", settings.engineNoWow64SingleStepWorkaround);
BridgeSettingSetUint("Engine", "DisableAslr", settings.engineDisableAslr);
//Exceptions tab
QString exceptionRange = "";
for(int i = 0; i < settings.exceptionFilters->size(); i++)
{
const ExceptionFilter & filter = settings.exceptionFilters->at(i);
exceptionRange.append(QString().asprintf("%.8X-%.8X:%s:%s:%s,",
filter.range.start, filter.range.end,
(filter.breakOn == ExceptionBreakOn::FirstChance ? "first" : filter.breakOn == ExceptionBreakOn::SecondChance ? "second" : "nobreak"),
(filter.logException ? "log" : "nolog"),
(filter.handledBy == ExceptionHandledBy::Debugger ? "debugger" : "debuggee")));
}
exceptionRange.chop(1); //remove last comma
if(exceptionRange.size())
BridgeSettingSet("Exceptions", "IgnoreRange", exceptionRange.toUtf8().constData());
else
BridgeSettingSet("Exceptions", "IgnoreRange", "");
//Disasm tab
BridgeSettingSetUint("Disassembler", "ArgumentSpaces", settings.disasmArgumentSpaces);
BridgeSettingSetUint("Disassembler", "HidePointerSizes", settings.disasmHidePointerSizes);
BridgeSettingSetUint("Disassembler", "HideNormalSegments", settings.disasmHideNormalSegments);
BridgeSettingSetUint("Disassembler", "MemorySpaces", settings.disasmMemorySpaces);
BridgeSettingSetUint("Disassembler", "Uppercase", settings.disasmUppercase);
BridgeSettingSetUint("Disassembler", "OnlyCipAutoComments", settings.disasmOnlyCipAutoComments);
BridgeSettingSetUint("Disassembler", "TabbedMnemonic", settings.disasmTabBetweenMnemonicAndArguments);
BridgeSettingSetUint("Disassembler", "NoHighlightOperands", settings.disasmNoHighlightOperands);
BridgeSettingSetUint("Disassembler", "PermanentHighlightingMode", settings.disasmPermanentHighlightingMode);
BridgeSettingSetUint("Disassembler", "NoCurrentModuleText", settings.disasmNoCurrentModuleText);
BridgeSettingSetUint("Disassembler", "0xPrefixValues", settings.disasm0xPrefixValues);
BridgeSettingSetUint("Disassembler", "NoBranchDisasmPreview", settings.disasmNoBranchDisasmPreview);
BridgeSettingSetUint("Disassembler", "NoSourceLineAutoComments", settings.disasmNoSourceLineAutoComments);
BridgeSettingSetUint("Disassembler", "AssembleOnDoubleClick", settings.disasmAssembleOnDoubleClick);
BridgeSettingSetUint("Disassembler", "MaxModuleSize", settings.disasmMaxModuleSize);
//Gui tab
BridgeSettingSetUint("Gui", "FpuRegistersLittleEndian", settings.guiFpuRegistersLittleEndian);
BridgeSettingSetUint("Gui", "SaveColumnOrder", settings.guiSaveColumnOrder);
BridgeSettingSetUint("Gui", "NoCloseDialog", settings.guiNoCloseDialog);
BridgeSettingSetUint("Gui", "PidTidInHex", settings.guiPidTidInHex);
BridgeSettingSetUint("Gui", "SidebarWatchLabels", settings.guiSidebarWatchLabels);
BridgeSettingSetUint("Gui", "NoForegroundWindow", settings.guiNoForegroundWindow);
BridgeSettingSetUint("Gui", "LoadSaveTabOrder", settings.guiLoadSaveTabOrder);
BridgeSettingSetUint("Gui", "ShowGraphRva", settings.guiShowGraphRva);
BridgeSettingSetUint("Gui", "GraphZoomMode", settings.guiGraphZoomMode);
BridgeSettingSetUint("Gui", "ShowExitConfirmation", settings.guiShowExitConfirmation);
BridgeSettingSetUint("Gui", "DisableAutoComplete", settings.guiDisableAutoComplete);
BridgeSettingSetUint("Gui", "AutoFollowInStack", settings.guiAutoFollowInStack);
BridgeSettingSetUint("Gui", "NoSeasons", settings.guiHideSeasonalIcons);
BridgeSettingSetUint("Gui", "EnableQtHighDpiScaling", settings.guiEnableQtHighDpiScaling);
BridgeSettingSetUint("Gui", "WindowLongPath", settings.guiEnableWindowLongPath);
BridgeSettingSetUint("Gui", "NoIcons", settings.guiNoIcons);
//Misc tab
if(DbgFunctions()->GetJit)
{
if(bJitOld != settings.miscSetJIT)
{
if(settings.miscSetJIT)
{
// Since Windows 10 WER will not trigger the JIT debugger at all without this
DbgCmdExec("setjitauto on");
DbgCmdExec("setjit oldsave");
}
else
DbgCmdExec("setjit restore");
}
}
if(settings.miscSymbolStore)
BridgeSettingSet("Symbols", "DefaultStore", ui->editSymbolStore->text().toUtf8().constData());
if(settings.miscSymbolCache)
BridgeSettingSet("Symbols", "CachePath", ui->editSymbolCache->text().toUtf8().constData());
BridgeSettingSet("Misc", "HelpOnSymbolicNameUrl", ui->editHelpOnSymbolicNameUrl->text().toUtf8().constData());
BridgeSettingSetUint("Misc", "Utf16LogRedirect", settings.miscUtf16LogRedirect);
BridgeSettingSetUint("Misc", "UseLocalHelpFile", settings.miscUseLocalHelpFile);
BridgeSettingSetUint("Misc", "QueryProcessCookie", settings.miscQueryProcessCookie);
BridgeSettingSetUint("Misc", "QueryWorkingSet", settings.miscQueryWorkingSet);
BridgeSettingSetUint("Misc", "TransparentExceptionStepping", settings.miscTransparentExceptionStepping);
BridgeSettingFlush();
Config()->load();
if(bTokenizerConfigUpdated)
{
emit Config()->tokenizerConfigUpdated();
bTokenizerConfigUpdated = false;
}
if(bDisableAutoCompleteUpdated)
{
emit Config()->disableAutoCompleteUpdated();
bDisableAutoCompleteUpdated = false;
}
if(bGuiOptionsUpdated)
{
emit Config()->guiOptionsUpdated();
bGuiOptionsUpdated = false;
}
DbgSettingsUpdated();
GuiUpdateAllViews();
}
void SettingsDialog::AddExceptionFilterToList(ExceptionFilter filter)
{
//check range
unsigned long start = filter.range.start;
unsigned long end = filter.range.end;
for(int i = settings.exceptionFilters->size() - 1; i > 0; i--)
{
unsigned long curStart = settings.exceptionFilters->at(i).range.start;
unsigned long curEnd = settings.exceptionFilters->at(i).range.end;
if(curStart <= end && curEnd >= start) //ranges overlap
{
if(curStart < start) //extend range to the left
start = curStart;
if(curEnd > end) //extend range to the right
end = curEnd;
settings.exceptionFilters->erase(settings.exceptionFilters->begin() + i); //remove old range
}
}
filter.range.start = start;
filter.range.end = end;
settings.exceptionFilters->push_back(filter);
UpdateExceptionListWidget();
}
void SettingsDialog::OnExceptionFilterSelectionChanged(QListWidgetItem* selected)
{
QModelIndexList indexes = ui->listExceptions->selectionModel()->selectedIndexes();
if(!indexes.size() && !selected) // no selection
return;
int row;
if(!indexes.size())
row = ui->listExceptions->row(selected);
else
row = indexes.at(0).row();
if(row < 0 || row >= settings.exceptionFilters->count())
return;
const ExceptionFilter & filter = settings.exceptionFilters->at(row);
if(filter.breakOn == ExceptionBreakOn::FirstChance)
ui->radioFirstChance->setChecked(true);
else if(filter.breakOn == ExceptionBreakOn::SecondChance)
ui->radioSecondChance->setChecked(true);
else
ui->radioDoNotBreak->setChecked(true);
if(filter.handledBy == ExceptionHandledBy::Debugger)
ui->radioHandledByDebugger->setChecked(true);
else
ui->radioHandledByDebuggee->setChecked(true);
ui->chkLogException->setChecked(filter.logException);
if(filter.range.start == 0 && filter.range.start == filter.range.end) // disallow deleting the 'unknown exceptions' filter
ui->btnDeleteRange->setEnabled(false);
else
ui->btnDeleteRange->setEnabled(true);
}
void SettingsDialog::OnCurrentExceptionFilterSettingsChanged()
{
QModelIndexList indexes = ui->listExceptions->selectionModel()->selectedIndexes();
if(!indexes.size()) // no selection
return;
int row = indexes.at(0).row();
if(row < 0 || row >= settings.exceptionFilters->count())
return;
ExceptionFilter filter = settings.exceptionFilters->at(row);
if(ui->radioFirstChance->isChecked())
filter.breakOn = ExceptionBreakOn::FirstChance;
else if(ui->radioSecondChance->isChecked())
filter.breakOn = ExceptionBreakOn::SecondChance;
else
filter.breakOn = ExceptionBreakOn::DoNotBreak;
filter.logException = ui->chkLogException->isChecked();
if(ui->radioHandledByDebugger->isChecked())
filter.handledBy = ExceptionHandledBy::Debugger;
else
filter.handledBy = ExceptionHandledBy::Debuggee;
settings.exceptionFilters->erase(settings.exceptionFilters->begin() + row);
settings.exceptionFilters->push_back(filter);
qSort(settings.exceptionFilters->begin(), settings.exceptionFilters->end(), ExceptionFilterLess());
}
void SettingsDialog::UpdateExceptionListWidget()
{
qSort(settings.exceptionFilters->begin(), settings.exceptionFilters->end(), ExceptionFilterLess());
ui->listExceptions->clear();
if(exceptionNames.empty() && DbgFunctions()->EnumExceptions)
{
BridgeList<CONSTANTINFO> exceptions;
DbgFunctions()->EnumExceptions(&exceptions);
for(int i = 0; i < exceptions.Count(); i++)
{
exceptionNames.insert({exceptions[i].value, exceptions[i].name});
}
}
for(int i = 0; i < settings.exceptionFilters->size(); i++)
{
const ExceptionFilter & filter = settings.exceptionFilters->at(i);
if(filter.range.start == 0 && filter.range.start == filter.range.end)
ui->listExceptions->addItem(QString("Unknown exceptions"));
else
{
const bool bSingleItemRange = filter.range.start == filter.range.end;
if(!bSingleItemRange)
{
ui->listExceptions->addItem(QString().asprintf("%.8X-%.8X", filter.range.start, filter.range.end));
}
else
{
auto found = exceptionNames.find(filter.range.start);
if(found == exceptionNames.end())
ui->listExceptions->addItem(QString().asprintf("%.8X", filter.range.start));
else
ui->listExceptions->addItem(QString().asprintf("%.8X\n %s", filter.range.start, found->second));
}
}
}
}
void SettingsDialog::setLastException(unsigned int exceptionCode)
{
lastException = exceptionCode;
}
void SettingsDialog::on_btnSave_clicked()
{
SaveSettings();
GuiAddStatusBarMessage(QString("%1\n").arg(tr("Settings saved!")).toUtf8().constData());
}
void SettingsDialog::on_chkSystemBreakpoint_stateChanged(int arg1)
{
settings.eventSystemBreakpoint = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkExitBreakpoint_stateChanged(int arg1)
{
settings.eventExitBreakpoint = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkTlsCallbacks_stateChanged(int arg1)
{
settings.eventTlsCallbacks = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkTlsCallbacksSystem_stateChanged(int arg1)
{
settings.eventTlsCallbacksSystem = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkEntryBreakpoint_stateChanged(int arg1)
{
settings.eventEntryBreakpoint = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkDllEntry_stateChanged(int arg1)
{
settings.eventDllEntry = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkDllEntrySystem_stateChanged(int arg1)
{
settings.eventDllEntrySystem = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkThreadEntry_stateChanged(int arg1)
{
settings.eventThreadEntry = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkSetJIT_stateChanged(int arg1)
{
if(arg1 == Qt::Unchecked)
{
if(DbgFunctions()->GetJit)
{
char jit_def_entry[MAX_SETTING_SIZE] = "";
QString qsjit_def_entry;
DbgFunctions()->GetDefJit(jit_def_entry);
qsjit_def_entry = jit_def_entry;
// if there are not an OLD JIT Stored GetJit(NULL,) returns false.
if((DbgFunctions()->GetJit(NULL, true) == false) && (ui->editJIT->text() == qsjit_def_entry))
{
/*
* Only do this when the user wants uncheck the JIT and there are not an OLD JIT Stored
* and the JIT in Windows registry its this debugger.
* Scenario 1: the JIT in Windows registry its this debugger, if the database of the
* debugger was removed and the user wants uncheck the JIT: he cant (this block its executed then)
* -
* Scenario 2: the JIT in Windows registry its NOT this debugger, if the database of the debugger
* was removed and the user in MISC tab wants check and uncheck the JIT checkbox: he can (this block its NOT executed then).
*/
SimpleWarningBox(this, tr("ERROR NOT FOUND OLD JIT"), tr("NOT FOUND OLD JIT ENTRY STORED, USE SETJIT COMMAND"));
settings.miscSetJIT = true;
}
else
settings.miscSetJIT = false;
ui->chkSetJIT->setCheckState(bool2check(settings.miscSetJIT));
}
settings.miscSetJIT = false;
}
else
settings.miscSetJIT = true;
}
void SettingsDialog::on_chkDllLoad_stateChanged(int arg1)
{
settings.eventDllLoad = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkDllUnload_stateChanged(int arg1)
{
settings.eventDllUnload = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkDllLoadSystem_stateChanged(int arg1)
{
settings.eventDllLoadSystem = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkDllUnloadSystem_stateChanged(int arg1)
{
settings.eventDllUnloadSystem = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkThreadStart_stateChanged(int arg1)
{
settings.eventThreadStart = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkThreadEnd_stateChanged(int arg1)
{
settings.eventThreadEnd = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkThreadNameSet_stateChanged(int arg1)
{
settings.eventThreadNameSet = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkDebugStrings_stateChanged(int arg1)
{
settings.eventDebugStrings = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_radioUnsigned_clicked()
{
settings.engineCalcType = calc_unsigned;
}
void SettingsDialog::on_radioSigned_clicked()
{
settings.engineCalcType = calc_signed;
}
void SettingsDialog::on_radioTitanEngine_clicked()
{
settings.engineType = DebugEngineTitanEngine;
}
void SettingsDialog::on_radioGleeBug_clicked()
{
settings.engineType = DebugEngineGleeBug;
}
void SettingsDialog::on_radioInt3Short_clicked()
{
settings.engineBreakpointType = break_int3short;
}
void SettingsDialog::on_radioInt3Long_clicked()
{
settings.engineBreakpointType = break_int3long;
}
void SettingsDialog::on_radioUd2_clicked()
{
settings.engineBreakpointType = break_ud2;
}
void SettingsDialog::on_chkUndecorateSymbolNames_stateChanged(int arg1)
{
if(arg1 == Qt::Unchecked)
settings.engineUndecorateSymbolNames = false;
else
settings.engineUndecorateSymbolNames = true;
}
void SettingsDialog::on_chkEnableDebugPrivilege_stateChanged(int arg1)
{
if(arg1 == Qt::Unchecked) //wtf stupid shit
settings.engineEnableDebugPrivilege = false;
else
settings.engineEnableDebugPrivilege = true;
}
void SettingsDialog::on_chkHardcoreThreadSwitchWarning_toggled(bool checked)
{
settings.engineHardcoreThreadSwitchWarning = checked;
}
void SettingsDialog::on_chkVerboseExceptionLogging_toggled(bool checked)
{
settings.engineVerboseExceptionLogging = checked;
}
void SettingsDialog::on_chkEnableSourceDebugging_stateChanged(int arg1)
{
settings.engineEnableSourceDebugging = arg1 == Qt::Checked;
}
void SettingsDialog::on_chkDisableDatabaseCompression_stateChanged(int arg1)
{
settings.engineDisableDatabaseCompression = arg1 == Qt::Checked;
}
void SettingsDialog::on_chkSaveDatabaseInProgramDirectory_stateChanged(int arg1)
{
settings.engineSaveDatabaseInProgramDirectory = arg1 == Qt::Checked;
}
void SettingsDialog::on_btnIgnoreRange_clicked()
{
ExceptionRangeDialog exceptionRange(this);
if(exceptionRange.exec() != QDialog::Accepted)
return;
ExceptionFilter filter;
filter.range.start = exceptionRange.rangeStart;
filter.range.end = exceptionRange.rangeEnd;
filter.breakOn = ExceptionBreakOn::SecondChance;
filter.logException = true;
filter.handledBy = ExceptionHandledBy::Debuggee;
AddExceptionFilterToList(filter);
}
void SettingsDialog::on_btnDeleteRange_clicked()
{
QModelIndexList indexes = ui->listExceptions->selectionModel()->selectedIndexes();
if(!indexes.size()) //no selection
return;
settings.exceptionFilters->erase(settings.exceptionFilters->begin() + indexes.at(0).row());
UpdateExceptionListWidget();
}
void SettingsDialog::on_btnIgnoreLast_clicked()
{
QMessageBox msg(QMessageBox::Question, tr("Question"), QString().sprintf(tr("Are you sure you want to add %.8X?").toUtf8().constData(), lastException));
msg.setWindowIcon(DIcon("question"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
msg.setDefaultButton(QMessageBox::Yes);
if(msg.exec() != QMessageBox::Yes)
return;
ExceptionFilter filter;
filter.range.start = lastException;
filter.range.end = lastException;
filter.breakOn = ExceptionBreakOn::SecondChance;
filter.logException = true;
filter.handledBy = ExceptionHandledBy::Debuggee;
AddExceptionFilterToList(filter);
}
// Shortcut to ignore all first chance exceptions and don't log
void SettingsDialog::on_btnIgnoreFirst_clicked()
{
for(int i = 0; i < settings.exceptionFilters->size(); i++)
{
ExceptionFilter & filter = (*settings.exceptionFilters)[i];
if(filter.range.start == 0 && filter.range.end == 0)
{
filter.breakOn = ExceptionBreakOn::SecondChance;
filter.handledBy = ExceptionHandledBy::Debuggee;
filter.logException = false;
}
}
UpdateExceptionListWidget();
}
void SettingsDialog::on_listExceptions_currentItemChanged(QListWidgetItem* current, QListWidgetItem*)
{
OnExceptionFilterSelectionChanged(current);
}
void SettingsDialog::on_listExceptions_itemClicked(QListWidgetItem* item)
{
OnExceptionFilterSelectionChanged(item);
}
void SettingsDialog::on_radioFirstChance_clicked()
{
OnCurrentExceptionFilterSettingsChanged();
}
void SettingsDialog::on_radioSecondChance_clicked()
{
OnCurrentExceptionFilterSettingsChanged();
}
void SettingsDialog::on_radioDoNotBreak_clicked()
{
OnCurrentExceptionFilterSettingsChanged();
}
void SettingsDialog::on_chkLogException_stateChanged(int arg1)
{
Q_UNUSED(arg1);
OnCurrentExceptionFilterSettingsChanged();
}
void SettingsDialog::on_radioHandledByDebugger_clicked()
{
OnCurrentExceptionFilterSettingsChanged();
}
void SettingsDialog::on_radioHandledByDebuggee_clicked()
{
OnCurrentExceptionFilterSettingsChanged();
}
void SettingsDialog::on_chkArgumentSpaces_stateChanged(int arg1)
{
bTokenizerConfigUpdated = true;
settings.disasmArgumentSpaces = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkHidePointerSizes_stateChanged(int arg1)
{
bTokenizerConfigUpdated = true;
settings.disasmHidePointerSizes = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkHideNormalSegments_stateChanged(int arg1)
{
bTokenizerConfigUpdated = true;
settings.disasmHideNormalSegments = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkMemorySpaces_stateChanged(int arg1)
{
bTokenizerConfigUpdated = true;
settings.disasmMemorySpaces = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkUppercase_stateChanged(int arg1)
{
bTokenizerConfigUpdated = true;
settings.disasmUppercase = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkOnlyCipAutoComments_stateChanged(int arg1)
{
settings.disasmOnlyCipAutoComments = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkTabBetweenMnemonicAndArguments_stateChanged(int arg1)
{
bTokenizerConfigUpdated = true;
settings.disasmTabBetweenMnemonicAndArguments = arg1 == Qt::Checked;
}
void SettingsDialog::on_editSymbolStore_textEdited(const QString & arg1)
{
Q_UNUSED(arg1);
settings.miscSymbolStore = true;
}
void SettingsDialog::on_editSymbolCache_textEdited(const QString & arg1)
{
Q_UNUSED(arg1);
settings.miscSymbolCache = true;
}
void SettingsDialog::on_chkSaveLoadTabOrder_stateChanged(int arg1)
{
settings.guiLoadSaveTabOrder = arg1 != Qt::Unchecked;
emit chkSaveLoadTabOrderStateChanged((bool)arg1);
}
void SettingsDialog::on_chkFpuRegistersLittleEndian_stateChanged(int arg1)
{
settings.guiFpuRegistersLittleEndian = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkSaveColumnOrder_stateChanged(int arg1)
{
settings.guiSaveColumnOrder = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkNoCloseDialog_toggled(bool checked)
{
settings.guiNoCloseDialog = checked;
}
void SettingsDialog::on_chkAutoFollowInStack_toggled(bool checked)
{
bGuiOptionsUpdated = true;
settings.guiAutoFollowInStack = checked;
}
void SettingsDialog::on_chkSkipInt3Stepping_toggled(bool checked)
{
settings.engineSkipInt3Stepping = checked;
}
void SettingsDialog::on_chkPidTidInHex_clicked(bool checked)
{
settings.guiPidTidInHex = checked;
}
void SettingsDialog::on_chkNoScriptTimeout_stateChanged(int arg1)
{
settings.engineNoScriptTimeout = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkSidebarWatchLabels_stateChanged(int arg1)
{
settings.guiSidebarWatchLabels = arg1 != Qt::Unchecked;
}
void SettingsDialog::on_chkIgnoreInconsistentBreakpoints_toggled(bool checked)
{
settings.engineIgnoreInconsistentBreakpoints = checked;
}
void SettingsDialog::on_chkNoForegroundWindow_toggled(bool checked)
{
settings.guiNoForegroundWindow = checked;
}
void SettingsDialog::on_spinMaxTraceCount_valueChanged(int arg1)
{
settings.engineMaxTraceCount = arg1;
}
void SettingsDialog::on_spinAnimateInterval_valueChanged(int arg1)
{
settings.engineAnimateInterval = arg1;
}
void SettingsDialog::on_chkNoHighlightOperands_toggled(bool checked)
{
bTokenizerConfigUpdated = true;
settings.disasmNoHighlightOperands = checked;
}
void SettingsDialog::on_chkUtf16LogRedirect_toggled(bool checked)
{
settings.miscUtf16LogRedirect = checked;
}
void SettingsDialog::on_chkPermanentHighlightingMode_toggled(bool checked)
{
bTokenizerConfigUpdated = true;
settings.disasmPermanentHighlightingMode = checked;
}
void SettingsDialog::on_chkNoWow64SingleStepWorkaround_toggled(bool checked)
{
settings.engineNoWow64SingleStepWorkaround = checked;
}
void SettingsDialog::on_chkDisableAslr_toggled(bool checked)
{
settings.engineDisableAslr = checked;
}
void SettingsDialog::on_chkNoCurrentModuleText_toggled(bool checked)
{
bTokenizerConfigUpdated = true;
settings.disasmNoCurrentModuleText = checked;
}
void SettingsDialog::on_chk0xPrefixValues_toggled(bool checked)
{
bTokenizerConfigUpdated = true;
settings.disasm0xPrefixValues = checked;
}
void SettingsDialog::on_chkNoBranchDisasmPreview_toggled(bool checked)
{
bGuiOptionsUpdated = true;
settings.disasmNoBranchDisasmPreview = checked;
}
void SettingsDialog::on_chkNoSourceLinesAutoComments_toggled(bool checked)
{
settings.disasmNoSourceLineAutoComments = checked;
}
void SettingsDialog::on_chkDoubleClickAssemble_toggled(bool checked)
{
settings.disasmAssembleOnDoubleClick = checked;
}
void SettingsDialog::on_spinMaximumModuleNameSize_valueChanged(int arg1)
{
settings.disasmMaxModuleSize = arg1;
}
void SettingsDialog::on_chkShowGraphRva_toggled(bool checked)
{
bTokenizerConfigUpdated = true;
settings.guiShowGraphRva = checked;
}
void SettingsDialog::on_chkGraphZoomMode_toggled(bool checked)
{
bTokenizerConfigUpdated = true;
settings.guiGraphZoomMode = checked;
}
void SettingsDialog::on_chkShowExitConfirmation_toggled(bool checked)
{
settings.guiShowExitConfirmation = checked;
}
void SettingsDialog::on_chkDisableAutoComplete_toggled(bool checked)
{
settings.guiDisableAutoComplete = checked;
bDisableAutoCompleteUpdated = true;
}
void SettingsDialog::on_chkHideSeasonalIcons_toggled(bool checked)
{
settings.guiHideSeasonalIcons = checked;
}
void SettingsDialog::on_chkUseLocalHelpFile_toggled(bool checked)
{
settings.miscUseLocalHelpFile = checked;
}
void SettingsDialog::on_chkQueryProcessCookie_toggled(bool checked)
{
settings.miscQueryProcessCookie = checked;
}
void SettingsDialog::on_chkQueryWorkingSet_toggled(bool checked)
{
settings.miscQueryWorkingSet = checked;
}
void SettingsDialog::on_chkTransparentExceptionStepping_toggled(bool checked)
{
settings.miscTransparentExceptionStepping = checked;
}
void SettingsDialog::on_chkQtHighDpiScaling_toggled(bool checked)
{
settings.guiEnableQtHighDpiScaling = checked;
}
void SettingsDialog::on_chkWindowLongPath_toggled(bool checked)
{
settings.guiEnableWindowLongPath = checked;
}
void SettingsDialog::on_chkNoIcons_toggled(bool checked)
{
settings.guiNoIcons = checked;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SettingsDialog.h | #pragma once
#include <QDialog>
#include <QListWidgetItem>
#include "Imports.h"
namespace Ui
{
class SettingsDialog;
}
class SettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit SettingsDialog(QWidget* parent = 0);
~SettingsDialog();
void SaveSettings();
unsigned int lastException;
signals:
void chkSaveLoadTabOrderStateChanged(bool state);
private slots:
//Manual slots
void setLastException(unsigned int exceptionCode);
//General
void on_btnSave_clicked();
//Event tab
void on_chkSystemBreakpoint_stateChanged(int arg1);
void on_chkExitBreakpoint_stateChanged(int arg1);
void on_chkTlsCallbacks_stateChanged(int arg1);
void on_chkTlsCallbacksSystem_stateChanged(int arg1);
void on_chkEntryBreakpoint_stateChanged(int arg1);
void on_chkDllEntry_stateChanged(int arg1);
void on_chkDllEntrySystem_stateChanged(int arg1);
void on_chkThreadEntry_stateChanged(int arg1);
void on_chkDllLoad_stateChanged(int arg1);
void on_chkDllUnload_stateChanged(int arg1);
void on_chkDllLoadSystem_stateChanged(int arg1);
void on_chkDllUnloadSystem_stateChanged(int arg1);
void on_chkThreadStart_stateChanged(int arg1);
void on_chkThreadEnd_stateChanged(int arg1);
void on_chkThreadNameSet_stateChanged(int arg1);
void on_chkDebugStrings_stateChanged(int arg1);
//Engine tab
void on_radioUnsigned_clicked();
void on_radioSigned_clicked();
void on_radioTitanEngine_clicked();
void on_radioGleeBug_clicked();
void on_radioInt3Short_clicked();
void on_radioInt3Long_clicked();
void on_radioUd2_clicked();
void on_chkUndecorateSymbolNames_stateChanged(int arg1);
void on_chkEnableDebugPrivilege_stateChanged(int arg1);
void on_chkEnableSourceDebugging_stateChanged(int arg1);
void on_chkDisableDatabaseCompression_stateChanged(int arg1);
void on_chkSaveDatabaseInProgramDirectory_stateChanged(int arg1);
void on_chkSkipInt3Stepping_toggled(bool checked);
void on_chkNoScriptTimeout_stateChanged(int arg1);
void on_chkIgnoreInconsistentBreakpoints_toggled(bool checked);
void on_chkHardcoreThreadSwitchWarning_toggled(bool checked);
void on_chkVerboseExceptionLogging_toggled(bool checked);
void on_chkNoWow64SingleStepWorkaround_toggled(bool checked);
void on_chkDisableAslr_toggled(bool checked);
void on_spinMaxTraceCount_valueChanged(int arg1);
void on_spinAnimateInterval_valueChanged(int arg1);
//Exception tab
void on_btnIgnoreRange_clicked();
void on_btnDeleteRange_clicked();
void on_btnIgnoreLast_clicked();
void on_btnIgnoreFirst_clicked();
void on_listExceptions_currentItemChanged(QListWidgetItem* current, QListWidgetItem* previous);
void on_listExceptions_itemClicked(QListWidgetItem* item);
void on_radioFirstChance_clicked();
void on_radioSecondChance_clicked();
void on_radioDoNotBreak_clicked();
void on_chkLogException_stateChanged(int arg1);
void on_radioHandledByDebugger_clicked();
void on_radioHandledByDebuggee_clicked();
//Disasm tab
void on_chkArgumentSpaces_stateChanged(int arg1);
void on_chkHidePointerSizes_stateChanged(int arg1);
void on_chkHideNormalSegments_stateChanged(int arg1);
void on_chkMemorySpaces_stateChanged(int arg1);
void on_chkUppercase_stateChanged(int arg1);
void on_chkOnlyCipAutoComments_stateChanged(int arg1);
void on_chkTabBetweenMnemonicAndArguments_stateChanged(int arg1);
void on_chkNoHighlightOperands_toggled(bool checked);
void on_chkNoCurrentModuleText_toggled(bool checked);
void on_chkPermanentHighlightingMode_toggled(bool checked);
void on_chk0xPrefixValues_toggled(bool checked);
void on_chkNoBranchDisasmPreview_toggled(bool checked);
void on_chkNoSourceLinesAutoComments_toggled(bool checked);
void on_chkDoubleClickAssemble_toggled(bool checked);
void on_spinMaximumModuleNameSize_valueChanged(int arg1);
//Gui Tab
void on_chkFpuRegistersLittleEndian_stateChanged(int arg1);
void on_chkSaveColumnOrder_stateChanged(int arg1);
void on_chkSaveLoadTabOrder_stateChanged(int arg1);
void on_chkNoCloseDialog_toggled(bool checked);
void on_chkPidTidInHex_clicked(bool checked);
void on_chkSidebarWatchLabels_stateChanged(int arg1);
void on_chkNoForegroundWindow_toggled(bool checked);
void on_chkShowExitConfirmation_toggled(bool checked);
void on_chkDisableAutoComplete_toggled(bool checked);
void on_chkAutoFollowInStack_toggled(bool checked);
void on_chkHideSeasonalIcons_toggled(bool checked);
void on_chkQtHighDpiScaling_toggled(bool checked);
void on_chkWindowLongPath_toggled(bool checked);
void on_chkNoIcons_toggled(bool checked);
//Misc tab
void on_chkSetJIT_stateChanged(int arg1);
void on_editSymbolStore_textEdited(const QString & arg1);
void on_editSymbolCache_textEdited(const QString & arg1);
void on_chkUtf16LogRedirect_toggled(bool checked);
void on_chkShowGraphRva_toggled(bool checked);
void on_chkGraphZoomMode_toggled(bool checked);
void on_chkUseLocalHelpFile_toggled(bool checked);
void on_chkQueryProcessCookie_toggled(bool checked);
void on_chkQueryWorkingSet_toggled(bool checked);
void on_chkTransparentExceptionStepping_toggled(bool checked);
private:
//enums
enum CalcType
{
calc_signed = 0,
calc_unsigned = 1
};
enum BreakpointType
{
break_int3short = 0,
break_int3long = 1,
break_ud2 = 2
};
enum class ExceptionBreakOn
{
FirstChance,
SecondChance,
DoNotBreak
};
enum class ExceptionHandledBy
{
Debugger,
Debuggee
};
//structures
struct RangeStruct
{
unsigned long start;
unsigned long end;
};
struct ExceptionFilter
{
RangeStruct range;
ExceptionBreakOn breakOn;
bool logException;
ExceptionHandledBy handledBy;
};
struct ExceptionFilterLess
{
bool operator()(const ExceptionFilter a, const ExceptionFilter b) const
{
return a.range.start < b.range.start;
}
};
// Unfortunately there are multiple sources of truth for the defaults.
// Some are in Configuration::Configuration and some in _exports.cpp
// case DBG_SETTINGS_UPDATED
struct SettingsStruct
{
//Event Tab
bool eventSystemBreakpoint = true;
bool eventExitBreakpoint = false;
bool eventTlsCallbacks = true;
bool eventTlsCallbacksSystem = true;
bool eventEntryBreakpoint = true;
bool eventDllEntry = false;
bool eventDllEntrySystem = false;
bool eventThreadEntry = false;
bool eventDllLoad = false;
bool eventDllUnload = false;
bool eventDllLoadSystem = false;
bool eventDllUnloadSystem = false;
bool eventThreadStart = false;
bool eventThreadEnd = false;
bool eventThreadNameSet = false;
bool eventDebugStrings = false;
//Engine Tab
CalcType engineCalcType = calc_unsigned;
DEBUG_ENGINE engineType = DebugEngineTitanEngine;
BreakpointType engineBreakpointType = break_int3short;
bool engineUndecorateSymbolNames = true;
bool engineEnableDebugPrivilege = true;
bool engineEnableSourceDebugging = false;
bool engineSaveDatabaseInProgramDirectory = false;
bool engineDisableDatabaseCompression = false;
bool engineSkipInt3Stepping = false;
bool engineNoScriptTimeout = false;
bool engineIgnoreInconsistentBreakpoints = false;
bool engineHardcoreThreadSwitchWarning = false;
bool engineVerboseExceptionLogging = true;
bool engineNoWow64SingleStepWorkaround = false;
bool engineDisableAslr = false;
int engineMaxTraceCount = 50000;
int engineAnimateInterval = 50;
//Exception Tab
QList<ExceptionFilter>* exceptionFilters = nullptr;
//Disasm Tab
bool disasmArgumentSpaces = false;
bool disasmMemorySpaces = false;
bool disasmHidePointerSizes = false;
bool disasmHideNormalSegments = false;
bool disasmUppercase = false;
bool disasmOnlyCipAutoComments = false;
bool disasmTabBetweenMnemonicAndArguments = false;
bool disasmNoHighlightOperands;
bool disasmNoCurrentModuleText = false;
bool disasmPermanentHighlightingMode;
bool disasm0xPrefixValues = false;
bool disasmNoBranchDisasmPreview = false;
bool disasmNoSourceLineAutoComments = false;
bool disasmAssembleOnDoubleClick = false;
int disasmMaxModuleSize = -1;
//Gui Tab
bool guiFpuRegistersLittleEndian = false;
bool guiSaveColumnOrder = false;
bool guiNoCloseDialog = false;
bool guiPidTidInHex = false;
bool guiSidebarWatchLabels = false;
bool guiNoForegroundWindow = true;
bool guiLoadSaveTabOrder = true;
bool guiShowGraphRva = false;
bool guiGraphZoomMode = true;
bool guiShowExitConfirmation = true;
bool guiDisableAutoComplete = false;
bool guiAutoFollowInStack = false;
bool guiHideSeasonalIcons = false;
bool guiEnableQtHighDpiScaling = true;
bool guiEnableWindowLongPath = false;
bool guiNoIcons = false;
//Misc Tab
bool miscSetJIT = false;
bool miscSymbolStore = false;
bool miscSymbolCache = false;
bool miscUtf16LogRedirect = false;
bool miscUseLocalHelpFile = false;
bool miscQueryProcessCookie = false;
bool miscQueryWorkingSet = false;
bool miscTransparentExceptionStepping = true;
};
//variables
Ui::SettingsDialog* ui;
SettingsStruct settings;
QList<ExceptionFilter> realExceptionFilters;
std::unordered_map<duint, const char*> exceptionNames;
bool bJitOld;
bool bGuiOptionsUpdated;
bool bTokenizerConfigUpdated;
bool bDisableAutoCompleteUpdated;
//functions
void GetSettingBool(const char* section, const char* name, bool* set);
Qt::CheckState bool2check(bool checked);
void LoadSettings();
void AddExceptionFilterToList(ExceptionFilter filter);
void OnExceptionFilterSelectionChanged(QListWidgetItem* selected);
void OnCurrentExceptionFilterSettingsChanged();
void UpdateExceptionListWidget();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/SettingsDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SettingsDialog</class>
<widget class="QDialog" name="SettingsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>365</width>
<height>561</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Preferences</string>
</property>
<property name="windowIcon">
<iconset theme="settings" resource="../../resource.qrc">
<normaloff>:/Default/icons/settings.png</normaloff>:/Default/icons/settings.png</iconset>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabEvents">
<attribute name="title">
<string>Events</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<item row="9" column="0">
<widget class="QCheckBox" name="chkDllLoad">
<property name="text">
<string>User DLL Load</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QCheckBox" name="chkThreadStart">
<property name="text">
<string>Thread Create</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QCheckBox" name="chkExitBreakpoint">
<property name="text">
<string>Exit Breakpoint*</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QCheckBox" name="chkThreadNameSet">
<property name="text">
<string>SetThreadName exceptions</string>
</property>
</widget>
</item>
<item row="9" column="1">
<widget class="QCheckBox" name="chkDllLoadSystem">
<property name="text">
<string>System DLL Load</string>
</property>
</widget>
</item>
<item row="13" column="0">
<spacer name="verticalSpacer_4">
<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 row="1" column="1">
<widget class="QCheckBox" name="chkThreadEntry">
<property name="text">
<string>Thread Entry</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QCheckBox" name="chkDebugStrings">
<property name="text">
<string>Debug Strings</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QCheckBox" name="chkThreadEnd">
<property name="text">
<string>Thread Exit</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QCheckBox" name="chkTlsCallbacksSystem">
<property name="text">
<string>System TLS Callbacks*</string>
</property>
</widget>
</item>
<item row="11" column="1">
<widget class="QCheckBox" name="chkDllUnloadSystem">
<property name="text">
<string>System DLL Unload</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="lblBreakOn">
<property name="text">
<string>Break on:</string>
</property>
</widget>
</item>
<item row="11" column="0">
<widget class="QCheckBox" name="chkDllUnload">
<property name="text">
<string>User DLL Unload</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QCheckBox" name="chkTlsCallbacks">
<property name="text">
<string>User TLS Callbacks*</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="chkSystemBreakpoint">
<property name="text">
<string>System Breakpoint*</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QCheckBox" name="chkEntryBreakpoint">
<property name="text">
<string>Entry Breakpoint*</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item row="8" column="1">
<widget class="QCheckBox" name="chkDllEntrySystem">
<property name="text">
<string>System DLL Entry</string>
</property>
</widget>
</item>
<item row="8" column="0">
<widget class="QCheckBox" name="chkDllEntry">
<property name="text">
<string>User DLL Entry</string>
</property>
</widget>
</item>
<item row="14" column="1">
<widget class="QLabel" name="label_2">
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="text">
<string>* Requires debuggee restart</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabEngine">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<attribute name="title">
<string>Engine</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QGroupBox" name="groupBoxCalculationType">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Calculation Type</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QRadioButton" name="radioSigned">
<property name="text">
<string>&Signed</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioUnsigned">
<property name="text">
<string>&Unsigned</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBoxDebugEngine">
<property name="title">
<string>Debug Engine*</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QRadioButton" name="radioTitanEngine">
<property name="text">
<string>TitanEngine</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioGleeBug">
<property name="text">
<string>GleeBug</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QGroupBox" name="groupBoxDefaultBreakpointType">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Default Breakpoint Type</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_7">
<item>
<layout class="QHBoxLayout" name="layoutBreakpointType">
<item>
<widget class="QRadioButton" name="radioInt3Short">
<property name="text">
<string>INT3</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioInt3Long">
<property name="text">
<string>Long INT3</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioUd2">
<property name="text">
<string>UD2</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkUndecorateSymbolNames">
<property name="text">
<string>Undecorate Symbol Names</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkEnableDebugPrivilege">
<property name="text">
<string>Enable Debug &Privilege</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkEnableSourceDebugging">
<property name="text">
<string>Enable Source Debugging</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkDisableDatabaseCompression">
<property name="text">
<string>Disable Database Compression</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkSaveDatabaseInProgramDirectory">
<property name="text">
<string>Save Database in Program Directory</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkSkipInt3Stepping">
<property name="text">
<string>Skip INT3 stepping</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoScriptTimeout">
<property name="text">
<string>No Script Timeout Warning</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkIgnoreInconsistentBreakpoints">
<property name="text">
<string>&Ignore inconsistent breakpoints</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkHardcoreThreadSwitchWarning">
<property name="text">
<string>Log If the Thread Has Switched</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkVerboseExceptionLogging">
<property name="text">
<string>Enable Verbose Exception Logging</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoWow64SingleStepWorkaround">
<property name="text">
<string>Disable WOW64 Single Step Workaround</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkDisableAslr">
<property name="text">
<string>Disable ASLR</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayoutMaxTraceCount">
<item>
<widget class="QLabel" name="lblMaxTraceCount">
<property name="text">
<string>Default maximum trace &count</string>
</property>
<property name="buddy">
<cstring>spinMaxTraceCount</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinMaxTraceCount">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="wrapping">
<bool>false</bool>
</property>
<property name="frame">
<bool>true</bool>
</property>
<property name="buttonSymbols">
<enum>QAbstractSpinBox::UpDownArrows</enum>
</property>
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>2147483647</number>
</property>
<property name="value">
<number>50000</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayoutAnimateInterval">
<item>
<widget class="QLabel" name="lblAnimateInterval">
<property name="text">
<string>Animation per-step interval (ms)</string>
</property>
<property name="buddy">
<cstring>spinAnimateInterval</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinAnimateInterval">
<property name="toolTip">
<string><html><head/><body><p>The debugger sleeps for a certain time in order to keep the interval between animation steps constant as specified in this setting.</p><p>If you want to animate as fast as possible set this to 0.</p></body></html></string>
</property>
<property name="maximum">
<number>99999</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::MinimumExpanding</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>* Requires debugger restart</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabExceptions">
<attribute name="title">
<string>Exceptions</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<widget class="QLabel" name="lblExceptionFilters">
<property name="text">
<string>Exception Filters:</string>
</property>
<property name="buddy">
<cstring>listExceptions</cstring>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayoutExceptions">
<item>
<widget class="QListWidget" name="listExceptions">
<property name="font">
<font>
<family>Courier New</family>
<pointsize>8</pointsize>
</font>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
</widget>
</item>
<item>
<layout class="QVBoxLayout" name="layoutExceptionButtons">
<item>
<spacer name="verticalSpacerExceptionsTop">
<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="QPushButton" name="btnIgnoreRange">
<property name="text">
<string>Ignore &Range</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDeleteRange">
<property name="text">
<string>&Delete Range</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnIgnoreLast">
<property name="text">
<string>Ignore &Last</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnIgnoreFirst">
<property name="toolTip">
<string>Ignore all first-chance exceptions, don't print log, pass them to the debuggee and only break on second-chance exceptions.</string>
</property>
<property name="text">
<string>Ignore First-Chance</string>
</property>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBoBreakOn">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Break On</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QRadioButton" name="radioFirstChance">
<property name="text">
<string>First chance</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioSecondChance">
<property name="text">
<string>Second chance</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioDoNotBreak">
<property name="text">
<string>Do not break</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBoxLogging">
<property name="title">
<string>Logging</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_6">
<item>
<widget class="QCheckBox" name="chkLogException">
<property name="text">
<string>Log exception</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBoxExceptionHandledBy">
<property name="title">
<string>Exception handled by</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_8">
<item>
<widget class="QRadioButton" name="radioHandledByDebugger">
<property name="text">
<string>Debugger</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioHandledByDebuggee">
<property name="text">
<string>Debuggee</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacerExceptionsBottom">
<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>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabDisasm">
<attribute name="title">
<string>Disasm</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QCheckBox" name="chkArgumentSpaces">
<property name="text">
<string>Argument Spaces</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkTabBetweenMnemonicAndArguments">
<property name="text">
<string>Tab between mnemonic and arguments</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkHidePointerSizes">
<property name="text">
<string>Hide pointer sizes</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkHideNormalSegments">
<property name="text">
<string>Only show FS/GS segments</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkMemorySpaces">
<property name="text">
<string>Memory Spaces</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkUppercase">
<property name="text">
<string>Uppercase</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkOnlyCipAutoComments">
<property name="text">
<string>Autocomments only on CIP</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoHighlightOperands">
<property name="text">
<string>Don't highlight operands</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoCurrentModuleText">
<property name="text">
<string>Hide module name for local memory addresses</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkPermanentHighlightingMode">
<property name="text">
<string>Permanent highlighting mode</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoBranchDisasmPreview">
<property name="text">
<string>Disable branch disassembly preview</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chk0xPrefixValues">
<property name="text">
<string>0x prefix for values</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoSourceLinesAutoComments">
<property name="text">
<string>Don't show source lines in comments</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkDoubleClickAssemble">
<property name="text">
<string>Assemble instruction on double-click</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="layoutMaximumModuleNameSize">
<item>
<widget class="QLabel" name="lblMaximumModuleNameSize">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>Maximum module name size</string>
</property>
<property name="buddy">
<cstring>spinMaximumModuleNameSize</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinMaximumModuleNameSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="minimum">
<number>-1</number>
</property>
<property name="maximum">
<number>2147483647</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacerDisasm">
<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>
<widget class="QWidget" name="tabGui">
<attribute name="title">
<string>GUI</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_11">
<item>
<widget class="QCheckBox" name="chkFpuRegistersLittleEndian">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Show FPU registers as little endian</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkSaveColumnOrder">
<property name="text">
<string>Save GUI layout and column orders</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoCloseDialog">
<property name="text">
<string>Don't show close dialog</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkPidTidInHex">
<property name="text">
<string>Show PID/TID in HEX</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkSaveLoadTabOrder">
<property name="text">
<string>Enable Load/Save Tab Order</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkSidebarWatchLabels">
<property name="text">
<string>Show Watch Labels in Side Bar</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoForegroundWindow">
<property name="text">
<string>Do not call SetForegroundWindow</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkShowGraphRva">
<property name="text">
<string>Show RVA addresses in graph view</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkGraphZoomMode">
<property name="text">
<string>Graph zoom mode</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkAutoFollowInStack">
<property name="text">
<string>Auto follow operand in stack</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkShowExitConfirmation">
<property name="text">
<string>Show exit confirmation dialog</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkDisableAutoComplete">
<property name="text">
<string>Disable auto completion in goto dialog</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkHideSeasonalIcons">
<property name="text">
<string>Hide seasonal icons</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkQtHighDpiScaling">
<property name="toolTip">
<string>Disabling this option will tell Windows that x64dbg is DPI unaware. This might result in blurry results in some configurations.</string>
</property>
<property name="text">
<string>Qt High DPI Scaling</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkWindowLongPath">
<property name="text">
<string>Full executable path in title</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkNoIcons">
<property name="text">
<string>Disable icons*</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacerGUI">
<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>
<widget class="QWidget" name="tabMisc">
<attribute name="title">
<string>Misc</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_10">
<item>
<layout class="QVBoxLayout" name="verticalLayoutSymbolJIT">
<item>
<layout class="QHBoxLayout" name="horizontalLayoutSymbol">
<item>
<layout class="QVBoxLayout" name="verticalLayoutSymbolLabels">
<item>
<widget class="QLabel" name="lblSymbolStore">
<property name="text">
<string>Symbol Store:</string>
</property>
<property name="buddy">
<cstring>editSymbolStore</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblSymbolPath">
<property name="text">
<string>Symbol Path:</string>
</property>
<property name="buddy">
<cstring>editSymbolCache</cstring>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayoutSymbolEdits">
<item>
<widget class="QLineEdit" name="editSymbolStore"/>
</item>
<item>
<widget class="QLineEdit" name="editSymbolCache"/>
</item>
</layout>
</item>
</layout>
</item>
<item>
<widget class="QCheckBox" name="chkSetJIT">
<property name="text">
<string>Set x64dbg as Just In Time Debugger</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayoutJIT">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>JIT:</string>
</property>
<property name="buddy">
<cstring>editJIT</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="editJIT">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="lblAdminWarning">
<property name="text">
<string><font color="red">DIE SCUM!</font></string>
</property>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBoxSearchEngineURL">
<property name="title">
<string>Search Engine URL</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QLineEdit" name="editHelpOnSymbolicNameUrl"/>
</item>
</layout>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QCheckBox" name="chkUtf16LogRedirect">
<property name="text">
<string>UTF-16 Log Redirect*</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkUseLocalHelpFile">
<property name="text">
<string>Use local help file (x64dbg.chm)</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkQueryProcessCookie">
<property name="text">
<string>Query process cookie*</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkQueryWorkingSet">
<property name="text">
<string>Query working set before reading memory</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkTransparentExceptionStepping">
<property name="text">
<string>Transparent exception stepping*</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacerMisc">
<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="label_3">
<property name="text">
<string>* Requires debuggee restart</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayoutSaveCancel">
<item>
<spacer name="horizontalSpacerSaveCancel">
<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="btnSave">
<property name="text">
<string>Save</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnCancel">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>chkSystemBreakpoint</tabstop>
<tabstop>chkEntryBreakpoint</tabstop>
<tabstop>radioInt3Short</tabstop>
<tabstop>radioInt3Long</tabstop>
<tabstop>radioUd2</tabstop>
<tabstop>chkUndecorateSymbolNames</tabstop>
<tabstop>chkEnableDebugPrivilege</tabstop>
<tabstop>chkEnableSourceDebugging</tabstop>
<tabstop>chkDisableDatabaseCompression</tabstop>
<tabstop>chkSaveDatabaseInProgramDirectory</tabstop>
<tabstop>listExceptions</tabstop>
<tabstop>btnIgnoreRange</tabstop>
<tabstop>btnDeleteRange</tabstop>
<tabstop>btnIgnoreLast</tabstop>
<tabstop>chkArgumentSpaces</tabstop>
<tabstop>chkTabBetweenMnemonicAndArguments</tabstop>
<tabstop>chkMemorySpaces</tabstop>
<tabstop>chkUppercase</tabstop>
<tabstop>chkOnlyCipAutoComments</tabstop>
<tabstop>editSymbolStore</tabstop>
<tabstop>editSymbolCache</tabstop>
<tabstop>chkSetJIT</tabstop>
<tabstop>editJIT</tabstop>
<tabstop>btnSave</tabstop>
<tabstop>btnCancel</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>SettingsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>420</x>
<y>622</y>
</hint>
<hint type="destinationlabel">
<x>357</x>
<y>236</y>
</hint>
</hints>
</connection>
<connection>
<sender>btnSave</sender>
<signal>clicked()</signal>
<receiver>SettingsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>320</x>
<y>622</y>
</hint>
<hint type="destinationlabel">
<x>279</x>
<y>236</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/ShortcutsDialog.cpp | #include "ShortcutsDialog.h"
#include "ui_ShortcutsDialog.h"
#include <QMessageBox>
ShortcutsDialog::ShortcutsDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ShortcutsDialog)
{
ui->setupUi(this);
//set window flags
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true);
// x64 has no model-view-controler pattern
QStringList tblHeader;
tblHeader << tr("Action") << tr("Hotkey");
currentRow = 0;
ui->tblShortcuts->setColumnCount(2);
ui->tblShortcuts->verticalHeader()->setVisible(false);
ui->tblShortcuts->setHorizontalHeaderLabels(tblHeader);
ui->tblShortcuts->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tblShortcuts->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tblShortcuts->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tblShortcuts->setShowGrid(false);
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
ui->tblShortcuts->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
#else
ui->tblShortcuts->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
#endif
ui->tblShortcuts->verticalHeader()->setDefaultSectionSize(15);
showShortcutsFiltered(QString());
connect(ui->tblShortcuts, SIGNAL(itemSelectionChanged()), this, SLOT(syncTextfield()));
connect(ui->shortcutEdit, SIGNAL(askForSave()), this, SLOT(updateShortcut()));
connect(this, SIGNAL(rejected()), this, SLOT(rejectedSlot()));
connect(ui->filterEdit, SIGNAL(textChanged(const QString &)), this, SLOT(on_FilterTextChanged(const QString &)));
}
void ShortcutsDialog::showShortcutsFiltered(const QString & actionName)
{
QMap<QString, Configuration::Shortcut> shorcutsToShow;
filterShortcutsByName(actionName, shorcutsToShow);
ui->tblShortcuts->clearContents();
ui->tblShortcuts->setRowCount(shorcutsToShow.count());
currentRow = 0;
int row = 0;
for(auto shortcut : shorcutsToShow)
{
QTableWidgetItem* shortcutName = new QTableWidgetItem(shortcut.Name);
QTableWidgetItem* shortcutKey = new QTableWidgetItem(shortcut.Hotkey.toString(QKeySequence::NativeText));
ui->tblShortcuts->setItem(row, 0, shortcutName);
ui->tblShortcuts->setItem(row, 1, shortcutKey);
row++;
}
ui->tblShortcuts->setSortingEnabled(true);
}
void ShortcutsDialog::filterShortcutsByName(const QString & nameFilter, QMap<QString, Configuration::Shortcut> & mapToFill)
{
for(auto shortcut : Config()->Shortcuts)
{
if(shortcut.Name.contains(nameFilter, Qt::CaseInsensitive) || nameFilter == QString())
{
mapToFill.insert(shortcut.Name, shortcut);
}
}
}
void ShortcutsDialog::updateShortcut()
{
const QKeySequence newKey = ui->shortcutEdit->getKeysequence();
if(newKey != currentShortcut.Hotkey)
{
bool good = true;
if(!newKey.isEmpty())
{
int idx = 0;
for(QMap<QString, Configuration::Shortcut>::iterator i = Config()->Shortcuts.begin(); i != Config()->Shortcuts.end(); ++i, idx++)
{
if(i.value().Name == currentShortcut.Name) //skip current shortcut in list
continue;
if(i.value().GlobalShortcut && i.value().Hotkey == newKey) //newkey is trying to override a global shortcut
{
good = false;
break;
}
else if(currentShortcut.GlobalShortcut && i.value().Hotkey == newKey) //current shortcut is global and overrides another local hotkey
{
ui->tblShortcuts->setItem(idx, 1, new QTableWidgetItem(""));
Config()->setShortcut(i.key(), QKeySequence());
}
else if(i.value().Hotkey == newKey) // This shortcut already exists (both are local)
{
// Ask user if they want to override the shortcut.
QMessageBox mbox;
mbox.setIcon(QMessageBox::Question);
mbox.setText("This hotkey is already used by the action \"" + i.value().Name + "\".\n"
"Do you want to override it?");
mbox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
mbox.setDefaultButton(QMessageBox::Yes);
good = mbox.exec() == QMessageBox::Yes;
if(good)
{
ui->tblShortcuts->setItem(idx, 1, new QTableWidgetItem(""));
Config()->setShortcut(i.key(), QKeySequence());
}
}
}
}
if(good)
{
for(QMap<QString, Configuration::Shortcut>::iterator i = Config()->Shortcuts.begin(); i != Config()->Shortcuts.end(); ++i)
{
if(i.value().Name == currentShortcut.Name)
{
Config()->setShortcut(i.key(), newKey);
break;
}
}
QString keyText = "";
if(!newKey.isEmpty())
keyText = newKey.toString(QKeySequence::NativeText);
ui->tblShortcuts->item(currentRow, 1)->setText(keyText);
ui->shortcutEdit->setErrorState(false);
}
else
{
ui->shortcutEdit->setErrorState(true);
}
}
}
void ShortcutsDialog::on_btnClearShortcut_clicked()
{
for(QMap<QString, Configuration::Shortcut>::iterator i = Config()->Shortcuts.begin(); i != Config()->Shortcuts.end(); ++i)
{
if(i.value().Name == currentShortcut.Name)
{
Config()->setShortcut(i.key(), QKeySequence());
break;
}
}
QString emptyString;
ui->tblShortcuts->item(currentRow, 1)->setText(emptyString);
ui->shortcutEdit->setText(emptyString);
ui->shortcutEdit->setErrorState(false);
}
void ShortcutsDialog::syncTextfield()
{
QModelIndexList indexes = ui->tblShortcuts->selectionModel()->selectedRows();
if(indexes.count() < 1)
return;
currentRow = indexes.at(0).row();
for(auto shortcut : Config()->Shortcuts)
{
if(shortcut.Name == ui->tblShortcuts->item(currentRow, 0)->text())
{
currentShortcut = shortcut;
break;
}
}
ui->shortcutEdit->setErrorState(false);
ui->shortcutEdit->setText(currentShortcut.Hotkey.toString(QKeySequence::NativeText));
ui->shortcutEdit->setFocus();
}
ShortcutsDialog::~ShortcutsDialog()
{
delete ui;
}
void ShortcutsDialog::on_btnSave_clicked()
{
Config()->writeShortcuts();
GuiAddStatusBarMessage(QString("%1\n").arg(tr("Settings saved!")).toUtf8().constData());
}
void ShortcutsDialog::rejectedSlot()
{
Config()->readShortcuts();
}
void ShortcutsDialog::on_FilterTextChanged(const QString & actionName)
{
showShortcutsFiltered(actionName);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ShortcutsDialog.h | #pragma once
#include <QDialog>
#include <QHeaderView>
#include "Configuration.h"
namespace Ui
{
class ShortcutsDialog;
}
class ShortcutsDialog : public QDialog
{
Q_OBJECT
Configuration::Shortcut currentShortcut;
int currentRow;
public:
explicit ShortcutsDialog(QWidget* parent = 0);
~ShortcutsDialog();
protected slots:
void syncTextfield();
void updateShortcut();
private slots:
void on_btnSave_clicked();
void on_btnClearShortcut_clicked();
void rejectedSlot();
void on_FilterTextChanged(const QString & actionName);
private:
Ui::ShortcutsDialog* ui;
QMap<QString, Configuration::Shortcut> ShortcutsBackup;
void filterShortcutsByName(const QString & nameFilter, QMap<QString, Configuration::Shortcut> & mapToFill);
void showShortcutsFiltered(const QString & actionName);
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/ShortcutsDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ShortcutsDialog</class>
<widget class="QDialog" name="ShortcutsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>622</width>
<height>401</height>
</rect>
</property>
<property name="windowTitle">
<string>Hotkeys</string>
</property>
<property name="windowIcon">
<iconset theme="shortcut" resource="../../resource.qrc">
<normaloff>:/Default/icons/shortcut.png</normaloff>:/Default/icons/shortcut.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="filterEdit">
<property name="placeholderText">
<string>Action filter</string>
</property>
</widget>
</item>
<item>
<widget class="QTableWidget" name="tblShortcuts"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Hotkey</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="ShortcutEdit" name="shortcutEdit"/>
</item>
<item>
<widget class="QPushButton" name="btnClearShortcut">
<property name="text">
<string>Clear</string>
</property>
</widget>
</item>
</layout>
</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="btnSave">
<property name="text">
<string>Save</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnCancel">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>ShortcutEdit</class>
<extends>QLineEdit</extends>
<header>ShortcutEdit.h</header>
</customwidget>
</customwidgets>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>ShortcutsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>572</x>
<y>379</y>
</hint>
<hint type="destinationlabel">
<x>558</x>
<y>368</y>
</hint>
</hints>
</connection>
<connection>
<sender>btnSave</sender>
<signal>clicked()</signal>
<receiver>ShortcutsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>498</x>
<y>380</y>
</hint>
<hint type="destinationlabel">
<x>443</x>
<y>378</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/SimpleTraceDialog.cpp | #include "SimpleTraceDialog.h"
#include "ui_SimpleTraceDialog.h"
#include "Bridge.h"
#include <QMessageBox>
#include "BrowseDialog.h"
#include "MiscUtil.h"
#include "Tracer/TraceBrowser.h"
SimpleTraceDialog::SimpleTraceDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::SimpleTraceDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
duint setting;
if(!BridgeSettingGetUint("Engine", "MaxTraceCount", &setting))
setting = 50000;
ui->spinMaxTraceCount->setValue(int(setting));
ui->editBreakCondition->setPlaceholderText(tr("Example: %1").arg("eax == 0 && ebx == 0"));
ui->editLogText->setPlaceholderText(tr("Example: %1").arg("0x{p:cip} {i:cip}"));
ui->editLogCondition->setPlaceholderText(tr("Example: %1").arg("eax == 0 && ebx == 0"));
ui->editCommandText->setPlaceholderText(tr("Example: %1").arg("eax=4;StepOut"));
ui->editCommandCondition->setPlaceholderText(tr("Example: %1").arg("eax == 0 && ebx == 0"));
}
SimpleTraceDialog::~SimpleTraceDialog()
{
delete ui;
}
void SimpleTraceDialog::setTraceCommand(const QString & command)
{
mTraceCommand = command;
}
static QString escapeText(QString str)
{
str.replace(QChar('\\'), QString("\\\\"));
str.replace(QChar('"'), QString("\\\""));
return str;
}
void SimpleTraceDialog::on_btnOk_clicked()
{
if(!mLogFile.isEmpty() && ui->editLogText->text().isEmpty())
{
QMessageBox msgyn(QMessageBox::Warning, tr("Trace log file"),
tr("It appears you have set the log file, but not the log text. <b>This will result in an empty log</b>. Do you really want to continue?"), QMessageBox::Yes | QMessageBox::No, this);
msgyn.setWindowIcon(DIcon("compile-warning"));
msgyn.setParent(this, Qt::Dialog);
msgyn.setWindowFlags(msgyn.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msgyn.exec() == QMessageBox::No)
return;
}
if(ui->chkRecordTrace->isChecked() && !TraceBrowser::isRecording())
{
if(!TraceBrowser::toggleTraceRecording(this))
{
ui->chkRecordTrace->setChecked(false);
SimpleWarningBox(this, tr("Error"), tr("Trace recording was requested, but not enabled."));
return;
}
ui->chkRecordTrace->setChecked(false);
}
auto logText = ui->editLogText->addHistoryClear();
auto logCondition = ui->editLogCondition->addHistoryClear();
if(!DbgCmdExecDirect(QString("TraceSetLog \"%1\", \"%2\"").arg(escapeText(logText), escapeText(logCondition)).toUtf8().constData()))
{
SimpleWarningBox(this, tr("Error"), tr("Failed to set log text/condition!"));
return;
}
auto commandText = ui->editCommandText->addHistoryClear();
auto commandCondition = ui->editCommandCondition->addHistoryClear();
if(!DbgCmdExecDirect(QString("TraceSetCommand \"%1\", \"%2\"").arg(escapeText(commandText), escapeText(commandCondition)).toUtf8().constData()))
{
SimpleWarningBox(this, tr("Error"), tr("Failed to set command text/condition!"));
return;
}
if(!DbgCmdExecDirect(QString("TraceSetLogFile \"%1\"").arg(escapeText(mLogFile)).toUtf8().constData()))
{
SimpleWarningBox(this, tr("Error"), tr("Failed to set log file!"));
return;
}
auto breakCondition = ui->editBreakCondition->addHistoryClear();
auto maxTraceCount = ui->spinMaxTraceCount->value();
if(!DbgCmdExecDirect(QString("%1 \"%2\", .%3").arg(mTraceCommand, escapeText(breakCondition)).arg(maxTraceCount).toUtf8().constData()))
{
SimpleWarningBox(this, tr("Error"), tr("Failed to start trace!"));
return;
}
accept();
}
void SimpleTraceDialog::on_btnLogFile_clicked()
{
BrowseDialog browse(
this,
tr("Trace log file"),
tr("Enter the path to the log file."),
tr("Log Files (*.txt *.log);;All Files (*.*)"),
getDbPath(mainModuleName() + ".log", true),
true
);
if(browse.exec() == QDialog::Accepted)
mLogFile = browse.path;
else
mLogFile.clear();
}
int SimpleTraceDialog::exec()
{
if(TraceBrowser::isRecording())
{
ui->chkRecordTrace->setEnabled(false);
ui->chkRecordTrace->setChecked(true);
ui->chkRecordTrace->setToolTip(tr("Trace recording already started"));
}
else
{
ui->chkRecordTrace->setEnabled(true);
ui->chkRecordTrace->setChecked(false);
ui->chkRecordTrace->setToolTip("");
}
return QDialog::exec();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SimpleTraceDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class SimpleTraceDialog;
}
class SimpleTraceDialog : public QDialog
{
Q_OBJECT
public:
explicit SimpleTraceDialog(QWidget* parent = 0);
~SimpleTraceDialog();
void setTraceCommand(const QString & command);
private slots:
void on_btnOk_clicked();
void on_btnLogFile_clicked();
public slots:
int exec() override;
private:
Ui::SimpleTraceDialog* ui;
QString mTraceCommand;
QString mLogFile;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/SimpleTraceDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SimpleTraceDialog</class>
<widget class="QDialog" name="SimpleTraceDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>502</width>
<height>218</height>
</rect>
</property>
<property name="windowTitle">
<string/>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="7" column="0" colspan="2">
<widget class="QLabel" name="lblHint">
<property name="text">
<string>Hint: History is available in every text field with the Up/Down arrows!</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="lblLogCondition">
<property name="text">
<string>Lo&g Condition:</string>
</property>
<property name="buddy">
<cstring>editLogCondition</cstring>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="lblCommandText">
<property name="text">
<string>&Command Text:</string>
</property>
<property name="buddy">
<cstring>editCommandText</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="HistoryLineEdit" name="editLogText"/>
</item>
<item row="2" column="1">
<widget class="HistoryLineEdit" name="editLogCondition"/>
</item>
<item row="0" column="1">
<widget class="HistoryLineEdit" name="editBreakCondition"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="lblBreakCondition">
<property name="text">
<string>&Break Condition:</string>
</property>
<property name="buddy">
<cstring>editBreakCondition</cstring>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="HistoryLineEdit" name="editCommandText"/>
</item>
<item row="6" column="1">
<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="QCheckBox" name="chkRecordTrace">
<property name="text">
<string>&Record trace</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnLogFile">
<property name="text">
<string>Log &File...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnOk">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&OK</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnCancel">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>C&ancel</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="4" column="0">
<widget class="QLabel" name="lblCommandCondition">
<property name="text">
<string>C&ommand Condition:</string>
</property>
<property name="buddy">
<cstring>editCommandCondition</cstring>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="lblMaxTraceCount">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Maximum trace count:</string>
</property>
<property name="buddy">
<cstring>spinMaxTraceCount</cstring>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="HistoryLineEdit" name="editCommandCondition"/>
</item>
<item row="5" column="1">
<widget class="QSpinBox" name="spinMaxTraceCount">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>2147483647</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="lblLogText">
<property name="text">
<string>&Log Text:</string>
</property>
<property name="buddy">
<cstring>editLogText</cstring>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>HistoryLineEdit</class>
<extends>QLineEdit</extends>
<header>HistoryLineEdit.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>editBreakCondition</tabstop>
<tabstop>editLogText</tabstop>
<tabstop>editLogCondition</tabstop>
<tabstop>editCommandText</tabstop>
<tabstop>editCommandCondition</tabstop>
<tabstop>spinMaxTraceCount</tabstop>
<tabstop>chkRecordTrace</tabstop>
<tabstop>btnLogFile</tabstop>
<tabstop>btnOk</tabstop>
<tabstop>btnCancel</tabstop>
</tabstops>
<resources/>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>SimpleTraceDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>491</x>
<y>214</y>
</hint>
<hint type="destinationlabel">
<x>501</x>
<y>153</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/SourceView.cpp | #include "SourceView.h"
#include <QFileDialog>
#include <QDesktopServices>
#include <QProcess>
#include <QInputDialog>
#include <memory>
#include "FileLines.h"
#include "Bridge.h"
#include "CommonActions.h"
SourceView::SourceView(QString path, duint addr, QWidget* parent)
: AbstractStdTable(parent),
mSourcePath(path),
mModBase(DbgFunctions()->ModBaseFromAddr(addr))
{
enableMultiSelection(true);
enableColumnSorting(false);
setDrawDebugOnly(false);
setAddressColumn(0);
int charwidth = getCharWidth();
addColumnAt(8 + charwidth * sizeof(duint) * 2, tr("Address"), false);
addColumnAt(8 + charwidth * 8, tr("Line"), false);
addColumnAt(0, tr("Code"), false);
loadColumnFromConfig("SourceView");
setupContextMenu();
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(followDisassemblerSlot()));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followDisassemblerSlot()));
connect(Bridge::getBridge(), SIGNAL(updateDisassembly()), this, SLOT(reloadData()));
Initialize();
loadFile();
}
SourceView::~SourceView()
{
clear();
}
QString SourceView::getCellContent(int r, int c)
{
if(!isValidIndex(r, c))
return QString();
LineData & line = mLines.at(r - mPrepareTableOffset);
switch(c)
{
case ColAddr:
return line.addr ? ToPtrString(line.addr) : QString();
case ColLine:
return QString("%1").arg(line.index + 1);
case ColCode:
return line.code.code;
}
__debugbreak();
return "INVALID";
}
bool SourceView::isValidIndex(int r, int c)
{
if(!mFileLines)
return false;
if(c < ColAddr || c > ColCode)
return false;
return r >= 0 && size_t(r) < mFileLines->size();
}
void SourceView::sortRows(int column, bool ascending)
{
Q_UNUSED(column);
Q_UNUSED(ascending);
}
void SourceView::prepareData()
{
AbstractTableView::prepareData();
if(mFileLines)
{
auto lines = getNbrOfLineToPrint();
mPrepareTableOffset = getTableOffset();
mLines.clear();
mLines.resize(lines);
for(auto i = 0; i < lines; i++)
parseLine(mPrepareTableOffset + i, mLines[i]);
}
}
void SourceView::setSelection(duint addr)
{
int line = 0;
if(!DbgFunctions()->GetSourceFromAddr(addr, nullptr, &line))
return;
scrollSelect(line - 1);
reloadData(); //repaint
}
void SourceView::clear()
{
delete mFileLines;
mFileLines = nullptr;
mSourcePath.clear();
mModBase = 0;
}
QString SourceView::getSourcePath()
{
return mSourcePath;
}
void SourceView::contextMenuSlot(const QPoint & pos)
{
QMenu wMenu(this);
mMenuBuilder->build(&wMenu);
wMenu.exec(mapToGlobal(pos));
}
void SourceView::gotoLineSlot()
{
bool ok = false;
int line = QInputDialog::getInt(this, tr("Go to line"), tr("Line (decimal):"), getInitialSelection() + 1, 1, getRowCount() - 1, 1, &ok, Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
if(ok)
{
scrollSelect(line - 1);
reloadData(); //repaint
}
}
void SourceView::openSourceFileSlot()
{
QDesktopServices::openUrl(QUrl::fromLocalFile(mSourcePath));
}
void SourceView::showInDirectorySlot()
{
QStringList args;
args << "/select," << QDir::toNativeSeparators(mSourcePath);
auto process = new QProcess(this);
process->start("explorer.exe", args);
}
void SourceView::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this);
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]()
{
return addrFromIndex(getInitialSelection());
});
mCommonActions->build(mMenuBuilder, CommonActions::ActionDisasm | CommonActions::ActionDump | CommonActions::ActionBreakpoint | CommonActions::ActionLabel | CommonActions::ActionComment
| CommonActions::ActionBookmark | CommonActions::ActionMemoryMap | CommonActions::ActionNewOrigin | CommonActions::ActionNewThread);
mMenuBuilder->addSeparator();
mMenuBuilder->addAction(makeShortcutAction(DIcon("geolocation-goto"), tr("Go to line"), SLOT(gotoLineSlot()), "ActionGotoExpression"));
mMenuBuilder->addAction(makeAction(DIcon("source"), tr("Open source file"), SLOT(openSourceFileSlot())));
mMenuBuilder->addAction(makeAction(DIcon("source_show_in_folder"), tr("Show source file in directory"), SLOT(showInDirectorySlot())));
mMenuBuilder->addSeparator();
MenuBuilder* copyMenu = new MenuBuilder(this);
setupCopyColumnMenu(copyMenu);
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
mMenuBuilder->loadFromConfig();
}
void SourceView::parseLine(size_t index, LineData & line)
{
QString lineText = QString::fromStdString((*mFileLines)[index]);
line.addr = addrFromIndex(index);
line.index = index;
line.code.code.clear();
for(int i = 0; i < lineText.length(); i++)
{
QChar ch = lineText[i];
if(ch == '\t')
{
int col = line.code.code.length();
int spaces = mTabSize - col % mTabSize;
line.code.code.append(QString(spaces, ' '));
}
else
{
line.code.code.append(ch);
}
}
//TODO: add syntax highlighting?
}
duint SourceView::addrFromIndex(size_t index)
{
return DbgFunctions()->GetAddrFromLineEx(mModBase, mSourcePath.toUtf8().constData(), int(index + 1));
}
void SourceView::loadFile()
{
if(!mSourcePath.length())
return;
if(mFileLines)
{
delete mFileLines;
mFileLines = nullptr;
}
mFileLines = new FileLines();
mFileLines->open(mSourcePath.toStdWString().c_str());
if(!mFileLines->isopen())
{
SimpleWarningBox(this, tr("Error"), tr("Failed to open file!"));
delete mFileLines;
mFileLines = nullptr;
return;
}
if(!mFileLines->parse())
{
SimpleWarningBox(this, tr("Error"), tr("Failed to parse file!"));
delete mFileLines;
mFileLines = nullptr;
return;
}
setRowCount(mFileLines->size());
setTableOffset(0);
reloadData();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SourceView.h | #pragma once
#include <QWidget>
#include <AbstractStdTable.h>
class FileLines;
class CommonActions;
class SourceView : public AbstractStdTable
{
Q_OBJECT
public:
SourceView(QString path, duint addr, QWidget* parent = nullptr);
~SourceView();
QString getCellContent(int r, int c) override;
bool isValidIndex(int r, int c) override;
void sortRows(int column, bool ascending) override;
void prepareData() override;
QString getSourcePath();
void setSelection(duint addr);
void clear();
private slots:
void contextMenuSlot(const QPoint & pos);
void gotoLineSlot();
void openSourceFileSlot();
void showInDirectorySlot();
private:
MenuBuilder* mMenuBuilder = nullptr;
CommonActions* mCommonActions = nullptr;
QString mSourcePath;
duint mModBase;
int mTabSize = 4; //TODO: make customizable?
FileLines* mFileLines = nullptr;
enum
{
ColAddr,
ColLine,
ColCode,
};
struct CodeData
{
QString code;
};
struct LineData
{
duint addr;
size_t index;
CodeData code;
};
dsint mPrepareTableOffset = 0;
std::vector<LineData> mLines;
void setupContextMenu();
void loadFile();
void parseLine(size_t index, LineData & line);
duint addrFromIndex(size_t index);
}; |
C++ | x64dbg-development/src/gui/Src/Gui/SourceViewerManager.cpp | #include "SourceViewerManager.h"
#include "Bridge.h"
#include <QFileInfo>
#include <QDir>
#include <QTimer>
SourceViewerManager::SourceViewerManager(QWidget* parent) : QTabWidget(parent)
{
setMovable(true);
setTabsClosable(true);
//Close All Tabs
mCloseAllTabs = new QPushButton(this);
mCloseAllTabs->setIcon(DIcon("close-all-tabs"));
mCloseAllTabs->setToolTip(tr("Close All Tabs"));
connect(mCloseAllTabs, SIGNAL(clicked()), this, SLOT(closeAllTabs()));
setCornerWidget(mCloseAllTabs, Qt::TopLeftCorner);
connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
connect(Bridge::getBridge(), SIGNAL(loadSourceFile(QString, duint)), this, SLOT(loadSourceFile(QString, duint)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChanged(DBGSTATE)));
}
void SourceViewerManager::loadSourceFile(QString path, duint addr)
{
for(int i = 0; i < count(); i++)
{
SourceView* curView = (SourceView*)this->widget(i);
if(curView->getSourcePath().compare(path, Qt::CaseInsensitive) == 0) //file already loaded
{
curView->setSelection(addr);
setCurrentIndex(i); //show that loaded tab
QTimer::singleShot(50, [curView]()
{
curView->setFocus();
});
return;
}
}
//check if file actually exists
if(!QFileInfo(path).exists())
{
return; //error?
}
//load the new file
QString title = path;
int idx = path.lastIndexOf(QDir::separator());
if(idx != -1)
title = path.mid(idx + 1);
SourceView* newView = new SourceView(path, addr, this);
connect(newView, SIGNAL(showCpu()), this, SIGNAL(showCpu()));
addTab(newView, title);
setCurrentIndex(count() - 1);
// https://forum.qt.io/post/132664
// For some reason the viewport() in the AbstractTableView does not have the right size which means setSelection completely fails
QTimer::singleShot(50, [newView, addr]()
{
newView->setSelection(addr);
newView->setFocus();
});
}
void SourceViewerManager::closeTab(int index)
{
auto sourceView = qobject_cast<SourceView*>(widget(index));
removeTab(index);
if(sourceView)
sourceView->clear();
}
void SourceViewerManager::closeAllTabs()
{
while(count())
{
auto sourceView = qobject_cast<SourceView*>(widget(0));
removeTab(0);
if(sourceView)
sourceView->clear();
}
}
void SourceViewerManager::dbgStateChanged(DBGSTATE state)
{
if(state == stopped)
closeAllTabs();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SourceViewerManager.h | #pragma once
#include <QTabWidget>
#include <QPushButton>
#include <QMap>
#include "SourceView.h"
class SourceViewerManager : public QTabWidget
{
Q_OBJECT
public:
explicit SourceViewerManager(QWidget* parent = 0);
public slots:
void loadSourceFile(QString path, duint addr);
void closeTab(int index);
void closeAllTabs();
void dbgStateChanged(DBGSTATE state);
private:
QPushButton* mCloseAllTabs;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/StructWidget.cpp | #include "StructWidget.h"
#include "ui_StructWidget.h"
#include "Configuration.h"
#include "MenuBuilder.h"
#include "LineEditDialog.h"
#include "GotoDialog.h"
#include <QFileDialog>
#include "StringUtil.h"
#include "MiscUtil.h"
#include "RichTextItemDelegate.h"
struct TypeDescriptor
{
TYPEDESCRIPTOR type;
QString name;
};
Q_DECLARE_METATYPE(TypeDescriptor)
StructWidget::StructWidget(QWidget* parent) :
QWidget(parent),
ui(new Ui::StructWidget)
{
ui->setupUi(this);
ui->treeWidget->setStyleSheet("QTreeWidget { background-color: #FFF8F0; alternate-background-color: #DCD9CF; }");
ui->treeWidget->setItemDelegate(new RichTextItemDelegate(&mTextColor, ui->treeWidget));
connect(Bridge::getBridge(), SIGNAL(typeAddNode(void*, const TYPEDESCRIPTOR*)), this, SLOT(typeAddNode(void*, const TYPEDESCRIPTOR*)));
connect(Bridge::getBridge(), SIGNAL(typeClear()), this, SLOT(typeClear()));
connect(Bridge::getBridge(), SIGNAL(typeUpdateWidget()), this, SLOT(typeUpdateWidget()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChangedSlot(DBGSTATE)));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(colorsUpdatedSlot()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(fontsUpdatedSlot()));
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(shortcutsUpdatedSlot()));
colorsUpdatedSlot();
fontsUpdatedSlot();
setupContextMenu();
setupColumns();
}
StructWidget::~StructWidget()
{
delete ui;
}
void StructWidget::saveWindowSettings()
{
auto saveColumn = [this](int column)
{
auto settingName = QString("StructWidgetColumn%1").arg(column);
BridgeSettingSetUint("Gui", settingName.toUtf8().constData(), ui->treeWidget->columnWidth(column));
};
saveColumn(0);
saveColumn(1);
saveColumn(2);
saveColumn(3);
}
void StructWidget::loadWindowSettings()
{
auto loadColumn = [this](int column)
{
auto settingName = QString("StructWidgetColumn%1").arg(column);
duint width = 0;
if(BridgeSettingGetUint("Gui", settingName.toUtf8().constData(), &width))
ui->treeWidget->setColumnWidth(column, width);
};
loadColumn(0);
loadColumn(1);
loadColumn(2);
loadColumn(3);
}
void StructWidget::colorsUpdatedSlot()
{
mTextColor = ConfigColor("StructTextColor");
auto background = ConfigColor("StructBackgroundColor");
auto altBackground = ConfigColor("StructAlternateBackgroundColor");
auto style = QString("QTreeWidget { background-color: %1; alternate-background-color: %2; }").arg(background.name(), altBackground.name());
ui->treeWidget->setStyleSheet(style);
}
void StructWidget::fontsUpdatedSlot()
{
auto font = ConfigFont("AbstractTableView");
setFont(font);
ui->treeWidget->setFont(font);
ui->treeWidget->header()->setFont(font);
}
void StructWidget::shortcutsUpdatedSlot()
{
updateShortcuts();
}
void StructWidget::typeAddNode(void* parent, const TYPEDESCRIPTOR* type)
{
// Disable updates until the next typeUpdateWidget()
ui->treeWidget->setUpdatesEnabled(false);
TypeDescriptor dtype;
dtype.type = *type;
dtype.name = highlightTypeName(dtype.type.name);
dtype.type.name = nullptr;
auto text = QStringList() << dtype.name << ToPtrString(dtype.type.addr + dtype.type.offset) << "0x" + ToHexString(dtype.type.size);
QTreeWidgetItem* item = parent ? new QTreeWidgetItem((QTreeWidgetItem*)parent, text) : new QTreeWidgetItem(ui->treeWidget, text);
item->setExpanded(dtype.type.expanded);
QVariant var;
var.setValue(dtype);
item->setData(0, Qt::UserRole, var);
Bridge::getBridge()->setResult(BridgeResult::TypeAddNode, dsint(item));
}
void StructWidget::typeClear()
{
ui->treeWidget->clear();
Bridge::getBridge()->setResult(BridgeResult::TypeClear);
}
void StructWidget::typeUpdateWidget()
{
ui->treeWidget->setUpdatesEnabled(false);
for(QTreeWidgetItemIterator it(ui->treeWidget); *it; ++it)
{
QTreeWidgetItem* item = *it;
auto type = item->data(0, Qt::UserRole).value<TypeDescriptor>();
auto name = type.name.toUtf8();
type.type.name = name.constData();
auto addr = type.type.addr + type.type.offset;
item->setText(1, ToPtrString(addr));
QString valueStr;
if(type.type.callback) //use the provided callback
{
char value[128] = "";
size_t valueCount = _countof(value);
if(!type.type.callback(&type.type, value, &valueCount) && valueCount && valueCount != _countof(value))
{
auto dest = new char[valueCount];
if(type.type.callback(&type.type, dest, &valueCount))
valueStr = value;
else
valueStr = "???";
delete[] dest;
}
else
valueStr = value;
}
else if(!item->childCount() && type.type.size > 0 && type.type.size <= sizeof(uint64_t)) //attempt to display small, non-parent values
{
uint64_t data;
if(DbgMemRead(addr, &data, type.type.size))
{
if(type.type.reverse)
std::reverse((char*)data, (char*)data + type.type.size);
valueStr = QString().sprintf("0x%llX, %llu", data, data, data);
}
else if(type.type.addr)
valueStr = "???";
}
item->setText(3, valueStr);
}
ui->treeWidget->setUpdatesEnabled(true);
}
void StructWidget::dbgStateChangedSlot(DBGSTATE state)
{
if(state == stopped)
ui->treeWidget->clear();
}
void StructWidget::setupColumns()
{
auto charWidth = ui->treeWidget->fontMetrics().width(' ');
ui->treeWidget->setColumnWidth(0, 4 + charWidth * 60); //Name
ui->treeWidget->setColumnWidth(1, 6 + charWidth * sizeof(duint) * 2); //Address
ui->treeWidget->setColumnWidth(2, 4 + charWidth * 6); //Size
}
#define hasSelection !!ui->treeWidget->selectedItems().count()
#define selectedItem ui->treeWidget->selectedItems()[0]
#define selectedType selectedItem->data(0, Qt::UserRole).value<TypeDescriptor>().type
void StructWidget::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this);
mMenuBuilder->addAction(makeAction(DIcon("dump"), tr("Follow value in Dump"), SLOT(followValueDumpSlot())), [this](QMenu*)
{
return DbgMemIsValidReadPtr(selectedValue());
});
mMenuBuilder->addAction(makeAction(DIcon("processor-cpu"), tr("Follow value in Disassembler"), SLOT(followValueDisasmSlot())), [this](QMenu*)
{
return DbgMemIsValidReadPtr(selectedValue());
});
mMenuBuilder->addAction(makeAction(DIcon("dump"), tr("&Follow address in Dump"), SLOT(followDumpSlot())), [this](QMenu*)
{
return hasSelection && DbgMemIsValidReadPtr(selectedType.addr + selectedType.offset);
});
mMenuBuilder->addAction(makeAction(DIcon("structaddr"), tr("Change address"), SLOT(changeAddrSlot())), [this](QMenu*)
{
return hasSelection && !selectedItem->parent() && DbgIsDebugging();
});
mMenuBuilder->addAction(makeAction(DIcon("visitstruct"), tr("Visit type"), SLOT(visitSlot())));
mMenuBuilder->addAction(makeAction(DIcon("database-import"), tr("Load JSON"), SLOT(loadJsonSlot())));
mMenuBuilder->addAction(makeAction(DIcon("source"), tr("Parse header"), SLOT(parseFileSlot())));
mMenuBuilder->addAction(makeAction(DIcon("removestruct"), tr("Remove"), SLOT(removeSlot())), [this](QMenu*)
{
return hasSelection && !selectedItem->parent();
});
mMenuBuilder->addAction(makeAction(DIcon("eraser"), tr("Clear"), SLOT(clearSlot())));
mMenuBuilder->addAction(makeShortcutAction(DIcon("sync"), tr("&Refresh"), SLOT(refreshSlot()), "ActionRefresh"));
mMenuBuilder->loadFromConfig();
}
QString StructWidget::highlightTypeName(QString name) const
{
// TODO: this can be improved with colors
static auto re = []
{
const char* keywords[] =
{
"uint64_t",
"uint32_t",
"uint16_t",
"char16_t",
"unsigned",
"int64_t",
"int32_t",
"wchar_t",
"int16_t",
"uint8_t",
"struct",
"double",
"size_t",
"uint64",
"uint32",
"ushort",
"uint16",
"signed",
"int8_t",
"union",
"const",
"float",
"duint",
"dsint",
"int64",
"int32",
"short",
"int16",
"ubyte",
"uchar",
"uint8",
"void",
"long",
"bool",
"byte",
"char",
"int8",
"ptr",
"int",
};
QString keywordRegex;
keywordRegex += "\\b(";
for(size_t i = 0; i < _countof(keywords); i++)
{
if(i > 0)
keywordRegex += '|';
keywordRegex += QRegExp::escape(keywords[i]);
}
keywordRegex += ")\\b";
return QRegExp(keywordRegex, Qt::CaseSensitive);
}();
name.replace(re, "<b>\\1</b>");
return std::move(name);
}
duint StructWidget::selectedValue() const
{
if(!hasSelection)
return 0;
QStringList split = selectedItem->text(3).split(',');
if(split.length() < 1)
return 0;
return split[0].toULongLong(nullptr, 0);
}
void StructWidget::on_treeWidget_customContextMenuRequested(const QPoint & pos)
{
QMenu wMenu;
mMenuBuilder->build(&wMenu);
if(wMenu.actions().count())
wMenu.exec(ui->treeWidget->viewport()->mapToGlobal(pos));
}
void StructWidget::followDumpSlot()
{
if(!hasSelection)
return;
DbgCmdExec(QString("dump %1").arg(ToPtrString(selectedType.addr + selectedType.offset)));
}
void StructWidget::followValueDumpSlot()
{
if(!hasSelection)
return;
DbgCmdExec(QString("dump %1").arg(ToPtrString(selectedValue())));
}
void StructWidget::followValueDisasmSlot()
{
if(!hasSelection)
return;
DbgCmdExec(QString("disasm %1").arg(ToPtrString(selectedValue())));
}
void StructWidget::clearSlot()
{
ui->treeWidget->clear();
}
void StructWidget::removeSlot()
{
if(!hasSelection)
return;
delete selectedItem;
}
void StructWidget::visitSlot()
{
//TODO: replace with a list to pick from
LineEditDialog mLineEdit(this);
mLineEdit.setWindowTitle(tr("Type to visit"));
if(mLineEdit.exec() != QDialog::Accepted || !mLineEdit.editText.length())
return;
if(!mGotoDialog)
mGotoDialog = new GotoDialog(this);
duint addr = 0;
mGotoDialog->setWindowTitle(tr("Address to visit"));
if(DbgIsDebugging() && mGotoDialog->exec() == QDialog::Accepted)
addr = DbgValFromString(mGotoDialog->expressionText.toUtf8().constData());
DbgCmdExec(QString("VisitType %1, %2, 2").arg(mLineEdit.editText, ToPtrString(addr)));
}
void StructWidget::loadJsonSlot()
{
auto filename = QFileDialog::getOpenFileName(this, tr("Load JSON"), QString(), tr("JSON files (*.json);;All files (*.*)"));
if(!filename.length())
return;
filename = QDir::toNativeSeparators(filename);
DbgCmdExec(QString("LoadTypes \"%1\"").arg(filename));
}
void StructWidget::parseFileSlot()
{
auto filename = QFileDialog::getOpenFileName(this, tr("Parse header"), QString(), tr("Header files (*.h *.hpp);;All files (*.*)"));
if(!filename.length())
return;
filename = QDir::toNativeSeparators(filename);
DbgCmdExec(QString("ParseTypes \"%1\"").arg(filename));
}
static void changeTypeAddr(QTreeWidgetItem* item, duint addr)
{
auto changeAddr = item->data(0, Qt::UserRole).value<TypeDescriptor>().type.addr;
for(QTreeWidgetItemIterator it(item); *it; ++it)
{
QTreeWidgetItem* item = *it;
auto type = item->data(0, Qt::UserRole).value<TypeDescriptor>();
type.type.addr = type.type.addr == changeAddr ? addr : 0; //invalidate pointers (requires revisit)
QVariant var;
var.setValue(type);
item->setData(0, Qt::UserRole, var);
}
}
void StructWidget::changeAddrSlot()
{
if(!hasSelection || !DbgIsDebugging())
return;
if(!mGotoDialog)
mGotoDialog = new GotoDialog(this);
mGotoDialog->setWindowTitle(tr("Change address"));
if(mGotoDialog->exec() != QDialog::Accepted)
return;
changeTypeAddr(selectedItem, DbgValFromString(mGotoDialog->expressionText.toUtf8().constData()));
refreshSlot();
}
void StructWidget::refreshSlot()
{
typeUpdateWidget();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/StructWidget.h | #pragma once
#include <QWidget>
#include "Bridge.h"
#include "ActionHelpers.h"
class MenuBuilder;
class GotoDialog;
namespace Ui
{
class StructWidget;
}
class StructWidget : public QWidget, public ActionHelper<StructWidget>
{
Q_OBJECT
public:
explicit StructWidget(QWidget* parent = 0);
~StructWidget();
void saveWindowSettings();
void loadWindowSettings();
public slots:
void colorsUpdatedSlot();
void fontsUpdatedSlot();
void shortcutsUpdatedSlot();
void typeAddNode(void* parent, const TYPEDESCRIPTOR* type);
void typeClear();
void typeUpdateWidget();
void dbgStateChangedSlot(DBGSTATE state);
private:
Ui::StructWidget* ui;
MenuBuilder* mMenuBuilder;
GotoDialog* mGotoDialog = nullptr;
QColor mTextColor;
void setupColumns();
void setupContextMenu();
QString highlightTypeName(QString name) const;
duint selectedValue() const;
private slots:
void on_treeWidget_customContextMenuRequested(const QPoint & pos);
void followDumpSlot();
void followValueDumpSlot();
void followValueDisasmSlot();
void clearSlot();
void removeSlot();
void visitSlot();
void loadJsonSlot();
void parseFileSlot();
void changeAddrSlot();
void refreshSlot();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/StructWidget.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>StructWidget</class>
<widget class="QWidget" name="StructWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>826</width>
<height>300</height>
</rect>
</property>
<property name="contextMenuPolicy">
<enum>Qt::DefaultContextMenu</enum>
</property>
<property name="windowTitle">
<string>Struct</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<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>0</number>
</property>
<item>
<widget class="QTreeWidget" name="treeWidget">
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="indentation">
<number>15</number>
</property>
<attribute name="headerCascadingSectionResizes">
<bool>false</bool>
</attribute>
<column>
<property name="text">
<string>Name</string>
</property>
</column>
<column>
<property name="text">
<string>Address</string>
</property>
</column>
<column>
<property name="text">
<string>Size</string>
</property>
</column>
<column>
<property name="text">
<string>Value</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/SymbolView.cpp | #include "SymbolView.h"
#include "ui_SymbolView.h"
#include <QMessageBox>
#include "Configuration.h"
#include "Bridge.h"
#include "BrowseDialog.h"
#include "StdIconSearchListView.h"
#include "ZehSymbolTable.h"
#include <QVBoxLayout>
#include <QProcess>
#include <QFileDialog>
#include <QStringList>
enum
{
ColBase = 0,
ColModule,
ColParty,
ColPath,
ColStatus,
};
class ModuleStdTable final : public StdIconTable
{
public:
ModuleStdTable()
{
Initialize();
setIconColumn(ColParty);
}
void updateColors() override
{
StdIconTable::updateColors();
mSymbolUnloadedTextColor = ConfigColor("SymbolUnloadedTextColor");
mSymbolLoadingTextColor = ConfigColor("SymbolLoadingTextColor");
mSymbolLoadedTextColor = ConfigColor("SymbolLoadedTextColor");
mSymbolUserTextColor = ConfigColor("SymbolUserTextColor");
mSymbolSystemTextColor = ConfigColor("SymbolSystemTextColor");
}
QColor getCellColor(int r, int c) override
{
if(c == ColParty || c == ColPath)
{
if(DbgFunctions()->ModGetParty(getCellUserdata(r, ColBase)) != mod_system)
return mSymbolUserTextColor;
else
return mSymbolSystemTextColor;
}
if(c != ColModule && c != ColStatus)
return mTextColor;
switch(getStatus(r))
{
default:
case MODSYMUNLOADED:
return mSymbolUnloadedTextColor;
case MODSYMLOADING:
return mSymbolLoadingTextColor;
case MODSYMLOADED:
return mSymbolLoadedTextColor;
}
}
QString getCellContent(int r, int c) override
{
if(c != ColStatus)
return StdTable::getCellContent(r, c);
switch(getStatus(r))
{
default:
case MODSYMUNLOADED:
return tr("Unloaded");
case MODSYMLOADING:
return tr("Loading");
case MODSYMLOADED:
return tr("Loaded");
}
}
private:
MODULESYMBOLSTATUS getStatus(int r)
{
return DbgFunctions()->ModSymbolStatus(getCellUserdata(r, 0));
}
QColor mSymbolSystemTextColor;
QColor mSymbolUserTextColor;
QColor mSymbolUnloadedTextColor;
QColor mSymbolLoadingTextColor;
QColor mSymbolLoadedTextColor;
};
class SymbolSearchList : public AbstractSearchList
{
public:
friend class SymbolView;
SymbolSearchList()
{
mList = new ZehSymbolTable();
mList->setAddressColumn(0);
mList->setAddressLabel(false);
mSearchList = new ZehSymbolTable();
mSearchList->setAddressColumn(0);
mSearchList->setAddressLabel(false);
}
void lock() override
{
mList->mMutex.lock();
mSearchList->mMutex.lock();
}
void unlock() override
{
mSearchList->mMutex.unlock();
mList->mMutex.unlock();
}
AbstractStdTable* list() const override
{
return mList;
}
AbstractStdTable* searchList() const override
{
return mSearchList;
}
void filter(const QString & filter, FilterType type, int startColumn) override
{
mSearchList->setRowCount(0);
int newRowCount = 0;
mSearchList->mData.clear();
mSearchList->mData.reserve(mList->mData.size());
mSearchList->mModules = mList->mModules;
int rows = mList->getRowCount();
for(int i = 0; i < rows; i++)
{
if(rowMatchesFilter(filter, type, i, startColumn))
{
newRowCount++;
mSearchList->mData.push_back(mList->mData.at(i));
}
}
mSearchList->setRowCount(newRowCount);
}
void addAction(QAction* action)
{
mList->addAction(action);
mSearchList->addAction(action);
}
private:
ZehSymbolTable* mList;
ZehSymbolTable* mSearchList;
};
SymbolView::SymbolView(QWidget* parent) : QWidget(parent), ui(new Ui::SymbolView)
{
ui->setupUi(this);
setAutoFillBackground(false);
// Set main layout
mMainLayout = new QVBoxLayout;
mMainLayout->setContentsMargins(0, 0, 0, 0);
mMainLayout->addWidget(ui->mainSplitter);
setLayout(mMainLayout);
// Create reference view
mSymbolSearchList = new SymbolSearchList();
mSymbolList = new SearchListView(this, mSymbolSearchList, true, true);
mSymbolList->mSearchStartCol = 1;
// Create module list
mModuleList = new StdIconSearchListView(this, true, false, new StdTableSearchList(new ModuleStdTable(), new ModuleStdTable()));
mModuleList->setSearchStartCol(ColBase);
mModuleList->enableMultiSelection(true);
mModuleList->setAddressColumn(ColBase, true);
mModuleList->setDisassemblyPopupEnabled(false);
int charwidth = mModuleList->getCharWidth();
mModuleList->addColumnAt(8 + charwidth * 2 * sizeof(dsint), tr("Base"), true);
mModuleList->addColumnAt(300, tr("Module"), true);
mModuleList->addColumnAt(charwidth * 9, tr("Party"), true); // with icon
mModuleList->addColumnAt(8 + charwidth * 60, tr("Path"), true);
mModuleList->addColumnAt(8 + charwidth * 8, tr("Status"), true);
mModuleList->loadColumnFromConfig("Module");
// Setup list splitter
ui->listSplitter->addWidget(mModuleList);
ui->listSplitter->addWidget(mSymbolList);
#ifdef _WIN64
// mModuleList : mSymbolList = 40 : 100
ui->listSplitter->setStretchFactor(0, 40);
ui->listSplitter->setStretchFactor(1, 100);
#else
// mModuleList : mSymbolList = 30 : 100
ui->listSplitter->setStretchFactor(0, 30);
ui->listSplitter->setStretchFactor(1, 100);
#endif //_WIN64
// Setup log edit
ui->symbolLogEdit->setFont(ConfigFont("Log"));
ui->symbolLogEdit->setStyleSheet("QTextEdit { background-color: rgb(255, 251, 240) }");
ui->symbolLogEdit->setUndoRedoEnabled(false);
ui->symbolLogEdit->setReadOnly(true);
// Log : List = 2 : 9
ui->mainSplitter->setStretchFactor(1, 9);
ui->mainSplitter->setStretchFactor(0, 2);
//setup context menu
setupContextMenu();
//Signals and slots
connect(Bridge::getBridge(), SIGNAL(repaintTableView()), this, SLOT(updateStyle()));
connect(Bridge::getBridge(), SIGNAL(addMsgToSymbolLog(QString)), this, SLOT(addMsgToSymbolLogSlot(QString)));
connect(Bridge::getBridge(), SIGNAL(clearLog()), this, SLOT(clearSymbolLogSlot()));
connect(Bridge::getBridge(), SIGNAL(clearSymbolLog()), this, SLOT(clearSymbolLogSlot()));
connect(Bridge::getBridge(), SIGNAL(selectionSymmodGet(SELECTIONDATA*)), this, SLOT(selectionGetSlot(SELECTIONDATA*)));
connect(mModuleList->stdList(), SIGNAL(selectionChangedSignal(int)), this, SLOT(moduleSelectionChanged(int)));
connect(mModuleList->stdSearchList(), SIGNAL(selectionChangedSignal(int)), this, SLOT(moduleSelectionChanged(int)));
connect(mModuleList, SIGNAL(emptySearchResult()), this, SLOT(emptySearchResultSlot()));
connect(mModuleList, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(moduleContextMenu(QMenu*)));
connect(mModuleList, SIGNAL(enterPressedSignal()), this, SLOT(moduleFollow()));
connect(Bridge::getBridge(), SIGNAL(updateSymbolList(int, SYMBOLMODULEINFO*)), this, SLOT(updateSymbolList(int, SYMBOLMODULEINFO*)));
connect(Bridge::getBridge(), SIGNAL(setSymbolProgress(int)), ui->symbolProgress, SLOT(setValue(int)));
connect(Bridge::getBridge(), SIGNAL(symbolRefreshCurrent()), this, SLOT(symbolRefreshCurrent()));
connect(Bridge::getBridge(), SIGNAL(symbolSelectModule(duint)), this, SLOT(symbolSelectModule(duint)));
connect(mSymbolList, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(symbolContextMenu(QMenu*)));
connect(mSymbolList, SIGNAL(enterPressedSignal()), this, SLOT(enterPressedSlot()));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateStyle()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(updateStyle()));
}
SymbolView::~SymbolView()
{
delete ui;
delete mSymbolSearchList;
}
inline void saveSymbolsSplitter(QSplitter* splitter, QString name)
{
BridgeSettingSet("SymbolsSettings", (name + "Geometry").toUtf8().constData(), splitter->saveGeometry().toBase64().data());
BridgeSettingSet("SymbolsSettings", (name + "State").toUtf8().constData(), splitter->saveState().toBase64().data());
}
inline void loadSymbolsSplitter(QSplitter* splitter, QString name)
{
char setting[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("SymbolsSettings", (name + "Geometry").toUtf8().constData(), setting))
splitter->restoreGeometry(QByteArray::fromBase64(QByteArray(setting)));
if(BridgeSettingGet("SymbolsSettings", (name + "State").toUtf8().constData(), setting))
splitter->restoreState(QByteArray::fromBase64(QByteArray(setting)));
splitter->splitterMoved(1, 0);
}
void SymbolView::saveWindowSettings()
{
saveSymbolsSplitter(ui->listSplitter, "mVSymbolsSplitter");
saveSymbolsSplitter(ui->mainSplitter, "mHSymbolsLogSplitter");
}
void SymbolView::loadWindowSettings()
{
loadSymbolsSplitter(ui->listSplitter, "mVSymbolsSplitter");
loadSymbolsSplitter(ui->mainSplitter, "mHSymbolsLogSplitter");
}
void SymbolView::invalidateSymbolSource(duint base)
{
mSymbolSearchList->lock();
for(auto mod : mSymbolSearchList->mList->mModules)
{
if(mod == base)
{
mSymbolSearchList->mList->mData.clear();
mSymbolSearchList->mList->mData.shrink_to_fit();
mSymbolSearchList->mList->setRowCount(0);
mSymbolSearchList->mSearchList->mData.clear();
mSymbolSearchList->mSearchList->mData.shrink_to_fit();
mSymbolSearchList->mSearchList->setRowCount(0);
mSymbolSearchList->mSearchList->setHighlightText(QString());
GuiSymbolLogAdd(QString("[SymbolView] reload symbols for base %1\n").arg(ToPtrString(base)).toUtf8().constData());
// TODO: properly reload symbol list
break;
}
}
mSymbolSearchList->unlock();
}
void SymbolView::setupContextMenu()
{
QIcon disassembler = DIcon(ArchValue("processor32", "processor64"));
//Symbols
mFollowSymbolAction = new QAction(disassembler, tr("&Follow in Disassembler"), this);
connect(mFollowSymbolAction, SIGNAL(triggered()), this, SLOT(symbolFollow()));
mFollowSymbolDumpAction = new QAction(DIcon("dump"), tr("Follow in &Dump"), this);
connect(mFollowSymbolDumpAction, SIGNAL(triggered()), this, SLOT(symbolFollowDump()));
mFollowSymbolImportAction = new QAction(DIcon("import"), tr("Follow &imported address"), this);
connect(mFollowSymbolImportAction, SIGNAL(triggered(bool)), this, SLOT(symbolFollowImport()));
mToggleBreakpoint = new QAction(DIcon("breakpoint"), tr("Toggle Breakpoint"), this);
mToggleBreakpoint->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mToggleBreakpoint);
mSymbolSearchList->addAction(mToggleBreakpoint);
connect(mToggleBreakpoint, SIGNAL(triggered()), this, SLOT(toggleBreakpoint()));
mToggleBookmark = new QAction(DIcon("bookmark_toggle"), tr("Toggle Bookmark"), this);
mToggleBookmark->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mToggleBookmark);
mSymbolSearchList->addAction(mToggleBookmark);
connect(mToggleBookmark, SIGNAL(triggered()), this, SLOT(toggleBookmark()));
//Modules
mFollowModuleAction = new QAction(disassembler, tr("&Follow in Disassembler"), this);
mFollowModuleAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
mFollowModuleAction->setShortcut(QKeySequence("enter"));
connect(mFollowModuleAction, SIGNAL(triggered()), this, SLOT(moduleFollow()));
mFollowModuleEntryAction = new QAction(disassembler, tr("Follow &Entry Point in Disassembler"), this);
connect(mFollowModuleEntryAction, SIGNAL(triggered()), this, SLOT(moduleEntryFollow()));
mFollowInMemMap = new QAction(DIcon("memmap_find_address_page"), tr("Follow in Memory Map"), this);
mFollowInMemMap->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mFollowInMemMap);
mModuleList->addAction(mFollowInMemMap);
connect(mFollowInMemMap, SIGNAL(triggered()), this, SLOT(moduleFollowMemMap()));
mDownloadSymbolsAction = new QAction(DIcon("pdb"), tr("&Download Symbols for This Module"), this);
mDownloadSymbolsAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mDownloadSymbolsAction);
mModuleList->addAction(mDownloadSymbolsAction);
connect(mDownloadSymbolsAction, SIGNAL(triggered()), this, SLOT(moduleDownloadSymbols()));
mDownloadAllSymbolsAction = new QAction(DIcon("pdb"), tr("Download Symbols for &All Modules"), this);
mDownloadAllSymbolsAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mDownloadAllSymbolsAction);
mModuleList->addAction(mDownloadAllSymbolsAction);
connect(mDownloadAllSymbolsAction, SIGNAL(triggered()), this, SLOT(moduleDownloadAllSymbols()));
mCopyPathAction = new QAction(DIcon("copyfilepath"), tr("Copy File &Path"), this);
mCopyPathAction->setShortcutContext(Qt::WidgetShortcut);
this->addAction(mCopyPathAction);
mModuleList->addAction(mCopyPathAction);
connect(mCopyPathAction, SIGNAL(triggered()), this, SLOT(moduleCopyPath()));
mBrowseInExplorer = new QAction(DIcon("browseinexplorer"), tr("Browse in Explorer"), this);
mBrowseInExplorer->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mBrowseInExplorer);
mModuleList->addAction(mBrowseInExplorer);
connect(mBrowseInExplorer, SIGNAL(triggered()), this, SLOT(moduleBrowse()));
mLoadLib = new QAction(DIcon("lib_load"), tr("Load library..."), this);
mLoadLib->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mLoadLib);
mModuleList->addAction(mLoadLib);
connect(mLoadLib, SIGNAL(triggered()), this, SLOT(moduleLoad()));
mFreeLib = new QAction(DIcon("lib_free"), tr("Free library"), this);
mFreeLib->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mFreeLib);
mModuleList->addAction(mFreeLib);
connect(mFreeLib, SIGNAL(triggered()), this, SLOT(moduleFree()));
mModSetUserAction = new QAction(DIcon("markasuser"), tr("Mark as &user module"), this);
mModSetUserAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mModSetUserAction);
mModuleList->addAction(mModSetUserAction);
connect(mModSetUserAction, SIGNAL(triggered()), this, SLOT(moduleSetUser()));
mModSetSystemAction = new QAction(DIcon("markassystem"), tr("Mark as &system module"), this);
mModSetSystemAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mModSetSystemAction);
mModuleList->addAction(mModSetSystemAction);
connect(mModSetSystemAction, SIGNAL(triggered()), this, SLOT(moduleSetSystem()));
mModSetPartyAction = new QAction(DIcon("markasparty"), tr("Mark as &party..."), this);
mModSetPartyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
this->addAction(mModSetPartyAction);
mModuleList->addAction(mModSetPartyAction);
connect(mModSetPartyAction, SIGNAL(triggered()), this, SLOT(moduleSetParty()));
mPluginMenu = new QMenu(this);
Bridge::getBridge()->emitMenuAddToList(this, mPluginMenu, GUI_SYMMOD_MENU);
//Shortcuts
refreshShortcutsSlot();
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcutsSlot()));
}
void SymbolView::refreshShortcutsSlot()
{
mToggleBreakpoint->setShortcut(ConfigShortcut("ActionToggleBreakpoint"));
mToggleBookmark->setShortcut(ConfigShortcut("ActionToggleBookmark"));
mModSetUserAction->setShortcut(ConfigShortcut("ActionMarkAsUser"));
mModSetSystemAction->setShortcut(ConfigShortcut("ActionMarkAsSystem"));
mModSetPartyAction->setShortcut(ConfigShortcut("ActionMarkAsParty"));
mBrowseInExplorer->setShortcut(ConfigShortcut("ActionBrowseInExplorer"));
mDownloadSymbolsAction->setShortcut(ConfigShortcut("ActionDownloadSymbol"));
mDownloadAllSymbolsAction->setShortcut(ConfigShortcut("ActionDownloadAllSymbol"));
mFollowInMemMap->setShortcut(ConfigShortcut("ActionFollowMemMap"));
}
void SymbolView::updateStyle()
{
mModuleList->stdList()->reloadData();
mModuleList->stdSearchList()->reloadData();
ui->symbolLogEdit->setFont(ConfigFont("Log"));
ui->symbolLogEdit->setStyleSheet(QString("QTextEdit { color: %1; background-color: %2 }").arg(ConfigColor("AbstractTableViewTextColor").name(), ConfigColor("AbstractTableViewBackgroundColor").name()));
}
void SymbolView::addMsgToSymbolLogSlot(QString msg)
{
ui->symbolLogEdit->moveCursor(QTextCursor::End);
ui->symbolLogEdit->insertPlainText(msg);
}
void SymbolView::clearSymbolLogSlot()
{
ui->symbolLogEdit->clear();
}
void SymbolView::moduleSelectionChanged(int index)
{
Q_UNUSED(index);
setUpdatesEnabled(false);
std::vector<duint> selectedModules;
for(auto index : mModuleList->mCurList->getSelection())
{
QString modBase = mModuleList->mCurList->getCellContent(index, ColBase);
duint wVA;
if(DbgFunctions()->ValFromString(modBase.toUtf8().constData(), &wVA))
selectedModules.push_back(wVA);
}
std::vector<SYMBOLPTR> data;
for(auto base : selectedModules)
{
DbgSymbolEnum(base, [](const SYMBOLPTR * info, void* userdata)
{
((std::vector<SYMBOLPTR>*)userdata)->push_back(*info);
return true; // TODO: allow aborting (enumeration in a separate thread)
}, &data);
}
mSymbolSearchList->lock();
mSymbolSearchList->mList->mModules = std::move(selectedModules);
mSymbolSearchList->mList->mData = std::move(data);
mSymbolSearchList->mList->setRowCount(mSymbolSearchList->mList->mData.size());
mSymbolSearchList->unlock();
mSymbolSearchList->mList->setSingleSelection(0);
mSymbolSearchList->mList->setTableOffset(0);
mSymbolSearchList->mList->reloadData();
if(!mSymbolList->isSearchBoxLocked())
mSymbolList->clearFilter();
else
mSymbolList->refreshSearchList();
setUpdatesEnabled(true);
}
void SymbolView::updateSymbolList(int module_count, SYMBOLMODULEINFO* modules)
{
mModuleList->stdList()->setRowCount(module_count);
if(!module_count)
{
// TODO
//mSymbolList->mList->setRowCount(0);
//mSymbolList->mList->setSingleSelection(0);
mModuleList->stdList()->setSingleSelection(0);
}
mModuleBaseList.clear();
for(int i = 0; i < module_count; i++)
{
QString modName(modules[i].name);
duint base = modules[i].base;
mModuleBaseList.insert(modName, base);
int party = DbgFunctions()->ModGetParty(base);
mModuleList->stdList()->setCellContent(i, ColBase, ToPtrString(base));
mModuleList->stdList()->setCellUserdata(i, ColBase, base);
mModuleList->stdList()->setCellContent(i, ColModule, modName);
switch(party)
{
case 0:
mModuleList->stdList()->setCellContent(i, ColParty, tr("User"));
mModuleList->setRowIcon(i, DIcon("markasuser"));
break;
case 1:
mModuleList->stdList()->setCellContent(i, ColParty, tr("System"));
mModuleList->setRowIcon(i, DIcon("markassystem"));
break;
default:
mModuleList->stdList()->setCellContent(i, ColParty, tr("Party: %1").arg(party));
mModuleList->setRowIcon(i, DIcon("markasparty"));
break;
}
char szModPath[MAX_PATH] = "";
if(!DbgFunctions()->ModPathFromAddr(base, szModPath, _countof(szModPath)))
*szModPath = '\0';
mModuleList->stdList()->setCellContent(i, ColPath, szModPath);
}
mModuleList->stdList()->reloadData();
//NOTE: DO NOT CALL mModuleList->refreshSearchList() IT WILL DEGRADE PERFORMANCE!
if(modules)
BridgeFree(modules);
}
void SymbolView::symbolContextMenu(QMenu* wMenu)
{
if(!mSymbolList->mCurList->getRowCount())
return;
wMenu->addAction(mFollowSymbolAction);
wMenu->addAction(mFollowSymbolDumpAction);
if(mSymbolList->mCurList->getCellContent(mSymbolList->mCurList->getInitialSelection(), 1) == tr("Import"))
wMenu->addAction(mFollowSymbolImportAction);
wMenu->addSeparator();
wMenu->addAction(mToggleBreakpoint);
wMenu->addAction(mToggleBookmark);
}
void SymbolView::symbolRefreshCurrent()
{
mModuleList->stdList()->setSingleSelection(mModuleList->stdList()->getInitialSelection());
}
void SymbolView::symbolFollow()
{
DbgCmdExec(QString("disasm " + mSymbolList->mCurList->getCellContent(mSymbolList->mCurList->getInitialSelection(), 0)));
}
void SymbolView::symbolFollowDump()
{
DbgCmdExecDirect(QString("dump " + mSymbolList->mCurList->getCellContent(mSymbolList->mCurList->getInitialSelection(), 0)));
}
void SymbolView::symbolFollowImport()
{
auto addrText = mSymbolList->mCurList->getCellContent(mSymbolList->mCurList->getInitialSelection(), 0);
auto addr = DbgValFromString(QString("[%1]").arg(addrText).toUtf8().constData());
if(!DbgMemIsValidReadPtr(addr))
return;
if(DbgFunctions()->MemIsCodePage(addr, false))
{
DbgCmdExec(QString("disasm %1").arg(ToPtrString(addr)));
}
else
{
DbgCmdExecDirect(QString("dump %1").arg(ToPtrString(addr)));
emit Bridge::getBridge()->getDumpAttention();
}
}
void SymbolView::symbolSelectModule(duint base)
{
for(dsint i = 0; i < mModuleList->stdList()->getRowCount(); i++)
{
if(mModuleList->stdList()->getCellUserdata(i, ColBase) == base)
{
mModuleList->stdList()->setSingleSelection(i);
mModuleList->stdSearchList()->hide(); //This could be described as a hack, but you could also say it's like wiping sandpaper over your new white Tesla.
mModuleList->clearFilter();
break;
}
}
}
void SymbolView::enterPressedSlot()
{
auto addr = DbgValFromString(mSymbolList->mCurList->getCellContent(mSymbolList->mCurList->getInitialSelection(), 0).toUtf8().constData());
if(!DbgMemIsValidReadPtr(addr))
return;
if(mSymbolList->mCurList->getCellContent(mSymbolList->mCurList->getInitialSelection(), 1) == tr("Import"))
symbolFollowImport();
else if(DbgFunctions()->MemIsCodePage(addr, false))
symbolFollow();
else
{
symbolFollowDump();
emit Bridge::getBridge()->getDumpAttention();
}
}
void SymbolView::moduleContextMenu(QMenu* wMenu)
{
if(!DbgIsDebugging() || !mModuleList->mCurList->getRowCount())
return;
wMenu->addAction(mFollowModuleAction);
wMenu->addAction(mFollowModuleEntryAction);
wMenu->addAction(mFollowInMemMap);
wMenu->addAction(mDownloadSymbolsAction);
wMenu->addAction(mDownloadAllSymbolsAction);
duint modbase = DbgValFromString(mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColBase).toUtf8().constData());
char szModPath[MAX_PATH] = "";
if(DbgFunctions()->ModPathFromAddr(modbase, szModPath, _countof(szModPath)))
{
wMenu->addAction(mCopyPathAction);
wMenu->addAction(mBrowseInExplorer);
}
wMenu->addAction(mLoadLib);
wMenu->addAction(mFreeLib);
wMenu->addSeparator();
int party = DbgFunctions()->ModGetParty(modbase);
if(party != 0)
wMenu->addAction(mModSetUserAction);
if(party != 1)
wMenu->addAction(mModSetSystemAction);
wMenu->addAction(mModSetPartyAction);
QMenu wCopyMenu(tr("&Copy"), this);
wCopyMenu.setIcon(DIcon("copy"));
mModuleList->mCurList->setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
{
wMenu->addSeparator();
wMenu->addMenu(&wCopyMenu);
}
wMenu->addSeparator();
DbgMenuPrepare(GUI_SYMMOD_MENU);
wMenu->addActions(mPluginMenu->actions());
}
void SymbolView::moduleFollow()
{
DbgCmdExec(QString("disasm " + mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColBase) + "+1000"));
}
void SymbolView::moduleEntryFollow()
{
//Test case: libstdc++-6.dll
DbgCmdExec(QString("disasm \"" + mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColModule) + "\":entry"));
}
void SymbolView::moduleCopyPath()
{
QString modulePaths;
auto selection = mModuleList->mCurList->getSelection();
for(auto i : selection)
{
duint modbase = DbgValFromString(mModuleList->mCurList->getCellContent(i, ColBase).toUtf8().constData());
char szModPath[MAX_PATH] = "";
if(!DbgFunctions()->ModPathFromAddr(modbase, szModPath, _countof(szModPath)))
memcpy(szModPath, "???", 4);
if(!modulePaths.isEmpty())
modulePaths.append("\r\n");
modulePaths.append(szModPath);
}
Bridge::CopyToClipboard(modulePaths);
}
void SymbolView::moduleBrowse()
{
auto selection = mModuleList->mCurList->getSelection();
for(auto i : selection)
{
duint modbase = DbgValFromString(mModuleList->mCurList->getCellContent(i, ColBase).toUtf8().constData());
char szModPath[MAX_PATH] = "";
if(DbgFunctions()->ModPathFromAddr(modbase, szModPath, _countof(szModPath)))
{
QStringList arguments;
arguments << QString("/select,");
arguments << QString(szModPath);
QProcess::startDetached(QString("%1/explorer.exe").arg(QProcessEnvironment::systemEnvironment().value("windir")), arguments);
}
}
}
void SymbolView::moduleDownloadSymbols()
{
auto selection = mModuleList->mCurList->getSelection();
for(auto i : selection)
DbgCmdExec(QString("symdownload \"%0\"").arg(mModuleList->mCurList->getCellContent(i, ColModule)));
}
void SymbolView::moduleDownloadAllSymbols()
{
DbgCmdExec("symdownload");
}
void SymbolView::moduleLoad()
{
if(!DbgIsDebugging())
return;
BrowseDialog browse(this, tr("Select DLL"), tr("Enter the path of a DLL to load in the debuggee."), tr("DLL Files (*.dll);;All Files (*.*)"), QString(), false);
if(browse.exec() != QDialog::Accepted && browse.path.length())
return;
auto fileName = browse.path;
DbgCmdExec(QString("loadlib \"%1\"").arg(fileName.replace("\\", "\\\\")));
}
void SymbolView::moduleFree()
{
if(!DbgIsDebugging())
return;
QString moduleName = mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColModule);
if(moduleName.length() != 0)
{
QMessageBox::StandardButton reply;
QString question = tr("Are you sure you want to free the module: %1?\n\nThis could introduce unexpected behaviour to your debugging session...").arg(moduleName);
reply = QMessageBox::question(this,
tr("Free Library").toUtf8().constData(),
question.toUtf8().constData(),
QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes)
{
auto selection = mModuleList->mCurList->getSelection();
for(auto module : selection)
DbgCmdExec(QString("freelib %1").arg(mModuleList->mCurList->getCellContent(module, ColBase)));
}
}
}
void SymbolView::toggleBreakpoint()
{
if(!DbgIsDebugging())
return;
if(!mSymbolList->mCurList->getRowCount())
return;
auto selection = mSymbolList->mCurList->getSelection();
for(auto selectedIdx : selection)
{
QString addrText = mSymbolList->mCurList->getCellContent(selectedIdx, 0);
duint wVA;
if(!DbgFunctions()->ValFromString(addrText.toUtf8().constData(), &wVA))
return;
//Import means that the address is an IAT entry so we read the actual function address
if(mSymbolList->mCurList->getCellContent(selectedIdx, 1) == tr("Import"))
DbgMemRead(wVA, &wVA, sizeof(wVA));
if(!DbgMemIsValidReadPtr(wVA))
return;
BPXTYPE wBpType = DbgGetBpxTypeAt(wVA);
QString wCmd;
if((wBpType & bp_normal) == bp_normal)
{
wCmd = "bc " + ToPtrString(wVA);
}
else
{
wCmd = "bp " + ToPtrString(wVA);
}
DbgCmdExec(wCmd);
}
}
void SymbolView::toggleBookmark()
{
if(!DbgIsDebugging())
return;
if(!mSymbolList->mCurList->getRowCount())
return;
auto selection = mSymbolList->mCurList->getSelection();
for(auto index : selection)
{
QString addrText = mSymbolList->mCurList->getCellContent(index, 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)
{
QMessageBox msg(QMessageBox::Critical, tr("Error!"), tr("DbgSetBookmarkAt failed!"));
msg.setWindowIcon(DIcon("compile-error"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.exec();
}
}
GuiUpdateAllViews();
}
void SymbolView::moduleSetSystem()
{
auto selection = mModuleList->mCurList->getSelection();
for(auto i : selection)
{
duint modbase = DbgValFromString(mModuleList->mCurList->getCellContent(i, ColBase).toUtf8().constData());
DbgFunctions()->ModSetParty(modbase, mod_system);
}
DbgFunctions()->RefreshModuleList();
}
void SymbolView::moduleSetUser()
{
auto selection = mModuleList->mCurList->getSelection();
for(auto i : selection)
{
duint modbase = DbgValFromString(mModuleList->mCurList->getCellContent(i, ColBase).toUtf8().constData());
DbgFunctions()->ModSetParty(modbase, mod_user);
}
DbgFunctions()->RefreshModuleList();
}
void SymbolView::moduleSetParty()
{
int party;
duint modbase = DbgValFromString(mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColBase).toUtf8().constData());
party = DbgFunctions()->ModGetParty(modbase);
QString mLineEditeditText;
QIcon bookmark = DIcon("bookmark");
if(SimpleInputBox(this, tr("Mark the party of the module as"), QString::number(party), mLineEditeditText, tr("0 is user module, 1 is system module."), &bookmark))
{
bool ok;
party = mLineEditeditText.toInt(&ok);
if(ok)
{
auto selection = mModuleList->mCurList->getSelection();
for(auto index : selection)
{
modbase = DbgValFromString(mModuleList->mCurList->getCellContent(index, ColBase).toUtf8().constData());
DbgFunctions()->ModSetParty(modbase, (MODULEPARTY)party);
}
}
else
SimpleErrorBox(this, tr("Error"), tr("The party number can only be 0 or 1"));
DbgFunctions()->RefreshModuleList();
}
}
void SymbolView::moduleFollowMemMap()
{
QString base = mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColBase);
DbgCmdExec(("memmapdump " + base));
}
void SymbolView::emptySearchResultSlot()
{
// No result after search
mSymbolList->mCurList->setRowCount(0);
}
void SymbolView::selectionGetSlot(SELECTIONDATA* selection)
{
selection->start = selection->end = duint(mModuleList->mCurList->getCellContent(mModuleList->mCurList->getInitialSelection(), ColBase).toULongLong(nullptr, 16));
Bridge::getBridge()->setResult(BridgeResult::SelectionGet, 1);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SymbolView.h | #pragma once
#include <QWidget>
#include "Bridge.h"
class QMenu;
class StdSearchListView;
class StdIconSearchListView;
class SearchListView;
class SymbolSearchList;
class QVBoxLayout;
namespace Ui
{
class SymbolView;
}
class SymbolView : public QWidget
{
Q_OBJECT
public:
explicit SymbolView(QWidget* parent = 0);
~SymbolView() override;
void setupContextMenu();
void saveWindowSettings();
void loadWindowSettings();
void invalidateSymbolSource(duint base);
private slots:
void updateStyle();
void addMsgToSymbolLogSlot(QString msg);
void clearSymbolLogSlot();
void moduleSelectionChanged(int index);
void updateSymbolList(int module_count, SYMBOLMODULEINFO* modules);
void symbolFollow();
void symbolFollowDump();
void symbolFollowImport();
void symbolSelectModule(duint base);
void enterPressedSlot();
void symbolContextMenu(QMenu* wMenu);
void symbolRefreshCurrent();
void moduleContextMenu(QMenu* wMenu);
void moduleFollow();
void moduleEntryFollow();
void moduleDownloadSymbols();
void moduleDownloadAllSymbols();
void moduleCopyPath();
void moduleBrowse();
void moduleSetUser();
void moduleSetSystem();
void moduleSetParty();
void moduleFollowMemMap();
void toggleBreakpoint();
void toggleBookmark();
void refreshShortcutsSlot();
void emptySearchResultSlot();
void selectionGetSlot(SELECTIONDATA* selection);
void moduleLoad();
void moduleFree();
signals:
void showReferences();
private:
Ui::SymbolView* ui;
QVBoxLayout* mMainLayout;
QVBoxLayout* mSymbolLayout;
QWidget* mSymbolPlaceHolder;
SearchListView* mSymbolList;
StdIconSearchListView* mModuleList;
SymbolSearchList* mSymbolSearchList;
QMap<QString, duint> mModuleBaseList;
QAction* mFollowSymbolAction;
QAction* mFollowSymbolDumpAction;
QAction* mFollowSymbolImportAction;
QAction* mToggleBreakpoint;
QAction* mToggleBookmark;
QAction* mFollowModuleAction;
QAction* mFollowModuleEntryAction;
QAction* mDownloadSymbolsAction;
QAction* mDownloadAllSymbolsAction;
QAction* mCopyPathAction;
QAction* mModSetUserAction;
QAction* mModSetSystemAction;
QAction* mModSetPartyAction;
QAction* mBrowseInExplorer;
QAction* mFollowInMemMap;
QAction* mLoadLib;
QAction* mFreeLib;
QMenu* mPluginMenu;
static void cbSymbolEnum(SYMBOLINFO* symbol, void* user);
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/SymbolView.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SymbolView</class>
<widget class="QWidget" name="SymbolView">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>694</width>
<height>605</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<widget class="QSplitter" name="mainSplitter">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>691</width>
<height>601</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Ignored" vsizetype="Ignored">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QSplitter" name="listSplitter">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="handleWidth">
<number>2</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
</widget>
<widget class="QWidget" name="layoutWidget">
<layout class="QVBoxLayout" name="logLayout">
<property name="spacing">
<number>3</number>
</property>
<item>
<widget class="QTextEdit" name="symbolLogEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Ignored" vsizetype="Ignored">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="symbolProgress">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>15</height>
</size>
</property>
<property name="value">
<number>0</number>
</property>
<property name="textVisible">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</widget>
<resources/>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/SystemBreakpointScriptDialog.cpp | #include "SystemBreakpointScriptDialog.h"
#include "ui_SystemBreakpointScriptDialog.h"
#include "Bridge.h"
#include "Configuration.h"
#include "MiscUtil.h"
#include <QDirModel>
#include <QFile>
#include <QFileDialog>
#include <QDesktopServices>
#include <QCompleter>
#include <QMessageBox>
SystemBreakpointScriptDialog::SystemBreakpointScriptDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::SystemBreakpointScriptDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
auto dirCompleter = [](QLineEdit * lineEdit)
{
QCompleter* completer = new QCompleter(lineEdit);
completer->setModel(new QDirModel(completer));
lineEdit->setCompleter(completer);
};
dirCompleter(ui->lineEditGlobal);
dirCompleter(ui->lineEditDebuggee);
{
char globalChar[MAX_SETTING_SIZE];
if(BridgeSettingGet("Engine", "InitializeScript", globalChar))
ui->lineEditGlobal->setText(globalChar);
}
if(DbgIsDebugging())
{
ui->groupBoxDebuggee->setTitle(tr("2. System breakpoint script for %1").arg(mainModuleName(true)));
ui->lineEditDebuggee->setText(DbgFunctions()->DbgGetDebuggeeInitScript());
}
else
{
ui->groupBoxDebuggee->setEnabled(false);
}
if(ui->lineEditGlobal->text().isEmpty())
ui->openGlobal->setText(tr("Create"));
if(ui->lineEditDebuggee->text().isEmpty())
ui->openDebuggee->setText(tr("Create"));
Config()->loadWindowGeometry(this);
}
SystemBreakpointScriptDialog::~SystemBreakpointScriptDialog()
{
delete ui;
}
void SystemBreakpointScriptDialog::on_pushButtonGlobal_clicked()
{
QString file = QFileDialog::getOpenFileName(this, ui->groupBoxGlobal->title(), ui->lineEditGlobal->text(), tr("Script files (*.txt *.scr);;All files (*.*)"));
if(!file.isEmpty())
ui->lineEditGlobal->setText(QDir::toNativeSeparators(file));
if(ui->lineEditGlobal->text().isEmpty())
ui->openGlobal->setText(tr("Create"));
else
ui->openGlobal->setText(tr("Open"));
}
void SystemBreakpointScriptDialog::on_pushButtonDebuggee_clicked()
{
QString file = QFileDialog::getOpenFileName(this, ui->groupBoxDebuggee->title(), ui->lineEditDebuggee->text(), tr("Script files (*.txt *.scr);;All files (*.*)"));
if(!file.isEmpty())
ui->lineEditDebuggee->setText(QDir::toNativeSeparators(file));
if(ui->lineEditDebuggee->text().isEmpty())
ui->openDebuggee->setText(tr("Create"));
else
ui->openDebuggee->setText(tr("Open"));
}
void SystemBreakpointScriptDialog::on_openGlobal_clicked()
{
// First open the script if that is available
if(!ui->lineEditGlobal->text().isEmpty())
QDesktopServices::openUrl(QUrl(QDir::fromNativeSeparators(ui->lineEditGlobal->text())));
else
{
// Ask the user to create a new script
QMessageBox msgyn(QMessageBox::Question, tr("File not found"), tr("Would you like to create a new script?"), QMessageBox::Yes | QMessageBox::No, this);
if(msgyn.exec() == QMessageBox::Yes)
{
// The new script is at app dir
QString defaultFileName("autorun.txt");
defaultFileName = QDir::toNativeSeparators(QString::fromWCharArray(BridgeUserDirectory()) + QDir::separator() + defaultFileName);
// Create it
if(!QFile::exists(defaultFileName))
{
QFile newScript(defaultFileName);
newScript.open(QIODevice::Append | QIODevice::WriteOnly);
newScript.close();
}
ui->lineEditGlobal->setText(defaultFileName);
ui->openGlobal->setText(tr("Open"));
// Open the file
QDesktopServices::openUrl(QUrl(QDir::fromNativeSeparators(ui->lineEditGlobal->text())));
}
}
}
void SystemBreakpointScriptDialog::on_openDebuggee_clicked()
{
// First open the script if that is available
if(!ui->lineEditDebuggee->text().isEmpty())
{
if(!QDesktopServices::openUrl(QUrl("file:///" + QDir::fromNativeSeparators(ui->lineEditDebuggee->text()))))
{
SimpleWarningBox(this, tr("Error!"), tr("File open failed! Please open the file yourself..."));
}
}
else
{
// Ask the user to create a new script
QMessageBox msgyn(QMessageBox::Question, tr("File not found"), tr("Would you like to create a new script?"), QMessageBox::Yes | QMessageBox::No, this);
if(msgyn.exec() == QMessageBox::Yes)
{
// The new script is at db dir
auto defaultFileName = getDbPath(mainModuleName() + ".autorun.txt");
// Create it
if(!QFile::exists(defaultFileName))
{
QFile newScript(defaultFileName);
newScript.open(QIODevice::Append | QIODevice::WriteOnly);
newScript.close();
}
ui->lineEditDebuggee->setText(defaultFileName);
ui->openDebuggee->setText(tr("Open"));
// Open the file
if(!QDesktopServices::openUrl(QUrl("file:///" + QDir::fromNativeSeparators(ui->lineEditDebuggee->text()))))
{
SimpleWarningBox(this, tr("Error!"), tr("File open failed! Please open the file yourself..."));
}
}
}
}
void SystemBreakpointScriptDialog::on_SystemBreakpointScriptDialog_accepted()
{
BridgeSettingSet("Engine", "InitializeScript", ui->lineEditGlobal->text().toUtf8().constData());
if(ui->groupBoxDebuggee->isEnabled())
DbgFunctions()->DbgSetDebuggeeInitScript(ui->lineEditDebuggee->text().toUtf8().constData());
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/SystemBreakpointScriptDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class SystemBreakpointScriptDialog;
}
class SystemBreakpointScriptDialog : public QDialog
{
Q_OBJECT
public:
explicit SystemBreakpointScriptDialog(QWidget* parent = nullptr);
~SystemBreakpointScriptDialog();
private slots:
void on_pushButtonGlobal_clicked();
void on_pushButtonDebuggee_clicked();
void on_openGlobal_clicked();
void on_openDebuggee_clicked();
void on_SystemBreakpointScriptDialog_accepted();
private:
Ui::SystemBreakpointScriptDialog* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/SystemBreakpointScriptDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SystemBreakpointScriptDialog</class>
<widget class="QDialog" name="SystemBreakpointScriptDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>865</width>
<height>169</height>
</rect>
</property>
<property name="windowTitle">
<string>System breakpoint scripts</string>
</property>
<property name="windowIcon">
<iconset theme="initscript" resource="../../resource.qrc">
<normaloff>:/Default/icons/initscript.png</normaloff>:/Default/icons/initscript.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBoxGlobal">
<property name="title">
<string>1. System breakpoint script for every process</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="labelGlobal">
<property name="text">
<string>Path:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditGlobal"/>
</item>
<item>
<widget class="QPushButton" name="pushButtonGlobal">
<property name="text">
<string>Browse</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="openGlobal">
<property name="text">
<string>Open</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBoxDebuggee">
<property name="title">
<string>2. System breakpoint script for a specific process (debug a process to specify)</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="labelDebuggee">
<property name="text">
<string>Path:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditDebuggee"/>
</item>
<item>
<widget class="QPushButton" name="pushButtonDebuggee">
<property name="text">
<string>Browse</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="openDebuggee">
<property name="text">
<string>Open</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>SystemBreakpointScriptDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>227</x>
<y>151</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>168</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>SystemBreakpointScriptDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>295</x>
<y>157</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>168</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/TabBar.cpp | // Qt includes
#include <QApplication>
#include <QMouseEvent>
#include <QImage>
#include <QPainter>
#include <QPixmap>
#include <QPaintDevice>
#include <QDrag>
#include <QMimeData>
#include <QMenu>
#include "tabbar.h"
#include "tabwidget.h"
//////////////////////////////////////////////////////////////
// Default Constructor
//////////////////////////////////////////////////////////////
MHTabBar::MHTabBar(QWidget* parent, bool allowDetach, bool allowDelete) : QTabBar(parent)
{
mAllowDetach = allowDetach;
mAllowDelete = allowDelete;
setAcceptDrops(true);
setElideMode(Qt::ElideNone);
setSelectionBehaviorOnRemove(QTabBar::SelectLeftTab);
setMovable(true);
setDrawBase(false);
}
//////////////////////////////////////////////////////////////
// Default Destructor
//////////////////////////////////////////////////////////////
MHTabBar::~MHTabBar()
{
}
void MHTabBar::contextMenuEvent(QContextMenuEvent* event)
{
if(!mAllowDetach && !mAllowDelete)
return;
QMenu wMenu(this);
QAction wDetach(tr("&Detach"), this);
if(mAllowDetach)
wMenu.addAction(&wDetach);
QAction wDelete(tr("&Close"), this);
if(mAllowDelete)
wMenu.addAction(&wDelete);
QAction* executed = wMenu.exec(event->globalPos());
if(executed == &wDetach)
{
QPoint p(0, 0);
emit OnDetachTab((int)tabAt(event->pos()), p);
}
else if(executed == &wDelete)
{
emit OnDeleteTab((int)tabAt(event->pos()));
}
}
void MHTabBar::mouseDoubleClickEvent(QMouseEvent* event)
{
// On tab double click emit the index of the tab that was double clicked
if(event->button() == Qt::LeftButton)
{
int tabIndex = tabAt(event->pos());
if(tabIndex != -1)
emit OnDoubleClickTabIndex(tabIndex);
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/TabBar.h | #pragma once
// Qt includes
#include <QTabBar>
//////////////////////////////////////////////////////////////////////////////
// Summary:
// MHTabBar implements the a Tab Bar with detach functionality.
//////////////////////////////////////////////////////////////////////////////
class MHTabBar: public QTabBar
{
Q_OBJECT
public:
MHTabBar(QWidget* parent, bool allowDetach, bool allowDelete);
~MHTabBar();
protected:
void contextMenuEvent(QContextMenuEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event);
signals:
// Detach Tab
void OnDetachTab(int index, const QPoint & dropPoint);
// Move Tab
void OnMoveTab(int fromIndex, int toIndex);
// Delete Tab
void OnDeleteTab(int index);
// Double Click on Tab, Get Index
void OnDoubleClickTabIndex(int index);
private:
bool mAllowDetach;
bool mAllowDelete;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/TabWidget.cpp | // Qt includes
#include "tabbar.h"
#include "tabwidget.h"
#include <QMoveEvent>
#include <QApplication>
#include <QDesktopWidget>
//////////////////////////////////////////////////////////////
// Default Constructor
//////////////////////////////////////////////////////////////
MHTabWidget::MHTabWidget(QWidget* parent, bool allowDetach, bool allowDelete) : QTabWidget(parent)
{
mHistoryPopup = new MultiItemsSelectWindow(this, parentWidget(), true);
mTabBar = new MHTabBar(this, allowDetach, allowDelete);
connect(mTabBar, SIGNAL(OnDetachTab(int, const QPoint &)), this, SLOT(DetachTab(int, const QPoint &)));
connect(mTabBar, SIGNAL(OnDeleteTab(int)), this, SLOT(DeleteTab(int)));
connect(mTabBar, SIGNAL(tabMoved(int, int)), this, SLOT(tabMoved(int, int)));
connect(mTabBar, SIGNAL(currentChanged(int)), this, SLOT(currentChanged(int)));
setTabBar(mTabBar);
setMovable(true);
mWindows.clear();
}
//////////////////////////////////////////////////////////////
// Default Destructor
//////////////////////////////////////////////////////////////
MHTabWidget::~MHTabWidget()
{
disconnect(mTabBar, SIGNAL(OnDetachTab(int, const QPoint &)), this, SLOT(DetachTab(int, const QPoint &)));
disconnect(mTabBar, SIGNAL(OnDeleteTab(int)), this, SLOT(DeleteTab(int)));
disconnect(mTabBar, SIGNAL(currentChanged(int)), this, SLOT(currentChanged(int)));
delete mTabBar;
}
QWidget* MHTabWidget::widget(int index) const
{
int baseCount = QTabWidget::count();
// Check if it's just a normal tab
if(index < baseCount)
return QTabWidget::widget(index);
// Otherwise it's going to be a window
return mWindows.at(index - baseCount);
}
int MHTabWidget::count() const
{
return QTabWidget::count() + mWindows.size();
}
QList<QWidget*> MHTabWidget::windows()
{
return mWindows;
}
// Add a tab
int MHTabWidget::addTabEx(QWidget* widget, const QIcon & icon, const QString & label, const QString & nativeName)
{
mNativeNames.append(nativeName);
mHistory.push_back((MIDPKey)widget);
widget->setAccessibleName(label);
return this->addTab(widget, icon, label);
}
// Convert an external window to a widget tab
void MHTabWidget::AttachTab(QWidget* parent)
{
// Retrieve widget
MHDetachedWindow* detachedWidget = reinterpret_cast<MHDetachedWindow*>(parent);
QWidget* tearOffWidget = detachedWidget->centralWidget();
// Reattach the tab
auto newIndex = addTabEx(tearOffWidget, detachedWidget->windowIcon(), detachedWidget->windowTitle(), detachedWidget->mNativeName);
// Remove it from the windows list
for(int i = 0; i < mWindows.size(); i++)
{
if(mWindows.at(i) == tearOffWidget)
{
mWindows.removeAt(i);
}
}
// Cleanup Window
disconnect(detachedWidget, SIGNAL(OnClose(QWidget*)), this, SLOT(AttachTab(QWidget*)));
disconnect(detachedWidget, SIGNAL(OnFocused(QWidget*)), this, SLOT(OnDetachFocused(QWidget*)));
detachedWidget->hide();
detachedWidget->close();
// Move the tab back to the previous index
if(detachedWidget->mPreviousIndex >= 0)
mTabBar->moveTab(newIndex, detachedWidget->mPreviousIndex);
}
// Convert a tab to an external window
void MHTabWidget::DetachTab(int index, const QPoint & dropPoint)
{
Q_UNUSED(dropPoint);
// Create the window
MHDetachedWindow* detachedWidget = new MHDetachedWindow(parentWidget());
detachedWidget->setWindowModality(Qt::NonModal);
// Find Widget and connect
connect(detachedWidget, SIGNAL(OnClose(QWidget*)), this, SLOT(AttachTab(QWidget*)));
connect(detachedWidget, SIGNAL(OnFocused(QWidget*)), this, SLOT(OnDetachFocused(QWidget*)));
detachedWidget->setWindowTitle(tabText(index));
detachedWidget->setWindowIcon(tabIcon(index));
detachedWidget->mNativeName = mNativeNames[index];
detachedWidget->mPreviousIndex = index;
mNativeNames.removeAt(index);
// Remove from tab bar
QWidget* tearOffWidget = widget(index);
tearOffWidget->setParent(detachedWidget);
// Add it to the windows list
mWindows.append(tearOffWidget);
// Make first active
if(count() > 0)
setCurrentIndex(0);
// 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();
}
// Remove a tab, while still keeping the widget intact
void MHTabWidget::DeleteTab(int index)
{
QWidget* w = widget(index);
mHistory.removeAll((MIDPKey)w);
removeTab(index);
mNativeNames.removeAt(index);
}
void MHTabWidget::tabMoved(int from, int to)
{
std::swap(mNativeNames[from], mNativeNames[to]);
emit tabMovedTabWidget(from, to);
}
void MHTabWidget::OnDetachFocused(QWidget* parent)
{
MHDetachedWindow* detachedWidget = reinterpret_cast<MHDetachedWindow*>(parent);
QWidget* tearOffWidget = detachedWidget->centralWidget();
setLatestFocused(tearOffWidget);
}
void MHTabWidget::currentChanged(int index)
{
setLatestFocused(widget(index));
}
void MHTabWidget::setCurrentIndex(int index)
{
// Check if it's just a normal tab
if(index < QTabWidget::count())
{
QTabWidget::setCurrentIndex(index);
}
else
{
// Otherwise it's going to be a window (just bring it up)
MHDetachedWindow* window = dynamic_cast<MHDetachedWindow*>(widget(index)->parent());
window->activateWindow();
window->showNormal();
window->setFocus();
}
setLatestFocused(widget(index));
}
MHTabBar* MHTabWidget::tabBar() const
{
return mTabBar;
}
const QList<MIDPKey> & MHTabWidget::MIDP_getItems() const
{
return mHistory;
}
QString MHTabWidget::MIDP_getItemName(MIDPKey index)
{
return reinterpret_cast<QWidget*>(index)->windowTitle();
}
void MHTabWidget::MIDP_selected(MIDPKey index)
{
setLatestFocused((QWidget*)index);
// check in tabbar
for(auto i = 0; i < QTabWidget::count(); ++i)
{
if(reinterpret_cast<QWidget*>(index) == QTabWidget::widget(i))
{
QTabWidget::setCurrentIndex(i);
parentWidget()->activateWindow();
parentWidget()->setFocus();
return;
}
}
// should be a detached window
MHDetachedWindow* window = dynamic_cast<MHDetachedWindow*>(reinterpret_cast<QWidget*>(index)->parent());
window->activateWindow();
window->showNormal();
window->setFocus();
}
QIcon MHTabWidget::MIDP_getIcon(MIDPKey index)
{
// check in tabbar
for(auto i = 0; i < QTabWidget::count(); ++i)
{
if(reinterpret_cast<QWidget*>(index) == QTabWidget::widget(i))
{
return mTabBar->tabIcon(i);
}
}
// should be a detached window
MHDetachedWindow* window = dynamic_cast<MHDetachedWindow*>(reinterpret_cast<QWidget*>(index)->parent());
return window->windowIcon();
}
void MHTabWidget::setLatestFocused(QWidget* w)
{
mHistory.removeAll((MIDPKey)w);
mHistory.push_front((MIDPKey)w);
}
QString MHTabWidget::getNativeName(int index)
{
if(index < QTabWidget::count())
{
return mNativeNames.at(index);
}
else
{
MHDetachedWindow* window = dynamic_cast<MHDetachedWindow*>(mWindows.at(index - QTabWidget::count())->parent());
if(window)
return window->mNativeName;
else
return QString();
}
}
void MHTabWidget::showPreviousTab()
{
if(QTabWidget::count() <= 1)
{
return;
}
int previousTabIndex = QTabWidget::currentIndex();
if(previousTabIndex == 0)
{
previousTabIndex = QTabWidget::count() - 1;
}
else
{
previousTabIndex--;
}
QTabWidget::setCurrentIndex(previousTabIndex);
}
void MHTabWidget::showNextTab()
{
if(QTabWidget::count() <= 1)
{
return;
}
QTabWidget::setCurrentIndex((QTabWidget::currentIndex() + 1) % QTabWidget::count());
}
void MHTabWidget::showPreviousView()
{
mHistoryPopup->gotoPreviousItem();
}
void MHTabWidget::showNextView()
{
mHistoryPopup->gotoNextItem();
}
void MHTabWidget::deleteCurrentTab()
{
if(QTabWidget::count() == 0)
{
return;
}
int index = QTabWidget::currentIndex();
DeleteTab(index);
if(index < count())
{
// open the tab to the right of the deleted tab
setCurrentIndex(index);
}
}
//----------------------------------------------------------------------------
MHDetachedWindow::MHDetachedWindow(QWidget* parent) : QMainWindow(parent)
{
}
MHDetachedWindow::~MHDetachedWindow()
{
}
void MHDetachedWindow::closeEvent(QCloseEvent* event)
{
Q_UNUSED(event);
emit OnClose(this);
}
bool MHDetachedWindow::event(QEvent* event)
{
if(event->type() == QEvent::WindowActivate && this->isActiveWindow())
{
emit OnFocused(this);
}
return QMainWindow::event(event);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/TabWidget.h | #pragma once
// Qt includes
#include <QWidget>
#include <QTabWidget>
#include <QMainWindow>
#include "TabBar.h"
#include "MultiItemsSelectWindow.h"
// Qt forward class definitions
class MHTabBar;
//////////////////////////////////////////////////////////////////////////////
// Summary:
// MHTabWidget implements the a Tab Widget with detach and attach
// functionality for MHTabBar.
//////////////////////////////////////////////////////////////////////////////
class MHTabWidget: public QTabWidget, public MultiItemsDataProvider
{
Q_OBJECT
public:
MHTabWidget(QWidget* parent = nullptr, bool allowDetach = true, bool allowDelete = false);
virtual ~MHTabWidget();
QWidget* widget(int index) const;
int count() const;
QList<QWidget*> windows();
int addTabEx(QWidget* widget, const QIcon & icon, const QString & label, const QString & nativeName);
QString getNativeName(int index);
signals:
void tabMovedTabWidget(int from, int to);
public slots:
void AttachTab(QWidget* parent);
void DetachTab(int index, const QPoint &);
void DeleteTab(int index);
void tabMoved(int from, int to);
void OnDetachFocused(QWidget* parent);
void currentChanged(int index);
void setCurrentIndex(int index);
void showPreviousTab();
void showNextTab();
void showPreviousView();
void showNextView();
void deleteCurrentTab();
protected:
MHTabBar* tabBar() const;
const QList<MIDPKey> & MIDP_getItems() const override;
QString MIDP_getItemName(MIDPKey index) override;
void MIDP_selected(MIDPKey index) override;
QIcon MIDP_getIcon(MIDPKey index) override;
void setLatestFocused(QWidget* w);
private:
MHTabBar* mTabBar;
QList<QWidget*> mWindows;
QList<QString> mNativeNames;
MultiItemsSelectWindow* mHistoryPopup;
QList<MIDPKey> mHistory;
};
//////////////////////////////////////////////////////////////////////////////
// Summary:
// MHDetachedWindow implements the WindowContainer for the Detached Widget
//
// Conditions:
// Header : MHTabWidget.h
//////////////////////////////////////////////////////////////////////////////
class MHDetachedWindow : public QMainWindow
{
Q_OBJECT
public:
MHDetachedWindow(QWidget* parent = 0);
~MHDetachedWindow();
QString mNativeName;
int mPreviousIndex = -1;
signals:
void OnClose(QWidget* widget);
void OnFocused(QWidget* widget);
protected:
void closeEvent(QCloseEvent* event);
bool event(QEvent* event);
}; |
C++ | x64dbg-development/src/gui/Src/Gui/ThreadView.cpp | #include "ThreadView.h"
#include "Configuration.h"
#include "Bridge.h"
#include "StringUtil.h"
#include "LineEditDialog.h"
void ThreadView::contextMenuSlot(const QPoint & pos)
{
if(!DbgIsDebugging())
return;
QMenu wMenu(this); //create context menu
mMenuBuilder->build(&wMenu);
wMenu.exec(mapToGlobal(pos)); //execute context menu
}
void ThreadView::GoToThreadEntry()
{
QString addr_text = getCellContent(getInitialSelection(), 2);
DbgCmdExecDirect(QString("disasm " + addr_text));
}
void ThreadView::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this);
//Switch thread menu
mMenuBuilder->addAction(makeCommandAction(new QAction(DIcon("thread-switch"), tr("Switch Thread"), this), "switchthread $"));
//Suspend thread menu
mMenuBuilder->addAction(makeCommandAction(new QAction(DIcon("thread-pause"), tr("Suspend Thread"), this), "suspendthread $"));
//Resume thread menu
mMenuBuilder->addAction(makeCommandAction(new QAction(DIcon("thread-resume"), tr("Resume Thread"), this), "resumethread $"));
mMenuBuilder->addAction(makeCommandAction(new QAction(DIcon("thread-pause"), tr("Suspend All Threads"), this), "suspendallthreads"));
mMenuBuilder->addAction(makeCommandAction(new QAction(DIcon("thread-resume"), tr("Resume All Threads"), this), "resumeallthreads"));
//Kill thread menu
mMenuBuilder->addAction(makeCommandAction(new QAction(DIcon("thread-kill"), tr("Kill Thread"), this), "killthread $"));
mMenuBuilder->addSeparator();
// Set name
mMenuBuilder->addAction(makeAction(DIcon("thread-setname"), tr("Set Name"), SLOT(SetNameSlot())));
// Set priority
QAction* mSetPriorityIdle = makeCommandAction(new QAction(DIcon("thread-priority-idle"), tr("Idle"), this), "setprioritythread $, Idle");
QAction* mSetPriorityAboveNormal = makeCommandAction(new QAction(DIcon("thread-priority-above-normal"), tr("Above Normal"), this), "setprioritythread $, AboveNormal");
QAction* mSetPriorityBelowNormal = makeCommandAction(new QAction(DIcon("thread-priority-below-normal"), tr("Below Normal"), this), "setprioritythread $, BelowNormal");
QAction* mSetPriorityHighest = makeCommandAction(new QAction(DIcon("thread-priority-highest"), tr("Highest"), this), "setprioritythread $, Highest");
QAction* mSetPriorityLowest = makeCommandAction(new QAction(DIcon("thread-priority-lowest"), tr("Lowest"), this), "setprioritythread $, Lowest");
QAction* mSetPriorityNormal = makeCommandAction(new QAction(DIcon("thread-priority-normal"), tr("Normal"), this), "setprioritythread $, Normal");
QAction* mSetPriorityTimeCritical = makeCommandAction(new QAction(DIcon("thread-priority-timecritical"), tr("Time Critical"), this), "setprioritythread $, TimeCritical");
MenuBuilder* mSetPriority = new MenuBuilder(this, [this, mSetPriorityIdle, mSetPriorityAboveNormal, mSetPriorityBelowNormal,
mSetPriorityHighest, mSetPriorityLowest, mSetPriorityNormal, mSetPriorityTimeCritical](QMenu*)
{
QString priority = getCellContent(getInitialSelection(), 6);
QAction* selectedaction = nullptr;
if(priority == tr("Normal"))
selectedaction = mSetPriorityNormal;
else if(priority == tr("AboveNormal"))
selectedaction = mSetPriorityAboveNormal;
else if(priority == tr("TimeCritical"))
selectedaction = mSetPriorityTimeCritical;
else if(priority == tr("Idle"))
selectedaction = mSetPriorityIdle;
else if(priority == tr("BelowNormal"))
selectedaction = mSetPriorityBelowNormal;
else if(priority == tr("Highest"))
selectedaction = mSetPriorityHighest;
else if(priority == tr("Lowest"))
selectedaction = mSetPriorityLowest;
mSetPriorityAboveNormal->setCheckable(true);
mSetPriorityAboveNormal->setChecked(selectedaction == mSetPriorityAboveNormal); // true if mSetPriorityAboveNormal is selected
mSetPriorityBelowNormal->setCheckable(true);
mSetPriorityBelowNormal->setChecked(selectedaction == mSetPriorityBelowNormal); // true if mSetPriorityBelowNormal is selected
mSetPriorityHighest->setCheckable(true);
mSetPriorityHighest->setChecked(selectedaction == mSetPriorityHighest); // true if mSetPriorityHighest is selected
mSetPriorityIdle->setCheckable(true);
mSetPriorityIdle->setChecked(selectedaction == mSetPriorityIdle); // true if mSetPriorityIdle is selected
mSetPriorityLowest->setCheckable(true);
mSetPriorityLowest->setChecked(selectedaction == mSetPriorityLowest); // true if mSetPriorityLowest is selected
mSetPriorityNormal->setCheckable(true);
mSetPriorityNormal->setChecked(selectedaction == mSetPriorityNormal); // true if mSetPriorityNormal is selected
mSetPriorityTimeCritical->setCheckable(true);
mSetPriorityTimeCritical->setChecked(selectedaction == mSetPriorityTimeCritical); // true if mSetPriorityTimeCritical is selected
return true;
});
mSetPriority->addAction(mSetPriorityTimeCritical);
mSetPriority->addAction(mSetPriorityHighest);
mSetPriority->addAction(mSetPriorityAboveNormal);
mSetPriority->addAction(mSetPriorityNormal);
mSetPriority->addAction(mSetPriorityBelowNormal);
mSetPriority->addAction(mSetPriorityLowest);
mSetPriority->addAction(mSetPriorityIdle);
mMenuBuilder->addMenu(makeMenu(DIcon("thread-setpriority_alt"), tr("Set Priority")), mSetPriority);
// GoToThreadEntry
mMenuBuilder->addAction(makeAction(DIcon("thread-entry"), tr("Go to Thread Entry"), SLOT(GoToThreadEntry())), [this](QMenu * menu)
{
bool ok;
ULONGLONG entry = getCellContent(getInitialSelection(), 2).toULongLong(&ok, 16);
if(ok && DbgMemIsValidReadPtr(entry))
{
menu->addSeparator();
return true;
}
else
return false;
});
MenuBuilder* mCopyMenu = new MenuBuilder(this);
setupCopyMenu(mCopyMenu);
// Column count cannot be zero
mMenuBuilder->addSeparator();
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), mCopyMenu);
mMenuBuilder->loadFromConfig();
}
/**
* @brief ThreadView::makeCommandAction Make action to execute the command. $ will be replaced with thread id at runtime.
* @param action The action to bind
* @param command The command to execute when the action is triggered.
* @return action
*/
QAction* ThreadView::makeCommandAction(QAction* action, const QString & command)
{
action->setData(QVariant(command));
connect(action, SIGNAL(triggered()), this, SLOT(ExecCommand()));
return action;
}
/**
* @brief ThreadView::ExecCommand execute command slot for menus. Only used by command that reference thread id.
*/
void ThreadView::ExecCommand()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action)
{
QString command = action->data().toString();
if(command.contains('$'))
{
for(int i : getSelection())
{
QString specializedCommand = command;
specializedCommand.replace(QChar('$'), ToHexString(getCellUserdata(i, 1))); // $ -> Thread Id
DbgCmdExec(specializedCommand);
}
}
else
DbgCmdExec(command);
}
}
ThreadView::ThreadView(StdTable* parent) : StdTable(parent)
{
enableMultiSelection(true);
int charwidth = getCharWidth();
addColumnAt(8 + charwidth * sizeof(unsigned int) * 2, tr("Number"), true, "", SortBy::AsInt);
addColumnAt(8 + charwidth * sizeof(unsigned int) * 2, tr("ID"), true, "", ConfigBool("Gui", "PidTidInHex") ? SortBy::AsHex : SortBy::AsInt);
addColumnAt(8 + charwidth * sizeof(duint) * 2, tr("Entry"), true, "", SortBy::AsHex);
addColumnAt(8 + charwidth * sizeof(duint) * 2, tr("TEB"), true, "", SortBy::AsHex);
addColumnAt(8 + charwidth * sizeof(duint) * 2, ArchValue(tr("EIP"), tr("RIP")), true, "", SortBy::AsHex);
addColumnAt(8 + charwidth * 14, tr("Suspend Count"), true, "", SortBy::AsInt);
addColumnAt(8 + charwidth * 12, tr("Priority"), true);
addColumnAt(8 + charwidth * 12, tr("Wait Reason"), true);
addColumnAt(8 + charwidth * 10, tr("Last Error"), true, "", SortBy::AsHex);
addColumnAt(8 + charwidth * 16, tr("User Time"), true);
addColumnAt(8 + charwidth * 16, tr("Kernel Time"), true);
addColumnAt(8 + charwidth * 16, tr("Creation Time"), true);
addColumnAt(8 + charwidth * 10, tr("CPU Cycles"), true, "", SortBy::AsHex);
addColumnAt(8, tr("Name"), true);
loadColumnFromConfig("Thread");
//setCopyMenuOnly(true);
connect(Bridge::getBridge(), SIGNAL(updateThreads()), this, SLOT(updateThreadList()));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(doubleClickedSlot()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
setupContextMenu();
}
void ThreadView::updateThreadList()
{
THREADLIST threadList;
memset(&threadList, 0, sizeof(THREADLIST));
DbgGetThreadList(&threadList);
setRowCount(threadList.count);
auto tidFormat = ConfigBool("Gui", "PidTidInHex") ? "%X" : "%d";
for(int i = 0; i < threadList.count; i++)
{
if(!threadList.list[i].BasicInfo.ThreadNumber)
setCellContent(i, 0, tr("Main"));
else
setCellContent(i, 0, ToDecString(threadList.list[i].BasicInfo.ThreadNumber));
setCellContent(i, 1, QString().sprintf(tidFormat, threadList.list[i].BasicInfo.ThreadId));
setCellUserdata(i, 1, threadList.list[i].BasicInfo.ThreadId);
setCellContent(i, 2, ToPtrString(threadList.list[i].BasicInfo.ThreadStartAddress));
setCellContent(i, 3, ToPtrString(threadList.list[i].BasicInfo.ThreadLocalBase));
setCellContent(i, 4, ToPtrString(threadList.list[i].ThreadCip));
setCellContent(i, 5, ToDecString(threadList.list[i].SuspendCount));
QString priorityString;
switch(threadList.list[i].Priority)
{
case _PriorityIdle:
priorityString = tr("Idle");
break;
case _PriorityAboveNormal:
priorityString = tr("AboveNormal");
break;
case _PriorityBelowNormal:
priorityString = tr("BelowNormal");
break;
case _PriorityHighest:
priorityString = tr("Highest");
break;
case _PriorityLowest:
priorityString = tr("Lowest");
break;
case _PriorityNormal:
priorityString = tr("Normal");
break;
case _PriorityTimeCritical:
priorityString = tr("TimeCritical");
break;
default:
priorityString = tr("Unknown");
break;
}
setCellContent(i, 6, priorityString);
QString waitReasonString;
switch(threadList.list[i].WaitReason)
{
case _Executive:
waitReasonString = "Executive";
break;
case _FreePage:
waitReasonString = "FreePage";
break;
case _PageIn:
waitReasonString = "PageIn";
break;
case _PoolAllocation:
waitReasonString = "PoolAllocation";
break;
case _DelayExecution:
waitReasonString = "DelayExecution";
break;
case _Suspended:
waitReasonString = "Suspended";
break;
case _UserRequest:
waitReasonString = "UserRequest";
break;
case _WrExecutive:
waitReasonString = "WrExecutive";
break;
case _WrFreePage:
waitReasonString = "WrFreePage";
break;
case _WrPageIn:
waitReasonString = "WrPageIn";
break;
case _WrPoolAllocation:
waitReasonString = "WrPoolAllocation";
break;
case _WrDelayExecution:
waitReasonString = "WrDelayExecution";
break;
case _WrSuspended:
waitReasonString = "WrSuspended";
break;
case _WrUserRequest:
waitReasonString = "WrUserRequest";
break;
case _WrEventPair:
waitReasonString = "WrEventPair";
break;
case _WrQueue:
waitReasonString = "WrQueue";
break;
case _WrLpcReceive:
waitReasonString = "WrLpcReceive";
break;
case _WrLpcReply:
waitReasonString = "WrLpcReply";
break;
case _WrVirtualMemory:
waitReasonString = "WrVirtualMemory";
break;
case _WrPageOut:
waitReasonString = "WrPageOut";
break;
case _WrRendezvous:
waitReasonString = "WrRendezvous";
break;
case _Spare2:
waitReasonString = "Spare2";
break;
case _Spare3:
waitReasonString = "Spare3";
break;
case _Spare4:
waitReasonString = "Spare4";
break;
case _Spare5:
waitReasonString = "Spare5";
break;
case _WrCalloutStack:
waitReasonString = "WrCalloutStack";
break;
case _WrKernel:
waitReasonString = "WrKernel";
break;
case _WrResource:
waitReasonString = "WrResource";
break;
case _WrPushLock:
waitReasonString = "WrPushLock";
break;
case _WrMutex:
waitReasonString = "WrMutex";
break;
case _WrQuantumEnd:
waitReasonString = "WrQuantumEnd";
break;
case _WrDispatchInt:
waitReasonString = "WrDispatchInt";
break;
case _WrPreempted:
waitReasonString = "WrPreempted";
break;
case _WrYieldExecution:
waitReasonString = "WrYieldExecution";
break;
case _WrFastMutex:
waitReasonString = "WrFastMutex";
break;
case _WrGuardedMutex:
waitReasonString = "WrGuardedMutex";
break;
case _WrRundown:
waitReasonString = "WrRundown";
break;
default:
waitReasonString = "Unknown";
break;
}
setCellContent(i, 7, waitReasonString);
setCellContent(i, 8, QString("%1").arg(threadList.list[i].LastError, sizeof(unsigned int) * 2, 16, QChar('0')).toUpper());
setCellContent(i, 9, FILETIMEToTime(threadList.list[i].UserTime));
setCellContent(i, 10, FILETIMEToTime(threadList.list[i].KernelTime));
setCellContent(i, 11, FILETIMEToDate(threadList.list[i].CreationTime));
setCellContent(i, 12, ToLongLongHexString(threadList.list[i].Cycles));
setCellContent(i, 13, threadList.list[i].BasicInfo.threadName);
}
mCurrentThreadId = -1;
if(threadList.count)
{
int currentThread = threadList.CurrentThread;
if(currentThread >= 0 && currentThread < threadList.count)
mCurrentThreadId = threadList.list[currentThread].BasicInfo.ThreadId;
BridgeFree(threadList.list);
}
reloadData();
}
QString ThreadView::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
QString ret = StdTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
duint threadId = getCellUserdata(rowBase + rowOffset, 1);
if(threadId == mCurrentThreadId && !col)
{
painter->fillRect(QRect(x, y, w, h), QBrush(ConfigColor("ThreadCurrentBackgroundColor")));
painter->setPen(QPen(ConfigColor("ThreadCurrentColor"))); //white text
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, ret);
ret = "";
}
return ret;
}
void ThreadView::doubleClickedSlot()
{
duint threadId = getCellUserdata(getInitialSelection(), 1);
DbgCmdExecDirect("switchthread " + ToHexString(threadId));
QString addr_text = getCellContent(getInitialSelection(), 4);
DbgCmdExec("disasm " + addr_text);
}
void ThreadView::SetNameSlot()
{
duint threadId = getCellUserdata(getInitialSelection(), 1);
LineEditDialog mLineEdit(this);
mLineEdit.setWindowTitle(tr("Name") + threadId);
mLineEdit.setText(getCellContent(getInitialSelection(), 13));
if(mLineEdit.exec() != QDialog::Accepted)
return;
QString escapedName = mLineEdit.editText.replace("\"", "\\\"");
DbgCmdExec(QString("setthreadname %1, \"%2\"").arg(ToHexString(threadId)).arg(escapedName));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ThreadView.h | #pragma once
#include "StdTable.h"
#include <QMenu>
class ThreadView : public StdTable
{
Q_OBJECT
public:
explicit ThreadView(StdTable* parent = 0);
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h);
void setupContextMenu();
public slots:
void updateThreadList();
void doubleClickedSlot();
void ExecCommand();
void GoToThreadEntry();
void contextMenuSlot(const QPoint & pos);
void SetNameSlot();
private:
QAction* makeCommandAction(QAction* action, const QString & command);
duint mCurrentThreadId;
MenuBuilder* mMenuBuilder;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/TimeWastedCounter.cpp | #include "TimeWastedCounter.h"
#include "Bridge.h"
#include <QLabel>
TimeWastedCounter::TimeWastedCounter(QObject* parent, QLabel* label)
: QObject(parent), mLabel(label)
{
connect(Bridge::getBridge(), SIGNAL(updateTimeWastedCounter()), this, SLOT(updateTimeWastedCounter()));
}
void TimeWastedCounter::updateTimeWastedCounter()
{
duint dbgEvents = DbgFunctions()->GetDbgEvents();
if(dbgEvents > 4)
{
mLabel->setText(tr("%1 events/s").arg(dbgEvents));
}
else
{
duint timeWasted = DbgGetTimeWastedCounter();
int days = timeWasted / (60 * 60 * 24);
int hours = (timeWasted / (60 * 60)) % 24;
int minutes = (timeWasted / 60) % 60;
int seconds = timeWasted % 60;
mLabel->setText(tr("Time Wasted Debugging:") + QString().sprintf(" %d:%02d:%02d:%02d", days, hours, minutes, seconds));
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/TimeWastedCounter.h | #pragma once
#include <QObject>
class QLabel;
class TimeWastedCounter : public QObject
{
Q_OBJECT
public:
explicit TimeWastedCounter(QObject* parent, QLabel* label);
private slots:
void updateTimeWastedCounter();
private:
QLabel* mLabel;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/VirtualModDialog.cpp | #include "VirtualModDialog.h"
#include "ui_VirtualModDialog.h"
#include "StringUtil.h"
VirtualModDialog::VirtualModDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::VirtualModDialog)
{
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
}
VirtualModDialog::~VirtualModDialog()
{
delete ui;
}
bool VirtualModDialog::getData(QString & modname, duint & base, duint & size)
{
modname = ui->editName->text();
if(!modname.length())
return false;
bool ok = false;
base = duint(ui->editBase->text().toLongLong(&ok, 16));
if(!ok || !DbgMemIsValidReadPtr(base))
return false;
size = duint(ui->editSize->text().toLongLong(&ok, 16));
if(!ok || ! size)
return false;
return true;
}
void VirtualModDialog::setData(const QString & modname, duint base, duint size)
{
ui->editName->setText(modname);
ui->editBase->setText(ToHexString(base));
ui->editSize->setText(ToHexString(size));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/VirtualModDialog.h | #pragma once
#include <QDialog>
#include "Imports.h"
namespace Ui
{
class VirtualModDialog;
}
class VirtualModDialog : public QDialog
{
Q_OBJECT
public:
explicit VirtualModDialog(QWidget* parent = 0);
~VirtualModDialog();
bool getData(QString & modname, duint & base, duint & size);
void setData(const QString & modname, duint base, duint size);
private:
Ui::VirtualModDialog* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/VirtualModDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>VirtualModDialog</class>
<widget class="QDialog" name="VirtualModDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>101</height>
</rect>
</property>
<property name="windowTitle">
<string>Virtual Module</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="layoutName">
<item>
<widget class="QLabel" name="labelName">
<property name="text">
<string>&Name:</string>
</property>
<property name="buddy">
<cstring>editName</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="editName"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layoutBaseSize">
<item>
<layout class="QHBoxLayout" name="layoutBase">
<item>
<widget class="QLabel" name="labelBase">
<property name="text">
<string>&Base:</string>
</property>
<property name="buddy">
<cstring>editBase</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="editBase"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layoutSize">
<item>
<widget class="QLabel" name="labelSize">
<property name="text">
<string>&Size:</string>
</property>
<property name="buddy">
<cstring>editSize</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="editSize"/>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layoutButtons">
<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>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>VirtualModDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>254</x>
<y>75</y>
</hint>
<hint type="destinationlabel">
<x>303</x>
<y>98</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonOk</sender>
<signal>clicked()</signal>
<receiver>VirtualModDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>136</x>
<y>80</y>
</hint>
<hint type="destinationlabel">
<x>113</x>
<y>98</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/WatchView.cpp | #include "Bridge.h"
#include "WatchView.h"
#include "CPUMultiDump.h"
#include "WordEditDialog.h"
#include "MiscUtil.h"
WatchView::WatchView(CPUMultiDump* parent) : StdTable(parent)
{
int charWidth = getCharWidth();
addColumnAt(8 + charWidth * 12, tr("Name"), true);
addColumnAt(8 + charWidth * 20, tr("Expression"), true);
addColumnAt(8 + charWidth * sizeof(duint) * 2, tr("Value"), true);
addColumnAt(8 + charWidth * 8, tr("Type"), true);
addColumnAt(150, tr("Watchdog Mode"), true);
addColumnAt(30, tr("ID"), true, "", SortBy::AsInt);
connect(Bridge::getBridge(), SIGNAL(updateWatch()), this, SLOT(updateWatch()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
setupContextMenu();
setDrawDebugOnly(true);
Initialize();
}
void WatchView::updateWatch()
{
if(!DbgIsDebugging())
{
setRowCount(0);
setSingleSelection(0);
return;
}
BridgeList<WATCHINFO> WatchList;
DbgGetWatchList(&WatchList);
setRowCount(WatchList.Count());
if(getInitialSelection() >= WatchList.Count() && WatchList.Count() > 0)
setSingleSelection(WatchList.Count() - 1);
for(int i = 0; i < WatchList.Count(); i++)
{
setCellContent(i, ColName, QString(WatchList[i].WatchName));
setCellContent(i, ColExpr, QString(WatchList[i].Expression));
switch(WatchList[i].varType)
{
case WATCHVARTYPE::TYPE_UINT:
setCellContent(i, ColType, "UINT");
setCellContent(i, ColValue, ToPtrString(WatchList[i].value));
break;
case WATCHVARTYPE::TYPE_INT:
setCellContent(i, ColType, "INT");
setCellContent(i, ColValue, QString::number((dsint)WatchList[i].value));
break;
case WATCHVARTYPE::TYPE_FLOAT:
setCellContent(i, ColType, "FLOAT");
setCellContent(i, ColValue, ToFloatString(&WatchList[i].value));
break;
case WATCHVARTYPE::TYPE_ASCII:
setCellContent(i, ColType, "ASCII");
{
char buffer[128];
// zero the buffer
memset(buffer, 0, sizeof(buffer));
if(DbgMemRead(WatchList[i].value, (unsigned char*)buffer, sizeof(buffer) - 1))
{
// convert the ASCII string to QString
QString text = QString::fromLocal8Bit(buffer);
if(strlen(buffer) == sizeof(buffer) - 1)
text.append("...");
// remove CRLF
text.replace(QChar('\x13'), "\\r");
text.replace(QChar('\x10'), "\\n");
setCellContent(i, ColValue, text);
}
else
setCellContent(i, ColValue, tr("%1 is not readable.").arg(ToPtrString(WatchList[i].value)));
}
break;
case WATCHVARTYPE::TYPE_UNICODE:
setCellContent(i, ColType, "UNICODE");
{
unsigned short buffer[128];
// zero the buffer
memset(buffer, 0, sizeof(buffer));
if(DbgMemRead(WatchList[i].value, (unsigned char*)buffer, sizeof(buffer) - sizeof(unsigned short)))
{
QString text = QString::fromUtf16(buffer);
size_t size = text.size();
// Check if the last character is an incomplete UTF-16 surrogate.
if(text.at(text.size() - 1).isHighSurrogate())
text.chop(text.size() - 1); // Delete the incomplete surrogate.
// Check if something is truncated.
if(size == sizeof(buffer) / sizeof(unsigned short) - 1)
text.append("...");
// remove CRLF
text.replace(QChar('\x13'), "\\r");
text.replace(QChar('\x10'), "\\n");
setCellContent(i, ColValue, text);
}
else
setCellContent(i, ColValue, tr("%1 is not readable.").arg(ToPtrString(WatchList[i].value)));
}
break;
case WATCHVARTYPE::TYPE_INVALID:
default:
setCellContent(i, ColType, "INVALID");
setCellContent(i, ColValue, "");
break;
}
switch(WatchList[i].watchdogMode)
{
case WATCHDOGMODE::MODE_DISABLED:
default:
setCellContent(i, ColWatchdog, tr("Disabled"));
break;
case WATCHDOGMODE::MODE_CHANGED:
setCellContent(i, ColWatchdog, tr("Changed"));
break;
case WATCHDOGMODE::MODE_ISTRUE:
setCellContent(i, ColWatchdog, tr("Is true"));
break;
case WATCHDOGMODE::MODE_ISFALSE:
setCellContent(i, ColWatchdog, tr("Is false"));
break;
case WATCHDOGMODE::MODE_UNCHANGED:
setCellContent(i, ColWatchdog, tr("Not changed"));
break;
}
setCellContent(i, ColId, QString::number(WatchList[i].id));
}
reloadData();
}
void WatchView::updateColors()
{
mWatchTriggeredColor = QPen(ConfigColor("WatchTriggeredColor"));
mWatchTriggeredBackgroundColor = QBrush(ConfigColor("WatchTriggeredBackgroundColor"));
StdTable::updateColors();
}
void WatchView::setupContextMenu()
{
mMenu = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
const auto & nonEmptyFunc = [this](QMenu*)
{
return getRowCount() != 0;
};
mMenu->addAction(makeAction(tr("&Add..."), SLOT(addWatchSlot())));
mMenu->addAction(makeShortcutAction(tr("&Delete"), SLOT(delWatchSlot()), "ActionDeleteBreakpoint"), nonEmptyFunc);
mMenu->addAction(makeAction(DIcon("labels"), tr("Rename"), SLOT(renameWatchSlot())), nonEmptyFunc);
mMenu->addAction(makeAction(DIcon("modify"), tr("&Edit..."), SLOT(editWatchSlot())), nonEmptyFunc);
mMenu->addAction(makeAction(DIcon("modify"), tr("&Modify..."), SLOT(modifyWatchSlot())), nonEmptyFunc);
MenuBuilder* watchdogBuilder = new MenuBuilder(this, nonEmptyFunc);
QMenu* watchdogMenu = new QMenu(tr("Watchdog"), this);
watchdogMenu->setIcon(DIcon("animal-dog"));
watchdogBuilder->addAction(makeAction(DIcon("disable"), tr("Disabled"), SLOT(watchdogDisableSlot())));
watchdogBuilder->addSeparator();
watchdogBuilder->addAction(makeAction(DIcon("arrow-restart"), tr("Changed"), SLOT(watchdogChangedSlot())));
watchdogBuilder->addAction(makeAction(DIcon("control-pause"), tr("Not changed"), SLOT(watchdogUnchangedSlot())));
watchdogBuilder->addAction(makeAction(DIcon("treat_selection_as_tbyte"), tr("Is true"), SLOT(watchdogIsTrueSlot()))); // TODO: better icon
watchdogBuilder->addAction(makeAction(DIcon("treat_selection_as_fword"), tr("Is false"), SLOT(watchdogIsFalseSlot())));
mMenu->addMenu(watchdogMenu, watchdogBuilder);
MenuBuilder* typeBuilder = new MenuBuilder(this, nonEmptyFunc);
QMenu* typeMenu = new QMenu(tr("Type"), this);
typeBuilder->addAction(makeAction(DIcon("integer"), tr("Uint"), SLOT(setTypeUintSlot())));
typeBuilder->addAction(makeAction(DIcon("integer"), tr("Int"), SLOT(setTypeIntSlot())));
typeBuilder->addAction(makeAction(DIcon("float"), tr("Float"), SLOT(setTypeFloatSlot())));
typeBuilder->addAction(makeAction(DIcon("ascii"), tr("Ascii"), SLOT(setTypeAsciiSlot())));
typeBuilder->addAction(makeAction(DIcon("ascii-extended"), tr("Unicode"), SLOT(setTypeUnicodeSlot())));
mMenu->addMenu(typeMenu, typeBuilder);
mMenu->addSeparator();
MenuBuilder* copyMenu = new MenuBuilder(this);
setupCopyMenu(copyMenu);
mMenu->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
mMenu->loadFromConfig();
}
QString WatchView::getSelectedId()
{
return QChar('.') + getCellContent(getInitialSelection(), ColId);
}
QString WatchView::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
QString ret = StdTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
const dsint row = rowBase + rowOffset;
if(row != getInitialSelection() && DbgFunctions()->WatchIsWatchdogTriggered(getCellContent(row, ColId).toUInt()))
{
painter->fillRect(QRect(x, y, w, h), mWatchTriggeredBackgroundColor);
painter->setPen(mWatchTriggeredColor); //white text
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, ret);
return QString();
}
else
return ret;
}
//SLOTS
void WatchView::contextMenuSlot(const QPoint & pos)
{
QMenu wMenu(this);
mMenu->build(&wMenu);
wMenu.exec(mapToGlobal(pos));
}
void WatchView::addWatchSlot()
{
QString name;
if(SimpleInputBox(this, tr("Enter the expression to watch"), "", name, tr("Example: [EAX]")))
DbgCmdExecDirect(QString("AddWatch ").append(name));
updateWatch();
}
void WatchView::delWatchSlot()
{
DbgCmdExecDirect(QString("DelWatch ").append(getSelectedId()));
updateWatch();
}
void WatchView::renameWatchSlot()
{
QString name;
QString originalName = getCellContent(getInitialSelection(), ColName);
if(SimpleInputBox(this, tr("Enter the name of the watch variable"), originalName, name, originalName))
DbgCmdExecDirect(QString("SetWatchName ").append(getSelectedId() + "," + name));
updateWatch();
}
void WatchView::modifyWatchSlot()
{
BridgeList<WATCHINFO> WatchList;
DbgGetWatchList(&WatchList);
auto sel = getInitialSelection();
if(sel > WatchList.Count())
return;
WordEditDialog modifyDialog(this);
modifyDialog.setup(tr("Modify \"%1\"").arg(QString(WatchList[sel].WatchName)), WatchList[sel].value, sizeof(duint));
if(modifyDialog.exec() == QDialog::Accepted)
{
if(!DbgValToString(WatchList[sel].Expression, modifyDialog.getVal()))
SimpleErrorBox(this, tr("Cannot modify \"%1\"").arg(QString(WatchList[sel].WatchName)), tr("It might not possible to assign a value to \"%1\".").arg(QString(WatchList[sel].Expression)));
}
updateWatch();
}
void WatchView::editWatchSlot()
{
QString expr;
QString originalExpr = getCellContent(getInitialSelection(), ColExpr);
QString currentType = getCellContent(getInitialSelection(), ColType);
if(SimpleInputBox(this, tr("Enter the expression to watch"), originalExpr, expr, tr("Example: [EAX]")))
DbgCmdExecDirect(QString("SetWatchExpression ").append(getSelectedId()).append(",").append(expr).append(",").append(currentType));
updateWatch();
}
void WatchView::watchdogDisableSlot()
{
DbgCmdExecDirect(QString("SetWatchdog %1, \"disabled\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::watchdogChangedSlot()
{
DbgCmdExecDirect(QString("SetWatchdog %1, \"changed\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::watchdogUnchangedSlot()
{
DbgCmdExecDirect(QString("SetWatchdog %1, \"unchanged\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::watchdogIsTrueSlot()
{
DbgCmdExecDirect(QString("SetWatchdog %1, \"istrue\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::watchdogIsFalseSlot()
{
DbgCmdExecDirect(QString("SetWatchdog %1, \"isfalse\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::setTypeUintSlot()
{
DbgCmdExecDirect(QString("SetWatchType %1, \"uint\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::setTypeIntSlot()
{
DbgCmdExecDirect(QString("SetWatchType %1, \"int\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::setTypeFloatSlot()
{
DbgCmdExecDirect(QString("SetWatchType %1, \"float\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::setTypeAsciiSlot()
{
DbgCmdExecDirect(QString("SetWatchType %1, \"ascii\"").arg(getSelectedId()));
updateWatch();
}
void WatchView::setTypeUnicodeSlot()
{
DbgCmdExecDirect(QString("SetWatchType %1, \"unicode\"").arg(getSelectedId()));
updateWatch();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/WatchView.h | #pragma once
#include "StdTable.h"
class CPUMultiDump;
class WatchView : public StdTable
{
Q_OBJECT
public:
WatchView(CPUMultiDump* parent);
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
void updateColors() override;
public slots:
void contextMenuSlot(const QPoint & event);
void updateWatch();
void addWatchSlot();
void delWatchSlot();
void renameWatchSlot();
void editWatchSlot();
void modifyWatchSlot();
void watchdogDisableSlot();
void watchdogChangedSlot();
void watchdogUnchangedSlot();
void watchdogIsTrueSlot();
void watchdogIsFalseSlot();
void setTypeUintSlot();
void setTypeIntSlot();
void setTypeFloatSlot();
void setTypeAsciiSlot();
void setTypeUnicodeSlot();
protected:
void setupContextMenu();
QString getSelectedId();
MenuBuilder* mMenu;
QPen mWatchTriggeredColor;
QBrush mWatchTriggeredBackgroundColor;
private:
enum
{
ColName = 0,
ColExpr,
ColValue,
ColType,
ColWatchdog,
ColId
};
}; |
C++ | x64dbg-development/src/gui/Src/Gui/WordEditDialog.cpp | #include "WordEditDialog.h"
#include "ui_WordEditDialog.h"
#include "ValidateExpressionThread.h"
#include "StringUtil.h"
#include <Configuration.h>
WordEditDialog::WordEditDialog(QWidget* parent)
: QDialog(parent),
ui(new Ui::WordEditDialog),
mHexLineEditPos(0),
mSignedEditPos(0),
mUnsignedEditPos(0),
mAsciiLineEditPos(0)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true);
// Set up default validators for numerical input
ui->signedLineEdit->setValidator(new QRegExpValidator(QRegExp("^-?\\d*(\\d+)?$"), this));// Optional negative, 0-9
ui->unsignedLineEdit->setValidator(new QRegExpValidator(QRegExp("^\\d*(\\d+)?$"), this));// No signs, 0-9
mValidateThread = new ValidateExpressionThread(this);
mValidateThread->setOnExpressionChangedCallback(std::bind(&WordEditDialog::validateExpression, this, std::placeholders::_1));
connect(mValidateThread, SIGNAL(expressionChanged(bool, bool, dsint)), this, SLOT(expressionChanged(bool, bool, dsint)));
connect(ui->expressionLineEdit, SIGNAL(textChanged(QString)), mValidateThread, SLOT(textChanged(QString)));
mWord = 0;
Config()->loadWindowGeometry(this);
}
void WordEditDialog::validateExpression(QString expression)
{
duint value;
bool validExpression = DbgFunctions()->ValFromString(expression.toUtf8().constData(), &value);
bool validPointer = validExpression && DbgMemIsValidReadPtr(value);
this->mValidateThread->emitExpressionChanged(validExpression, validPointer, value);
}
WordEditDialog::~WordEditDialog()
{
Config()->saveWindowGeometry(this);
mValidateThread->stop();
mValidateThread->wait();
delete ui;
}
void WordEditDialog::showEvent(QShowEvent* event)
{
Q_UNUSED(event);
mValidateThread->start();
}
void WordEditDialog::hideEvent(QHideEvent* event)
{
Q_UNUSED(event);
mValidateThread->stop();
mValidateThread->wait();
}
void WordEditDialog::setup(QString title, duint defVal, int byteCount)
{
this->setWindowTitle(title);
this->byteCount = byteCount;
ui->hexLineEdit->setInputMask(QString("hh").repeated(byteCount));
ui->expressionLineEdit->setText(QString("%1").arg(defVal, byteCount * 2, 16, QChar('0')).toUpper());
ui->expressionLineEdit->selectAll();
ui->expressionLineEdit->setFocus();
}
duint WordEditDialog::getVal()
{
return mWord;
}
void WordEditDialog::expressionChanged(bool validExpression, bool validPointer, dsint value)
{
Q_UNUSED(validPointer);
if(validExpression)
{
ui->btnOk->setEnabled(true);
//hex
mWord = value;
duint hexWord = 0;
unsigned char* hex = (unsigned char*)&hexWord;
unsigned char* word = (unsigned char*)&mWord;
// ascii
int asciiWidth = 0;
#ifdef _WIN64
hex[0] = word[7];
hex[1] = word[6];
hex[2] = word[5];
hex[3] = word[4];
hex[4] = word[3];
hex[5] = word[2];
hex[6] = word[1];
hex[7] = word[0];
asciiWidth = 8;
#else //x86
hex[0] = word[3];
hex[1] = word[2];
hex[2] = word[1];
hex[3] = word[0];
asciiWidth = 4;
#endif //_WIN64
// Save the original index for inputs
saveCursorPositions();
// Byte edit line
ui->hexLineEdit->setText(ToPtrString(hexWord));
// Signed edit
if(byteCount == sizeof(signed char))
ui->signedLineEdit->setText(QString::number((signed char)mWord));
else if(byteCount == sizeof(signed short))
ui->signedLineEdit->setText(QString::number((signed short)mWord));
else if(byteCount == sizeof(signed int))
ui->signedLineEdit->setText(QString::number((signed int)mWord));
else
ui->signedLineEdit->setText(QString::number((long long)mWord));
// Unsigned edit
if(byteCount == sizeof(unsigned char))
ui->unsignedLineEdit->setText(QString::number((unsigned char)mWord));
else if(byteCount == sizeof(unsigned short))
ui->unsignedLineEdit->setText(QString::number((unsigned short)mWord));
else if(byteCount == sizeof(unsigned int))
ui->unsignedLineEdit->setText(QString::number((unsigned int)mWord));
else
ui->unsignedLineEdit->setText(QString::number((unsigned long long)mWord));
// ASCII edit
QString asciiExp;
for(int i = 0; i < asciiWidth; i++)
{
// replace non-printable chars with a dot
if(hex[i] != NULL && QChar(hex[i]).isPrint())
asciiExp.append(QChar(hex[i]));
else
asciiExp.append("."); // dots padding
}
ui->asciiLineEdit->setText(asciiExp);
// Use the same indices, but with different text
restoreCursorPositions();
}
else
{
ui->expressionLineEdit->setStyleSheet("border: 1px solid red");
ui->btnOk->setEnabled(false);
}
}
void WordEditDialog::on_signedLineEdit_textEdited(const QString & arg1)
{
LONGLONG value;
if(sscanf_s(arg1.toUtf8().constData(), "%lld", &value) == 1)
{
ui->signedLineEdit->setStyleSheet("");
ui->btnOk->setEnabled(true);
ui->expressionLineEdit->setText(convertValueToHexString((duint)value));
}
else
{
ui->signedLineEdit->setStyleSheet("border: 1px solid red");
ui->btnOk->setEnabled(false);
}
}
void WordEditDialog::on_unsignedLineEdit_textEdited(const QString & arg1)
{
LONGLONG value;
if(sscanf_s(arg1.toUtf8().constData(), "%llu", &value) == 1)
{
ui->unsignedLineEdit->setStyleSheet("");
ui->btnOk->setEnabled(true);
ui->expressionLineEdit->setText(convertValueToHexString((duint)value));
}
else
{
ui->unsignedLineEdit->setStyleSheet("border: 1px solid red");
ui->btnOk->setEnabled(false);
}
}
QString WordEditDialog::convertValueToHexString(duint value)
{
if(byteCount == sizeof(unsigned char))
return ToByteString(value);
else if(byteCount == sizeof(unsigned short))
return ToWordString(value);
else if(byteCount == sizeof(unsigned int))
return ToDwordString(value);
return ToPtrString(value);
}
void WordEditDialog::saveCursorPositions()
{
// Save the user's cursor index
mHexLineEditPos = ui->hexLineEdit->cursorPosition();
mSignedEditPos = ui->signedLineEdit->cursorPosition();
mUnsignedEditPos = ui->unsignedLineEdit->cursorPosition();
mAsciiLineEditPos = ui->asciiLineEdit->cursorPosition();
}
void WordEditDialog::restoreCursorPositions()
{
// Load the old cursor index (bounds checking is automatic)
ui->hexLineEdit->setCursorPosition(mHexLineEditPos);
ui->signedLineEdit->setCursorPosition(mSignedEditPos);
ui->unsignedLineEdit->setCursorPosition(mUnsignedEditPos);
ui->asciiLineEdit->setCursorPosition(mAsciiLineEditPos);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/WordEditDialog.h | #pragma once
#include <QValidator>
#include <QDialog>
#include <QPushButton>
#include "Imports.h"
class ValidateExpressionThread;
namespace Ui
{
class WordEditDialog;
}
class WordEditDialog : public QDialog
{
Q_OBJECT
public:
explicit WordEditDialog(QWidget* parent = 0);
~WordEditDialog();
void validateExpression(QString expression);
void setup(QString title, duint defVal, int byteCount);
duint getVal();
void showEvent(QShowEvent* event);
void hideEvent(QHideEvent* event);
protected:
void saveCursorPositions();
void restoreCursorPositions();
private slots:
void expressionChanged(bool validExpression, bool validPointer, dsint value);
void on_signedLineEdit_textEdited(const QString & arg1);
void on_unsignedLineEdit_textEdited(const QString & arg1);
private:
QString convertValueToHexString(duint value);
Ui::WordEditDialog* ui;
duint mWord;
ValidateExpressionThread* mValidateThread;
int mHexLineEditPos;
int mSignedEditPos;
int mUnsignedEditPos;
int mAsciiLineEditPos;
int byteCount;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/WordEditDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WordEditDialog</class>
<widget class="QDialog" name="WordEditDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>260</width>
<height>166</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Edit</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">
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Expression:</string>
</property>
<property name="buddy">
<cstring>expressionLineEdit</cstring>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="signedLineEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>140</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>Lucida Console</family>
</font>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="hexLineEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>140</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>Lucida Console</family>
</font>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Bytes:</string>
</property>
<property name="buddy">
<cstring>hexLineEdit</cstring>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Unsigned:</string>
</property>
<property name="buddy">
<cstring>unsignedLineEdit</cstring>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>ASCII:</string>
</property>
<property name="buddy">
<cstring>asciiLineEdit</cstring>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Signed:</string>
</property>
<property name="buddy">
<cstring>signedLineEdit</cstring>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLineEdit" name="unsignedLineEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>140</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>Lucida Console</family>
</font>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLineEdit" name="asciiLineEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>140</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>Lucida Console</family>
</font>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="expressionLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>140</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>Lucida Console</family>
</font>
</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="QHBoxLayout" name="layoutOkCancel">
<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="btnOk">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnCancel">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>expressionLineEdit</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnOk</sender>
<signal>clicked()</signal>
<receiver>WordEditDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>109</x>
<y>147</y>
</hint>
<hint type="destinationlabel">
<x>48</x>
<y>136</y>
</hint>
</hints>
</connection>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>WordEditDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>215</x>
<y>138</y>
</hint>
<hint type="destinationlabel">
<x>260</x>
<y>128</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/XrefBrowseDialog.cpp | #include "XrefBrowseDialog.h"
#include "ui_XrefBrowseDialog.h"
#include "StringUtil.h"
#include "MiscUtil.h"
#include "MenuBuilder.h"
XrefBrowseDialog::XrefBrowseDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::XrefBrowseDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setWindowIcon(DIcon("xrefs"));
setModal(false);
mXrefInfo.refcount = 0;
ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(onDebuggerClose(DBGSTATE)));
setupContextMenu();
}
QString XrefBrowseDialog::GetFunctionSymbol(duint addr)
{
QString line;
char clabel[MAX_LABEL_SIZE] = "";
DbgGetLabelAt(addr, SEG_DEFAULT, clabel);
if(*clabel)
line = QString(clabel);
else
{
duint start;
if(DbgFunctionGet(addr, &start, nullptr) && DbgGetLabelAt(start, SEG_DEFAULT, clabel) && start != addr)
line = QString("%1+%2").arg(clabel).arg(ToHexString(addr - start));
else
line = QString("%1").arg(ToHexString(addr));
}
return line;
}
void XrefBrowseDialog::setup(duint address, GotoFunction gotoFunction)
{
if(mXrefInfo.refcount)
{
BridgeFree(mXrefInfo.references);
mXrefInfo.refcount = 0;
}
mAddress = address;
mGotoFunction = std::move(gotoFunction);
mPrevSelectionSize = 0;
ui->listWidget->clear();
if(DbgXrefGet(address, &mXrefInfo))
{
std::vector<XREF_RECORD> data;
for(duint i = 0; i < mXrefInfo.refcount; i++)
data.push_back(mXrefInfo.references[i]);
std::sort(data.begin(), data.end(), [](const XREF_RECORD A, const XREF_RECORD B)
{
if(A.type != B.type)
return (A.type < B.type);
return (A.addr < B.addr);
});
for(duint i = 0; i < mXrefInfo.refcount; i++)
mXrefInfo.references[i] = data[i];
data.clear();
char disasm[GUI_MAX_DISASSEMBLY_SIZE] = "";
setWindowTitle(QString(tr("xrefs at <%1>")).arg(GetFunctionSymbol(address)));
for(duint i = 0; i < mXrefInfo.refcount; i++)
{
if(GuiGetDisassembly(mXrefInfo.references[i].addr, disasm))
ui->listWidget->addItem(disasm);
else
ui->listWidget->addItem("???");
}
ui->listWidget->setCurrentRow(0);
}
ui->listWidget->setFocus();
}
void XrefBrowseDialog::setupContextMenu()
{
mMenu = new MenuBuilder(this);
mMenu->addAction(makeAction(DIcon("breakpoint_toggle"), tr("Toggle &Breakpoint"), SLOT(breakpointSlot())));
//Breakpoint (hardware access) menu
auto hardwareAccessMenu = makeMenu(DIcon("breakpoint_access"), tr("Hardware, Access"));
hardwareAccessMenu->addAction(makeAction(DIcon("breakpoint_byte"), tr("&Byte"), SLOT(hardwareAccess1Slot())));
hardwareAccessMenu->addAction(makeAction(DIcon("breakpoint_word"), tr("&Word"), SLOT(hardwareAccess2Slot())));
hardwareAccessMenu->addAction(makeAction(DIcon("breakpoint_dword"), tr("&Dword"), SLOT(hardwareAccess4Slot())));
#ifdef _WIN64
hardwareAccessMenu->addAction(makeAction(DIcon("breakpoint_qword"), tr("&Qword"), SLOT(hardwareAccess8Slot())));
#endif //_WIN64
//Breakpoint (hardware write) menu
auto hardwareWriteMenu = makeMenu(DIcon("breakpoint_write"), tr("Hardware, Write"));
hardwareWriteMenu->addAction(makeAction(DIcon("breakpoint_byte"), tr("&Byte"), SLOT(hardwareWrite1Slot())));
hardwareWriteMenu->addAction(makeAction(DIcon("breakpoint_word"), tr("&Word"), SLOT(hardwareWrite2Slot())));
hardwareWriteMenu->addAction(makeAction(DIcon("breakpoint_dword"), tr("&Dword"), SLOT(hardwareWrite4Slot())));
#ifdef _WIN64
hardwareWriteMenu->addAction(makeAction(DIcon("breakpoint_qword"), tr("&Qword"), SLOT(hardwareAccess8Slot())));
#endif //_WIN64
//Breakpoint (remove hardware)
auto hardwareRemove = makeAction(DIcon("breakpoint_remove"), tr("Remove &Hardware"), SLOT(hardwareRemoveSlot()));
//Breakpoint (memory access) menu
auto memoryAccessMenu = makeMenu(DIcon("breakpoint_memory_access"), tr("Memory, Access"));
memoryAccessMenu->addAction(makeAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), SLOT(memoryAccessSingleshootSlot())));
memoryAccessMenu->addAction(makeAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), SLOT(memoryAccessRestoreSlot())));
//Breakpoint (memory write) menu
auto memoryWriteMenu = makeMenu(DIcon("breakpoint_memory_write"), tr("Memory, Write"));
memoryWriteMenu->addAction(makeAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), SLOT(memoryWriteSingleshootSlot())));
memoryWriteMenu->addAction(makeAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), SLOT(memoryWriteRestoreSlot())));
//Breakpoint (remove memory) menu
auto memoryRemove = makeAction(DIcon("breakpoint_remove"), tr("Remove &Memory"), SLOT(memoryRemoveSlot()));
//Breakpoint menu
auto breakpointMenu = new MenuBuilder(this);
//Breakpoint menu
breakpointMenu->addBuilder(new MenuBuilder(this, [ = ](QMenu * menu)
{
duint selectedAddr = mXrefInfo.references[ui->listWidget->currentRow()].addr;
if(DbgGetBpxTypeAt(selectedAddr) & bp_hardware) //hardware breakpoint set
{
menu->addAction(hardwareRemove);
}
else //memory breakpoint not set
{
menu->addMenu(hardwareAccessMenu);
menu->addMenu(hardwareWriteMenu);
}
menu->addSeparator();
if(DbgGetBpxTypeAt(selectedAddr) & bp_memory) //memory breakpoint set
{
menu->addAction(memoryRemove);
}
else //memory breakpoint not set
{
menu->addMenu(memoryAccessMenu);
menu->addMenu(memoryWriteMenu);
}
return true;
}));
mMenu->addMenu(makeMenu(DIcon("breakpoint"), tr("Brea&kpoint")), breakpointMenu);
mMenu->addAction(makeAction(DIcon("breakpoint_toggle"), tr("Toggle breakpoints on all xrefs"), SLOT(breakpointAllSlot())));
auto mCopyMenu = new MenuBuilder(mMenu);
mCopyMenu->addAction(makeAction(tr("Selected xref"), SLOT(copyThisSlot())));
mCopyMenu->addAction(makeAction(tr("All xrefs"), SLOT(copyAllSlot())));
mMenu->addMenu(makeMenu(DIcon("copy"), tr("Copy")), mCopyMenu);
mMenu->loadFromConfig();
}
void XrefBrowseDialog::changeAddress(duint address)
{
mGotoFunction(address);
}
XrefBrowseDialog::~XrefBrowseDialog()
{
delete ui;
if(mXrefInfo.refcount)
BridgeFree(mXrefInfo.references);
}
void XrefBrowseDialog::on_listWidget_itemDoubleClicked(QListWidgetItem*)
{
accept();
}
void XrefBrowseDialog::on_listWidget_itemSelectionChanged()
{
if(ui->listWidget->selectedItems().size() != mPrevSelectionSize)
{
duint address;
if(mPrevSelectionSize == 0)
address = mXrefInfo.references[ui->listWidget->currentRow()].addr;
else
address = mAddress;
changeAddress(address);
}
mPrevSelectionSize = ui->listWidget->selectedItems().size();
}
void XrefBrowseDialog::on_listWidget_currentRowChanged(int row)
{
if(ui->listWidget->selectedItems().size() != 0)
{
duint address = mXrefInfo.references[row].addr;
changeAddress(address);
}
}
void XrefBrowseDialog::on_XrefBrowseDialog_rejected()
{
if(DbgIsDebugging())
mGotoFunction(mAddress);
}
void XrefBrowseDialog::on_listWidget_itemClicked(QListWidgetItem*)
{
on_listWidget_currentRowChanged(ui->listWidget->currentRow());
}
void XrefBrowseDialog::on_listWidget_customContextMenuRequested(const QPoint & pos)
{
QMenu menu(this);
mMenu->build(&menu);
menu.exec(ui->listWidget->mapToGlobal(pos));
}
/**
* @brief XrefBrowseDialog::onDebuggerClose Close this dialog when the debuggee stops.
* @param state The argument passed in representing the debugger state.
*/
void XrefBrowseDialog::onDebuggerClose(DBGSTATE state)
{
if(state == stopped)
emit close();
}
void XrefBrowseDialog::breakpointSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
if(DbgGetBpxTypeAt(mXrefInfo.references[ui->listWidget->currentRow()].addr) & bp_normal)
DbgCmdExec(QString("bc " + addr_text));
else
DbgCmdExec(QString("bp " + addr_text));
}
void XrefBrowseDialog::hardwareAccess1Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", r, 1"));
}
void XrefBrowseDialog::hardwareAccess2Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", r, 2"));
}
void XrefBrowseDialog::hardwareAccess4Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", r, 4"));
}
void XrefBrowseDialog::hardwareAccess8Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", r, 8"));
}
void XrefBrowseDialog::hardwareWrite1Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", w, 1"));
}
void XrefBrowseDialog::hardwareWrite2Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", w, 2"));
}
void XrefBrowseDialog::hardwareWrite4Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", w, 4"));
}
void XrefBrowseDialog::hardwareWrite8Slot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphws " + addr_text + ", w, 8"));
}
void XrefBrowseDialog::hardwareRemoveSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bphwc " + addr_text));
}
void XrefBrowseDialog::memoryAccessSingleshootSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bpm " + addr_text + ", 0, a"));
}
void XrefBrowseDialog::memoryAccessRestoreSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bpm " + addr_text + ", 1, a"));
}
void XrefBrowseDialog::memoryWriteSingleshootSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bpm " + addr_text + ", 0, w"));
}
void XrefBrowseDialog::memoryWriteRestoreSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bpm " + addr_text + ", 1, w"));
}
void XrefBrowseDialog::memoryRemoveSlot()
{
QString addr_text = ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr);
DbgCmdExec(QString("bpmc " + addr_text));
}
void XrefBrowseDialog::copyThisSlot()
{
Bridge::CopyToClipboard(ToPtrString(mXrefInfo.references[ui->listWidget->currentRow()].addr) + " " + ui->listWidget->selectedItems()[0]->text());
}
void XrefBrowseDialog::breakpointAllSlot()
{
for(int i = 0; i < ui->listWidget->count(); i++)
{
QString addr_text = ToPtrString(mXrefInfo.references[i].addr);
if(DbgGetBpxTypeAt(mXrefInfo.references[i].addr) & bp_normal)
DbgCmdExec(QString("bc " + addr_text));
else
DbgCmdExec(QString("bp " + addr_text));
}
}
void XrefBrowseDialog::copyAllSlot()
{
QString temp;
for(int i = 0; i < ui->listWidget->count(); i++)
{
temp.append(ToPtrString(mXrefInfo.references[i].addr) + " ");
temp.append(ui->listWidget->selectedItems()[0]->text());
temp.append("\r\n");
}
Bridge::CopyToClipboard(temp);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/XrefBrowseDialog.h | #pragma once
#include "Bridge.h"
#include "ActionHelpers.h"
#include <QDialog>
#include <QListWidgetItem>
namespace Ui
{
class XrefBrowseDialog;
}
class XrefBrowseDialog : public QDialog, public ActionHelper<XrefBrowseDialog>
{
Q_OBJECT
public:
explicit XrefBrowseDialog(QWidget* parent);
~XrefBrowseDialog();
using GotoFunction = std::function<void(duint)>;
void setup(duint address, GotoFunction gotoFunction);
private slots:
void on_listWidget_itemDoubleClicked(QListWidgetItem* item);
void on_listWidget_itemSelectionChanged();
void on_listWidget_currentRowChanged(int currentRow);
void on_XrefBrowseDialog_rejected();
void on_listWidget_itemClicked(QListWidgetItem* item);
void on_listWidget_customContextMenuRequested(const QPoint & pos);
void onDebuggerClose(DBGSTATE state);
void memoryAccessSingleshootSlot();
void memoryAccessRestoreSlot();
void memoryWriteSingleshootSlot();
void memoryWriteRestoreSlot();
void memoryRemoveSlot();
void hardwareAccess1Slot();
void hardwareAccess2Slot();
void hardwareAccess4Slot();
void hardwareAccess8Slot();
void hardwareWrite1Slot();
void hardwareWrite2Slot();
void hardwareWrite4Slot();
void hardwareWrite8Slot();
void hardwareRemoveSlot();
void breakpointSlot();
void copyThisSlot();
void copyAllSlot();
void breakpointAllSlot();
private:
Ui::XrefBrowseDialog* ui;
void changeAddress(duint address);
void setupContextMenu();
QString GetFunctionSymbol(duint addr);
XREF_INFO mXrefInfo;
duint mAddress;
int mPrevSelectionSize;
MenuBuilder* mMenu;
GotoFunction mGotoFunction;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/XrefBrowseDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>XrefBrowseDialog</class>
<widget class="QDialog" name="XrefBrowseDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>328</width>
<height>426</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListWidget" name="listWidget">
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
</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="pushButton">
<property name="text">
<string>&OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_2">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>pushButton</sender>
<signal>clicked()</signal>
<receiver>XrefBrowseDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>167</x>
<y>398</y>
</hint>
<hint type="destinationlabel">
<x>141</x>
<y>398</y>
</hint>
</hints>
</connection>
<connection>
<sender>pushButton_2</sender>
<signal>clicked()</signal>
<receiver>XrefBrowseDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>266</x>
<y>405</y>
</hint>
<hint type="destinationlabel">
<x>324</x>
<y>396</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/ZehSymbolTable.cpp | #include "ZehSymbolTable.h"
#include "Bridge.h"
#include "RichTextPainter.h"
class SymbolInfoWrapper
{
void free()
{
if(info.freeDecorated)
BridgeFree(info.decoratedSymbol);
if(info.freeUndecorated)
BridgeFree(info.undecoratedSymbol);
}
SYMBOLINFO info{};
public:
SymbolInfoWrapper() = default;
~SymbolInfoWrapper() { free(); }
SymbolInfoWrapper(const SymbolInfoWrapper &) = delete;
SymbolInfoWrapper & operator=(const SymbolInfoWrapper &) = delete;
SYMBOLINFO* put()
{
free();
memset(&info, 0, sizeof(info));
return &info;
}
SYMBOLINFO* get() { return &info; }
const SYMBOLINFO* get() const { return &info; }
SYMBOLINFO* operator->() { return &info; }
const SYMBOLINFO* operator->() const { return &info; }
};
ZehSymbolTable::ZehSymbolTable(QWidget* parent)
: AbstractStdTable(parent),
mMutex(QMutex::Recursive)
{
auto charwidth = getCharWidth();
enableMultiSelection(true);
setAddressColumn(0);
addColumnAt(charwidth * 2 * sizeof(dsint) + 8, tr("Address"), true);
addColumnAt(charwidth * 6 + 8, tr("Type"), true);
addColumnAt(charwidth * 7 + 8, tr("Ordinal"), true);
addColumnAt(charwidth * 80, tr("Symbol"), true);
addColumnAt(2000, tr("Symbol (undecorated)"), true);
loadColumnFromConfig("Symbol");
trImport = tr("Import");
trExport = tr("Export");
trSymbol = tr("Symbol");
Initialize();
}
QString ZehSymbolTable::getCellContent(int r, int c)
{
QMutexLocker lock(&mMutex);
if(!isValidIndex(r, c))
return QString();
SymbolInfoWrapper info;
DbgGetSymbolInfo(&mData.at(r), info.put());
return symbolInfoString(info.get(), c);
}
bool ZehSymbolTable::isValidIndex(int r, int c)
{
QMutexLocker lock(&mMutex);
return r >= 0 && r < (int)mData.size() && c >= 0 && c <= ColUndecorated;
}
void ZehSymbolTable::sortRows(int column, bool ascending)
{
QMutexLocker lock(&mMutex);
std::stable_sort(mData.begin(), mData.end(), [this, column, ascending](const SYMBOLPTR & a, const SYMBOLPTR & b)
{
SymbolInfoWrapper ainfo, binfo;
DbgGetSymbolInfo(&a, ainfo.put());
DbgGetSymbolInfo(&b, binfo.put());
switch(column)
{
case ColAddr:
return ascending ? ainfo->addr < binfo->addr : ainfo->addr > binfo->addr;
case ColType:
return ascending ? ainfo->type < binfo->type : ainfo->type > binfo->type;
case ColOrdinal:
// If we are sorting by ordinal make the exports the first entries
if(ainfo->type == sym_export && binfo->type != sym_export)
return ascending;
else if(ainfo->type != sym_export && binfo->type == sym_export)
return !ascending;
else
return ascending ? ainfo->ordinal < binfo->ordinal : ainfo->ordinal > binfo->ordinal;
case ColDecorated:
{
auto acell = symbolInfoString(ainfo.get(), ColDecorated);
auto bcell = symbolInfoString(binfo.get(), ColDecorated);
int result = QString::compare(acell, bcell);
return ascending ? result < 0 : result > 0;
}
case ColUndecorated:
{
auto acell = symbolInfoString(ainfo.get(), ColUndecorated);
auto bcell = symbolInfoString(binfo.get(), ColUndecorated);
int result = QString::compare(acell, bcell);
return ascending ? result < 0 : result > 0;
}
default:
return false;
}
});
}
QString ZehSymbolTable::symbolInfoString(const SYMBOLINFO* info, int c)
{
switch(c)
{
case ColAddr:
return ToPtrString(info->addr);
case ColType:
switch(info->type)
{
case sym_import:
return trImport;
case sym_export:
return trExport;
case sym_symbol:
return trSymbol;
default:
__debugbreak();
}
case ColOrdinal:
if(info->type == sym_export)
return QString::number(info->ordinal);
else
return QString();
case ColDecorated:
{
char modname[MAX_MODULE_SIZE];
// Get module name for import symbols
if(info->type == sym_import)
{
duint wVA;
if(DbgMemRead(info->addr, &wVA, sizeof(duint)))
if(DbgGetModuleAt(wVA, modname))
return QString(modname).append('.').append(info->decoratedSymbol);
}
return info->decoratedSymbol;
}
case ColUndecorated:
{
if(*info->undecoratedSymbol == '\0' && strstr(info->decoratedSymbol, "Ordinal") == info->decoratedSymbol)
{
char label[MAX_LABEL_SIZE] = "";
switch(info->type)
{
case sym_import:
{
duint wVA;
if(DbgMemRead(info->addr, &wVA, sizeof(duint)))
{
DbgGetLabelAt(wVA, SEG_DEFAULT, label);
return label;
}
}
break;
case sym_export:
{
DbgGetLabelAt(info->addr, SEG_DEFAULT, label);
return label;
}
break;
default:
break;
}
}
return info->undecoratedSymbol;
}
default:
return QString();
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ZehSymbolTable.h | #pragma once
#include "AbstractStdTable.h"
#include <QMutex>
class ZehSymbolTable : public AbstractStdTable
{
Q_OBJECT
public:
ZehSymbolTable(QWidget* parent = nullptr);
QString getCellContent(int r, int c) override;
bool isValidIndex(int r, int c) override;
void sortRows(int column, bool ascending) override;
friend class SymbolView;
friend class SearchListViewSymbols;
friend class SymbolSearchList;
private:
std::vector<duint> mModules;
std::vector<SYMBOLPTR> mData;
QMutex mMutex;
//Caching of translations to fix a bottleneck
QString trImport;
QString trExport;
QString trSymbol;
enum
{
ColAddr,
ColType,
ColOrdinal,
ColDecorated,
ColUndecorated
};
QString symbolInfoString(const SYMBOLINFO* info, int c);
}; |
C++ | x64dbg-development/src/gui/Src/Memory/MemoryPage.cpp | #include "MemoryPage.h"
MemoryPage::MemoryPage(duint parBase, duint parSize, QObject* parent) : QObject(parent), mBase(0), mSize(0)
{
Q_UNUSED(parBase);
Q_UNUSED(parSize);
}
bool MemoryPage::read(void* parDest, dsint parRVA, duint parSize) const
{
return DbgMemRead(mBase + parRVA, reinterpret_cast<unsigned char*>(parDest), parSize);
}
bool MemoryPage::write(const void* parDest, dsint parRVA, duint parSize)
{
bool ret = DbgFunctions()->MemPatch(mBase + parRVA, reinterpret_cast<const unsigned char*>(parDest), parSize);
GuiUpdatePatches();
return ret;
}
duint MemoryPage::getSize() const
{
return mSize;
}
duint MemoryPage::getBase() const
{
return mBase;
}
duint MemoryPage::va(dsint rva) const
{
return mBase + rva;
}
void MemoryPage::setAttributes(duint base, duint size)
{
mBase = base;
mSize = size;
}
bool MemoryPage::inRange(duint va) const
{
return va >= mBase && va < mBase + mSize;
} |
C/C++ | x64dbg-development/src/gui/Src/Memory/MemoryPage.h | #pragma once
#include <QObject>
#include "Imports.h"
class MemoryPage : public QObject
{
Q_OBJECT
public:
explicit MemoryPage(duint parBase, duint parSize, QObject* parent = 0);
bool read(void* parDest, dsint parRVA, duint parSize) const;
bool write(const void* parDest, dsint parRVA, duint parSize);
duint getSize() const;
duint getBase() const;
duint va(dsint rva) const;
void setAttributes(duint base, duint size);
bool inRange(duint va) const;
private:
duint mBase;
duint mSize;
}; |
C++ | x64dbg-development/src/gui/Src/QHexEdit/ArrayCommand.cpp | #include "ArrayCommand.h"
#include "XByteArray.h"
CharCommand::CharCommand(XByteArray* xData, Cmd cmd, int charPos, char newChar, QUndoCommand* parent) : QUndoCommand(parent)
{
_xData = xData;
_charPos = charPos;
_newChar = newChar;
_cmd = cmd;
_oldChar = 0;
}
bool CharCommand::mergeWith(const QUndoCommand* command)
{
const CharCommand* nextCommand = static_cast<const CharCommand*>(command);
bool result = false;
if(_cmd != remove)
{
if(nextCommand->_cmd == replace)
if(nextCommand->_charPos == _charPos)
{
_newChar = nextCommand->_newChar;
result = true;
}
}
return result;
}
void CharCommand::undo()
{
switch(_cmd)
{
case insert:
_xData->remove(_charPos, 1);
break;
case replace:
_xData->replace(_charPos, _oldChar);
break;
case remove:
_xData->insert(_charPos, _oldChar);
break;
}
}
void CharCommand::redo()
{
switch(_cmd)
{
case insert:
_xData->insert(_charPos, _newChar);
break;
case replace:
_oldChar = _xData->data()[_charPos];
_xData->replace(_charPos, _newChar);
break;
case remove:
_oldChar = _xData->data()[_charPos];
_xData->remove(_charPos, 1);
break;
}
}
ArrayCommand::ArrayCommand(XByteArray* xData, Cmd cmd, int baPos, QByteArray newBa, int len, QUndoCommand* parent)
: QUndoCommand(parent)
{
_cmd = cmd;
_xData = xData;
_baPos = baPos;
_newBa = newBa;
_len = len;
}
void ArrayCommand::undo()
{
switch(_cmd)
{
case insert:
_xData->remove(_baPos, _newBa.length());
break;
case replace:
_xData->replace(_baPos, _oldBa);
break;
case remove:
_xData->insert(_baPos, _oldBa);
break;
}
}
void ArrayCommand::redo()
{
switch(_cmd)
{
case insert:
_xData->insert(_baPos, _newBa);
break;
case replace:
_oldBa = _xData->data().mid(_baPos, _len);
_xData->replace(_baPos, _newBa);
break;
case remove:
_oldBa = _xData->data().mid(_baPos, _len);
_xData->remove(_baPos, _len);
break;
}
} |
C/C++ | x64dbg-development/src/gui/Src/QHexEdit/ArrayCommand.h | #pragma once
#include <QUndoCommand>
#include <QByteArray>
class XByteArray;
class CharCommand : public QUndoCommand
{
public:
enum { Id = 1234 };
enum Cmd {insert, remove, replace};
CharCommand(XByteArray* xData, Cmd cmd, int charPos, char newChar,
QUndoCommand* parent = 0);
void undo();
void redo();
bool mergeWith(const QUndoCommand* command);
int id() const
{
return Id;
}
private:
XByteArray* _xData;
int _charPos;
char _newChar;
char _oldChar;
Cmd _cmd;
};
class ArrayCommand : public QUndoCommand
{
public:
enum Cmd {insert, remove, replace};
ArrayCommand(XByteArray* xData, Cmd cmd, int baPos, QByteArray newBa = QByteArray(), int len = 0, QUndoCommand* parent = 0);
void undo();
void redo();
private:
Cmd _cmd;
XByteArray* _xData;
int _baPos;
int _len;
QByteArray _wasChanged;
QByteArray _newBa;
QByteArray _oldBa;
}; |
C++ | x64dbg-development/src/gui/Src/QHexEdit/QHexEdit.cpp | #include <QtGui>
#include "QHexEdit.h"
#include "QHexEditPrivate.h"
QHexEdit::QHexEdit(QWidget* parent) : QScrollArea(parent)
{
qHexEdit_p = new QHexEditPrivate(this);
setWidget(qHexEdit_p);
setWidgetResizable(true);
connect(qHexEdit_p, SIGNAL(currentAddressChanged(int)), this, SIGNAL(currentAddressChanged(int)));
connect(qHexEdit_p, SIGNAL(currentSizeChanged(int)), this, SIGNAL(currentSizeChanged(int)));
connect(qHexEdit_p, SIGNAL(dataChanged()), this, SIGNAL(dataChanged()));
connect(qHexEdit_p, SIGNAL(dataEdited()), this, SIGNAL(dataEdited()));
connect(qHexEdit_p, SIGNAL(overwriteModeChanged(bool)), this, SIGNAL(overwriteModeChanged(bool)));
setFocusPolicy(Qt::NoFocus);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
}
void QHexEdit::setEditFont(const QFont & font)
{
qHexEdit_p->setFont(font);
}
void QHexEdit::insert(int i, const QByteArray & ba, const QByteArray & mask)
{
qHexEdit_p->insert(i, ba, mask);
}
void QHexEdit::insert(int i, char ch, char mask)
{
qHexEdit_p->insert(i, ch, mask);
}
void QHexEdit::remove(int pos, int len)
{
qHexEdit_p->remove(pos, len);
}
void QHexEdit::replace(int pos, int len, const QByteArray & after, const QByteArray & mask)
{
qHexEdit_p->replace(pos, len, after, mask);
}
void QHexEdit::fill(int index, const QString & pattern)
{
QString convert;
for(int i = 0; i < pattern.length(); i++)
{
QChar ch = pattern[i].toLower();
if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (wildcardEnabled() && ch == '?'))
convert += ch;
}
if(!convert.length())
return;
if(convert.length() % 2) //odd length
convert += "0";
QByteArray data(convert.length(), 0);
QByteArray mask(data.length(), 0);
for(int i = 0; i < convert.length(); i++)
{
if(convert[i] == '?')
{
data[i] = '0';
mask[i] = '1';
}
else
{
data[i] = convert[i].toLatin1();
mask[i] = '0';
}
}
qHexEdit_p->fill(index, QByteArray().fromHex(data), QByteArray().fromHex(mask));
}
void QHexEdit::redo()
{
qHexEdit_p->redo();
}
void QHexEdit::undo()
{
qHexEdit_p->undo();
}
void QHexEdit::setCursorPosition(int cursorPos)
{
// cursorPos in QHexEditPrivate is the position of the textcoursor without
// blanks, means bytePos*2
qHexEdit_p->setCursorPos(cursorPos * 2);
}
int QHexEdit::cursorPosition()
{
return qHexEdit_p->cursorPos() / 2;
}
void QHexEdit::setData(const QByteArray & data, const QByteArray & mask)
{
qHexEdit_p->setData(data, mask);
}
void QHexEdit::setData(const QByteArray & data)
{
qHexEdit_p->setData(data, QByteArray(data.size(), 0));
}
void QHexEdit::setData(const QString & pattern)
{
QString convert;
for(int i = 0; i < pattern.length(); i++)
{
QChar ch = pattern[i].toLower();
if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (wildcardEnabled() && ch == '?'))
convert += ch;
}
if(convert.length() % 2) //odd length
convert += "0";
QByteArray data(convert.length(), 0);
QByteArray mask(data.length(), 0);
for(int i = 0; i < convert.length(); i++)
{
if(convert[i] == '?')
{
data[i] = '0';
mask[i] = '1';
}
else
{
data[i] = convert[i].toLatin1();
mask[i] = '0';
}
}
qHexEdit_p->setData(QByteArray().fromHex(data), QByteArray().fromHex(mask));
}
QByteArray QHexEdit::applyMaskedData(const QByteArray & data)
{
QByteArray ret = data.toHex();
QByteArray _data = this->data().toHex();
QByteArray _mask = this->mask().toHex();
if(ret.size() != _data.size())
ret.resize(_data.size());
for(int i = 0; i < _data.size(); i++)
{
if(_mask[i] != '1')
ret[i] = _data[i];
}
return QByteArray().fromHex(ret);
}
QByteArray QHexEdit::data()
{
return qHexEdit_p->data();
}
QByteArray QHexEdit::mask()
{
return qHexEdit_p->mask();
}
QString QHexEdit::pattern(bool space)
{
QString result;
for(int i = 0; i < this->data().size(); i++)
{
QString byte = this->data().mid(i, 1).toHex();
QString mask = this->mask().mid(i, 1).toHex();
if(mask[0] == '1')
result += "?";
else
result += byte[0];
if(mask[1] == '1')
result += "?";
else
result += byte[1];
if(space)
result += " ";
}
return result.toUpper().trimmed();
}
void QHexEdit::setOverwriteMode(bool overwriteMode)
{
qHexEdit_p->setOverwriteMode(overwriteMode);
}
bool QHexEdit::overwriteMode()
{
return qHexEdit_p->overwriteMode();
}
void QHexEdit::setWildcardEnabled(bool enabled)
{
qHexEdit_p->setWildcardEnabled(enabled);
}
bool QHexEdit::wildcardEnabled()
{
return qHexEdit_p->wildcardEnabled();
}
void QHexEdit::setKeepSize(bool enabled)
{
qHexEdit_p->setKeepSize(enabled);
}
bool QHexEdit::keepSize()
{
return qHexEdit_p->keepSize();
}
void QHexEdit::setTextColor(QColor color)
{
qHexEdit_p->setTextColor(color);
}
void QHexEdit::setHorizontalSpacing(int x)
{
qHexEdit_p->setHorizontalSpacing(x);
}
int QHexEdit::horizontalSpacing()
{
return qHexEdit_p->horizontalSpacing();
}
QColor QHexEdit::textColor()
{
return qHexEdit_p->textColor();
}
void QHexEdit::setWildcardColor(QColor color)
{
qHexEdit_p->setWildcardColor(color);
}
QColor QHexEdit::wildcardColor()
{
return qHexEdit_p->wildcardColor();
}
void QHexEdit::setBackgroundColor(QColor color)
{
qHexEdit_p->setBackgroundColor(color);
}
QColor QHexEdit::backgroundColor()
{
return qHexEdit_p->backgroundColor();
}
void QHexEdit::setSelectionColor(QColor color)
{
qHexEdit_p->setSelectionColor(color);
}
QColor QHexEdit::selectionColor()
{
return qHexEdit_p->selectionColor();
} |
C/C++ | x64dbg-development/src/gui/Src/QHexEdit/QHexEdit.h | #pragma once
#include <QScrollArea>
class QHexEditPrivate;
class QHexEdit : public QScrollArea
{
Q_OBJECT
public:
QHexEdit(QWidget* parent = 0);
//data management
void setData(const QByteArray & data, const QByteArray & mask);
void setData(const QByteArray & data);
void setData(const QString & pattern);
QByteArray applyMaskedData(const QByteArray & data);
QByteArray data();
QByteArray mask();
QString pattern(bool space = false);
void insert(int i, const QByteArray & ba, const QByteArray & mask);
void insert(int i, char ch, char mask);
void remove(int pos, int len = 1);
void replace(int pos, int len, const QByteArray & after, const QByteArray & mask);
void fill(int index, const QString & pattern);
//properties
void setCursorPosition(int cusorPos);
int cursorPosition();
void setOverwriteMode(bool overwriteMode);
bool overwriteMode();
void setWildcardEnabled(bool enabled);
bool wildcardEnabled();
void setKeepSize(bool enabled);
bool keepSize();
void setHorizontalSpacing(int x);
int horizontalSpacing();
void setTextColor(QColor color);
QColor textColor();
void setWildcardColor(QColor color);
QColor wildcardColor();
void setBackgroundColor(QColor color);
QColor backgroundColor();
void setSelectionColor(QColor color);
QColor selectionColor();
void setEditFont(const QFont & font);
public slots:
void redo();
void undo();
signals:
void currentAddressChanged(int address);
void currentSizeChanged(int size);
void dataChanged();
void dataEdited();
void overwriteModeChanged(bool state);
private:
QHexEditPrivate* qHexEdit_p;
}; |
C++ | x64dbg-development/src/gui/Src/QHexEdit/QHexEditPrivate.cpp | #include "QHexEditPrivate.h"
#include <QApplication>
#include <QClipboard>
#include <QPainter>
#include "ArrayCommand.h"
const int HEXCHARS_IN_LINE = 47;
const int BYTES_PER_LINE = 16;
QHexEditPrivate::QHexEditPrivate(QScrollArea* parent) : QWidget(parent)
{
_undoDataStack = new QUndoStack(this);
_undoMaskStack = new QUndoStack(this);
_scrollArea = parent;
setOverwriteMode(true);
QFont font("Monospace", 8, QFont::Normal, false);
font.setFixedPitch(true);
font.setStyleHint(QFont::Monospace);
this->setFont(font);
_size = 0;
_horizonalSpacing = 3;
resetSelection(0);
setCursorPos(0);
setFocusPolicy(Qt::StrongFocus);
connect(&_cursorTimer, SIGNAL(timeout()), this, SLOT(updateCursor()));
_cursorTimer.setInterval(500);
_cursorTimer.start();
_textColor = QColor("#000000");
_wildcardColor = QColor("#FF0000");
_backgroundColor = QColor("#FFF8F0");
_selectionColor = QColor("#C0C0C0");
_overwriteMode = false;
_wildcardEnabled = true;
_keepSize = false;
}
void QHexEditPrivate::setData(const QByteArray & data, const QByteArray & mask)
{
_xData.setData(data);
_xMask.setData(mask);
_undoDataStack->clear();
_undoMaskStack->clear();
_initSize = _xData.size();
adjust();
setCursorPos(0);
emit dataChanged();
}
QByteArray QHexEditPrivate::data()
{
return _xData.data();
}
QByteArray QHexEditPrivate::mask()
{
return _xMask.data();
}
void QHexEditPrivate::insert(int index, const QByteArray & ba, const QByteArray & mask)
{
if(ba.length() > 0)
{
if(_overwriteMode)
{
_undoDataStack->push(new ArrayCommand(&_xData, ArrayCommand::replace, index, ba, ba.length()));
_undoMaskStack->push(new ArrayCommand(&_xMask, ArrayCommand::replace, index, mask, mask.length()));
}
else
{
_undoDataStack->push(new ArrayCommand(&_xData, ArrayCommand::insert, index, ba, ba.length()));
_undoMaskStack->push(new ArrayCommand(&_xMask, ArrayCommand::insert, index, mask, mask.length()));
}
emit dataChanged();
emit dataEdited();
}
}
void QHexEditPrivate::insert(int index, char ch, char mask)
{
_undoDataStack->push(new CharCommand(&_xData, CharCommand::insert, index, ch));
_undoMaskStack->push(new CharCommand(&_xMask, CharCommand::insert, index, mask));
emit dataChanged();
emit dataEdited();
}
void QHexEditPrivate::remove(int index, int len)
{
if(len > 0)
{
if(len == 1)
{
if(_overwriteMode)
{
_undoDataStack->push(new CharCommand(&_xData, CharCommand::replace, index, char(0)));
_undoMaskStack->push(new CharCommand(&_xMask, CharCommand::replace, index, char(0)));
}
else
{
_undoDataStack->push(new CharCommand(&_xData, CharCommand::remove, index, char(0)));
_undoMaskStack->push(new CharCommand(&_xMask, CharCommand::remove, index, char(0)));
}
}
else
{
QByteArray ba = QByteArray(len, char(0));
if(_overwriteMode)
{
_undoDataStack->push(new ArrayCommand(&_xData, ArrayCommand::replace, index, ba, ba.length()));
_undoMaskStack->push(new ArrayCommand(&_xMask, ArrayCommand::replace, index, ba, ba.length()));
}
else
{
_undoDataStack->push(new ArrayCommand(&_xData, ArrayCommand::remove, index, ba, len));
_undoMaskStack->push(new ArrayCommand(&_xMask, ArrayCommand::remove, index, ba, len));
}
}
emit dataChanged();
emit dataEdited();
}
}
void QHexEditPrivate::replace(int index, char ch, char mask)
{
_undoDataStack->push(new CharCommand(&_xData, CharCommand::replace, index, ch));
_undoMaskStack->push(new CharCommand(&_xMask, CharCommand::replace, index, mask));
resetSelection();
emit dataChanged();
emit dataEdited();
}
void QHexEditPrivate::replace(int index, const QByteArray & ba, const QByteArray & mask)
{
_undoDataStack->push(new ArrayCommand(&_xData, ArrayCommand::replace, index, ba, ba.length()));
_undoMaskStack->push(new ArrayCommand(&_xMask, ArrayCommand::replace, index, mask, mask.length()));
resetSelection();
emit dataChanged();
emit dataEdited();
}
void QHexEditPrivate::replace(int pos, int len, const QByteArray & after, const QByteArray & mask)
{
_undoDataStack->push(new ArrayCommand(&_xData, ArrayCommand::replace, pos, after, len));
_undoMaskStack->push(new ArrayCommand(&_xMask, ArrayCommand::replace, pos, mask, len));
resetSelection();
emit dataChanged();
emit dataEdited();
}
void QHexEditPrivate::fill(int index, const QByteArray & ba, const QByteArray & mask)
{
int dataSize = _xData.size();
if(index >= dataSize)
return;
int repeat = dataSize / ba.size() + 1;
QByteArray fillData = ba.repeated(repeat);
fillData.resize(dataSize);
fillData = fillData.toHex();
QByteArray fillMask = mask.repeated(repeat);
fillMask.resize(dataSize);
fillMask = fillMask.toHex();
QByteArray origData = _xData.data().mid(index).toHex();
for(int i = 0; i < dataSize * 2; i++)
if(fillMask[i] == '1')
fillData[i] = origData[i];
this->replace(index, QByteArray().fromHex(fillData), QByteArray().fromHex(fillMask));
}
void QHexEditPrivate::setOverwriteMode(bool overwriteMode)
{
_overwriteMode = overwriteMode;
}
bool QHexEditPrivate::overwriteMode()
{
return _overwriteMode;
}
void QHexEditPrivate::setWildcardEnabled(bool enabled)
{
_wildcardEnabled = enabled;
}
bool QHexEditPrivate::wildcardEnabled()
{
return _wildcardEnabled;
}
void QHexEditPrivate::setKeepSize(bool enabled)
{
_keepSize = enabled;
}
bool QHexEditPrivate::keepSize()
{
return _keepSize;
}
void QHexEditPrivate::setHorizontalSpacing(int x)
{
_horizonalSpacing = x;
adjust();
setCursorPos(cursorPos());
this->update();
}
int QHexEditPrivate::horizontalSpacing()
{
return _horizonalSpacing;
}
void QHexEditPrivate::setTextColor(QColor color)
{
_textColor = color;
}
QColor QHexEditPrivate::textColor()
{
return _textColor;
}
void QHexEditPrivate::setWildcardColor(QColor color)
{
_wildcardColor = color;
}
QColor QHexEditPrivate::wildcardColor()
{
return _wildcardColor;
}
void QHexEditPrivate::setBackgroundColor(QColor color)
{
_backgroundColor = color;
}
QColor QHexEditPrivate::backgroundColor()
{
return _backgroundColor;
}
void QHexEditPrivate::setSelectionColor(QColor color)
{
_selectionColor = color;
}
QColor QHexEditPrivate::selectionColor()
{
return _selectionColor;
}
void QHexEditPrivate::redo()
{
if(!_undoDataStack->canRedo() || !_undoMaskStack->canRedo())
return;
_undoDataStack->redo();
_undoMaskStack->redo();
emit dataChanged();
emit dataEdited();
setCursorPos(_cursorPosition);
update();
}
void QHexEditPrivate::undo()
{
if(!_undoDataStack->canUndo() || !_undoMaskStack->canUndo())
return;
_undoDataStack->undo();
_undoMaskStack->undo();
emit dataChanged();
emit dataEdited();
setCursorPos(_cursorPosition);
update();
}
void QHexEditPrivate::focusInEvent(QFocusEvent* event)
{
ensureVisible();
QWidget::focusInEvent(event);
}
void QHexEditPrivate::resizeEvent(QResizeEvent* event)
{
adjust();
QWidget::resizeEvent(event);
}
void QHexEditPrivate::keyPressEvent(QKeyEvent* event)
{
int charX = (_cursorX - _xPosHex) / _charWidth;
int posX = (charX / 3) * 2 + (charX % 3);
int posBa = (_cursorY / _charHeight) * BYTES_PER_LINE + posX / 2;
/*****************************************************************************/
/* Cursor movements */
/*****************************************************************************/
if(event->matches(QKeySequence::MoveToNextChar))
{
setCursorPos(_cursorPosition + 1);
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToPreviousChar))
{
setCursorPos(_cursorPosition - 1);
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToEndOfLine))
{
setCursorPos(_cursorPosition | (2 * BYTES_PER_LINE - 1));
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToStartOfLine))
{
setCursorPos(_cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)));
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToPreviousLine))
{
setCursorPos(_cursorPosition - (2 * BYTES_PER_LINE));
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToNextLine))
{
setCursorPos(_cursorPosition + (2 * BYTES_PER_LINE));
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToNextPage))
{
setCursorPos(_cursorPosition + (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE));
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToPreviousPage))
{
setCursorPos(_cursorPosition - (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE));
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToEndOfDocument))
{
setCursorPos(_xData.size() * 2);
resetSelection(_cursorPosition);
}
if(event->matches(QKeySequence::MoveToStartOfDocument))
{
setCursorPos(0);
resetSelection(_cursorPosition);
}
/*****************************************************************************/
/* Select commands */
/*****************************************************************************/
if(event->matches(QKeySequence::SelectAll))
{
resetSelection(0);
setSelection(2 * _xData.size() + 1);
}
if(event->matches(QKeySequence::SelectNextChar))
{
int pos = _cursorPosition + 1;
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectPreviousChar))
{
int pos = _cursorPosition - 1;
setSelection(pos);
setCursorPos(pos);
}
if(event->matches(QKeySequence::SelectEndOfLine))
{
int pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectStartOfLine))
{
int pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE));
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectPreviousLine))
{
int pos = _cursorPosition - (2 * BYTES_PER_LINE);
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectNextLine))
{
int pos = _cursorPosition + (2 * BYTES_PER_LINE);
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectNextPage))
{
int pos = _cursorPosition + (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE);
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectPreviousPage))
{
int pos = _cursorPosition - (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE);
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectEndOfDocument))
{
int pos = _xData.size() * 2;
setCursorPos(pos);
setSelection(pos);
}
if(event->matches(QKeySequence::SelectStartOfDocument))
{
int pos = 0;
setCursorPos(pos);
setSelection(pos);
}
/*****************************************************************************/
/* Edit Commands */
/*****************************************************************************/
/* Hex input */
int key = int(event->text().toLower()[0].toLatin1());
if((key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (_wildcardEnabled && key == '?'))
{
if(getSelectionBegin() != getSelectionEnd())
{
posBa = getSelectionBegin();
remove(posBa, getSelectionEnd() - posBa);
setCursorPos(2 * posBa);
resetSelection(2 * posBa);
}
// If insert mode, then insert a byte
if(_overwriteMode == false)
{
if(_keepSize && _xData.size() >= _initSize)
{
QWidget::keyPressEvent(event);
return;
}
if((charX % 3) == 0)
insert(posBa, char(0), _wildcardEnabled);
}
// Change content
if(_xData.size() > 0)
{
QByteArray hexMask = _xMask.data().mid(posBa, 1).toHex();
QByteArray hexValue = _xData.data().mid(posBa, 1).toHex();
if(key == '?') //wildcard
{
if((charX % 3) == 0)
hexMask[0] = '1';
else
hexMask[1] = '1';
}
else
{
if((charX % 3) == 0)
{
hexValue[0] = key;
hexMask[0] = '0';
}
else
{
hexValue[1] = key;
hexMask[1] = '0';
}
}
replace(posBa, QByteArray().fromHex(hexValue)[0], QByteArray().fromHex(hexMask)[0]);
setCursorPos(_cursorPosition + 1);
resetSelection(_cursorPosition);
}
}
/* Cut & Paste */
if(event->matches(QKeySequence::Cut))
{
QString result;
for(int idx = getSelectionBegin(); idx < getSelectionEnd(); idx++)
{
QString byte = _xData.data().mid(idx, 1).toHex();
QString mask = _xMask.data().mid(idx, 1).toHex();
if(mask[0] == '1')
result += "?";
else
result += byte[0];
if(mask[1] == '1')
result += "?";
else
result += byte[1];
result += " ";
}
remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin());
QClipboard* clipboard = QApplication::clipboard();
clipboard->setText(result.toUpper());
setCursorPos(getSelectionBegin() + 2);
resetSelection(getSelectionBegin() + 2);
}
if(event->matches(QKeySequence::Paste))
{
QClipboard* clipboard = QApplication::clipboard();
QString convert;
QString pattern = clipboard->text();
for(int i = 0; i < pattern.length(); i++)
{
QChar ch = pattern[i].toLower();
if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (_wildcardEnabled && ch == '?'))
convert += ch;
}
if(convert.length() % 2) //odd length
convert += "0";
if(_keepSize && convert.length() / 2 >= _initSize)
convert.truncate((_initSize - _xData.size()) * 2 - 1);
QByteArray data(convert.length(), 0);
QByteArray mask(data.length(), 0);
for(int i = 0; i < convert.length(); i++)
{
if(convert[i] == '?')
{
data[i] = '0';
mask[i] = '1';
}
else
{
data[i] = convert[i].toLatin1();
mask[i] = '0';
}
}
data = QByteArray().fromHex(data);
mask = QByteArray().fromHex(mask);
insert(_cursorPosition / 2, data, mask);
setCursorPos(_cursorPosition + 2 * data.length());
resetSelection(getSelectionBegin());
}
/* Delete char */
if(event->matches(QKeySequence::Delete))
{
if(getSelectionBegin() != getSelectionEnd())
{
posBa = getSelectionBegin();
remove(posBa, getSelectionEnd() - posBa);
setCursorPos(2 * posBa);
resetSelection(2 * posBa);
}
else
{
if(_overwriteMode)
replace(posBa, char(0), char(0));
else
remove(posBa, 1);
}
}
/* Backspace */
if((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier))
{
if(getSelectionBegin() != getSelectionEnd())
{
posBa = getSelectionBegin();
remove(posBa, getSelectionEnd() - posBa);
setCursorPos(2 * posBa);
resetSelection(2 * posBa);
}
else if(_cursorPosition == 1)
{
if(getSelectionBegin() != getSelectionEnd())
{
posBa = getSelectionBegin();
remove(posBa, getSelectionEnd() - posBa);
setCursorPos(2 * posBa);
resetSelection(2 * posBa);
}
else
{
if(_overwriteMode)
replace(posBa, char(0), char(0));
else
remove(posBa, 1);
}
setCursorPos(0);
}
else if(posBa > 0)
{
int delta = 1;
if(_cursorPosition % 2) //odd cursor position
delta = 0;
if(_overwriteMode)
replace(posBa - delta, char(0), char(0));
else
remove(posBa - delta, 1);
setCursorPos(_cursorPosition - 1 - delta);
}
}
/* undo */
if(event->matches(QKeySequence::Undo))
{
undo();
}
/* redo */
if(event->matches(QKeySequence::Redo))
{
redo();
}
if(event->matches(QKeySequence::Copy))
{
QString result;
for(int idx = getSelectionBegin(); idx < getSelectionEnd(); idx++)
{
QString byte = _xData.data().mid(idx, 1).toHex();
if(!byte.length())
break;
QString mask = _xMask.data().mid(idx, 1).toHex();
if(mask[0] == '1')
result += "?";
else
result += byte[0];
if(mask[1] == '1')
result += "?";
else
result += byte[1];
result += " ";
}
QClipboard* clipboard = QApplication::clipboard();
if(result.length())
clipboard->setText(result.toUpper().trimmed());
}
// Switch between insert/overwrite mode
if((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier))
{
_overwriteMode = !_overwriteMode;
setCursorPos(_cursorPosition);
overwriteModeChanged(_overwriteMode);
}
ensureVisible();
update();
QWidget::keyPressEvent(event);
}
void QHexEditPrivate::mouseMoveEvent(QMouseEvent* event)
{
_blink = false;
update();
int actPos = cursorPos(event->pos());
setCursorPos(actPos);
setSelection(actPos);
QWidget::mouseMoveEvent(event);
}
void QHexEditPrivate::mousePressEvent(QMouseEvent* event)
{
_blink = false;
update();
int cPos = cursorPos(event->pos());
if((event->modifiers()&Qt::ShiftModifier) == Qt::ShiftModifier)
{
setCursorPos(cPos);
setSelection(cPos);
}
else
{
resetSelection(cPos);
setCursorPos(cPos);
}
QWidget::mousePressEvent(event);
}
void QHexEditPrivate::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.setFont(font());
painter.fillRect(event->rect(), _backgroundColor);
// calc position
int firstLineIdx = ((event->rect().top() / _charHeight) - _charHeight) * BYTES_PER_LINE;
if(firstLineIdx < 0)
firstLineIdx = 0;
int lastLineIdx = ((event->rect().bottom() / _charHeight) + _charHeight) * BYTES_PER_LINE;
if(lastLineIdx > _xData.size())
lastLineIdx = _xData.size();
int yPosStart = ((firstLineIdx) / BYTES_PER_LINE) * _charHeight + _charHeight;
// paint hex area
QByteArray hexBa(_xData.data().mid(firstLineIdx, lastLineIdx - firstLineIdx + 1).toHex());
if(_wildcardEnabled)
{
QByteArray hexMask(_xMask.data().mid(firstLineIdx, lastLineIdx - firstLineIdx + 1).toHex());
for(int i = 0; i < hexBa.size(); i++)
if(hexMask[i] == '1')
hexBa[i] = '?';
}
for(int lineIdx = firstLineIdx, yPos = yPosStart; lineIdx < lastLineIdx; lineIdx += BYTES_PER_LINE, yPos += _charHeight)
{
QString hex;
int xPos = _xPosHex;
for(int colIdx = 0; ((lineIdx + colIdx) < _xData.size() && (colIdx < BYTES_PER_LINE)); colIdx++)
{
int posBa = lineIdx + colIdx;
if((getSelectionBegin() <= posBa) && (getSelectionEnd() > posBa))
{
painter.setBackground(_selectionColor);
painter.setBackgroundMode(Qt::OpaqueMode);
}
else
{
painter.setBackground(_backgroundColor);
painter.setBackgroundMode(Qt::TransparentMode);
}
// render hex value
painter.setPen(_textColor);
if(colIdx == 0)
{
hex = hexBa.mid((lineIdx - firstLineIdx) * 2, 2).toUpper();
for(int i = 0; i < hex.length(); i++)
{
if(hex[i] == '?') //wildcard
painter.setPen(_wildcardColor);
else
painter.setPen(_textColor);
painter.drawText(xPos + _charWidth * i, yPos, QString(hex[i]));
}
xPos += 2 * _charWidth;
}
else
{
if(getSelectionBegin() == posBa)
{
hex = hexBa.mid((lineIdx + colIdx - firstLineIdx) * 2, 2).toUpper();
xPos += _charWidth;
}
else
hex = hexBa.mid((lineIdx + colIdx - firstLineIdx) * 2, 2).prepend(" ").toUpper();
for(int i = 0; i < hex.length(); i++)
{
if(hex[i] == '?') //wildcard
painter.setPen(_wildcardColor);
else
painter.setPen(_textColor);
painter.drawText(xPos + _charWidth * i, yPos, QString(hex[i]));
}
xPos += hex.length() * _charWidth;
}
}
}
painter.setBackgroundMode(Qt::TransparentMode);
painter.setPen(this->palette().color(QPalette::WindowText));
// paint cursor
if(_blink && hasFocus())
{
if(_overwriteMode)
painter.fillRect(_cursorX, _cursorY + _charHeight - 2, _charWidth, 2, this->palette().color(QPalette::WindowText));
else
painter.fillRect(_cursorX, _cursorY, 2, _charHeight, this->palette().color(QPalette::WindowText));
}
if(_size != _xData.size())
{
_size = _xData.size();
emit currentSizeChanged(_size);
}
}
void QHexEditPrivate::setCursorPos(int position)
{
// delete cursor
_blink = false;
update();
// cursor in range?
if(_overwriteMode)
{
if(position > (_xData.size() * 2 - 1))
position = _xData.size() * 2 - 1;
}
else
{
if(position > (_xData.size() * 2))
position = _xData.size() * 2;
}
if(position < 0)
position = 0;
// calc position
_cursorPosition = position;
_cursorY = (position / (2 * BYTES_PER_LINE)) * _charHeight + 4;
int x = (position % (2 * BYTES_PER_LINE));
_cursorX = (((x / 2) * 3) + (x % 2)) * _charWidth + _xPosHex;
// immiadately draw cursor
_blink = true;
update();
emit currentAddressChanged(_cursorPosition / 2);
}
int QHexEditPrivate::cursorPos(QPoint pos)
{
int result = -1;
// find char under cursor
if((pos.x() >= _xPosHex) && (pos.x() < (_xPosHex + HEXCHARS_IN_LINE * _charWidth)))
{
int x = (pos.x() - _xPosHex) / _charWidth;
if((x % 3) == 0)
x = (x / 3) * 2;
else
x = ((x / 3) * 2) + 1;
int y = ((pos.y() - 3) / _charHeight) * 2 * BYTES_PER_LINE;
result = x + y;
}
return result;
}
int QHexEditPrivate::cursorPos()
{
return _cursorPosition;
}
void QHexEditPrivate::resetSelection()
{
_selectionBegin = _selectionInit;
_selectionEnd = _selectionInit;
}
void QHexEditPrivate::resetSelection(int pos)
{
if(pos < 0)
pos = 0;
pos++;
pos = pos / 2;
_selectionInit = pos;
_selectionBegin = pos;
_selectionEnd = pos;
}
void QHexEditPrivate::setSelection(int pos)
{
if(pos < 0)
pos = 0;
pos++;
pos = pos / 2;
if(pos >= _selectionInit)
{
_selectionEnd = pos;
_selectionBegin = _selectionInit;
}
else
{
_selectionBegin = pos;
_selectionEnd = _selectionInit;
}
}
int QHexEditPrivate::getSelectionBegin()
{
return _selectionBegin;
}
int QHexEditPrivate::getSelectionEnd()
{
return _selectionEnd;
}
void QHexEditPrivate::updateCursor()
{
if(_blink)
_blink = false;
else
_blink = true;
update(_cursorX, _cursorY, _charWidth, _charHeight);
}
void QHexEditPrivate::adjust()
{
QFontMetrics metrics(this->font());
_charWidth = metrics.width(QLatin1Char('9'));
_charHeight = metrics.height();
_xPosHex = _horizonalSpacing;
// tell QAbstractScollbar, how big we are
setMinimumHeight(((_xData.size() / 16 + 1) * _charHeight) + 5);
setMinimumWidth(_xPosHex + HEXCHARS_IN_LINE * _charWidth);
update();
}
void QHexEditPrivate::ensureVisible()
{
// scrolls to cursorx, cusory (which are set by setCursorPos)
// x-margin is 3 pixels, y-margin is half of charHeight
_scrollArea->ensureVisible(_cursorX, _cursorY + _charHeight / 2, 3, _charHeight / 2 + 2);
} |
C/C++ | x64dbg-development/src/gui/Src/QHexEdit/QHexEditPrivate.h | #pragma once
#include <QWidget>
#include <QScrollArea>
#include <QUndoStack>
#include <QKeyEvent>
#include <QTimer>
#include "XByteArray.h"
class QHexEditPrivate : public QWidget
{
Q_OBJECT
public:
QHexEditPrivate(QScrollArea* parent);
//properties
void setCursorPos(int position);
int cursorPos();
void setOverwriteMode(bool overwriteMode);
bool overwriteMode();
void setWildcardEnabled(bool enabled);
bool wildcardEnabled();
void setKeepSize(bool enabled);
bool keepSize();
void setHorizontalSpacing(int x);
int horizontalSpacing();
void setTextColor(QColor color);
QColor textColor();
void setWildcardColor(QColor color);
QColor wildcardColor();
void setBackgroundColor(QColor color);
QColor backgroundColor();
void setSelectionColor(QColor color);
QColor selectionColor();
//data management
void setData(const QByteArray & data, const QByteArray & mask);
QByteArray data();
QByteArray mask();
void insert(int index, const QByteArray & ba, const QByteArray & mask);
void insert(int index, char ch, char mask);
void remove(int index, int len = 1);
void replace(int index, char ch, char mask);
void replace(int index, const QByteArray & ba, const QByteArray & mask);
void replace(int pos, int len, const QByteArray & after, const QByteArray & mask);
void fill(int index, const QByteArray & ba, const QByteArray & mask);
void undo();
void redo();
signals:
void currentAddressChanged(int address);
void currentSizeChanged(int size);
void dataChanged();
void dataEdited();
void overwriteModeChanged(bool state);
protected:
void focusInEvent(QFocusEvent* event);
void resizeEvent(QResizeEvent* event);
void keyPressEvent(QKeyEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
void paintEvent(QPaintEvent* event);
int cursorPos(QPoint pos); // calc cursorpos from graphics position. DOES NOT STORE POSITION
void resetSelection(int pos); // set selectionStart && selectionEnd to pos
void resetSelection(); // set selectionEnd to selectionStart
void setSelection(int pos); // set min (if below init) || max (if greater init)
int getSelectionBegin();
int getSelectionEnd();
private slots:
void updateCursor();
private:
void adjust();
void ensureVisible();
QScrollArea* _scrollArea;
QTimer _cursorTimer;
QUndoStack* _undoDataStack;
QUndoStack* _undoMaskStack;
XByteArray _xData;
XByteArray _xMask;
QColor _textColor;
QColor _wildcardColor;
QColor _backgroundColor;
QColor _selectionColor;
bool _blink; // true: then cursor blinks
bool _overwriteMode;
bool _wildcardEnabled;
bool _keepSize;
int _charWidth, _charHeight; // char dimensions (dpendend on font)
int _cursorX, _cursorY; // graphics position of the cursor
int _cursorPosition; // character positioin in stream (on byte ends in to steps)
int _xPosHex; // graphics x-position of the areas
int _selectionBegin; // First selected char
int _selectionEnd; // Last selected char
int _selectionInit; // That's, where we pressed the mouse button
int _size;
int _initSize;
int _horizonalSpacing;
}; |
C++ | x64dbg-development/src/gui/Src/QHexEdit/XByteArray.cpp | #include "XByteArray.h"
XByteArray::XByteArray()
{
}
QByteArray & XByteArray::data()
{
return _data;
}
void XByteArray::setData(const QByteArray & data)
{
_data = data;
}
int XByteArray::size()
{
return _data.size();
}
QByteArray & XByteArray::insert(int i, char ch)
{
_data.insert(i, ch);
return _data;
}
QByteArray & XByteArray::insert(int i, const QByteArray & ba)
{
_data.insert(i, ba);
return _data;
}
QByteArray & XByteArray::remove(int i, int len)
{
_data.remove(i, len);
return _data;
}
QByteArray & XByteArray::replace(int index, char ch)
{
_data[index] = ch;
return _data;
}
QByteArray & XByteArray::replace(int index, const QByteArray & ba)
{
int len = ba.length();
return replace(index, len, ba);
}
QByteArray & XByteArray::replace(int index, int length, const QByteArray & ba)
{
int len;
if((index + length) > _data.length())
len = _data.length() - index;
else
len = length;
_data.replace(index, len, ba.mid(0, len));
return _data;
} |
C/C++ | x64dbg-development/src/gui/Src/QHexEdit/XByteArray.h | #pragma once
#include <QByteArray>
class XByteArray
{
public:
explicit XByteArray();
QByteArray & data();
void setData(const QByteArray & data);
int size();
QByteArray & insert(int i, char ch);
QByteArray & insert(int i, const QByteArray & ba);
QByteArray & remove(int pos, int len);
QByteArray & replace(int index, char ch);
QByteArray & replace(int index, const QByteArray & ba);
QByteArray & replace(int index, int length, const QByteArray & ba);
private:
QByteArray _data; //raw byte array
}; |
C/C++ | x64dbg-development/src/gui/Src/ThirdPartyLibs/ldconvert/ldconvert.h | #pragma once
//Converts a long double to string.
//This function uses sprintf with the highest supported precision.
//pld: Pointer to an 80-bit (10 byte) long double.
//str: Buffer with at least 32 bytes of space.
extern "C" __declspec(dllimport) void ld2str(const void* pld, char* str);
//Converts a string to a long double.
//This function uses http://en.cppreference.com/w/c/string/byte/strtof
//str: The string to convert.
//pld: Pointer to an 80-bit (10 byte) long double.
extern "C" __declspec(dllimport) bool str2ld(const char* str, void* pld);
//Converts a long double to a double.
//pld: Pointer to an 80-bit (10 byte) long double.
//pd: Pointer to a 64-bit (8 byte) double.
extern "C" __declspec(dllexport) void ld2d(const void* pld, void* pd);
//Converts a double to a long double.
//pd: Pointer to a 64-bit (8 byte) double.
//pld: Pointer to an 80-bit (10 byte) long double.
extern "C" __declspec(dllexport) void d2ld(const void* pd, void* pld); |
x64dbg-development/src/gui/Src/ThirdPartyLibs/ldconvert/ldconvert_x64.lib | !<arch>
/ 1492645626 0 202 `
P ˆ ® ® J J æ æ__IMPORT_DESCRIPTOR_ldconvert __NULL_IMPORT_DESCRIPTOR ldconvert_NULL_THUNK_DATA __imp_ld2str ld2str __imp_str2ld str2ld __imp_ld2d ld2d __imp_d2ld d2ld / 1492645626 0 212 `
P ˆ ® J æ __IMPORT_DESCRIPTOR_ldconvert __NULL_IMPORT_DESCRIPTOR __imp_d2ld __imp_ld2d __imp_ld2str __imp_str2ld d2ld ld2d ld2str str2ld ldconvert_NULL_THUNK_DATA ldconvert.dll/ 1492645626 0 501 `
d† úö÷X .debug$S C Œ @ B.idata$2 Ï ã @ 0À.idata$6 ã @ À
ldconvert.dll' Ð µžMicrosoft (R) LINK ldconvert.dll @comp.idµžÝ ÿÿ .idata$2@ À h .idata$6 .idata$4@ À h .idata$5@ À h " ; V __IMPORT_DESCRIPTOR_ldconvert __NULL_IMPORT_DESCRIPTOR ldconvert_NULL_THUNK_DATA
ldconvert.dll/ 1492645626 0 252 `
d† úö÷X» .debug$S C d @ B.idata$3 § @ 0À
ldconvert.dll' Ð µžMicrosoft (R) LINK @comp.idµžÝ ÿÿ __NULL_IMPORT_DESCRIPTOR ldconvert.dll/ 1492645626 0 290 `
d† úö÷Xß .debug$S C Œ @ B.idata$5 Ï @ @À.idata$4 × @ @À
ldconvert.dll' Ð µžMicrosoft (R) LINK @comp.idµžÝ ÿÿ ldconvert_NULL_THUNK_DATA ldconvert.dll/ 1492645626 0 39 `
ÿÿ d†úö÷X d2ld ldconvert.dll
ldconvert.dll/ 1492645626 0 39 `
ÿÿ d†úö÷X ld2d ldconvert.dll
ldconvert.dll/ 1492645626 0 41 `
ÿÿ d†úö÷X ld2str ldconvert.dll
ldconvert.dll/ 1492645626 0 41 `
ÿÿ d†úö÷X str2ld ldconvert.dll |
|
x64dbg-development/src/gui/Src/ThirdPartyLibs/ldconvert/ldconvert_x86.lib | !<arch>
/ 1492645635 0 210 `
. ` ˜ ¶ ¶ R R î î__IMPORT_DESCRIPTOR_ldconvert __NULL_IMPORT_DESCRIPTOR ldconvert_NULL_THUNK_DATA __imp__ld2str _ld2str __imp__str2ld _str2ld __imp__ld2d _ld2d __imp__d2ld _d2ld / 1492645635 0 220 `
. ` ˜ ¶ R î __IMPORT_DESCRIPTOR_ldconvert __NULL_IMPORT_DESCRIPTOR __imp__d2ld __imp__ld2d __imp__ld2str __imp__str2ld _d2ld _ld2d _ld2str _str2ld ldconvert_NULL_THUNK_DATA ldconvert.dll/ 1492645635 0 501 `
L ÷÷X .debug$S C Œ @ B.idata$2 Ï ã @ 0À.idata$6 ã @ À
ldconvert.dll' µžMicrosoft (R) LINK ldconvert.dll @comp.idµžÝ ÿÿ .idata$2@ À h .idata$6 .idata$4@ À h .idata$5@ À h " ; V __IMPORT_DESCRIPTOR_ldconvert __NULL_IMPORT_DESCRIPTOR ldconvert_NULL_THUNK_DATA
ldconvert.dll/ 1492645635 0 252 `
L ÷÷X» .debug$S C d @ B.idata$3 § @ 0À
ldconvert.dll' µžMicrosoft (R) LINK @comp.idµžÝ ÿÿ __NULL_IMPORT_DESCRIPTOR ldconvert.dll/ 1492645635 0 282 `
L ÷÷X× .debug$S C Œ @ B.idata$5 Ï @ 0À.idata$4 Ó @ 0À
ldconvert.dll' µžMicrosoft (R) LINK @comp.idµžÝ ÿÿ ldconvert_NULL_THUNK_DATA ldconvert.dll/ 1492645635 0 40 `
ÿÿ L÷÷X _d2ld ldconvert.dll ldconvert.dll/ 1492645635 0 40 `
ÿÿ L÷÷X _ld2d ldconvert.dll ldconvert.dll/ 1492645635 0 42 `
ÿÿ L÷÷X _ld2str ldconvert.dll ldconvert.dll/ 1492645635 0 42 `
ÿÿ L÷÷X _str2ld ldconvert.dll |
|
C++ | x64dbg-development/src/gui/Src/Tracer/TraceBrowser.cpp | #include "TraceBrowser.h"
#include "TraceFileReader.h"
#include "TraceFileSearch.h"
#include "RichTextPainter.h"
#include "main.h"
#include "BrowseDialog.h"
#include "QBeaEngine.h"
#include "GotoDialog.h"
#include "CommonActions.h"
#include "LineEditDialog.h"
#include "WordEditDialog.h"
#include "CachedFontMetrics.h"
#include "MRUList.h"
#include <QFileDialog>
TraceBrowser::TraceBrowser(QWidget* parent) : AbstractTableView(parent)
{
mTraceFile = nullptr;
addColumnAt(getCharWidth() * 2 * 2 + 8, tr("Index"), false); //index
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() * 50, tr("Registers"), false); //registers
addColumnAt(getCharWidth() * 50, tr("Memory"), false); //memory
addColumnAt(1000, tr("Comments"), false); //comments
loadColumnFromConfig("Trace");
setShowHeader(false); //hide header
mSelection.firstSelectedIndex = 0;
mSelection.fromIndex = 0;
mSelection.toIndex = 0;
setRowCount(0);
mRvaDisplayBase = 0;
mRvaDisplayEnabled = false;
duint setting = 0;
BridgeSettingGetUint("Gui", "TraceSyncCpu", &setting);
mTraceSyncCpu = setting != 0;
mHighlightingMode = false;
mPermanentHighlightingMode = false;
mShowMnemonicBrief = false;
mMRUList = new MRUList(this, "Recent Trace Files");
connect(mMRUList, SIGNAL(openFile(QString)), this, SLOT(openSlot(QString)));
mMRUList->load();
setupRightClickContextMenu();
Initialize();
connect(Bridge::getBridge(), SIGNAL(updateTraceBrowser()), this, SLOT(updateSlot()));
connect(Bridge::getBridge(), SIGNAL(openTraceFile(const QString &)), this, SLOT(openSlot(const QString &)));
connect(Bridge::getBridge(), SIGNAL(gotoTraceIndex(duint)), this, SLOT(gotoIndexSlot(duint)));
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(tokenizerConfigUpdatedSlot()));
connect(this, SIGNAL(selectionChanged(unsigned long long)), this, SLOT(selectionChangedSlot(unsigned long long)));
connect(Bridge::getBridge(), SIGNAL(shutdown()), this, SLOT(closeFileSlot()));
}
TraceBrowser::~TraceBrowser()
{
if(mTraceFile)
{
mTraceFile->Close();
delete mTraceFile;
}
}
bool TraceBrowser::isFileOpened() const
{
return mTraceFile && mTraceFile->Progress() == 100 && mTraceFile->Length() > 0;
}
bool TraceBrowser::isRecording()
{
return DbgEval("tr.isrecording()") != 0;
}
bool TraceBrowser::toggleTraceRecording(QWidget* parent)
{
if(!DbgIsDebugging())
return false;
if(isRecording())
{
return DbgCmdExecDirect("StopTraceRecording");
}
else
{
auto extension = ArchValue(".trace32", ".trace64");
BrowseDialog browse(
parent,
tr("Start trace recording"),
tr("Trace recording file"),
tr("Trace recordings (*.%1);;All files (*.*)").arg(extension),
getDbPath(mainModuleName() + extension, true),
true
);
if(browse.exec() == QDialog::Accepted)
{
if(browse.path.contains(QChar('"')) || browse.path.contains(QChar('\'')))
SimpleErrorBox(parent, tr("Error"), tr("File name contains invalid character."));
else
return DbgCmdExecDirect(QString("StartTraceRecording \"%1\"").arg(browse.path));
}
}
return false;
}
QString TraceBrowser::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.&"))
addrText += " <" + QString(module) + "." + QString(label_) + ">";
else
addrText += " <" + QString(label_) + ">";
}
else
*label_ = 0;
if(label)
strcpy_s(label, MAX_LABEL_SIZE, label_);
return addrText;
}
//The following function is modified from "RichTextPainter::List Disassembly::getRichBytes(const Instruction_t & instr) const"
//with patch and code folding features removed.
RichTextPainter::List TraceBrowser::getRichBytes(const Instruction_t & instr) const
{
RichTextPainter::List richBytes;
std::vector<std::pair<size_t, bool>> realBytes;
formatOpcodeString(instr, richBytes, realBytes);
const duint cur_addr = instr.rva;
if(!richBytes.empty() && richBytes.back().text.endsWith(' '))
richBytes.back().text.chop(1); //remove trailing space if exists
for(size_t i = 0; i < richBytes.size(); i++)
{
auto byteIdx = realBytes[i].first;
auto isReal = realBytes[i].second;
RichTextPainter::CustomRichText_t & curByte = richBytes.at(i);
DBGRELOCATIONINFO relocInfo;
curByte.underlineColor = mDisassemblyRelocationUnderlineColor;
if(DbgIsDebugging() && DbgFunctions()->ModRelocationAtAddr(cur_addr + byteIdx, &relocInfo))
{
bool prevInSameReloc = relocInfo.rva < cur_addr + byteIdx - DbgFunctions()->ModBaseFromAddr(cur_addr + byteIdx);
curByte.underline = isReal;
curByte.underlineConnectPrev = i > 0 && prevInSameReloc;
}
else
{
curByte.underline = false;
curByte.underlineConnectPrev = false;
}
curByte.textColor = mBytesColor;
curByte.textBackground = mBytesBackgroundColor;
}
return richBytes;
}
#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
/**
* @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 TraceBrowser::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;
}
QString TraceBrowser::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if(!isFileOpened())
{
return "";
}
if(mTraceFile->isError())
{
GuiAddLogMessage(tr("An error occurred when reading trace file.\r\n").toUtf8().constData());
mTraceFile->Close();
delete mTraceFile;
mTraceFile = nullptr;
setRowCount(0);
return "";
}
if(mHighlightingMode)
{
QPen pen(mInstructionHighlightColor);
pen.setWidth(2);
painter->setPen(pen);
QRect rect = viewport()->rect();
rect.adjust(1, 1, -1, -1);
painter->drawRect(rect);
}
duint index = rowBase + rowOffset;
duint cur_addr;
REGDUMP reg;
reg = mTraceFile->Registers(index);
cur_addr = reg.regcontext.cip;
auto traceCount = DbgFunctions()->GetTraceRecordHitCount(cur_addr);
bool wIsSelected = (index >= mSelection.fromIndex && index <= mSelection.toIndex);
// 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)))));
}
if(index >= mTraceFile->Length())
return "";
Instruction_t inst = mTraceFile->Instruction(index);
switch(static_cast<TableColumnIndex>(col))
{
case Index:
{
return mTraceFile->getIndexText(index);
}
case Address:
{
QString addrText;
char label[MAX_LABEL_SIZE] = "";
if(!DbgIsDebugging())
{
addrText = ToPtrString(cur_addr);
goto NotDebuggingLabel;
}
else
addrText = getAddrText(cur_addr, label, true);
BPXTYPE bpxtype = DbgGetBpxTypeAt(cur_addr);
bool isbookmark = DbgGetBookmarkAt(cur_addr);
//todo: cip
{
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
{
NotDebuggingLabel:
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, addrText);
}
return "";
case Opcode:
{
//draw functions
Function_t funcType;
FUNCTYPE funcFirst = DbgGetFunctionTypeAt(cur_addr);
FUNCTYPE funcLast = DbgGetFunctionTypeAt(cur_addr + inst.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 = inst.branchType;
painter->setPen(mConditionalTruePen);
int halfRow = getRowHeight() / 2 + 1;
int jumpsize = 0;
if((branchType == Instruction_t::Conditional || branchType == Instruction_t::Unconditional) && index < mTraceFile->Length())
{
duint next_addr;
next_addr = mTraceFile->Registers(index + 1).regcontext.cip;
if(next_addr < cur_addr)
{
QPoint wPoints[] =
{
QPoint(x + funcsize, y + halfRow + 1),
QPoint(x + funcsize + 2, y + halfRow - 1),
QPoint(x + funcsize + 4, y + halfRow + 1),
};
jumpsize = 8;
painter->drawPolyline(wPoints, 3);
}
else if(next_addr > cur_addr)
{
QPoint wPoints[] =
{
QPoint(x + funcsize, y + halfRow - 1),
QPoint(x + funcsize + 2, y + halfRow + 1),
QPoint(x + funcsize + 4, y + halfRow - 1),
};
jumpsize = 8;
painter->drawPolyline(wPoints, 3);
}
}
RichTextPainter::paintRichText(painter, x, y, getColumnWidth(col), getRowHeight(), jumpsize + funcsize, getRichBytes(inst), mFontMetrics);
return "";
}
case Disassembly:
{
RichTextPainter::List richText;
int loopsize = 0;
int depth = 0;
while(1) //paint all loop depths
{
LOOPTYPE loopFirst = DbgGetLoopTypeAt(cur_addr, depth);
LOOPTYPE loopLast = DbgGetLoopTypeAt(cur_addr + inst.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++;
}
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(inst.tokens, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::paintRichText(painter, x + loopsize, y, getColumnWidth(col) - 0, getRowHeight(), 4, richText, mFontMetrics);
return "";
}
case Registers:
{
RichTextPainter::List richText;
auto fakeInstruction = registersTokens(index);
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(fakeInstruction, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(fakeInstruction, richText, 0);
RichTextPainter::paintRichText(painter, x + 0, y, getColumnWidth(col) - 0, getRowHeight(), 4, richText, mFontMetrics);
return "";
}
case Memory:
{
auto fakeInstruction = memoryTokens(index);
RichTextPainter::List richText;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(fakeInstruction, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(fakeInstruction, richText, nullptr);
RichTextPainter::paintRichText(painter, x + 0, y, getColumnWidth(col) - 0, getRowHeight(), 4, richText, mFontMetrics);
return "";
}
case Comments:
{
int xinc = 3;
int width;
if(DbgIsDebugging())
{
//TODO: draw arguments
QString comment;
bool autoComment = false;
char label[MAX_LABEL_SIZE] = "";
if(GetCommentFormat(cur_addr, comment, &autoComment))
{
QColor backgroundColor;
if(autoComment)
{
//TODO: autocomments from trace file will be much more helpful
painter->setPen(mAutoCommentColor);
backgroundColor = mAutoCommentBackgroundColor;
}
else //user comment
{
painter->setPen(mCommentColor);
backgroundColor = mCommentBackgroundColor;
}
width = mFontMetrics->width(comment);
if(width > w)
width = w;
if(width)
painter->fillRect(QRect(x + xinc, y, width, h), QBrush(backgroundColor)); //fill comment color
painter->drawText(QRect(x + xinc, y, width, h), Qt::AlignVCenter | Qt::AlignLeft, comment);
}
else if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label)) // label but no comment
{
QString labelText(label);
QColor backgroundColor;
painter->setPen(mLabelColor);
backgroundColor = mLabelBackgroundColor;
width = mFontMetrics->width(labelText);
if(width > w)
width = w;
if(width)
painter->fillRect(QRect(x + xinc, y, width, h), QBrush(backgroundColor)); //fill comment color
painter->drawText(QRect(x + xinc, y, width, h), Qt::AlignVCenter | Qt::AlignLeft, labelText);
}
else
width = 0;
x += width + 3;
}
if(mShowMnemonicBrief)
{
char brief[MAX_STRING_SIZE] = "";
QString mnem;
for(const ZydisTokenizer::SingleToken & token : inst.tokens.tokens)
{
if(token.type != ZydisTokenizer::TokenType::Space && token.type != ZydisTokenizer::TokenType::Prefix)
{
mnem = token.text;
break;
}
}
if(mnem.isEmpty())
mnem = inst.instStr;
int index = mnem.indexOf(' ');
if(index != -1)
mnem.truncate(index);
DbgFunctions()->GetMnemonicBrief(mnem.toUtf8().constData(), MAX_STRING_SIZE, brief);
painter->setPen(mMnemonicBriefColor);
QString mnemBrief = brief;
if(mnemBrief.length())
{
width = mFontMetrics->width(mnemBrief);
if(width > w)
width = w;
if(width)
painter->fillRect(QRect(x, y, width, h), QBrush(mMnemonicBriefBackgroundColor)); //mnemonic brief background color
painter->drawText(QRect(x, y, width, h), Qt::AlignVCenter | Qt::AlignLeft, mnemBrief);
}
}
return "";
}
default:
return "";
}
}
ZydisTokenizer::InstructionToken TraceBrowser::memoryTokens(unsigned long long atIndex)
{
duint MemoryAddress[MAX_MEMORY_OPERANDS];
duint MemoryOldContent[MAX_MEMORY_OPERANDS];
duint MemoryNewContent[MAX_MEMORY_OPERANDS];
bool MemoryIsValid[MAX_MEMORY_OPERANDS];
int MemoryOperandsCount;
ZydisTokenizer::InstructionToken fakeInstruction = ZydisTokenizer::InstructionToken();
MemoryOperandsCount = mTraceFile->MemoryAccessCount(atIndex);
if(MemoryOperandsCount > 0)
{
mTraceFile->MemoryAccessInfo(atIndex, MemoryAddress, MemoryOldContent, MemoryNewContent, MemoryIsValid);
std::vector<ZydisTokenizer::SingleToken> tokens;
for(int i = 0; i < MemoryOperandsCount; i++)
{
ZydisTokenizer::TokenizeTraceMemory(MemoryAddress[i], MemoryOldContent[i], MemoryNewContent[i], tokens);
}
fakeInstruction.tokens.insert(fakeInstruction.tokens.begin(), tokens.begin(), tokens.end());
}
return fakeInstruction;
}
ZydisTokenizer::InstructionToken TraceBrowser::registersTokens(unsigned long long atIndex)
{
ZydisTokenizer::InstructionToken fakeInstruction = ZydisTokenizer::InstructionToken();
REGDUMP now = mTraceFile->Registers(atIndex);
REGDUMP next = (atIndex + 1 < mTraceFile->Length()) ? mTraceFile->Registers(atIndex + 1) : now;
std::vector<ZydisTokenizer::SingleToken> tokens;
#define addRegValues(str, reg) if (atIndex ==0 || now.regcontext.##reg != next.regcontext.##reg) { \
ZydisTokenizer::TokenizeTraceRegister(str, now.regcontext.##reg, next.regcontext.##reg, tokens);};
addRegValues(ArchValue("eax", "rax"), cax)
addRegValues(ArchValue("ebx", "rbx"), cbx)
addRegValues(ArchValue("ecx", "rcx"), ccx)
addRegValues(ArchValue("edx", "rdx"), cdx)
addRegValues(ArchValue("esp", "rsp"), csp)
addRegValues(ArchValue("ebp", "rbp"), cbp)
addRegValues(ArchValue("esi", "rsi"), csi)
addRegValues(ArchValue("edi", "rdi"), cdi)
#ifdef _WIN64
addRegValues("r8", r8)
addRegValues("r9", r9)
addRegValues("r10", r10)
addRegValues("r11", r11)
addRegValues("r12", r12)
addRegValues("r13", r13)
addRegValues("r14", r14)
addRegValues("r15", r15)
#endif //_WIN64
addRegValues(ArchValue("eflags", "rflags"), eflags)
fakeInstruction.tokens.insert(fakeInstruction.tokens.begin(), tokens.begin(), tokens.end());
return fakeInstruction;
}
void TraceBrowser::prepareData()
{
auto viewables = getViewableRowsCount();
int lines = 0;
if(isFileOpened())
{
duint tableOffset = getTableOffset();
if(mTraceFile->Length() < tableOffset + viewables)
lines = mTraceFile->Length() - tableOffset;
else
lines = viewables;
}
setNbrOfLineToPrint(lines);
}
void TraceBrowser::setupRightClickContextMenu()
{
mMenuBuilder = new MenuBuilder(this);
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100 || mTraceFile->Length() == 0)
return (duint)0;
else
return mTraceFile->Registers(getInitialSelection()).regcontext.cip;
});
QAction* toggleTraceRecording = makeShortcutAction(DIcon("control-record"), tr("Start recording"), SLOT(toggleTraceRecordingSlot()), "ActionToggleRunTrace");
mMenuBuilder->addAction(toggleTraceRecording, [toggleTraceRecording](QMenu*)
{
if(!DbgIsDebugging())
return false;
if(isRecording())
{
toggleTraceRecording->setText(tr("Stop recording"));
toggleTraceRecording->setIcon(DIcon("control-stop"));
}
else
{
toggleTraceRecording->setText(tr("Start recording"));
toggleTraceRecording->setIcon(DIcon("control-record"));
}
return true;
});
auto mTraceFileIsNull = [this](QMenu*)
{
return mTraceFile == nullptr;
};
mMenuBuilder->addAction(makeAction(DIcon("folder-horizontal-open"), tr("Open"), SLOT(openFileSlot())), mTraceFileIsNull);
mMenuBuilder->addMenu(makeMenu(DIcon("recentfiles"), tr("Recent Files")), [this](QMenu * menu)
{
if(mTraceFile == nullptr)
{
mMRUList->appendMenu(menu);
return true;
}
else
return false;
});
mMenuBuilder->addAction(makeAction(DIcon("close"), tr("Close recording"), SLOT(closeFileSlot())), [this](QMenu*)
{
return mTraceFile != nullptr;
});
mMenuBuilder->addAction(makeAction(DIcon("delete"), tr("Delete recording"), SLOT(closeDeleteSlot())), [this](QMenu*)
{
return mTraceFile != nullptr;
});
mMenuBuilder->addSeparator();
auto isValid = [this](QMenu*)
{
return mTraceFile != nullptr && mTraceFile->Progress() == 100 && mTraceFile->Length() > 0;
};
auto isDebugging = [this](QMenu*)
{
return mTraceFile != nullptr && mTraceFile->Progress() == 100 && mTraceFile->Length() > 0 && DbgIsDebugging();
};
MenuBuilder* copyMenu = new MenuBuilder(this, isValid);
copyMenu->addAction(makeShortcutAction(DIcon("copy_selection"), tr("&Selection"), SLOT(copySelectionSlot()), "ActionCopy"));
copyMenu->addAction(makeAction(DIcon("copy_selection"), tr("Selection to &File"), SLOT(copySelectionToFileSlot())));
copyMenu->addAction(makeAction(DIcon("copy_selection_no_bytes"), tr("Selection (&No Bytes)"), SLOT(copySelectionNoBytesSlot())));
copyMenu->addAction(makeAction(DIcon("copy_selection_no_bytes"), tr("Selection to File (No Bytes)"), SLOT(copySelectionToFileNoBytesSlot())));
copyMenu->addAction(makeShortcutAction(DIcon("database-export"), tr("&Export Table"), SLOT(exportSlot()), "ActionExport"));
copyMenu->addAction(makeShortcutAction(DIcon("copy_address"), tr("Address"), SLOT(copyCipSlot()), "ActionCopyAddress"));
copyMenu->addAction(makeShortcutAction(DIcon("copy_address"), tr("&RVA"), SLOT(copyRvaSlot()), "ActionCopyRva"), isDebugging);
copyMenu->addAction(makeShortcutAction(DIcon("fileoffset"), tr("&File Offset"), SLOT(copyFileOffsetSlot()), "ActionCopyFileOffset"), isDebugging);
copyMenu->addAction(makeAction(DIcon("copy_disassembly"), tr("Disassembly"), SLOT(copyDisassemblySlot())));
copyMenu->addAction(makeAction(DIcon("copy_address"), tr("Index"), SLOT(copyIndexSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
mCommonActions->build(mMenuBuilder, CommonActions::ActionDisasm | CommonActions::ActionBreakpoint | CommonActions::ActionLabel | CommonActions::ActionComment | CommonActions::ActionBookmark);
mMenuBuilder->addAction(makeShortcutAction(DIcon("highlight"), tr("&Highlighting mode"), SLOT(enableHighlightingModeSlot()), "ActionHighlightingMode"), isValid);
mMenuBuilder->addAction(makeShortcutAction(DIcon("helpmnemonic"), tr("Help on mnemonic"), SLOT(mnemonicHelpSlot()), "ActionHelpOnMnemonic"), isValid);
QAction* mnemonicBrief = makeShortcutAction(DIcon("helpbrief"), tr("Show mnemonic brief"), SLOT(mnemonicBriefSlot()), "ActionToggleMnemonicBrief");
mMenuBuilder->addAction(mnemonicBrief, [this, mnemonicBrief](QMenu*)
{
if(mShowMnemonicBrief)
mnemonicBrief->setText(tr("Hide mnemonic brief"));
else
mnemonicBrief->setText(tr("Show mnemonic brief"));
return true;
});
MenuBuilder* gotoMenu = new MenuBuilder(this, isValid);
gotoMenu->addAction(makeShortcutAction(DIcon("goto"), tr("Index"), SLOT(gotoSlot()), "ActionGotoExpression"), isValid);
gotoMenu->addAction(makeAction(DIcon("arrow-step-rtr"), tr("Function return"), SLOT(rtrSlot())), isValid);
gotoMenu->addAction(makeShortcutAction(DIcon("previous"), tr("Previous"), SLOT(gotoPreviousSlot()), "ActionGotoPrevious"), [this](QMenu*)
{
return mHistory.historyHasPrev();
});
gotoMenu->addAction(makeShortcutAction(DIcon("next"), tr("Next"), SLOT(gotoNextSlot()), "ActionGotoNext"), [this](QMenu*)
{
return mHistory.historyHasNext();
});
mMenuBuilder->addMenu(makeMenu(DIcon("goto"), tr("Go to")), gotoMenu);
MenuBuilder* searchMenu = new MenuBuilder(this, isValid);
searchMenu->addAction(makeAction(DIcon("search_for_constant"), tr("Address/Constant"), SLOT(searchConstantSlot())));
searchMenu->addAction(makeAction(DIcon("memory-map"), tr("Memory Reference"), SLOT(searchMemRefSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("search"), tr("&Search")), searchMenu);
// The following code adds a menu to view the information about currently selected instruction. When info box is completed, remove me.
MenuBuilder* infoMenu = new MenuBuilder(this, [this, isValid](QMenu * menu)
{
duint MemoryAddress[MAX_MEMORY_OPERANDS];
duint MemoryOldContent[MAX_MEMORY_OPERANDS];
duint MemoryNewContent[MAX_MEMORY_OPERANDS];
bool MemoryIsValid[MAX_MEMORY_OPERANDS];
int MemoryOperandsCount;
unsigned long long index;
if(!isValid(nullptr))
return false;
index = getInitialSelection();
MemoryOperandsCount = mTraceFile->MemoryAccessCount(index);
if(MemoryOperandsCount > 0)
{
mTraceFile->MemoryAccessInfo(index, MemoryAddress, MemoryOldContent, MemoryNewContent, MemoryIsValid);
bool RvaDisplayEnabled = mRvaDisplayEnabled;
char nolabel[MAX_LABEL_SIZE];
mRvaDisplayEnabled = false;
for(int i = 0; i < MemoryOperandsCount; i++)
{
menu->addAction(QString("%1: %2 -> %3").arg(getAddrText(MemoryAddress[i], nolabel, false)).arg(ToPtrString(MemoryOldContent[i])).arg(ToPtrString(MemoryNewContent[i])));
}
mRvaDisplayEnabled = RvaDisplayEnabled;
return true;
}
else
return false; //The information menu now only contains memory access info
});
mMenuBuilder->addMenu(makeMenu(tr("Information")), infoMenu);
auto synchronizeCpuAction = makeShortcutAction(DIcon("sync"), tr("Sync with CPU"), SLOT(synchronizeCpuSlot()), "ActionSync");
synchronizeCpuAction->setCheckable(true);
synchronizeCpuAction->setChecked(mTraceSyncCpu);
mMenuBuilder->addAction(synchronizeCpuAction);
mMenuBuilder->loadFromConfig();
}
void TraceBrowser::contextMenuEvent(QContextMenuEvent* event)
{
QMenu menu(this);
mMenuBuilder->build(&menu);
menu.exec(event->globalPos());
}
void TraceBrowser::mousePressEvent(QMouseEvent* event)
{
auto index = getIndexOffsetFromY(transY(event->y())) + getTableOffset();
if(getGuiState() != AbstractTableView::NoState || !mTraceFile || mTraceFile->Progress() < 100)
{
AbstractTableView::mousePressEvent(event);
return;
}
switch(event->button())
{
case Qt::LeftButton:
if(index < getRowCount())
{
if(mHighlightingMode || mPermanentHighlightingMode)
{
ZydisTokenizer::InstructionToken tokens;
int columnPosition = 0;
if(getColumnIndexFromX(event->x()) == Disassembly)
{
tokens = mTraceFile->Instruction(index).tokens;
columnPosition = getColumnPosition(Disassembly);
}
else if(getColumnIndexFromX(event->x()) == TableColumnIndex::Registers)
{
tokens = registersTokens(index);
columnPosition = getColumnPosition(Registers);
}
else if(getColumnIndexFromX(event->x()) == Memory)
{
tokens = memoryTokens(index);
columnPosition = getColumnPosition(Memory);
}
ZydisTokenizer::SingleToken token;
if(ZydisTokenizer::TokenFromX(tokens, token, event->x() - columnPosition, 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();
}
}
if(mHighlightingMode) //disable highlighting mode after clicked
{
mHighlightingMode = false;
reloadData();
}
if(event->modifiers() & Qt::ShiftModifier)
expandSelectionUpTo(index);
else
setSingleSelection(index);
mHistory.addVaToHistory(index);
emit selectionChanged(getInitialSelection());
}
updateViewport();
return;
break;
case Qt::MiddleButton:
copyCipSlot();
MessageBeep(MB_OK);
break;
case Qt::BackButton:
gotoPreviousSlot();
break;
case Qt::ForwardButton:
gotoNextSlot();
break;
}
AbstractTableView::mousePressEvent(event);
}
void TraceBrowser::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->button() == Qt::LeftButton && mTraceFile != nullptr && mTraceFile->Progress() == 100)
{
switch(getColumnIndexFromX(event->x()))
{
case Index://Index: follow
mCommonActions->followDisassemblySlot();
break;
case Address://Address: set RVA
if(mRvaDisplayEnabled && mTraceFile->Registers(getInitialSelection()).regcontext.cip == mRvaDisplayBase)
mRvaDisplayEnabled = false;
else
{
mRvaDisplayEnabled = true;
mRvaDisplayBase = mTraceFile->Registers(getInitialSelection()).regcontext.cip;
}
reloadData();
break;
case Opcode: //Opcode: Breakpoint
mCommonActions->toggleInt3BPActionSlot();
break;
case Disassembly: //Instructions: follow
mCommonActions->followDisassemblySlot();
break;
case Comments: //Comment
mCommonActions->setCommentSlot();
break;
}
}
AbstractTableView::mouseDoubleClickEvent(event);
}
void TraceBrowser::mouseMoveEvent(QMouseEvent* event)
{
dsint index = getIndexOffsetFromY(transY(event->y())) + getTableOffset();
if((event->buttons() & Qt::LeftButton) != 0 && getGuiState() == AbstractTableView::NoState && mTraceFile != nullptr && mTraceFile->Progress() == 100)
{
if(index < getRowCount())
{
setSingleSelection(getInitialSelection());
expandSelectionUpTo(index);
}
if(transY(event->y()) > this->height())
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
else if(transY(event->y()) < 0)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
updateViewport();
}
AbstractTableView::mouseMoveEvent(event);
}
void TraceBrowser::keyPressEvent(QKeyEvent* event)
{
int key = event->key();
auto curindex = getInitialSelection();
auto visibleindex = curindex;
if((key == Qt::Key_Up || key == Qt::Key_Down) && mTraceFile && mTraceFile->Progress() == 100)
{
if(key == Qt::Key_Up)
{
if(event->modifiers() == Qt::ShiftModifier)
{
if(curindex == getSelectionStart())
{
if(getSelectionEnd() > 0)
{
visibleindex = getSelectionEnd() - 1;
expandSelectionUpTo(visibleindex);
}
}
else
{
if(getSelectionStart() > 0)
{
visibleindex = getSelectionStart() - 1;
expandSelectionUpTo(visibleindex);
}
}
}
else
{
if(curindex > 0)
{
visibleindex = curindex - 1;
setSingleSelection(visibleindex);
}
}
}
else
{
if(getSelectionEnd() + 1 < mTraceFile->Length())
{
if(event->modifiers() == Qt::ShiftModifier)
{
visibleindex = getSelectionEnd() + 1;
expandSelectionUpTo(visibleindex);
}
else
{
visibleindex = getSelectionEnd() + 1;
setSingleSelection(visibleindex);
}
}
}
makeVisible(visibleindex);
mHistory.addVaToHistory(visibleindex);
updateViewport();
emit selectionChanged(getInitialSelection());
}
else
AbstractTableView::keyPressEvent(event);
}
void TraceBrowser::selectionChangedSlot(unsigned long long selection)
{
if(mTraceSyncCpu && isFileOpened())
{
GuiDisasmAt(mTraceFile->Registers(selection).regcontext.cip, 0);
}
}
void TraceBrowser::tokenizerConfigUpdatedSlot()
{
mPermanentHighlightingMode = ConfigBool("Disassembler", "PermanentHighlightingMode");
}
void TraceBrowser::expandSelectionUpTo(duint to)
{
if(to < mSelection.firstSelectedIndex)
{
mSelection.fromIndex = to;
}
else if(to > mSelection.firstSelectedIndex)
{
mSelection.toIndex = to;
}
else if(to == mSelection.firstSelectedIndex)
{
setSingleSelection(to);
}
}
void TraceBrowser::setSingleSelection(duint index)
{
mSelection.firstSelectedIndex = index;
mSelection.fromIndex = index;
mSelection.toIndex = index;
}
duint TraceBrowser::getInitialSelection()
{
return mSelection.firstSelectedIndex;
}
duint TraceBrowser::getSelectionSize()
{
return mSelection.toIndex - mSelection.fromIndex + 1;
}
duint TraceBrowser::getSelectionStart()
{
return mSelection.fromIndex;
}
duint TraceBrowser::getSelectionEnd()
{
return mSelection.toIndex;
}
void TraceBrowser::makeVisible(duint index)
{
duint tableOffset = getTableOffset();
if(index < tableOffset)
setTableOffset(index);
else if(index + 2 > tableOffset + getViewableRowsCount())
setTableOffset(index - getViewableRowsCount() + 2);
}
void TraceBrowser::updateColors()
{
AbstractTableView::updateColors();
//ZydisTokenizer::UpdateColors(); //Already called in disassembly
mBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
mInstructionHighlightColor = ConfigColor("InstructionHighlightColor");
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");
mAutoCommentColor = ConfigColor("DisassemblyAutoCommentColor");
mAutoCommentBackgroundColor = ConfigColor("DisassemblyAutoCommentBackgroundColor");
mMnemonicBriefColor = ConfigColor("DisassemblyMnemonicBriefColor");
mMnemonicBriefBackgroundColor = ConfigColor("DisassemblyMnemonicBriefBackgroundColor");
mCommentColor = ConfigColor("DisassemblyCommentColor");
mCommentBackgroundColor = ConfigColor("DisassemblyCommentBackgroundColor");
mConditionalJumpLineTrueColor = ConfigColor("DisassemblyConditionalJumpLineTrueColor");
mDisassemblyRelocationUnderlineColor = ConfigColor("DisassemblyRelocationUnderlineColor");
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);
mConditionalTruePen = QPen(mConditionalJumpLineTrueColor);
}
void TraceBrowser::openFileSlot()
{
BrowseDialog browse(
this,
tr("Open trace recording"),
tr("Trace recording"),
tr("Trace recordings (*.%1);;All files (*.*)").arg(ArchValue("trace32", "trace64")),
getDbPath(),
false
);
if(browse.exec() != QDialog::Accepted)
return;
emit openSlot(browse.path);
}
void TraceBrowser::openSlot(const QString & fileName)
{
if(mTraceFile != nullptr)
{
mTraceFile->Close();
delete mTraceFile;
}
mTraceFile = new TraceFileReader(this);
connect(mTraceFile, SIGNAL(parseFinished()), this, SLOT(parseFinishedSlot()));
mFileName = fileName;
mTraceFile->Open(fileName);
}
void TraceBrowser::toggleTraceRecordingSlot()
{
toggleTraceRecording(this);
}
void TraceBrowser::closeFileSlot()
{
if(isRecording())
DbgCmdExecDirect("StopTraceRecording");
if(mTraceFile != nullptr)
{
mTraceFile->Close();
delete mTraceFile;
mTraceFile = nullptr;
}
emit Bridge::getBridge()->updateTraceBrowser();
}
void TraceBrowser::closeDeleteSlot()
{
QMessageBox msgbox(QMessageBox::Critical, tr("Delete recording"), tr("Are you sure you want to delete this recording?"), QMessageBox::Yes | QMessageBox::No, this);
if(msgbox.exec() == QMessageBox::Yes)
{
if(isRecording())
DbgCmdExecDirect("StopTraceRecording");
mTraceFile->Delete();
delete mTraceFile;
mTraceFile = nullptr;
emit Bridge::getBridge()->updateTraceBrowser();
}
}
void TraceBrowser::parseFinishedSlot()
{
if(mTraceFile->isError())
{
SimpleErrorBox(this, tr("Error"), tr("Error when opening trace recording"));
delete mTraceFile;
mTraceFile = nullptr;
setRowCount(0);
}
else
{
if(mTraceFile->HashValue() && DbgIsDebugging())
if(DbgFunctions()->DbGetHash() != mTraceFile->HashValue())
{
SimpleWarningBox(this, tr("Trace file is recorded for another debuggee"),
tr("Checksum is different for current trace file and the debugee. This probably means you have opened a wrong trace file. This trace file is recorded for \"%1\"").arg(mTraceFile->ExePath()));
}
setRowCount(mTraceFile->Length());
mMRUList->addEntry(mFileName);
mMRUList->save();
}
setSingleSelection(0);
makeVisible(0);
emit Bridge::getBridge()->updateTraceBrowser();
emit selectionChanged(getInitialSelection());
}
void TraceBrowser::mnemonicBriefSlot()
{
mShowMnemonicBrief = !mShowMnemonicBrief;
reloadData();
}
void TraceBrowser::mnemonicHelpSlot()
{
unsigned char data[16] = { 0xCC };
int size;
mTraceFile->OpCode(getInitialSelection(), data, &size);
Zydis zydis;
zydis.Disassemble(mTraceFile->Registers(getInitialSelection()).regcontext.cip, data);
DbgCmdExecDirect(QString("mnemonichelp %1").arg(zydis.Mnemonic().c_str()));
emit displayLogWidget();
}
void TraceBrowser::disasm(unsigned long long index, bool history)
{
setSingleSelection(index);
makeVisible(index);
if(history)
mHistory.addVaToHistory(index);
updateViewport();
emit selectionChanged(getInitialSelection());
}
void TraceBrowser::gotoSlot()
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
GotoDialog gotoDlg(this, false, true, true);
if(gotoDlg.exec() == QDialog::Accepted)
{
auto val = DbgValFromString(gotoDlg.expressionText.toUtf8().constData());
if(val >= 0 && val < mTraceFile->Length())
disasm(val);
}
}
void TraceBrowser::rtrSlot()
{
// Let's hope this search will be fast...
disasm(TraceFileSearchFuncReturn(mTraceFile, getInitialSelection()));
}
void TraceBrowser::gotoNextSlot()
{
if(mHistory.historyHasNext())
disasm(mHistory.historyNext(), false);
}
void TraceBrowser::gotoPreviousSlot()
{
if(mHistory.historyHasPrev())
disasm(mHistory.historyPrev(), false);
}
void TraceBrowser::copyCipSlot()
{
QString clipboard;
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
clipboard += "\r\n";
clipboard += ToPtrString(mTraceFile->Registers(i).regcontext.cip);
}
Bridge::CopyToClipboard(clipboard);
}
void TraceBrowser::copyIndexSlot()
{
QString clipboard;
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
clipboard += "\r\n";
clipboard += mTraceFile->getIndexText(i);
}
Bridge::CopyToClipboard(clipboard);
}
void TraceBrowser::pushSelectionInto(bool copyBytes, QTextStream & stream, QTextStream* htmlStream)
{
const int addressLen = getColumnWidth(Address) / getCharWidth() - 1;
const int bytesLen = getColumnWidth(Opcode) / getCharWidth() - 1;
const int disassemblyLen = getColumnWidth(Disassembly) / getCharWidth() - 1;
const int registersLen = getColumnWidth(Registers) / getCharWidth() - 1;
const int memoryLen = getColumnWidth(Memory) / getCharWidth() - 1;
if(htmlStream)
*htmlStream << QString("<table style=\"border-width:0px;border-color:#000000;font-family:%1;font-size:%2px;\">").arg(font().family()).arg(getRowHeight());
for(unsigned long long i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
stream << "\r\n";
const Instruction_t & inst = mTraceFile->Instruction(i);
duint cur_addr = inst.rva;
QString address = getAddrText(cur_addr, 0, addressLen > sizeof(duint) * 2 + 1);
QString bytes;
QString bytesHTML;
if(copyBytes)
RichTextPainter::htmlRichText(getRichBytes(inst), &bytesHTML, bytes);
QString disassembly;
QString htmlDisassembly;
if(htmlStream)
{
RichTextPainter::List richText;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(inst.tokens, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, &htmlDisassembly, disassembly);
}
else
{
for(const auto & token : inst.tokens.tokens)
disassembly += token.text;
}
QString fullComment;
QString comment;
bool autocomment;
if(GetCommentFormat(cur_addr, comment, &autocomment))
fullComment = " " + comment;
QString registersText;
QString registersHtml;
ZydisTokenizer::InstructionToken regTokens = registersTokens(i);
if(htmlStream)
{
RichTextPainter::List richText;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(regTokens, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(regTokens, richText, 0);
RichTextPainter::htmlRichText(richText, ®istersHtml, registersText);
}
else
{
for(const auto & token : regTokens.tokens)
registersText += token.text;
}
QString memoryText;
QString memoryHtml;
ZydisTokenizer::InstructionToken memTokens = memoryTokens(i);
if(htmlStream)
{
RichTextPainter::List richText;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(memTokens, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(memTokens, richText, 0);
RichTextPainter::htmlRichText(richText, &memoryHtml, memoryText);
}
else
{
for(const auto & token : memTokens.tokens)
memoryText += token.text;
}
stream << mTraceFile->getIndexText(i) + " | " + address.leftJustified(addressLen, QChar(' '), true);
if(copyBytes)
stream << " | " + bytes.leftJustified(bytesLen, QChar(' '), true);
stream << " | " + disassembly.leftJustified(disassemblyLen, QChar(' '), true);
stream << " | " + registersText.leftJustified(registersLen, QChar(' '), true);
stream << " | " + memoryText.leftJustified(memoryLen, QChar(' '), true) + " |" + fullComment;
if(htmlStream)
{
*htmlStream << QString("<tr><td>%1</td><td>%2</td><td>").arg(mTraceFile->getIndexText(i), address.toHtmlEscaped());
if(copyBytes)
*htmlStream << QString("%1</td><td>").arg(bytesHTML);
*htmlStream << QString("%1</td><td>").arg(htmlDisassembly);
*htmlStream << QString("%1</td><td>").arg(registersText);
*htmlStream << QString("%1</td><td>").arg(memoryText);
if(!comment.isEmpty())
{
if(autocomment)
{
*htmlStream << QString("<span style=\"color:%1").arg(mAutoCommentColor.name());
if(mAutoCommentBackgroundColor != Qt::transparent)
*htmlStream << QString(";background-color:%2").arg(mAutoCommentBackgroundColor.name());
}
else
{
*htmlStream << QString("<span style=\"color:%1").arg(mCommentColor.name());
if(mCommentBackgroundColor != Qt::transparent)
*htmlStream << QString(";background-color:%2").arg(mCommentBackgroundColor.name());
}
*htmlStream << "\">" << comment.toHtmlEscaped() << "</span></td></tr>";
}
else
{
char label[MAX_LABEL_SIZE];
if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label))
{
comment = QString::fromUtf8(label);
*htmlStream << QString("<span style=\"color:%1").arg(mLabelColor.name());
if(mLabelBackgroundColor != Qt::transparent)
*htmlStream << QString(";background-color:%2").arg(mLabelBackgroundColor.name());
*htmlStream << "\">" << comment.toHtmlEscaped() << "</span></td></tr>";
}
else
*htmlStream << "</td></tr>";
}
}
}
if(htmlStream)
*htmlStream << "</table>";
}
void TraceBrowser::copySelectionSlot(bool copyBytes)
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
QString selectionString = "";
QString selectionHtmlString = "";
QTextStream stream(&selectionString);
if(getSelectionEnd() - getSelectionStart() < 2048)
{
QTextStream htmlStream(&selectionHtmlString);
pushSelectionInto(copyBytes, stream, &htmlStream);
Bridge::CopyToClipboard(selectionString, selectionHtmlString);
}
else
{
pushSelectionInto(copyBytes, stream, nullptr);
Bridge::CopyToClipboard(selectionString);
}
}
void TraceBrowser::copySelectionToFileSlot(bool copyBytes)
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
QString fileName = QFileDialog::getSaveFileName(this, tr("Open File"), "", tr("Text Files (*.txt)"));
if(fileName != "")
{
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly))
{
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream stream(&file);
pushSelectionInto(copyBytes, stream);
file.close();
}
}
void TraceBrowser::copySelectionSlot()
{
copySelectionSlot(true);
}
void TraceBrowser::copySelectionToFileSlot()
{
copySelectionToFileSlot(true);
}
void TraceBrowser::copySelectionNoBytesSlot()
{
copySelectionSlot(false);
}
void TraceBrowser::copySelectionToFileNoBytesSlot()
{
copySelectionToFileSlot(false);
}
void TraceBrowser::copyDisassemblySlot()
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
QString clipboard = "";
if(getSelectionEnd() - getSelectionStart() < 2048)
{
QString clipboardHtml = QString("<div style=\"font-family: %1; font-size: %2px\">").arg(font().family()).arg(getRowHeight());
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
{
clipboard += "\r\n";
clipboardHtml += "<br/>";
}
RichTextPainter::List richText;
const Instruction_t & inst = mTraceFile->Instruction(i);
ZydisTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, &clipboardHtml, clipboard);
}
clipboardHtml += QString("</div>");
Bridge::CopyToClipboard(clipboard, clipboardHtml);
}
else
{
for(auto i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
if(i != getSelectionStart())
{
clipboard += "\r\n";
}
RichTextPainter::List richText;
const Instruction_t & inst = mTraceFile->Instruction(i);
ZydisTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, nullptr, clipboard);
}
Bridge::CopyToClipboard(clipboard);
}
}
void TraceBrowser::copyRvaSlot()
{
QString text;
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
for(unsigned long long i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
duint cip = mTraceFile->Registers(i).regcontext.cip;
duint base = DbgFunctions()->ModBaseFromAddr(cip);
if(base)
{
if(i != getSelectionStart())
text += "\r\n";
text += ToHexString(cip - base);
}
else
{
SimpleWarningBox(this, tr("Error!"), tr("Selection not in a module..."));
return;
}
}
Bridge::CopyToClipboard(text);
}
void TraceBrowser::copyFileOffsetSlot()
{
QString text;
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
for(unsigned long long i = getSelectionStart(); i <= getSelectionEnd(); i++)
{
duint cip = mTraceFile->Registers(i).regcontext.cip;
cip = DbgFunctions()->VaToFileOffset(cip);
if(cip)
{
if(i != getSelectionStart())
text += "\r\n";
text += ToHexString(cip);
}
else
{
SimpleErrorBox(this, tr("Error!"), tr("Selection not in a file..."));
return;
}
}
Bridge::CopyToClipboard(text);
}
void TraceBrowser::exportSlot()
{
if(mTraceFile == nullptr || mTraceFile->Progress() < 100)
return;
std::vector<QString> headers;
headers.reserve(getColumnCount());
for(int i = 0; i < getColumnCount(); i++)
headers.push_back(getColTitle(i));
ExportCSV(getRowCount(), getColumnCount(), headers, [this](dsint row, dsint col)
{
QString temp;
switch(col)
{
case Index:
return mTraceFile->getIndexText(row);
case Address:
{
if(!DbgIsDebugging())
return ToPtrString(mTraceFile->Registers(row).regcontext.cip);
else
return getAddrText(mTraceFile->Registers(row).regcontext.cip, 0, true);
}
case Opcode:
{
for(auto i : getRichBytes(mTraceFile->Instruction(row)))
temp += i.text;
return temp;
}
case Disassembly:
{
for(auto i : mTraceFile->Instruction(row).tokens.tokens)
temp += i.text;
return temp;
}
case Registers:
{
for(auto i : registersTokens(row).tokens)
temp += i.text;
return temp;
}
case Memory:
{
for(auto i : memoryTokens(row).tokens)
temp += i.text;
return temp;
}
case Comments:
{
if(DbgIsDebugging())
{
//TODO: draw arguments
QString comment;
bool autoComment = false;
char label[MAX_LABEL_SIZE] = "";
if(GetCommentFormat(mTraceFile->Registers(row).regcontext.cip, comment, &autoComment))
{
return QString(comment);
}
else if(DbgGetLabelAt(mTraceFile->Registers(row).regcontext.cip, SEG_DEFAULT, label)) // label but no comment
{
return QString(label);
}
}
return QString();
}
default:
return QString();
}
});
}
void TraceBrowser::enableHighlightingModeSlot()
{
if(mHighlightingMode)
mHighlightingMode = false;
else
mHighlightingMode = true;
reloadData();
}
void TraceBrowser::searchConstantSlot()
{
if(!isFileOpened())
return;
WordEditDialog constantDlg(this);
duint initialConstant = mTraceFile->Registers(getInitialSelection()).regcontext.cip;
constantDlg.setup(tr("Constant"), initialConstant, sizeof(duint));
if(constantDlg.exec() == QDialog::Accepted)
{
TraceFileSearchConstantRange(mTraceFile, constantDlg.getVal(), constantDlg.getVal());
emit displayReferencesWidget();
}
}
void TraceBrowser::searchMemRefSlot()
{
WordEditDialog memRefDlg(this);
memRefDlg.setup(tr("References"), 0, sizeof(duint));
if(memRefDlg.exec() == QDialog::Accepted)
{
TraceFileSearchMemReference(mTraceFile, memRefDlg.getVal());
emit displayReferencesWidget();
}
}
void TraceBrowser::updateSlot()
{
if(mTraceFile && mTraceFile->Progress() == 100) // && this->isVisible()
{
if(isRecording())
{
mTraceFile->purgeLastPage();
setRowCount(mTraceFile->Length());
}
}
else
setRowCount(0);
reloadData();
}
void TraceBrowser::synchronizeCpuSlot()
{
mTraceSyncCpu = !mTraceSyncCpu;
BridgeSettingSetUint("Gui", "TraceSyncCpu", mTraceSyncCpu);
selectionChangedSlot(getSelectionStart());
}
void TraceBrowser::gotoIndexSlot(duint index)
{
disasm(index, false);
} |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceBrowser.h | #pragma once
#include "AbstractTableView.h"
#include "VaHistory.h"
#include "QBeaEngine.h"
class TraceFileReader;
class BreakpointMenu;
class MRUList;
class CommonActions;
class TraceBrowser : public AbstractTableView
{
Q_OBJECT
public:
explicit TraceBrowser(QWidget* parent = 0);
~TraceBrowser() override;
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
void prepareData() override;
void updateColors() override;
void expandSelectionUpTo(duint to);
void setSingleSelection(duint index);
duint getInitialSelection();
duint getSelectionSize();
duint getSelectionStart();
duint getSelectionEnd();
bool isFileOpened() const;
TraceFileReader* getTraceFile() { return mTraceFile; }
static bool isRecording();
static bool toggleTraceRecording(QWidget* parent);
private:
enum TableColumnIndex
{
Index,
Address,
Opcode,
Disassembly,
Registers,
Memory,
Comments
};
void setupRightClickContextMenu();
void makeVisible(duint index);
QString getAddrText(dsint cur_addr, char label[MAX_LABEL_SIZE], bool getLabel);
RichTextPainter::List getRichBytes(const Instruction_t & instr) const;
void pushSelectionInto(bool copyBytes, QTextStream & stream, QTextStream* htmlStream = nullptr);
void copySelectionSlot(bool copyBytes);
void copySelectionToFileSlot(bool copyBytes);
void contextMenuEvent(QContextMenuEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
ZydisTokenizer::InstructionToken memoryTokens(unsigned long long atIndex);
ZydisTokenizer::InstructionToken registersTokens(unsigned long long atIndex);
VaHistory mHistory;
MenuBuilder* mMenuBuilder;
CommonActions* mCommonActions;
bool mRvaDisplayEnabled;
duint mRvaDisplayBase;
struct SelectionData
{
duint firstSelectedIndex;
duint fromIndex;
duint toIndex;
};
SelectionData mSelection;
ZydisTokenizer::SingleToken mHighlightToken;
bool mHighlightingMode;
bool mPermanentHighlightingMode;
bool mTraceSyncCpu;
bool mShowMnemonicBrief;
TraceFileReader* mTraceFile;
BreakpointMenu* mBreakpointMenu;
MRUList* mMRUList;
QString mFileName;
QColor mBytesColor;
QColor mBytesBackgroundColor;
QColor mInstructionHighlightColor;
QColor mSelectionColor;
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 mAutoCommentColor;
QColor mAutoCommentBackgroundColor;
QColor mCommentColor;
QColor mCommentBackgroundColor;
QColor mDisassemblyRelocationUnderlineColor;
QColor mMnemonicBriefColor;
QColor mMnemonicBriefBackgroundColor;
QColor mConditionalJumpLineTrueColor;
QColor mLoopColor;
QColor mFunctionColor;
QPen mLoopPen;
QPen mFunctionPen;
QPen mConditionalTruePen;
// 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);
signals:
void displayReferencesWidget();
void displayLogWidget();
void selectionChanged(unsigned long long selection);
public slots:
void openFileSlot();
void openSlot(const QString & fileName);
void toggleTraceRecordingSlot();
void closeFileSlot();
void closeDeleteSlot();
void parseFinishedSlot();
void tokenizerConfigUpdatedSlot();
void selectionChangedSlot(unsigned long long selection);
void gotoSlot();
void rtrSlot();
void gotoPreviousSlot();
void gotoNextSlot();
void enableHighlightingModeSlot();
void mnemonicBriefSlot();
void mnemonicHelpSlot();
void copyDisassemblySlot();
void copyCipSlot();
void copyIndexSlot();
void copySelectionSlot();
void copySelectionNoBytesSlot();
void copySelectionToFileSlot();
void copySelectionToFileNoBytesSlot();
void copyFileOffsetSlot();
void copyRvaSlot();
void exportSlot();
void searchConstantSlot();
void searchMemRefSlot();
void updateSlot();
void synchronizeCpuSlot();
void gotoIndexSlot(duint index);
protected:
void disasm(unsigned long long index, bool history = true);
}; |
C++ | x64dbg-development/src/gui/Src/Tracer/TraceFileReader.cpp | #include "TraceFileReaderInternal.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
#include "MiscUtil.h"
#include "StringUtil.h"
#include <sysinfoapi.h>
TraceFileReader::TraceFileReader(QObject* parent) : QObject(parent)
{
length = 0;
progress = 0;
error = true;
parser = nullptr;
lastAccessedPage = nullptr;
lastAccessedIndexOffset = 0;
hashValue = 0;
EXEPath.clear();
int maxModuleSize = (int)ConfigUint("Disassembler", "MaxModuleSize");
mDisasm = new QBeaEngine(maxModuleSize);
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(tokenizerUpdatedSlot()));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(tokenizerUpdatedSlot()));
}
TraceFileReader::~TraceFileReader()
{
delete mDisasm;
}
bool TraceFileReader::Open(const QString & fileName)
{
if(parser != NULL && parser->isRunning()) //Trace file parser is busy
{
parser->requestInterruption();
parser->wait();
}
error = true;
traceFile.setFileName(fileName);
traceFile.open(QFile::ReadOnly);
if(traceFile.isReadable())
{
parser = new TraceFileParser(this);
connect(parser, SIGNAL(finished()), this, SLOT(parseFinishedSlot()));
progress.store(0);
traceFile.moveToThread(parser);
parser->start();
return true;
}
else
{
progress.store(0);
emit parseFinished();
return false;
}
}
void TraceFileReader::Close()
{
if(parser != NULL)
{
parser->requestInterruption();
parser->wait();
}
traceFile.close();
progress.store(0);
length = 0;
fileIndex.clear();
hashValue = 0;
EXEPath.clear();
error = false;
}
bool TraceFileReader::Delete()
{
if(parser != NULL)
{
parser->requestInterruption();
parser->wait();
}
bool value = traceFile.remove();
progress.store(0);
length = 0;
fileIndex.clear();
hashValue = 0;
EXEPath.clear();
error = false;
return value;
}
void TraceFileReader::parseFinishedSlot()
{
if(!error)
progress.store(100);
else
progress.store(0);
delete parser;
parser = nullptr;
emit parseFinished();
//for(auto i : fileIndex)
//GuiAddLogMessage(QString("%1;%2;%3\r\n").arg(i.first).arg(i.second.first).arg(i.second.second).toUtf8().constData());
}
// Return if the file read was error
bool TraceFileReader::isError() const
{
return error;
}
// Return 100 when loading is completed
int TraceFileReader::Progress() const
{
return progress.load();
}
// Return the count of instructions
unsigned long long TraceFileReader::Length() const
{
return length;
}
QString TraceFileReader::getIndexText(unsigned long long index) const
{
QString indexString;
indexString = QString::number(index, 16).toUpper();
if(length < 16)
return indexString;
int digits;
digits = floor(log2(length - 1) / 4) + 1;
digits -= indexString.size();
while(digits > 0)
{
indexString = '0' + indexString;
digits = digits - 1;
}
return indexString;
}
// Return the hash value of executable to be matched against current executable
duint TraceFileReader::HashValue() const
{
return hashValue;
}
// Return the executable name of executable
const QString & TraceFileReader::ExePath() const
{
return EXEPath;
}
// Return the registers context at a given index
REGDUMP TraceFileReader::Registers(unsigned long long index)
{
unsigned long long base;
TraceFilePage* page = getPage(index, &base);
if(page == nullptr)
{
REGDUMP registers;
memset(®isters, 0, sizeof(registers));
return registers;
}
else
return page->Registers(index - base);
}
// Return the opcode at a given index. buffer must be 16 bytes long.
void TraceFileReader::OpCode(unsigned long long index, unsigned char* buffer, int* opcodeSize)
{
unsigned long long base;
TraceFilePage* page = getPage(index, &base);
if(page == nullptr)
{
memset(buffer, 0, 16);
*opcodeSize = 0;
return;
}
else
page->OpCode(index - base, buffer, opcodeSize);
}
// Return the disassembled instruction at a given index.
const Instruction_t & TraceFileReader::Instruction(unsigned long long index)
{
unsigned long long base;
TraceFilePage* page = getPage(index, &base);
// The caller must guarantee page is not null, most likely they have already called some other getters.
return page->Instruction(index - base, *mDisasm);
}
// Return the thread id at a given index
DWORD TraceFileReader::ThreadId(unsigned long long index)
{
unsigned long long base;
TraceFilePage* page = getPage(index, &base);
if(page == nullptr)
return 0;
else
return page->ThreadId(index - base);
}
// Return the number of recorded memory accesses at a given index
int TraceFileReader::MemoryAccessCount(unsigned long long index)
{
unsigned long long base;
TraceFilePage* page = getPage(index, &base);
if(page == nullptr)
return 0;
else
return page->MemoryAccessCount(index - base);
}
// Return the memory access info at a given index
void TraceFileReader::MemoryAccessInfo(unsigned long long index, duint* address, duint* oldMemory, duint* newMemory, bool* isValid)
{
unsigned long long base;
TraceFilePage* page = getPage(index, &base);
if(page == nullptr)
return;
else
return page->MemoryAccessInfo(index - base, address, oldMemory, newMemory, isValid);
}
static size_t getMaxCachedPages()
{
#ifdef _WIN64
MEMORYSTATUSEX meminfo;
memset(&meminfo, 0, sizeof(meminfo));
meminfo.dwLength = sizeof(meminfo);
if(GlobalMemoryStatusEx(&meminfo))
{
meminfo.ullAvailPhys >>= 20;
if(meminfo.ullAvailPhys >= 4096) // more than 4GB free memory!
return 2048;
else if(meminfo.ullAvailPhys <= 1024) // less than 1GB free memory!
return 100;
else
return 512;
} // GlobalMemoryStatusEx failed?
else
return 100;
#else //x86
return 100;
#endif
}
// Used internally to get the page for the given index and read from disk if necessary
TraceFilePage* TraceFileReader::getPage(unsigned long long index, unsigned long long* base)
{
// Try to access the most recently used page
if(lastAccessedPage)
{
if(index >= lastAccessedIndexOffset && index < lastAccessedIndexOffset + lastAccessedPage->Length())
{
*base = lastAccessedIndexOffset;
return lastAccessedPage;
}
}
// Try to access pages in memory
const auto cache = pages.find(Range(index, index));
if(cache != pages.cend())
{
if(cache->first.first >= index && cache->first.second <= index)
{
if(lastAccessedPage)
GetSystemTimes(nullptr, nullptr, &lastAccessedPage->lastAccessed);
lastAccessedPage = &cache->second;
lastAccessedIndexOffset = cache->first.first;
GetSystemTimes(nullptr, nullptr, &lastAccessedPage->lastAccessed);
*base = lastAccessedIndexOffset;
return lastAccessedPage;
}
}
else if(index >= Length()) //Out of bound
return nullptr;
// Remove an oldest page from system memory to make room for a new one.
size_t maxPages = getMaxCachedPages();
while(pages.size() >= maxPages)
{
FILETIME pageOutTime = pages.begin()->second.lastAccessed;
Range pageOutIndex = pages.begin()->first;
for(auto & i : pages)
{
if(pageOutTime.dwHighDateTime < i.second.lastAccessed.dwHighDateTime || (pageOutTime.dwHighDateTime == i.second.lastAccessed.dwHighDateTime && pageOutTime.dwLowDateTime < i.second.lastAccessed.dwLowDateTime))
{
pageOutTime = i.second.lastAccessed;
pageOutIndex = i.first;
}
}
pages.erase(pageOutIndex);
}
//binary search fileIndex to get file offset, push a TraceFilePage into cache and return it.
size_t start = 0;
size_t end = fileIndex.size() - 1;
size_t middle = (start + end) / 2;
std::pair<unsigned long long, Range>* fileOffset;
while(true)
{
if(start == end || start == end - 1)
{
if(fileIndex[end].first <= index)
fileOffset = &fileIndex[end];
else
fileOffset = &fileIndex[start];
break;
}
if(fileIndex[middle].first > index)
end = middle;
else if(fileIndex[middle].first == index)
{
fileOffset = &fileIndex[middle];
break;
}
else
start = middle;
middle = (start + end) / 2;
}
// Read the requested page from disk and return
if(fileOffset->second.second + fileOffset->first >= index && fileOffset->first <= index)
{
pages.insert(std::make_pair(Range(fileOffset->first, fileOffset->first + fileOffset->second.second - 1), TraceFilePage(this, fileOffset->second.first, fileOffset->second.second)));
const auto newPage = pages.find(Range(index, index));
if(newPage != pages.cend())
{
if(lastAccessedPage)
GetSystemTimes(nullptr, nullptr, &lastAccessedPage->lastAccessed);
lastAccessedPage = &newPage->second;
lastAccessedIndexOffset = newPage->first.first;
GetSystemTimes(nullptr, nullptr, &lastAccessedPage->lastAccessed);
*base = lastAccessedIndexOffset;
return lastAccessedPage;
}
else
{
GuiAddLogMessage("PAGEFAULT2\r\n"); //debug
return nullptr; //???
}
}
else
{
GuiAddLogMessage("PAGEFAULT1\r\n"); //debug
return nullptr; //???
}
}
void TraceFileReader::tokenizerUpdatedSlot()
{
mDisasm->UpdateConfig();
for(auto & i : pages)
i.second.updateInstructions();
}
//Parser
static bool checkKey(const QJsonObject & root, const QString & key, const QString & value)
{
const auto obj = root.find(key);
if(obj == root.constEnd())
throw std::wstring(L"Unspecified");
QJsonValue val = obj.value();
if(val.isString())
if(val.toString() == value)
return true;
return false;
}
void TraceFileParser::readFileHeader(TraceFileReader* that)
{
LARGE_INTEGER header;
bool ok;
if(that->traceFile.read((char*)&header, 8) != 8)
throw std::wstring(L"Unspecified");
if(header.LowPart != MAKEFOURCC('T', 'R', 'A', 'C'))
throw std::wstring(L"File type mismatch");
if(header.HighPart > 16384)
throw std::wstring(L"Header info is too big");
QByteArray jsonData = that->traceFile.read(header.HighPart);
if(jsonData.size() != header.HighPart)
throw std::wstring(L"JSON header is corrupted");
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
if(jsonDoc.isNull())
throw std::wstring(L"JSON header is corrupted");
const QJsonObject jsonRoot = jsonDoc.object();
const auto ver = jsonRoot.find("ver");
if(ver == jsonRoot.constEnd())
throw std::wstring(L"Version not supported");
QJsonValue verVal = ver.value();
if(verVal.toInt(0) != 1)
throw std::wstring(L"Version not supported");
checkKey(jsonRoot, "arch", ArchValue("x86", "x64"));
checkKey(jsonRoot, "compression", "");
const auto hashAlgorithmObj = jsonRoot.find("hashAlgorithm");
if(hashAlgorithmObj != jsonRoot.constEnd())
{
QJsonValue hashAlgorithmVal = hashAlgorithmObj.value();
if(hashAlgorithmVal.toString() == "murmurhash")
{
const auto hashObj = jsonRoot.find("hash");
if(hashObj != jsonRoot.constEnd())
{
QJsonValue hashVal = hashObj.value();
QString a = hashVal.toString();
if(a.startsWith("0x"))
{
a = a.mid(2);
#ifdef _WIN64
that->hashValue = a.toLongLong(&ok, 16);
#else //x86
that->hashValue = a.toLong(&ok, 16);
#endif //_WIN64
if(!ok)
that->hashValue = 0;
}
}
}
}
const auto pathObj = jsonRoot.find("path");
if(pathObj != jsonRoot.constEnd())
{
QJsonValue pathVal = pathObj.value();
that->EXEPath = pathVal.toString();
}
}
static bool readBlock(QFile & traceFile)
{
if(!traceFile.isReadable())
throw std::wstring(L"File is not readable");
unsigned char blockType;
unsigned char changedCountFlags[3]; //reg changed count, mem accessed count, flags
if(traceFile.read((char*)&blockType, 1) != 1)
throw std::wstring(L"Read block type failed");
if(blockType == 0)
{
if(traceFile.read((char*)&changedCountFlags, 3) != 3)
throw std::wstring(L"Read flags failed");
//skipping: thread id, registers
if(traceFile.seek(traceFile.pos() + ((changedCountFlags[2] & 0x80) ? 4 : 0) + (changedCountFlags[2] & 0x0F) + changedCountFlags[0] * (1 + sizeof(duint))) == false)
throw std::wstring(L"Unspecified");
QByteArray memflags;
memflags = traceFile.read(changedCountFlags[1]);
if(memflags.length() < changedCountFlags[1])
throw std::wstring(L"Read memory flags failed");
unsigned int skipOffset = 0;
for(unsigned char i = 0; i < changedCountFlags[1]; i++)
skipOffset += ((memflags[i] & 1) == 1) ? 2 : 3;
if(traceFile.seek(traceFile.pos() + skipOffset * sizeof(duint)) == false)
throw std::wstring(L"Unspecified");
//Gathered information, build index
if(changedCountFlags[0] == (FIELD_OFFSET(REGDUMP, lastError) + sizeof(DWORD)) / sizeof(duint))
return true;
else
return false;
}
else
throw std::wstring(L"Unsupported block type");
return false;
}
void TraceFileParser::run()
{
TraceFileReader* that = dynamic_cast<TraceFileReader*>(parent());
unsigned long long index = 0;
unsigned long long lastIndex = 0;
if(that == NULL)
{
return; //Error
}
try
{
auto filesize = that->traceFile.size();
if(filesize == 0)
throw std::wstring(L"File is empty");
//Process file header
readFileHeader(that);
//Update progress
that->progress.store(that->traceFile.pos() * 100 / filesize);
//Process file content
while(!that->traceFile.atEnd())
{
quint64 blockStart = that->traceFile.pos();
bool isPageBoundary = readBlock(that->traceFile);
if(isPageBoundary)
{
if(lastIndex != 0)
that->fileIndex.back().second.second = index - (lastIndex - 1);
that->fileIndex.push_back(std::make_pair(index, TraceFileReader::Range(blockStart, 0)));
lastIndex = index + 1;
//Update progress
that->progress.store(that->traceFile.pos() * 100 / filesize);
if(that->progress == 100)
that->progress = 99;
if(this->isInterruptionRequested() && !that->traceFile.atEnd()) //Cancel loading
throw std::wstring(L"Canceled");
}
index++;
}
if(index > 0)
that->fileIndex.back().second.second = index - (lastIndex - 1);
that->error = false;
that->length = index;
that->progress = 100;
}
catch(const std::wstring & errReason)
{
Q_UNUSED(errReason);
//MessageBox(0, errReason.c_str(), L"debug", MB_ICONERROR);
that->error = true;
}
catch(std::bad_alloc &)
{
that->error = true;
}
that->traceFile.moveToThread(that->thread());
}
// Remove last page from memory and read from disk again to show updates
void TraceFileReader::purgeLastPage()
{
unsigned long long index = 0;
unsigned long long lastIndex = 0;
bool isBlockExist = false;
if(length > 0)
{
index = fileIndex.back().first;
const auto lastpage = pages.find(Range(index, index));
if(lastpage != pages.cend())
{
//Purge last accessed page
if(index == lastAccessedIndexOffset)
lastAccessedPage = nullptr;
//Remove last page from page cache
pages.erase(lastpage);
}
//Seek start of last page
traceFile.seek(fileIndex.back().second.first);
//Remove last page from file index cache
fileIndex.pop_back();
}
try
{
while(!traceFile.atEnd())
{
quint64 blockStart = traceFile.pos();
bool isPageBoundary = readBlock(traceFile);
if(isPageBoundary)
{
if(lastIndex != 0)
fileIndex.back().second.second = index - (lastIndex - 1);
fileIndex.push_back(std::make_pair(index, TraceFileReader::Range(blockStart, 0)));
lastIndex = index + 1;
isBlockExist = true;
}
index++;
}
if(isBlockExist)
fileIndex.back().second.second = index - (lastIndex - 1);
error = false;
length = index;
}
catch(std::wstring & errReason)
{
Q_UNUSED(errReason);
error = true;
}
}
//TraceFilePage
TraceFilePage::TraceFilePage(TraceFileReader* parent, unsigned long long fileOffset, unsigned long long maxLength)
{
DWORD lastThreadId = 0;
union
{
REGDUMP registers;
duint regwords[(FIELD_OFFSET(REGDUMP, lastError) + sizeof(DWORD)) / sizeof(duint)];
};
unsigned char changed[_countof(regwords)];
duint regContent[_countof(regwords)];
duint memAddress[MAX_MEMORY_OPERANDS];
duint memOldContent[MAX_MEMORY_OPERANDS];
duint memNewContent[MAX_MEMORY_OPERANDS];
size_t memOperandOffset = 0;
mParent = parent;
length = 0;
GetSystemTimes(nullptr, nullptr, &lastAccessed); //system user time, no GetTickCount64() for XP compatibility.
memset(®isters, 0, sizeof(registers));
try
{
if(mParent->traceFile.seek(fileOffset) == false)
throw std::exception();
//Process file content
while(!mParent->traceFile.atEnd() && length < maxLength)
{
if(!mParent->traceFile.isReadable())
throw std::exception();
unsigned char blockType;
unsigned char changedCountFlags[3]; //reg changed count, mem accessed count, flags
mParent->traceFile.read((char*)&blockType, 1);
if(blockType == 0)
{
if(mParent->traceFile.read((char*)&changedCountFlags, 3) != 3)
throw std::exception();
if(changedCountFlags[2] & 0x80) //Thread Id
mParent->traceFile.read((char*)&lastThreadId, 4);
threadId.push_back(lastThreadId);
if((changedCountFlags[2] & 0x0F) > 0) //Opcode
{
QByteArray opcode = mParent->traceFile.read(changedCountFlags[2] & 0x0F);
if(opcode.isEmpty())
throw std::exception();
opcodeOffset.push_back(opcodes.size());
opcodeSize.push_back(opcode.size());
opcodes.append(opcode);
}
else
throw std::exception();
if(changedCountFlags[0] > 0) //registers
{
int lastPosition = -1;
if(changedCountFlags[0] > _countof(regwords)) //Bad count?
throw std::exception();
if(mParent->traceFile.read((char*)changed, changedCountFlags[0]) != changedCountFlags[0])
throw std::exception();
if(mParent->traceFile.read((char*)regContent, changedCountFlags[0] * sizeof(duint)) != changedCountFlags[0] * sizeof(duint))
{
throw std::exception();
}
for(int i = 0; i < changedCountFlags[0]; i++)
{
lastPosition = lastPosition + changed[i] + 1;
if(lastPosition < _countof(regwords) && lastPosition >= 0)
regwords[lastPosition] = regContent[i];
else //out of bounds?
{
throw std::exception();
}
}
mRegisters.push_back(registers);
}
if(changedCountFlags[1] > 0) //memory
{
QByteArray memflags;
if(changedCountFlags[1] > _countof(memAddress)) //too many memory operands?
throw std::exception();
memflags = mParent->traceFile.read(changedCountFlags[1]);
if(memflags.length() < changedCountFlags[1])
throw std::exception();
memoryOperandOffset.push_back(memOperandOffset);
memOperandOffset += changedCountFlags[1];
if(mParent->traceFile.read((char*)memAddress, sizeof(duint) * changedCountFlags[1]) != sizeof(duint) * changedCountFlags[1])
throw std::exception();
if(mParent->traceFile.read((char*)memOldContent, sizeof(duint) * changedCountFlags[1]) != sizeof(duint) * changedCountFlags[1])
throw std::exception();
for(unsigned char i = 0; i < changedCountFlags[1]; i++)
{
if((memflags[i] & 1) == 0)
{
if(mParent->traceFile.read((char*)&memNewContent[i], sizeof(duint)) != sizeof(duint))
throw std::exception();
}
else
memNewContent[i] = memOldContent[i];
}
for(unsigned char i = 0; i < changedCountFlags[1]; i++)
{
memoryFlags.push_back(memflags[i]);
memoryAddress.push_back(memAddress[i]);
oldMemory.push_back(memOldContent[i]);
newMemory.push_back(memNewContent[i]);
}
}
else
memoryOperandOffset.push_back(memOperandOffset);
length++;
}
else
throw std::exception();
}
}
catch(const std::exception &)
{
mParent->error = true;
}
}
unsigned long long TraceFilePage::Length() const
{
return length;
}
const REGDUMP & TraceFilePage::Registers(unsigned long long index) const
{
return mRegisters.at(index);
}
void TraceFilePage::OpCode(unsigned long long index, unsigned char* buffer, int* opcodeSize) const
{
*opcodeSize = this->opcodeSize.at(index);
memcpy(buffer, opcodes.constData() + opcodeOffset.at(index), *opcodeSize);
}
const Instruction_t & TraceFilePage::Instruction(unsigned long long index, QBeaEngine & mDisasm)
{
if(instructions.size() == 0)
{
instructions.reserve(length);
for(unsigned long long i = 0; i < length; i++)
{
instructions.emplace_back(mDisasm.DisassembleAt((const byte_t*)opcodes.constData() + opcodeOffset.at(i), opcodeSize.at(i), 0, Registers(i).regcontext.cip, false));
}
}
return instructions.at(index);
}
DWORD TraceFilePage::ThreadId(unsigned long long index) const
{
return threadId.at(index);
}
int TraceFilePage::MemoryAccessCount(unsigned long long index) const
{
size_t a = memoryOperandOffset.at(index);
if(index == length - 1)
return (int)(memoryAddress.size() - a);
else
return (int)(memoryOperandOffset.at(index + 1) - a);
}
void TraceFilePage::MemoryAccessInfo(unsigned long long index, duint* address, duint* oldMemory, duint* newMemory, bool* isValid) const
{
auto count = MemoryAccessCount(index);
auto base = memoryOperandOffset.at(index);
for(int i = 0; i < count; i++)
{
address[i] = memoryAddress.at(base + i);
oldMemory[i] = this->oldMemory.at(base + i);
newMemory[i] = this->newMemory.at(base + i);
isValid[i] = true; // proposed flag
}
}
void TraceFilePage::updateInstructions()
{
instructions.clear();
} |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceFileReader.h | #pragma once
#include "Bridge.h"
#include <QFile>
#include <atomic>
class TraceFileParser;
class TraceFilePage;
class QBeaEngine;
struct Instruction_t;
#define MAX_MEMORY_OPERANDS 32
class TraceFileReader : public QObject
{
Q_OBJECT
public:
TraceFileReader(QObject* parent = NULL);
~TraceFileReader();
bool Open(const QString & fileName);
void Close();
bool Delete();
bool isError() const;
int Progress() const;
QString getIndexText(unsigned long long index) const;
unsigned long long Length() const;
REGDUMP Registers(unsigned long long index);
void OpCode(unsigned long long index, unsigned char* buffer, int* opcodeSize);
const Instruction_t & Instruction(unsigned long long index);
DWORD ThreadId(unsigned long long index);
int MemoryAccessCount(unsigned long long index);
void MemoryAccessInfo(unsigned long long index, duint* address, duint* oldMemory, duint* newMemory, bool* isValid);
duint HashValue() const;
const QString & ExePath() const;
void purgeLastPage();
signals:
void parseFinished();
public slots:
void parseFinishedSlot();
private slots:
void tokenizerUpdatedSlot();
private:
typedef std::pair<unsigned long long, unsigned long long> Range;
struct RangeCompare //from addrinfo.h
{
bool operator()(const Range & a, const Range & b) const //a before b?
{
return a.second < b.first;
}
};
QFile traceFile;
unsigned long long length;
duint hashValue;
QString EXEPath;
std::vector<std::pair<unsigned long long, Range>> fileIndex; //index;<file offset;length>
std::atomic<int> progress;
bool error;
TraceFilePage* lastAccessedPage;
unsigned long long lastAccessedIndexOffset;
friend class TraceFileParser;
friend class TraceFilePage;
TraceFileParser* parser;
std::map<Range, TraceFilePage, RangeCompare> pages;
TraceFilePage* getPage(unsigned long long index, unsigned long long* base);
QBeaEngine* mDisasm;
}; |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceFileReaderInternal.h | #pragma once
#include <QThread>
#include "TraceFileReader.h"
#include "QBeaEngine.h"
class TraceFileParser : public QThread
{
Q_OBJECT
friend class TraceFileReader;
TraceFileParser(TraceFileReader* parent) : QThread(parent) {}
static void readFileHeader(TraceFileReader* that);
void run();
};
class TraceFilePage
{
public:
TraceFilePage(TraceFileReader* parent, unsigned long long fileOffset, unsigned long long maxLength);
unsigned long long Length() const;
const REGDUMP & Registers(unsigned long long index) const;
void OpCode(unsigned long long index, unsigned char* buffer, int* opcodeSize) const;
const Instruction_t & Instruction(unsigned long long index, QBeaEngine & mDisasm);
DWORD ThreadId(unsigned long long index) const;
int MemoryAccessCount(unsigned long long index) const;
void MemoryAccessInfo(unsigned long long index, duint* address, duint* oldMemory, duint* newMemory, bool* isValid) const;
FILETIME lastAccessed; //system user time
void updateInstructions();
private:
friend class TraceFileReader;
TraceFileReader* mParent;
std::vector<REGDUMP> mRegisters;
QByteArray opcodes;
std::vector<size_t> opcodeOffset;
std::vector<unsigned char> opcodeSize;
std::vector<Instruction_t> instructions;
std::vector<size_t> memoryOperandOffset;
std::vector<char> memoryFlags;
std::vector<duint> memoryAddress;
std::vector<duint> oldMemory;
std::vector<duint> newMemory;
std::vector<DWORD> threadId;
unsigned long long length;
}; |
C++ | x64dbg-development/src/gui/Src/Tracer/TraceFileSearch.cpp | #include "TraceFileReader.h"
#include "TraceFileSearch.h"
#include "zydis_wrapper.h"
#include "StringUtil.h"
#include <QCoreApplication>
static bool inRange(duint value, duint start, duint end)
{
return value >= start && value <= end;
}
int TraceFileSearchConstantRange(TraceFileReader* file, duint start, duint end)
{
int count = 0;
Zydis zy;
QString title;
if(start == end)
title = QCoreApplication::translate("TraceFileSearch", "Constant: %1").arg(ToPtrString(start));
else
title = QCoreApplication::translate("TraceFileSearch", "Range: %1-%2").arg(ToPtrString(start)).arg(ToPtrString(end));
GuiReferenceInitialize(title.toUtf8().constData());
GuiReferenceAddColumn(sizeof(duint) * 2, QCoreApplication::translate("TraceFileSearch", "Address").toUtf8().constData());
GuiReferenceAddColumn(5, QCoreApplication::translate("TraceFileSearch", "Index").toUtf8().constData());
GuiReferenceAddColumn(100, QCoreApplication::translate("TraceFileSearch", "Disassembly").toUtf8().constData());
GuiReferenceAddCommand(QCoreApplication::translate("TraceFileSearch", "Follow index in trace").toUtf8().constData(), "gototrace 0x$1");
GuiReferenceSetRowCount(0);
REGISTERCONTEXT regcontext;
for(unsigned long long index = 0; index < file->Length(); index++)
{
regcontext = file->Registers(index).regcontext;
bool found = false;
//Registers
#define FINDREG(fieldName) found |= inRange(regcontext.##fieldName, start, end)
FINDREG(cax);
FINDREG(ccx);
FINDREG(cdx);
FINDREG(cbx);
FINDREG(csp);
FINDREG(cbp);
FINDREG(csi);
FINDREG(cdi);
FINDREG(cip);
#ifdef _WIN64
FINDREG(r8);
FINDREG(r9);
FINDREG(r10);
FINDREG(r11);
FINDREG(r12);
FINDREG(r13);
FINDREG(r14);
FINDREG(r15);
#endif //_WIN64
#undef FINDREG
//Memory
duint memAddr[MAX_MEMORY_OPERANDS];
duint memOldContent[MAX_MEMORY_OPERANDS];
duint memNewContent[MAX_MEMORY_OPERANDS];
bool isValid[MAX_MEMORY_OPERANDS];
int memAccessCount = file->MemoryAccessCount(index);
if(memAccessCount > 0)
{
file->MemoryAccessInfo(index, memAddr, memOldContent, memNewContent, isValid);
for(int i = 0; i < memAccessCount; i++)
{
found |= inRange(memAddr[i], start, end);
found |= inRange(memOldContent[i], start, end);
found |= inRange(memNewContent[i], start, end);
}
}
//Constants: TO DO
//Populate reference view
if(found)
{
GuiReferenceSetRowCount(count + 1);
GuiReferenceSetCellContent(count, 0, ToPtrString(file->Registers(index).regcontext.cip).toUtf8().constData());
GuiReferenceSetCellContent(count, 1, file->getIndexText(index).toUtf8().constData());
unsigned char opcode[16];
int opcodeSize = 0;
file->OpCode(index, opcode, &opcodeSize);
zy.Disassemble(file->Registers(index).regcontext.cip, opcode, opcodeSize);
GuiReferenceSetCellContent(count, 2, zy.InstructionText(true).c_str());
//GuiReferenceSetCurrentTaskProgress; GuiReferenceSetProgress
count++;
}
}
return count;
}
int TraceFileSearchMemReference(TraceFileReader* file, duint address)
{
int count = 0;
Zydis zy;
GuiReferenceInitialize(QCoreApplication::translate("TraceFileSearch", "Reference").toUtf8().constData());
GuiReferenceAddColumn(sizeof(duint) * 2, QCoreApplication::translate("TraceFileSearch", "Address").toUtf8().constData());
GuiReferenceAddColumn(5, QCoreApplication::translate("TraceFileSearch", "Index").toUtf8().constData());
GuiReferenceAddColumn(100, QCoreApplication::translate("TraceFileSearch", "Disassembly").toUtf8().constData());
GuiReferenceAddCommand(QCoreApplication::translate("TraceFileSearch", "Follow index in trace").toUtf8().constData(), "gototrace 0x$1");
GuiReferenceSetRowCount(0);
for(unsigned long long index = 0; index < file->Length(); index++)
{
bool found = false;
//Memory
duint memAddr[MAX_MEMORY_OPERANDS];
duint memOldContent[MAX_MEMORY_OPERANDS];
duint memNewContent[MAX_MEMORY_OPERANDS];
bool isValid[MAX_MEMORY_OPERANDS];
int memAccessCount = file->MemoryAccessCount(index);
if(memAccessCount > 0)
{
file->MemoryAccessInfo(index, memAddr, memOldContent, memNewContent, isValid);
for(int i = 0; i < memAccessCount; i++)
{
found |= inRange(memAddr[i], address, address + sizeof(duint) - 1);
}
//Constants: TO DO
//Populate reference view
if(found)
{
GuiReferenceSetRowCount(count + 1);
GuiReferenceSetCellContent(count, 0, ToPtrString(file->Registers(index).regcontext.cip).toUtf8().constData());
GuiReferenceSetCellContent(count, 1, file->getIndexText(index).toUtf8().constData());
unsigned char opcode[16];
int opcodeSize = 0;
file->OpCode(index, opcode, &opcodeSize);
zy.Disassemble(file->Registers(index).regcontext.cip, opcode, opcodeSize);
GuiReferenceSetCellContent(count, 2, zy.InstructionText(true).c_str());
//GuiReferenceSetCurrentTaskProgress; GuiReferenceSetProgress
count++;
}
}
}
return count;
}
unsigned long long TraceFileSearchFuncReturn(TraceFileReader* file, unsigned long long start)
{
auto mCsp = file->Registers(start).regcontext.csp;
auto TID = file->ThreadId(start);
Zydis zy;
for(unsigned long long index = start; index < file->Length(); index++)
{
if(mCsp <= file->Registers(index).regcontext.csp && file->ThreadId(index) == TID) //"Run until return" should break only if RSP is bigger than or equal to current value
{
unsigned char data[16];
int opcodeSize = 0;
file->OpCode(index, data, &opcodeSize);
if(data[0] == 0xC3 || data[0] == 0xC2) //retn instruction
return index;
else if(data[0] == 0x26 || data[0] == 0x36 || data[0] == 0x2e || data[0] == 0x3e || (data[0] >= 0x64 && data[0] <= 0x67) || data[0] == 0xf2 || data[0] == 0xf3 //instruction prefixes
#ifdef _WIN64
|| (data[0] >= 0x40 && data[0] <= 0x4f)
#endif //_WIN64
)
{
if(zy.Disassemble(file->Registers(index).regcontext.cip, data, opcodeSize) && zy.IsRet())
return index;
}
}
}
return start; //Nothing found, so just stay here
} |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceFileSearch.h | #pragma once
#include "Bridge.h"
class TraceFileReader;
int TraceFileSearchConstantRange(TraceFileReader* file, duint start, duint end);
int TraceFileSearchMemReference(TraceFileReader* file, duint address);
unsigned long long TraceFileSearchFuncReturn(TraceFileReader* file, unsigned long long start); |
C++ | x64dbg-development/src/gui/Src/Tracer/TraceInfoBox.cpp | #include "TraceInfoBox.h"
#include "TraceWidget.h"
#include "TraceFileReader.h"
#include "CPUInfoBox.h"
#include "zydis_wrapper.h"
TraceInfoBox::TraceInfoBox(TraceWidget* parent) : StdTable(parent)
{
addColumnAt(0, "", true);
setShowHeader(false);
clear();
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setMinimumHeight((getRowHeight() + 1) * 4);
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
// Deselect any row (visual reasons only)
setSingleSelection(-1);
}
TraceInfoBox::~TraceInfoBox()
{
}
void TraceInfoBox::update(unsigned long long selection, TraceFileReader* traceFile, const REGDUMP & registers)
{
int infoline = 0;
Zydis zydis;
unsigned char opcode[16];
QString line;
int opsize;
traceFile->OpCode(selection, opcode, &opsize);
clear();
auto resolveRegValue = [®isters](ZydisRegister regname)
{
switch(regname)
{
#ifdef _WIN64
case ZYDIS_REGISTER_RAX:
return registers.regcontext.cax;
case ZYDIS_REGISTER_RCX:
return registers.regcontext.ccx;
case ZYDIS_REGISTER_RDX:
return registers.regcontext.cdx;
case ZYDIS_REGISTER_RBX:
return registers.regcontext.cbx;
case ZYDIS_REGISTER_RSP:
return registers.regcontext.csp;
case ZYDIS_REGISTER_RBP:
return registers.regcontext.cbp;
case ZYDIS_REGISTER_RSI:
return registers.regcontext.csi;
case ZYDIS_REGISTER_RDI:
return registers.regcontext.cdi;
case ZYDIS_REGISTER_R8:
return registers.regcontext.r8;
case ZYDIS_REGISTER_R9:
return registers.regcontext.r9;
case ZYDIS_REGISTER_R10:
return registers.regcontext.r10;
case ZYDIS_REGISTER_R11:
return registers.regcontext.r11;
case ZYDIS_REGISTER_R12:
return registers.regcontext.r12;
case ZYDIS_REGISTER_R13:
return registers.regcontext.r13;
case ZYDIS_REGISTER_R14:
return registers.regcontext.r14;
case ZYDIS_REGISTER_R15:
return registers.regcontext.r15;
case ZYDIS_REGISTER_R8D:
return registers.regcontext.r8 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R9D:
return registers.regcontext.r9 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R10D:
return registers.regcontext.r10 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R11D:
return registers.regcontext.r11 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R12D:
return registers.regcontext.r12 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R13D:
return registers.regcontext.r13 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R15D:
return registers.regcontext.r15 & 0xFFFFFFFF;
case ZYDIS_REGISTER_R8W:
return registers.regcontext.r8 & 0xFFFF;
case ZYDIS_REGISTER_R9W:
return registers.regcontext.r9 & 0xFFFF;
case ZYDIS_REGISTER_R10W:
return registers.regcontext.r10 & 0xFFFF;
case ZYDIS_REGISTER_R11W:
return registers.regcontext.r11 & 0xFFFF;
case ZYDIS_REGISTER_R12W:
return registers.regcontext.r12 & 0xFFFF;
case ZYDIS_REGISTER_R13W:
return registers.regcontext.r13 & 0xFFFF;
case ZYDIS_REGISTER_R15W:
return registers.regcontext.r15 & 0xFFFF;
case ZYDIS_REGISTER_R8B:
return registers.regcontext.r8 & 0xFF;
case ZYDIS_REGISTER_R9B:
return registers.regcontext.r9 & 0xFF;
case ZYDIS_REGISTER_R10B:
return registers.regcontext.r10 & 0xFF;
case ZYDIS_REGISTER_R11B:
return registers.regcontext.r11 & 0xFF;
case ZYDIS_REGISTER_R12B:
return registers.regcontext.r12 & 0xFF;
case ZYDIS_REGISTER_R13B:
return registers.regcontext.r13 & 0xFF;
case ZYDIS_REGISTER_R15B:
return registers.regcontext.r15 & 0xFF;
#endif //_WIN64
case ZYDIS_REGISTER_EAX:
return registers.regcontext.cax & 0xFFFFFFFF;
case ZYDIS_REGISTER_ECX:
return registers.regcontext.ccx & 0xFFFFFFFF;
case ZYDIS_REGISTER_EDX:
return registers.regcontext.cdx & 0xFFFFFFFF;
case ZYDIS_REGISTER_EBX:
return registers.regcontext.cbx & 0xFFFFFFFF;
case ZYDIS_REGISTER_ESP:
return registers.regcontext.csp & 0xFFFFFFFF;
case ZYDIS_REGISTER_EBP:
return registers.regcontext.cbp & 0xFFFFFFFF;
case ZYDIS_REGISTER_ESI:
return registers.regcontext.csi & 0xFFFFFFFF;
case ZYDIS_REGISTER_EDI:
return registers.regcontext.cdi & 0xFFFFFFFF;
case ZYDIS_REGISTER_AX:
return registers.regcontext.cax & 0xFFFF;
case ZYDIS_REGISTER_CX:
return registers.regcontext.ccx & 0xFFFF;
case ZYDIS_REGISTER_DX:
return registers.regcontext.cdx & 0xFFFF;
case ZYDIS_REGISTER_BX:
return registers.regcontext.cbx & 0xFFFF;
case ZYDIS_REGISTER_SP:
return registers.regcontext.csp & 0xFFFF;
case ZYDIS_REGISTER_BP:
return registers.regcontext.cbp & 0xFFFF;
case ZYDIS_REGISTER_SI:
return registers.regcontext.csi & 0xFFFF;
case ZYDIS_REGISTER_DI:
return registers.regcontext.cdi & 0xFFFF;
case ZYDIS_REGISTER_AL:
return registers.regcontext.cax & 0xFF;
case ZYDIS_REGISTER_CL:
return registers.regcontext.ccx & 0xFF;
case ZYDIS_REGISTER_DL:
return registers.regcontext.cdx & 0xFF;
case ZYDIS_REGISTER_BL:
return registers.regcontext.cbx & 0xFF;
case ZYDIS_REGISTER_AH:
return (registers.regcontext.cax & 0xFF00) >> 8;
case ZYDIS_REGISTER_CH:
return (registers.regcontext.ccx & 0xFF00) >> 8;
case ZYDIS_REGISTER_DH:
return (registers.regcontext.cdx & 0xFF00) >> 8;
case ZYDIS_REGISTER_BH:
return (registers.regcontext.cbx & 0xFF00) >> 8;
default:
return static_cast<ULONG_PTR>(0);
}
};
duint MemoryAddress[MAX_MEMORY_OPERANDS];
duint MemoryOldContent[MAX_MEMORY_OPERANDS];
duint MemoryNewContent[MAX_MEMORY_OPERANDS];
bool MemoryIsValid[MAX_MEMORY_OPERANDS];
int MemoryOperandsCount;
MemoryOperandsCount = traceFile->MemoryAccessCount(selection);
if(MemoryOperandsCount > 0)
traceFile->MemoryAccessInfo(selection, MemoryAddress, MemoryOldContent, MemoryNewContent, MemoryIsValid);
if(zydis.Disassemble(registers.regcontext.cip, opcode, opsize))
{
int opindex;
int memaccessindex;
//Jumps
if(zydis.IsBranchType(Zydis::BTCondJmp))
{
if(zydis.IsBranchGoingToExecute(registers.regcontext.eflags, registers.regcontext.ccx))
{
line = tr("Jump is taken");
}
else
{
line = tr("Jump is not taken");
}
setCellContent(infoline, 0, line);
infoline++;
}
//Operands
QString registerLine, memoryLine;
for(opindex = 0; opindex < zydis.OpCount(); opindex++)
{
size_t value = zydis.ResolveOpValue(opindex, resolveRegValue);
if(zydis[opindex].type == ZYDIS_OPERAND_TYPE_MEMORY)
{
if(!memoryLine.isEmpty())
memoryLine += ", ";
const char* memsize = zydis.MemSizeName(zydis[opindex].size / 8);
if(memsize != nullptr)
{
memoryLine += memsize;
}
else
{
memoryLine += QString("m%1").arg(zydis[opindex].size / 8);
}
memoryLine += " ptr ";
memoryLine += zydis.RegName(zydis[opindex].mem.segment);
memoryLine += ":[";
memoryLine += ToPtrString(value);
memoryLine += "]";
if(zydis[opindex].size == 64 && zydis.getVectorElementType(opindex) == Zydis::VETFloat64)
{
// Double precision
#ifdef _WIN64
//TODO: Untested
for(memaccessindex = 0; memaccessindex < MemoryOperandsCount; memaccessindex++)
{
if(MemoryAddress[memaccessindex] == value)
{
memoryLine += "= ";
memoryLine += ToDoubleString(&MemoryOldContent[memaccessindex]);
memoryLine += " -> ";
memoryLine += ToDoubleString(&MemoryNewContent[memaccessindex]);
break;
}
}
#else
// On 32-bit platform it is saved as 2 memory accesses.
for(memaccessindex = 0; memaccessindex < MemoryOperandsCount - 1; memaccessindex++)
{
if(MemoryAddress[memaccessindex] == value && MemoryAddress[memaccessindex + 1] == value + 4)
{
double dblval;
memoryLine += "= ";
memcpy(&dblval, &MemoryOldContent[memaccessindex], 4);
memcpy(((char*)&dblval) + 4, &MemoryOldContent[memaccessindex + 1], 4);
memoryLine += ToDoubleString(&dblval);
memoryLine += " -> ";
memcpy(&dblval, &MemoryNewContent[memaccessindex], 4);
memcpy(((char*)&dblval) + 4, &MemoryNewContent[memaccessindex + 1], 4);
memoryLine += ToDoubleString(&dblval);
break;
}
}
#endif //_WIN64
}
else if(zydis[opindex].size == 32 && zydis.getVectorElementType(opindex) == Zydis::VETFloat32)
{
// Single precision
//TODO: Untested
for(memaccessindex = 0; memaccessindex < MemoryOperandsCount; memaccessindex++)
{
if(MemoryAddress[memaccessindex] == value)
{
memoryLine += "= ";
memoryLine += ToFloatString(&MemoryOldContent[memaccessindex]);
memoryLine += " -> ";
memoryLine += ToFloatString(&MemoryNewContent[memaccessindex]);
break;
}
}
}
else if(zydis[opindex].size <= sizeof(void*) * 8)
{
// Handle the most common case (ptr-sized)
duint mask;
if(zydis[opindex].size < sizeof(void*) * 8)
mask = ((duint)1 << zydis[opindex].size) - 1;
else
mask = ~(duint)0;
for(memaccessindex = 0; memaccessindex < MemoryOperandsCount; memaccessindex++)
{
if(MemoryAddress[memaccessindex] == value)
{
memoryLine += "=";
memoryLine += ToHexString(MemoryOldContent[memaccessindex] & mask);
memoryLine += " -> ";
memoryLine += ToHexString(MemoryNewContent[memaccessindex] & mask);
break;
}
}
}
}
else if(zydis[opindex].type == ZYDIS_OPERAND_TYPE_REGISTER)
{
const auto registerName = zydis[opindex].reg.value;
if(!registerLine.isEmpty())
registerLine += ", ";
registerLine += zydis.RegName(registerName);
registerLine += " = ";
// Special treatment for FPU registers
if(registerName >= ZYDIS_REGISTER_ST0 && registerName <= ZYDIS_REGISTER_ST7)
{
// x87 FPU
registerLine += ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + registerName - ZYDIS_REGISTER_ST0) & 7].data);
}
else if(registerName >= ZYDIS_REGISTER_XMM0 && registerName <= ArchValue(ZYDIS_REGISTER_XMM7, ZYDIS_REGISTER_XMM15))
{
registerLine += CPUInfoBox::formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[registerName - ZYDIS_REGISTER_XMM0], 16), zydis.getVectorElementType(opindex));
}
else if(registerName >= ZYDIS_REGISTER_YMM0 && registerName <= ArchValue(ZYDIS_REGISTER_YMM7, ZYDIS_REGISTER_YMM15))
{
//TODO: Untested
registerLine += CPUInfoBox::formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[registerName - ZYDIS_REGISTER_XMM0], 32), zydis.getVectorElementType(opindex));
}
else
{
// GPR
registerLine += ToPtrString(value);
}
}
}
if(!registerLine.isEmpty())
{
setCellContent(infoline, 0, registerLine);
infoline++;
}
if(!memoryLine.isEmpty())
{
setCellContent(infoline, 0, memoryLine);
infoline++;
}
DWORD tid;
tid = traceFile->ThreadId(selection);
line = QString("ThreadID: %1").arg(ConfigBool("Gui", "PidTidInHex") ? ToHexString(tid) : QString::number(tid));
setCellContent(3, 0, line);
}
reloadData();
}
void TraceInfoBox::clear()
{
setRowCount(4);
for(int i = 0; i < 4; i++)
setCellContent(i, 0, QString());
reloadData();
}
void TraceInfoBox::setupContextMenu()
{
mCopyLineAction = makeAction(tr("Copy Line"), SLOT(copyLineSlot()));
setupShortcuts();
}
void TraceInfoBox::contextMenuSlot(QPoint pos)
{
QMenu wMenu(this); //create context menu
QMenu wCopyMenu(tr("&Copy"), this);
setupCopyMenu(&wCopyMenu);
wMenu.addMenu(&wCopyMenu);
wMenu.exec(mapToGlobal(pos)); //execute context menu
}
void TraceInfoBox::setupShortcuts()
{
mCopyLineAction->setShortcut(ConfigShortcut("ActionCopyLine"));
addAction(mCopyLineAction);
} |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceInfoBox.h | #pragma once
#include "StdTable.h"
class TraceWidget;
class TraceFileReader;
class TraceInfoBox : public StdTable
{
Q_OBJECT
public:
TraceInfoBox(TraceWidget* parent);
~TraceInfoBox();
void update(unsigned long long selection, TraceFileReader* traceFile, const REGDUMP & registers);
void clear();
public slots:
void contextMenuSlot(QPoint pos);
private:
void setupContextMenu();
void setupShortcuts();
QAction* mCopyLineAction;
}; |
C++ | x64dbg-development/src/gui/Src/Tracer/TraceRegisters.cpp | #include <QMouseEvent>
#include "TraceRegisters.h"
#include "Configuration.h"
#include "EditFloatRegister.h"
#include "StringUtil.h"
#include "MiscUtil.h"
TraceRegisters::TraceRegisters(QWidget* parent) : RegistersView(parent)
{
wCM_CopySIMDRegister = setupAction(DIcon("copy"), tr("Copy floating point value"));
connect(wCM_CopySIMDRegister, SIGNAL(triggered()), this, SLOT(onCopySIMDRegister()));
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(displayCustomContextMenuSlot(QPoint)));
}
void TraceRegisters::setRegisters(REGDUMP* registers)
{
this->RegistersView::setRegisters(registers);
}
void TraceRegisters::setActive(bool isActive)
{
this->isActive = isActive;
this->RegistersView::setRegisters(&this->wRegDumpStruct);
}
void TraceRegisters::displayCustomContextMenuSlot(QPoint pos)
{
if(!isActive)
return;
QMenu wMenu(this);
setupSIMDModeMenu();
if(mSelected != UNKNOWN)
{
wMenu.addAction(wCM_CopyToClipboard);
if(mFPUx87_80BITSDISPLAY.contains(mSelected))
{
wMenu.addAction(wCM_CopyFloatingPointValueToClipboard);
}
if(mFPUMMX.contains(mSelected) || mFPUXMM.contains(mSelected) || mFPUYMM.contains(mSelected))
{
wMenu.addAction(wCM_CopySIMDRegister);
}
if(mLABELDISPLAY.contains(mSelected))
{
QString symbol = getRegisterLabel(mSelected);
if(symbol != "")
wMenu.addAction(wCM_CopySymbolToClipboard);
}
wMenu.addAction(wCM_CopyAll);
if(mFPUMMX.contains(mSelected) || mFPUXMM.contains(mSelected) || mFPUYMM.contains(mSelected))
{
wMenu.addMenu(mSwitchSIMDDispMode);
}
if(mFPUMMX.contains(mSelected) || mFPUx87_80BITSDISPLAY.contains(mSelected))
{
if(mFpuMode != 0)
wMenu.addAction(mDisplaySTX);
if(mFpuMode != 1)
wMenu.addAction(mDisplayx87rX);
if(mFpuMode != 2)
wMenu.addAction(mDisplayMMX);
}
wMenu.exec(this->mapToGlobal(pos));
}
else // Right-click on empty space
{
wMenu.addSeparator();
wMenu.addAction(wCM_ChangeFPUView);
wMenu.addAction(wCM_CopyAll);
wMenu.addMenu(mSwitchSIMDDispMode);
if(mFpuMode != 0)
wMenu.addAction(mDisplaySTX);
if(mFpuMode != 1)
wMenu.addAction(mDisplayx87rX);
if(mFpuMode != 2)
wMenu.addAction(mDisplayMMX);
}
}
static void showCopyFloatRegister(int bits, QWidget* parent, const QString & title, char* registerData)
{
EditFloatRegister mEditFloat(bits, parent);
mEditFloat.setWindowTitle(title);
mEditFloat.loadData(registerData);
mEditFloat.show();
mEditFloat.selectAllText();
mEditFloat.exec();
}
void TraceRegisters::onCopySIMDRegister()
{
if(mFPUYMM.contains(mSelected))
showCopyFloatRegister(256, this, tr("View YMM register"), registerValue(&wRegDumpStruct, mSelected));
else if(mFPUXMM.contains(mSelected))
showCopyFloatRegister(128, this, tr("View XMM register"), registerValue(&wRegDumpStruct, mSelected));
else if(mFPUMMX.contains(mSelected))
showCopyFloatRegister(64, this, tr("View MMX register"), registerValue(&wRegDumpStruct, mSelected));
}
void TraceRegisters::mouseDoubleClickEvent(QMouseEvent* event)
{
if(!isActive || event->button() != Qt::LeftButton)
return;
// get mouse position
const int y = (event->y() - yTopSpacing) / (double)mRowHeight;
const int x = event->x() / (double)mCharWidth;
// do we find a corresponding register?
if(!identifyRegister(y, x, 0))
return;
if(mSelected == CIP) //double clicked on CIP register: follow in disassembly
DbgCmdExec(QString("disasm %1").arg(ToPtrString(wRegDumpStruct.regcontext.cip)));
// double clicked on XMM register: open view XMM register dialog
else if(mFPUXMM.contains(mSelected) || mFPUYMM.contains(mSelected) || mFPUMMX.contains(mSelected))
onCopySIMDRegister();
// double clicked on GPR: nothing to do (copy?)
} |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceRegisters.h | #pragma once
#include "RegistersView.h"
class TraceRegisters : public RegistersView
{
Q_OBJECT
public:
TraceRegisters(QWidget* parent = 0);
void setRegisters(REGDUMP* registers);
void setActive(bool isActive);
public slots:
virtual void displayCustomContextMenuSlot(QPoint pos);
void onCopySIMDRegister();
protected:
virtual void mouseDoubleClickEvent(QMouseEvent* event);
private:
QAction* wCM_CopySIMDRegister;
}; |
C++ | x64dbg-development/src/gui/Src/Tracer/TraceWidget.cpp | #include "TraceWidget.h"
#include "ui_TraceWidget.h"
#include "TraceBrowser.h"
#include "TraceInfoBox.h"
#include "TraceFileReader.h"
#include "TraceRegisters.h"
#include "StdTable.h"
#include "CPUInfoBox.h"
TraceWidget::TraceWidget(QWidget* parent) :
QWidget(parent),
ui(new Ui::TraceWidget)
{
ui->setupUi(this);
mTraceWidget = new TraceBrowser(this);
mOverview = new StdTable(this);
mInfo = new TraceInfoBox(this);
mGeneralRegs = new TraceRegisters(this);
//disasm
ui->mTopLeftUpperRightFrameLayout->addWidget(mTraceWidget);
//registers
mGeneralRegs->setFixedWidth(1000);
mGeneralRegs->ShowFPU(true);
QScrollArea* upperScrollArea = new QScrollArea(this);
upperScrollArea->setFrameShape(QFrame::NoFrame);
upperScrollArea->setWidget(mGeneralRegs);
upperScrollArea->setWidgetResizable(true);
//upperScrollArea->horizontalScrollBar()->setStyleSheet(ConfigHScrollBarStyle());
//upperScrollArea->verticalScrollBar()->setStyleSheet(ConfigVScrollBarStyle());
QPushButton* button_changeview = new QPushButton("", this);
button_changeview->setStyleSheet("Text-align:left;padding: 4px;padding-left: 10px;");
connect(button_changeview, SIGNAL(clicked()), mGeneralRegs, SLOT(onChangeFPUViewAction()));
connect(mTraceWidget, SIGNAL(selectionChanged(unsigned long long)), this, SLOT(traceSelectionChanged(unsigned long long)));
connect(Bridge::getBridge(), SIGNAL(updateTraceBrowser()), this, SLOT(updateSlot()));
mGeneralRegs->SetChangeButton(button_changeview);
ui->mTopRightUpperFrameLayout->addWidget(button_changeview);
ui->mTopRightUpperFrameLayout->addWidget(upperScrollArea);
ui->mTopHSplitter->setCollapsible(1, true); // allow collapsing the RegisterView
//info
ui->mTopLeftLowerFrameLayout->addWidget(mInfo);
int height = (mInfo->getRowHeight() + 1) * 4;
ui->mTopLeftLowerFrame->setMinimumHeight(height + 2);
ui->mTopHSplitter->setSizes(QList<int>({1000, 1}));
ui->mTopLeftVSplitter->setSizes(QList<int>({1000, 1}));
//overview
ui->mTopRightLowerFrameLayout->addWidget(mOverview);
//set up overview
mOverview->addColumnAt(0, "", true);
mOverview->setShowHeader(false);
mOverview->setRowCount(4);
mOverview->setCellContent(0, 0, "hello");
mOverview->setCellContent(1, 0, "world");
mOverview->setCellContent(2, 0, "00000000");
mOverview->setCellContent(3, 0, "here we will list all control flow transfers");
mOverview->hide();
}
TraceWidget::~TraceWidget()
{
delete ui;
}
void TraceWidget::traceSelectionChanged(unsigned long long selection)
{
REGDUMP registers;
TraceFileReader* traceFile;
traceFile = mTraceWidget->getTraceFile();
if(traceFile != nullptr && traceFile->Progress() == 100)
{
if(selection < traceFile->Length())
{
registers = traceFile->Registers(selection);
mInfo->update(selection, traceFile, registers);
}
else
memset(®isters, 0, sizeof(registers));
}
mGeneralRegs->setRegisters(®isters);
}
void TraceWidget::updateSlot()
{
auto fileOpened = mTraceWidget->isFileOpened();
mGeneralRegs->setActive(fileOpened);
if(!fileOpened)
mInfo->clear();
}
TraceBrowser* TraceWidget::getTraceBrowser()
{
return mTraceWidget;
} |
C/C++ | x64dbg-development/src/gui/Src/Tracer/TraceWidget.h | #pragma once
#include <QWidget>
#include "Bridge.h"
class QVBoxLayout;
class CPUWidget;
class TraceRegisters;
class TraceBrowser;
class TraceFileReader;
class TraceInfoBox;
class StdTable;
namespace Ui
{
class TraceWidget;
}
class TraceWidget : public QWidget
{
Q_OBJECT
public:
explicit TraceWidget(QWidget* parent);
~TraceWidget();
TraceBrowser* getTraceBrowser();
protected slots:
void traceSelectionChanged(unsigned long long selection);
void updateSlot();
protected:
TraceBrowser* mTraceWidget;
TraceInfoBox* mInfo;
TraceRegisters* mGeneralRegs;
StdTable* mOverview;
private:
Ui::TraceWidget* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Tracer/TraceWidget.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>TraceWidget</class>
<widget class="QWidget" name="TraceWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="sizeConstraint">
<enum>QLayout::SetMaximumSize</enum>
</property>
<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>0</number>
</property>
<item>
<widget class="QSplitter" name="mVSplitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QSplitter" name="mTopHSplitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QSplitter" name="mTopLeftVSplitter">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>true</bool>
</property>
<widget class="QFrame" name="mTopLeftUpperRightFrame">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mTopLeftUpperRightFrameLayout">
<property name="spacing">
<number>0</number>
</property>
<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>0</number>
</property>
</layout>
</widget>
<widget class="QFrame" name="mTopLeftLowerFrame">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mTopLeftLowerFrameLayout">
<property name="spacing">
<number>0</number>
</property>
<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>0</number>
</property>
</layout>
</widget>
</widget>
<widget class="QSplitter" name="mTopRightVSplitter">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QFrame" name="mTopRightUpperFrame">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mTopRightUpperFrameLayout">
<property name="spacing">
<number>0</number>
</property>
<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>0</number>
</property>
</layout>
</widget>
<widget class="QFrame" name="mTopRightLowerFrame">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mTopRightLowerFrameLayout">
<property name="spacing">
<number>0</number>
</property>
<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>0</number>
</property>
</layout>
</widget>
</widget>
</widget>
</widget>
</item>
</layout>
<action name="actionGoto">
<property name="text">
<string>Goto</string>
</property>
<property name="shortcut">
<string>Ctrl+G</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui> |
C/C++ | x64dbg-development/src/gui/Src/Utils/ActionHelpers.h | #pragma once
#include <QMenu>
#include <QAction>
#include <functional>
#include "Configuration.h"
//TODO: find the right "const &" "&", "&&" "" etc for passing around std::function
using SlotFunc = std::function<void()>;
using MakeMenuFunc1 = std::function<QMenu*(const QString &)>;
using MakeMenuFunc2 = std::function<QMenu*(const QIcon &, const QString &)>;
using MakeActionFunc1 = std::function<QAction*(const QString &, const SlotFunc &)>;
using MakeActionFunc2 = std::function<QAction*(const QIcon &, const QString &, const SlotFunc &)>;
using MakeShortcutActionFunc1 = std::function<QAction*(const QString &, const SlotFunc &, const char*)>;
using MakeShortcutActionFunc2 = std::function<QAction*(const QIcon &, const QString &, const SlotFunc &, const char*)>;
using MakeShortcutDescActionFunc2 = std::function<QAction*(const QIcon &, const QString &, const QString &, const SlotFunc &, const char*)>;
using MakeMenuActionFunc1 = std::function<QAction*(QMenu*, const QString &, const SlotFunc &)>;
using MakeMenuActionFunc2 = std::function<QAction*(QMenu*, const QIcon &, const QString &, const SlotFunc &)>;
using MakeShortcutMenuActionFunc1 = std::function<QAction*(QMenu*, const QString &, const SlotFunc &, const char*)>;
using MakeShortcutMenuActionFunc2 = std::function<QAction*(QMenu*, const QIcon &, const QString &, const SlotFunc &, const char*)>;
struct ActionHelperFuncs
{
MakeMenuFunc1 makeMenu1;
MakeMenuFunc2 makeMenu2;
MakeActionFunc1 makeAction1;
MakeActionFunc2 makeAction2;
MakeShortcutActionFunc1 makeShortcutAction1;
MakeShortcutActionFunc2 makeShortcutAction2;
MakeShortcutDescActionFunc2 makeShortcutDescAction2;
MakeMenuActionFunc1 makeMenuAction1;
MakeMenuActionFunc2 makeMenuAction2;
MakeShortcutMenuActionFunc1 makeShortcutMenuAction1;
MakeShortcutMenuActionFunc2 makeShortcutMenuAction2;
};
template<class Base>
class ActionHelper
{
private:
Base* getBase()
{
return static_cast<Base*>(this);
}
struct ActionShortcut
{
QAction* action;
QString shortcut;
inline ActionShortcut(QAction* action, const char* shortcut)
: action(action),
shortcut(shortcut)
{
}
};
public:
virtual void updateShortcuts()
{
for(const auto & actionShortcut : actionShortcutPairs)
actionShortcut.action->setShortcut(ConfigShortcut(actionShortcut.shortcut));
}
private:
inline QAction* connectAction(QAction* action, const char* slot)
{
QObject::connect(action, SIGNAL(triggered(bool)), getBase(), slot);
return action;
}
template<class T> // lambda or base member pointer
inline QAction* connectAction(QAction* action, T callback)
{
//in case of a lambda getBase() is used as the 'context' object and not the 'receiver'
QObject::connect(action, &QAction::triggered, getBase(), callback);
return action;
}
inline QAction* connectShortcutAction(QAction* action, const char* shortcut)
{
actionShortcutPairs.push_back(ActionShortcut(action, shortcut));
action->setShortcut(ConfigShortcut(shortcut));
action->setShortcutContext(Qt::WidgetShortcut);
getBase()->addAction(action);
return action;
}
inline QAction* connectMenuAction(QMenu* menu, QAction* action)
{
menu->addAction(action);
return action;
}
protected:
inline ActionHelperFuncs getActionHelperFuncs()
{
ActionHelperFuncs funcs;
funcs.makeMenu1 = [this](const QString & title)
{
return makeMenu(title);
};
funcs.makeMenu2 = [this](const QIcon & icon, const QString & title)
{
return makeMenu(icon, title);
};
funcs.makeAction1 = [this](const QString & text, const SlotFunc & slot)
{
return makeAction(text, slot);
};
funcs.makeAction2 = [this](const QIcon & icon, const QString & text, const SlotFunc & slot)
{
return makeAction(icon, text, slot);
};
funcs.makeShortcutAction1 = [this](const QString & text, const SlotFunc & slot, const char* shortcut)
{
return makeShortcutAction(text, slot, shortcut);
};
funcs.makeShortcutAction2 = [this](const QIcon & icon, const QString & text, const SlotFunc & slot, const char* shortcut)
{
return makeShortcutAction(icon, text, slot, shortcut);
};
funcs.makeShortcutDescAction2 = [this](const QIcon & icon, const QString & text, const QString & description, const SlotFunc & slot, const char* shortcut)
{
auto action = makeShortcutAction(icon, text, slot, shortcut);
action->setStatusTip(description);
return action;
};
funcs.makeMenuAction1 = [this](QMenu * menu, const QString & text, const SlotFunc & slot)
{
return makeMenuAction(menu, text, slot);
};
funcs.makeMenuAction2 = [this](QMenu * menu, const QIcon & icon, const QString & text, const SlotFunc & slot)
{
return makeMenuAction(menu, icon, text, slot);
};
funcs.makeShortcutMenuAction1 = [this](QMenu * menu, const QString & text, const SlotFunc & slot, const char* shortcut)
{
return makeShortcutMenuAction(menu, text, slot, shortcut);
};
funcs.makeShortcutMenuAction2 = [this](QMenu * menu, const QIcon & icon, const QString & text, const SlotFunc & slot, const char* shortcut)
{
return makeShortcutMenuAction(menu, icon, text, slot, shortcut);
};
return funcs;
}
inline QMenu* makeMenu(const QString & title)
{
return new QMenu(title, getBase());
}
inline QMenu* makeMenu(const QIcon & icon, const QString & title)
{
QMenu* menu = new QMenu(title, getBase());
menu->setIcon(icon);
return menu;
}
template<typename T>
inline QAction* makeAction(const QString & text, T slot)
{
return connectAction(new QAction(text, getBase()), slot);
}
template<typename T>
inline QAction* makeAction(const QIcon & icon, const QString & text, T slot)
{
return connectAction(new QAction(icon, text, getBase()), slot);
}
template<typename T>
inline QAction* makeShortcutAction(const QString & text, T slot, const char* shortcut)
{
return connectShortcutAction(makeAction(text, slot), shortcut);
}
template<typename T>
inline QAction* makeShortcutAction(const QIcon & icon, const QString & text, T slot, const char* shortcut)
{
return connectShortcutAction(makeAction(icon, text, slot), shortcut);
}
template<typename T>
inline QAction* makeMenuAction(QMenu* menu, const QString & text, T slot)
{
return connectMenuAction(menu, makeAction(text, slot));
}
template<typename T>
inline QAction* makeMenuAction(QMenu* menu, const QIcon & icon, const QString & text, T slot)
{
return connectMenuAction(menu, makeAction(icon, text, slot));
}
template<typename T>
inline QAction* makeShortcutMenuAction(QMenu* menu, const QString & text, T slot, const char* shortcut)
{
return connectShortcutAction(makeMenuAction(menu, text, slot), shortcut);
}
template<typename T>
inline QAction* makeShortcutMenuAction(QMenu* menu, const QIcon & icon, const QString & text, T slot, const char* shortcut)
{
return connectShortcutAction(makeMenuAction(menu, icon, text, slot), shortcut);
}
private:
std::vector<ActionShortcut> actionShortcutPairs;
};
class MenuBuilder;
class ActionHelperProxy
{
ActionHelperFuncs funcs;
public:
ActionHelperProxy(ActionHelperFuncs funcs)
: funcs(funcs) { }
protected:
inline QMenu* makeMenu(const QString & title)
{
return funcs.makeMenu1(title);
}
inline QMenu* makeMenu(const QIcon & icon, const QString & title)
{
return funcs.makeMenu2(icon, title);
}
inline QAction* makeAction(const QString & text, const SlotFunc & slot)
{
return funcs.makeAction1(text, slot);
}
inline QAction* makeAction(const QIcon & icon, const QString & text, const SlotFunc & slot)
{
return funcs.makeAction2(icon, text, slot);
}
inline QAction* makeShortcutAction(const QString & text, const SlotFunc & slot, const char* shortcut)
{
return funcs.makeShortcutAction1(text, slot, shortcut);
}
inline QAction* makeShortcutAction(const QIcon & icon, const QString & text, const SlotFunc & slot, const char* shortcut)
{
return funcs.makeShortcutAction2(icon, text, slot, shortcut);
}
inline QAction* makeMenuAction(QMenu* menu, const QString & text, const SlotFunc & slot)
{
return funcs.makeMenuAction1(menu, text, slot);
}
inline QAction* makeMenuAction(QMenu* menu, const QIcon & icon, const QString & text, const SlotFunc & slot)
{
return funcs.makeMenuAction2(menu, icon, text, slot);
}
inline QAction* makeShortcutMenuAction(QMenu* menu, const QString & text, const SlotFunc & slot, const char* shortcut)
{
return funcs.makeShortcutMenuAction1(menu, text, slot, shortcut);
}
inline QAction* makeShortcutMenuAction(QMenu* menu, const QIcon & icon, const QString & text, const SlotFunc & slot, const char* shortcut)
{
return funcs.makeShortcutMenuAction2(menu, icon, text, slot, shortcut);
}
inline QAction* makeShortcutDescAction(const QIcon & icon, const QString & text, const QString & description, const SlotFunc & slot, const char* shortcut)
{
return funcs.makeShortcutDescAction2(icon, text, description, slot, shortcut);
}
}; |
C++ | x64dbg-development/src/gui/Src/Utils/BackgroundFlickerThread.cpp | #include "BackgroundFlickerThread.h"
#include "Configuration.h"
#include <Windows.h>
BackgroundFlickerThread::BackgroundFlickerThread(QWidget* widget, QColor & background, QObject* parent) : QThread(parent), background(background)
{
mWidget = widget;
setProperties();
}
void BackgroundFlickerThread::setProperties(int count, int delay)
{
this->count = count;
this->delay = delay;
}
void BackgroundFlickerThread::run()
{
QColor flickerColor = ConfigColor("BackgroundFlickerColor");
QColor oldColor = background;
for(int i = 0; i < count; i++)
{
background = flickerColor;
mWidget->update();
Sleep(delay);
background = oldColor;
mWidget->update();
Sleep(delay);
}
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/BackgroundFlickerThread.h | #pragma once
#include <QThread>
#include <QWidget>
#include <QColor>
class BackgroundFlickerThread : public QThread
{
Q_OBJECT
public:
explicit BackgroundFlickerThread(QWidget* widget, QColor & background, QObject* parent = 0);
void setProperties(int count = 3, int delay = 300);
private:
void run();
QWidget* mWidget;
QColor & background;
int count;
int delay;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/Breakpoints.cpp | #include "Breakpoints.h"
#include "EditBreakpointDialog.h"
#include "StringUtil.h"
Breakpoints::Breakpoints(QObject* parent) : QObject(parent)
{
}
/**
* @brief Set a new breakpoint according to the given type at the given address.
*
* @param[in] type Type of the breakpoint
* @param[in] va Virtual Address
*
* @return Nothing.
*/
void Breakpoints::setBP(BPXTYPE type, duint va)
{
QString wCmd = "";
switch(type)
{
case bp_normal:
{
wCmd = "bp " + ToPtrString(va);
}
break;
case bp_hardware:
{
wCmd = "bph " + ToPtrString(va);
}
break;
case bp_memory:
{
wCmd = "bpm " + ToPtrString(va);
}
break;
default:
{
}
break;
}
DbgCmdExecDirect(wCmd);
}
/**
* @brief Enable breakpoint according to the given breakpoint descriptor.
*
* @param[in] bp Breakpoint descriptor
*
* @return Nothing.
*/
void Breakpoints::enableBP(const BRIDGEBP & bp)
{
QString wCmd = "";
if(bp.type == bp_hardware)
{
wCmd = QString("bphwe \"%1\"").arg(ToPtrString(bp.addr));
}
else if(bp.type == bp_normal)
{
wCmd = QString("be \"%1\"").arg(ToPtrString(bp.addr));
}
else if(bp.type == bp_memory)
{
wCmd = QString("bpme \"%1\"").arg(ToPtrString(bp.addr));
}
else if(bp.type == bp_dll)
{
wCmd = QString("LibrarianEnableBreakPoint \"%1\"").arg(QString(bp.mod));
}
else if(bp.type == bp_exception)
{
wCmd = QString("EnableExceptionBPX \"%1\"").arg(ToPtrString(bp.addr));
}
DbgCmdExecDirect(wCmd);
}
/**
* @brief Enable breakpoint that has been previously disabled according to its type and virtual address.
* If breakpoint was removed, this method has no effect.@n
* Breakpoint type is useful when there are several types of breakpoints on the same address.
* bp_none enables all breakpoints at the given address.
*
* @param[in] type Type of the breakpoint.
* @param[in] va Virtual Address
*
* @return Nothing.
*/
void Breakpoints::enableBP(BPXTYPE type, duint va)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].addr == va)
{
enableBP(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
/**
* @brief Disable breakpoint according to the given breakpoint descriptor.
*
* @param[in] bp Breakpoint descriptor
*
* @return Nothing.
*/
void Breakpoints::disableBP(const BRIDGEBP & bp)
{
QString wCmd = "";
if(bp.type == bp_hardware)
{
wCmd = QString("bphwd \"%1\"").arg(ToPtrString(bp.addr));
}
else if(bp.type == bp_normal)
{
wCmd = QString("bd \"%1\"").arg(ToPtrString(bp.addr));
}
else if(bp.type == bp_memory)
{
wCmd = QString("bpmd \"%1\"").arg(ToPtrString(bp.addr));
}
else if(bp.type == bp_dll)
{
wCmd = QString("LibrarianDisableBreakPoint \"%1\"").arg(QString(bp.mod));
}
else if(bp.type == bp_exception)
{
wCmd = QString("DisableExceptionBPX \"%1\"").arg(ToPtrString(bp.addr));
}
DbgCmdExecDirect(wCmd);
}
/**
* @brief Disable breakpoint that has been previously enabled according to its type and virtual address.
* If breakpoint was removed, this method has no effect.@n
* Breakpoint type is useful when there are several types of breakpoints on the same address.
* bp_none disbales all breakpoints at the given address.
*
* @param[in] type Type of the breakpoint.
* @param[in] va Virtual Address
*
* @return Nothing.
*/
void Breakpoints::disableBP(BPXTYPE type, duint va)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].addr == va)
{
disableBP(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
static QString getBpIdentifier(const BRIDGEBP & bp)
{
if(*bp.mod)
{
auto modbase = DbgModBaseFromName(bp.mod);
if(!modbase)
return QString("\"%1\":$%2").arg(bp.mod).arg(ToHexString(bp.addr));
}
return ToPtrString(bp.addr);
}
/**
* @brief Remove breakpoint according to the given breakpoint descriptor.
*
* @param[in] bp Breakpoint descriptor
*
* @return Nothing.
*/
void Breakpoints::removeBP(const BRIDGEBP & bp)
{
QString wCmd = "";
switch(bp.type)
{
case bp_normal:
wCmd = QString("bc \"%1\"").arg(getBpIdentifier(bp));
break;
case bp_hardware:
wCmd = QString("bphc \"%1\"").arg(getBpIdentifier(bp));
break;
case bp_memory:
wCmd = QString("bpmc \"%1\"").arg(getBpIdentifier(bp));
break;
case bp_dll:
wCmd = QString("bcdll \"%1\"").arg(QString(bp.mod));
break;
case bp_exception:
wCmd = QString("DeleteExceptionBPX \"%1\"").arg(ToPtrString(bp.addr));
break;
default:
break;
}
DbgCmdExecDirect(wCmd);
}
/**
* @brief Remove breakpoint at the given given address and type
* If breakpoint doesn't exists, this method has no effect.@n
* Breakpoint type is useful when there are several types of breakpoints on the same address.
* bp_none disbales all breakpoints at the given address.
*
* @param[in] type Type of the breakpoint.
* @param[in] va Virtual Address
*
* @return Nothing.
*/
void Breakpoints::removeBP(BPXTYPE type, duint va)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].addr == va)
{
removeBP(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
void Breakpoints::removeBP(const QString & DLLName)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(bp_dll, &wBPList);
// Find breakpoint at DLLName
for(int wI = 0; wI < wBPList.count; wI++)
{
if(QString(wBPList.bp[wI].mod) == DLLName)
{
removeBP(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
/**
* @brief Toggle the given breakpoint by disabling it when enabled.@n
* If breakpoint is initially active and enabled, it will be disabled.@n
* If breakpoint is initially active and disabled, it will stay disabled.@n
*
* @param[in] bp Breakpoint descriptor
*
* @return Nothing.
*/
void Breakpoints::toggleBPByDisabling(const BRIDGEBP & bp)
{
if(bp.enabled)
disableBP(bp);
else
enableBP(bp);
}
/**
* @brief Toggle the given breakpoint by disabling it when enabled.@n
* If breakpoint is initially active and enabled, it will be disabled.@n
* If breakpoint is initially active and disabled, it will stay disabled.@n
* If breakpoint was previously removed, this method has no effect.@n
*
* @param[in] type Type of the breakpoint.
* @param[in] va Virtual Address
*
* @return Nothing.
*/
void Breakpoints::toggleBPByDisabling(BPXTYPE type, duint va)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].addr == va)
{
toggleBPByDisabling(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
void Breakpoints::toggleBPByDisabling(const QString & DLLName)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(bp_dll, &wBPList);
// Find breakpoint at module name
for(int wI = 0; wI < wBPList.count; wI++)
{
if(QString(wBPList.bp[wI].mod) == DLLName)
{
toggleBPByDisabling(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
void Breakpoints::toggleAllBP(BPXTYPE type, bool bEnable)
{
BPMAP wBPList;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
if(bEnable)
{
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
enableBP(wBPList.bp[wI]);
}
}
else
{
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
disableBP(wBPList.bp[wI]);
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
/**
* @brief returns if a breakpoint is disabled or not
*
* @param[in] type Type of the breakpoint.
* @param[in] va Virtual Address
*
* @return enabled/disabled.
*/
BPXSTATE Breakpoints::BPState(BPXTYPE type, duint va)
{
BPMAP wBPList;
BPXSTATE result = bp_non_existent;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].addr == va)
{
if(wBPList.bp[wI].enabled)
{
result = bp_enabled;
break;
}
else
{
result = bp_disabled;
break;
}
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
return result;
}
bool Breakpoints::BPTrival(BPXTYPE type, duint va)
{
BPMAP wBPList;
bool trival = true;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoint at address VA
for(int wI = 0; wI < wBPList.count; wI++)
{
BRIDGEBP & bp = wBPList.bp[wI];
if(bp.addr == va)
{
trival = !(bp.breakCondition[0] || bp.logCondition[0] || bp.commandCondition[0] || bp.commandText[0] || bp.logText[0] || bp.name[0] || bp.fastResume || bp.silent);
break;
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
return trival;
}
/**
* @brief Toggle the given breakpoint by disabling it when enabled.@n
* If breakpoint is initially active and enabled, it will be disabled.@n
* If breakpoint is initially active and disabled, it will stay disabled.@n
* If breakpoint was previously removed, this method has no effect.@n
*
* @param[in] type Type of the breakpoint.
* @param[in] va Virtual Address
*
* @return Nothing.
*/
void Breakpoints::toggleBPByRemoving(BPXTYPE type, duint va)
{
BPMAP wBPList;
bool wNormalWasRemoved = false;
bool wMemoryWasRemoved = false;
bool wHardwareWasRemoved = false;
// Get breakpoints list
DbgGetBpList(type, &wBPList);
// Find breakpoints at address VA and remove them
for(int wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].addr == va)
{
removeBP(wBPList.bp[wI]);
switch(wBPList.bp[wI].type)
{
case bp_normal:
wNormalWasRemoved = true;
break;
case bp_memory:
wMemoryWasRemoved = true;
break;
case bp_hardware:
wHardwareWasRemoved = true;
break;
default:
break;
}
}
}
if(wBPList.count)
BridgeFree(wBPList.bp);
if((type == bp_none || type == bp_normal) && (wNormalWasRemoved == false))
{
setBP(bp_normal, va);
}
else if((type == bp_none || type == bp_memory) && (wMemoryWasRemoved == false))
{
setBP(bp_memory, va);
}
else if((type == bp_none || type == bp_hardware) && (wHardwareWasRemoved == false))
{
setBP(bp_hardware, va);
}
}
bool Breakpoints::editBP(BPXTYPE type, const QString & addrText, QWidget* widget, const QString & createCommand)
{
BRIDGEBP bridgebp = {};
bool found = false;
if(type == bp_dll)
{
found = DbgFunctions()->GetBridgeBp(type, reinterpret_cast<duint>(addrText.toUtf8().constData()), &bridgebp);
}
else
{
found = DbgFunctions()->GetBridgeBp(type, (duint)addrText.toULongLong(nullptr, 16), &bridgebp);
}
if(!createCommand.isEmpty() && !found)
{
// Create a dummy BRIDGEBP to edit
bridgebp.type = type;
if(type == bp_dll)
{
strncpy_s(bridgebp.mod, addrText.toUtf8().constData(), _TRUNCATE);
}
else
{
bridgebp.addr = (duint)addrText.toULongLong(nullptr, 16);
}
}
else if(!found)
{
// Fail if the breakpoint doesn't exist and we cannot create a new one
return false;
}
EditBreakpointDialog dialog(widget, bridgebp);
if(dialog.exec() != QDialog::Accepted)
return false;
auto bp = dialog.getBp();
auto exec = [](const QString & command)
{
return DbgCmdExecDirect(command);
};
// Create the breakpoint if it didn't exist yet
if(!createCommand.isEmpty() && !found)
{
if(!exec(createCommand))
{
return false;
}
}
switch(type)
{
case bp_normal:
exec(QString("SetBreakpointName %1, \"%2\"").arg(addrText).arg(bp.name));
exec(QString("SetBreakpointCondition %1, \"%2\"").arg(addrText).arg(bp.breakCondition));
exec(QString("SetBreakpointLog %1, \"%2\"").arg(addrText).arg(bp.logText));
exec(QString("SetBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(bp.logCondition));
exec(QString("SetBreakpointCommand %1, \"%2\"").arg(addrText).arg(bp.commandText));
exec(QString("SetBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(bp.commandCondition));
exec(QString("ResetBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(bp.hitCount)));
exec(QString("SetBreakpointFastResume %1, %2").arg(addrText).arg(bp.fastResume));
exec(QString("SetBreakpointSilent %1, %2").arg(addrText).arg(bp.silent));
exec(QString("SetBreakpointSingleshoot %1, %2").arg(addrText).arg(bp.singleshoot));
break;
case bp_hardware:
exec(QString("SetHardwareBreakpointName %1, \"%2\"").arg(addrText).arg(bp.name));
exec(QString("SetHardwareBreakpointCondition %1, \"%2\"").arg(addrText).arg(bp.breakCondition));
exec(QString("SetHardwareBreakpointLog %1, \"%2\"").arg(addrText).arg(bp.logText));
exec(QString("SetHardwareBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(bp.logCondition));
exec(QString("SetHardwareBreakpointCommand %1, \"%2\"").arg(addrText).arg(bp.commandText));
exec(QString("SetHardwareBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(bp.commandCondition));
exec(QString("ResetHardwareBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(bp.hitCount)));
exec(QString("SetHardwareBreakpointFastResume %1, %2").arg(addrText).arg(bp.fastResume));
exec(QString("SetHardwareBreakpointSilent %1, %2").arg(addrText).arg(bp.silent));
exec(QString("SetHardwareBreakpointSingleshoot %1, %2").arg(addrText).arg(bp.singleshoot));
break;
case bp_memory:
exec(QString("SetMemoryBreakpointName %1, \"\"%2\"\"").arg(addrText).arg(bp.name));
exec(QString("SetMemoryBreakpointCondition %1, \"%2\"").arg(addrText).arg(bp.breakCondition));
exec(QString("SetMemoryBreakpointLog %1, \"%2\"").arg(addrText).arg(bp.logText));
exec(QString("SetMemoryBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(bp.logCondition));
exec(QString("SetMemoryBreakpointCommand %1, \"%2\"").arg(addrText).arg(bp.commandText));
exec(QString("SetMemoryBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(bp.commandCondition));
exec(QString("ResetMemoryBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(bp.hitCount)));
exec(QString("SetMemoryBreakpointFastResume %1, %2").arg(addrText).arg(bp.fastResume));
exec(QString("SetMemoryBreakpointSilent %1, %2").arg(addrText).arg(bp.silent));
exec(QString("SetMemoryBreakpointSingleshoot %1, %2").arg(addrText).arg(bp.singleshoot));
break;
case bp_dll:
exec(QString("SetLibrarianBreakpointName \"%1\", \"\"%2\"\"").arg(addrText).arg(bp.name));
exec(QString("SetLibrarianBreakpointCondition \"%1\", \"%2\"").arg(addrText).arg(bp.breakCondition));
exec(QString("SetLibrarianBreakpointLog \"%1\", \"%2\"").arg(addrText).arg(bp.logText));
exec(QString("SetLibrarianBreakpointLogCondition \"%1\", \"%2\"").arg(addrText).arg(bp.logCondition));
exec(QString("SetLibrarianBreakpointCommand \"%1\", \"%2\"").arg(addrText).arg(bp.commandText));
exec(QString("SetLibrarianBreakpointCommandCondition \"%1\", \"%2\"").arg(addrText).arg(bp.commandCondition));
exec(QString("ResetLibrarianBreakpointHitCount \"%1\", %2").arg(addrText).arg(ToPtrString(bp.hitCount)));
exec(QString("SetLibrarianBreakpointFastResume \"%1\", %2").arg(addrText).arg(bp.fastResume));
exec(QString("SetLibrarianBreakpointSilent \"%1\", %2").arg(addrText).arg(bp.silent));
exec(QString("SetLibrarianBreakpointSingleshoot \"%1\", %2").arg(addrText).arg(bp.singleshoot));
break;
case bp_exception:
exec(QString("SetExceptionBreakpointName %1, \"%2\"").arg(addrText).arg(bp.name));
exec(QString("SetExceptionBreakpointCondition %1, \"%2\"").arg(addrText).arg(bp.breakCondition));
exec(QString("SetExceptionBreakpointLog %1, \"%2\"").arg(addrText).arg(bp.logText));
exec(QString("SetExceptionBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(bp.logCondition));
exec(QString("SetExceptionBreakpointCommand %1, \"%2\"").arg(addrText).arg(bp.commandText));
exec(QString("SetExceptionBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(bp.commandCondition));
exec(QString("ResetExceptionBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(bp.hitCount)));
exec(QString("SetExceptionBreakpointFastResume %1, %2").arg(addrText).arg(bp.fastResume));
exec(QString("SetExceptionBreakpointSilent %1, %2").arg(addrText).arg(bp.silent));
exec(QString("SetExceptionBreakpointSingleshoot %1, %2").arg(addrText).arg(bp.singleshoot));
break;
default:
return false;
}
GuiUpdateBreakpointsView();
return true;
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/Breakpoints.h | #pragma once
#include <QObject>
#include "Bridge.h"
enum BPXSTATE
{
bp_enabled = 0,
bp_disabled = 1,
bp_non_existent = -1
};
class Breakpoints : public QObject
{
Q_OBJECT
public:
explicit Breakpoints(QObject* parent = 0);
static void setBP(BPXTYPE type, duint va);
static void enableBP(const BRIDGEBP & bp);
static void enableBP(BPXTYPE type, duint va);
static void disableBP(const BRIDGEBP & bp);
static void disableBP(BPXTYPE type, duint va);
static void removeBP(const BRIDGEBP & bp);
static void removeBP(BPXTYPE type, duint va);
static void removeBP(const QString & DLLName);
static void toggleBPByDisabling(const BRIDGEBP & bp);
static void toggleBPByDisabling(BPXTYPE type, duint va);
static void toggleBPByDisabling(const QString & DLLName);
static void toggleAllBP(BPXTYPE type, bool bEnable);
static void toggleBPByRemoving(BPXTYPE type, duint va);
static BPXSTATE BPState(BPXTYPE type, duint va);
static bool BPTrival(BPXTYPE type, duint va);
static bool editBP(BPXTYPE type, const QString & addrText, QWidget* widget, const QString & createCommand = QString());
}; |
C/C++ | x64dbg-development/src/gui/Src/Utils/CachedFontMetrics.h | #pragma once
#include <QObject>
#include <QFont>
#include <QFontMetrics>
class CachedFontMetrics : public QObject
{
Q_OBJECT
public:
explicit CachedFontMetrics(QObject* parent, const QFont & font)
: QObject(parent),
mFontMetrics(font)
{
memset(mWidths, 0, sizeof(mWidths));
mHeight = mFontMetrics.height();
}
int width(const QChar & ch)
{
auto unicode = ch.unicode();
if(unicode >= 0xD800)
{
if(unicode >= 0xE000)
unicode -= 0xE000 - 0xD800;
else
// is lonely surrogate
return mFontMetrics.width(ch);
}
if(!mWidths[unicode])
return mWidths[unicode] = mFontMetrics.width(ch);
return mWidths[unicode];
}
int width(const QString & text)
{
int result = 0;
QChar temp;
for(const QChar & ch : text)
{
if(ch.isHighSurrogate())
temp = ch;
else if(ch.isLowSurrogate())
result += mFontMetrics.width(QString(temp) + ch);
else
result += width(ch);
}
return result;
}
int height()
{
return mHeight;
}
private:
QFontMetrics mFontMetrics;
uchar mWidths[0x10000 - 0xE000 + 0xD800];
int mHeight;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/CodeFolding.cpp | #include "CodeFolding.h"
CodeFoldingHelper::CodeFoldingHelper()
{
}
CodeFoldingHelper::~CodeFoldingHelper()
{
}
/**
* @brief Whether va is the beginning ot of a code folding segment.
* @param va The virtual address
* @return True if va satifies condition.
*/
bool CodeFoldingHelper::isFoldStart(duint va) const
{
const FoldTree* temp = getFoldTree(va);
return temp != nullptr && va == temp->range.first;
}
/**
* @brief Whether va is inside a code folding segment.
* @param va The virtual address.
* @return True if va satisfies condition.
*/
bool CodeFoldingHelper::isFoldBody(duint va) const
{
return root.find(Range(va, va)) != root.cend();
}
/**
* @brief Whether va is the end of a code folding segment.
* @param va The virtual address.
* @return True if va satisfies condition.
*/
bool CodeFoldingHelper::isFoldEnd(duint va) const
{
const FoldTree* temp = getFoldTree(va);
return temp != nullptr && va == temp->range.second;
}
/**
* @brief Whether va is folded and should be invisible.
* @param va The virtual address.
* @return True if va satisfies condition.
*/
bool CodeFoldingHelper::isFolded(duint va) const
{
const FoldTree* temp = getFoldTree(va);
return temp != nullptr && temp->folded;
}
/**
* @brief Whether there are some code folding segments within the specified range.
* @param vaStart The beginning virtual address of the data range.
* @param vaEnd The ending virtual address of the data range.
* @return True if such code folding segment present.
*/
bool CodeFoldingHelper::isDataRangeFolded(duint vaStart, duint vaEnd) const
{
CompareFunc less;
Range lower(vaStart, vaStart);
Range upper(vaEnd, vaEnd);
auto iteratorStart = root.upper_bound(lower);
auto iteratorEnd = root.lower_bound(upper);
return (iteratorStart != root.cend() && less(iteratorStart->first, upper)) && (iteratorEnd != root.cend() && less(lower, iteratorEnd->first));
}
/**
* @brief Get the beginning virtual address of the code folding segment.
* @param va The virtual address which lies within the code folding segment.
* @return The beginning virtual address, or 0 if such code folding segment is not found.
*/
duint CodeFoldingHelper::getFoldBegin(duint va) const
{
const FoldTree* temp = getFirstFoldedTree(va);
return temp == nullptr ? 0 : temp->range.first;
}
/**
* @brief Get the ending virtual address of the code folding segment.
* @param va The virtual address which lies within the code folding segment.
* @return The ending virtual address, or 0 if such code folding segment is not found.
*/
duint CodeFoldingHelper::getFoldEnd(duint va) const
{
const FoldTree* temp = getFirstFoldedTree(va);
return temp == nullptr ? 0 : temp->range.second;
}
/**
* @brief Get the total bytes within range that should be invisible due to code folding.
* @param vaStart The beginning virtual address of the range.
* @param vaEnd The ending virtual address of the range.
* @return The total number bytes that are folded.
*/
duint CodeFoldingHelper::getFoldedSize(duint vaStart, duint vaEnd) const
{
CompareFunc less;
Range keyLower(vaStart, vaStart);
Range keyUpper(vaEnd, vaEnd);
duint size = 0;
auto iteratorLower = root.upper_bound(keyLower);
auto iteratorUpper = root.lower_bound(keyUpper);
if(iteratorLower == root.cend() || iteratorUpper == root.cend() || less(iteratorUpper->first, iteratorLower->first))
return 0;
for(auto i = iteratorLower; i != iteratorUpper; i ++)
size += getFoldedSize(&i->second);
return size;
}
/**
* @brief Internal. Get the total bytes that should be invisible due to code folding withing a code folding segment.
* @param node The code folding segment.
* @return Number of bytes folded.
*/
duint CodeFoldingHelper::getFoldedSize(const FoldTree* node) const
{
if(node->folded)
return node->range.second - node->range.first;
else
{
duint size = 0;
for(auto i = node->children.cbegin(); i != node->children.cend(); i++)
size += getFoldedSize(&i->second);
return size;
}
}
/**
* @brief Set the folding state of a code folding segment.
* @param va The virtual address within the specified code folding segment.
* @param folded True if the segment should be folded, false otherwise.
*/
void CodeFoldingHelper::setFolded(duint va, bool folded)
{
FoldTree* temp = getFoldTree(va);
if(temp)
temp->folded = folded;
}
/**
* @brief Add a code folding segment.
* @param va The beginning virtual address of the new code folding segment.
* @param length The total number of bytes within the new code folding segment.
* @param folded The initial state of the new code folding segment.
* @return True if the operation succeeded.
* @remark It cannot add a new code folding segment that overlaps an existing code folding segments.
*/
bool CodeFoldingHelper::addFoldSegment(duint va, duint length, bool folded)
{
FoldTree* temp = getFoldTree(va);
FoldTree* temp2 = getFoldTree(va + length);
if(temp != temp2)
return false;
if(isDataRangeFolded(va, va + length))
{
// There's some folded code inside the range
return false;
}
auto map = (temp == nullptr) ? &root : &temp->children;
auto result = map->insert(std::make_pair(std::make_pair(va, va + length), FoldTree(folded, va, va + length)));
return result.second;
}
/**
* @brief Deletes an existing code folding segment.
* @param va The virtual address within the specified code folding segment.
* @return True if such code folding segment is found and successfully deleted.
*/
bool CodeFoldingHelper::delFoldSegment(duint va)
{
Range key(va, va);
auto temp1 = root.find(key);
if(temp1 == root.cend())
return false;
auto parent = &root;
do
{
auto temp2 = temp1->second.children.find(key);
if(temp2 == temp1->second.children.cend())
break;
parent = &temp1->second.children;
temp1 = temp2;
}
while(true);
parent->erase(temp1);
return true;
}
const CodeFoldingHelper::FoldTree* CodeFoldingHelper::getFoldTree(duint va) const
{
Range key(va, va);
auto temp1 = root.find(key);
if(temp1 == root.cend())
return nullptr;
do
{
auto temp2 = temp1->second.children.find(key);
if(temp2 == temp1->second.children.cend())
break;
temp1 = temp2;
}
while(true);
return &temp1->second;
}
const CodeFoldingHelper::FoldTree* CodeFoldingHelper::getFirstFoldedTree(duint va) const
{
Range key(va, va);
auto temp1 = root.find(key);
if(temp1 == root.cend())
return nullptr;
while(!temp1->second.folded)
{
auto temp2 = temp1->second.children.find(key);
if(temp2 == temp1->second.children.cend())
break;
temp1 = temp2;
}
return &temp1->second;
}
CodeFoldingHelper::FoldTree* CodeFoldingHelper::getFoldTree(duint va)
{
Range key(va, va);
auto temp1 = root.find(key);
if(temp1 == root.cend())
return nullptr;
do
{
auto temp2 = temp1->second.children.find(key);
if(temp2 == temp1->second.children.cend())
break;
temp1 = temp2;
}
while(true);
return &temp1->second;
}
CodeFoldingHelper::FoldTree* CodeFoldingHelper::getFirstFoldedTree(duint va)
{
Range key(va, va);
auto temp1 = root.find(key);
if(temp1 == root.cend())
return nullptr;
while(!temp1->second.folded)
{
auto temp2 = temp1->second.children.find(key);
if(temp2 == temp1->second.children.cend())
break;
temp1 = temp2;
}
return &temp1->second;
}
/**
* @brief Expands appropriate code folding segments so that the specified virtual address is unfolded.
* @param va The specified virtual address.
*/
void CodeFoldingHelper::expandFoldSegment(duint va)
{
Range key(va, va);
auto temp1 = root.find(key);
if(temp1 == root.cend())
return;
temp1->second.folded = false;
do
{
auto temp2 = temp1->second.children.find(key);
if(temp2 == temp1->second.children.cend())
break;
temp2->second.folded = false;
temp1 = temp2;
}
while(true);
}
bool CodeFoldingHelper::CompareFunc::operator()(const CodeFoldingHelper::Range & lhs, const CodeFoldingHelper::Range & rhs) const
{
return lhs.second < rhs.first;
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/CodeFolding.h | #pragma once
#include "Imports.h"
#include <map>
class CodeFoldingHelper
{
public:
CodeFoldingHelper();
~CodeFoldingHelper();
bool isFoldStart(duint va) const;
bool isFoldBody(duint va) const;
bool isFoldEnd(duint va) const;
bool isFolded(duint va) const;
bool isDataRangeFolded(duint vaStart, duint vaEnd) const;
duint getFoldBegin(duint va) const;
duint getFoldEnd(duint va) const;
duint getFoldedSize(duint vaStart, duint vaEnd) const;
void setFolded(duint va, bool folded);
bool addFoldSegment(duint va, duint length, bool folded = true);
bool delFoldSegment(duint va);
void expandFoldSegment(duint va);
protected:
typedef std::pair<duint, duint> Range;
class CompareFunc
{
public:
bool operator()(const Range & lhs, const Range & rhs) const;
};
class FoldTree
{
public:
FoldTree(bool _folded, duint start, duint end) : folded(_folded), range(std::make_pair(start, end)) {}
bool folded;
Range range;
std::map<Range, FoldTree, CompareFunc> children;
};
std::map<Range, FoldTree, CompareFunc> root;
const FoldTree* getFoldTree(duint va) const;
FoldTree* getFoldTree(duint va);
const FoldTree* getFirstFoldedTree(duint va) const;
FoldTree* getFirstFoldedTree(duint va);
duint getFoldedSize(const FoldTree* node) const;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/CommonActions.cpp | #include "CommonActions.h"
#include "MenuBuilder.h"
#include <QAction>
#include <QMessageBox>
#include <QFile>
#include "StringUtil.h"
#include "MiscUtil.h"
#include "Breakpoints.h"
#include "LineEditDialog.h"
#include "WordEditDialog.h"
CommonActions::CommonActions(QWidget* parent, ActionHelperFuncs funcs, GetSelectionFunc getSelection)
: QObject(parent), ActionHelperProxy(funcs), mGetSelection(getSelection)
{
}
void CommonActions::build(MenuBuilder* builder, int actions)
{
// Condition Lambda
auto wIsDebugging = [this](QMenu*)
{
return mGetSelection() != 0 && DbgIsDebugging();
};
auto wIsValidReadPtrCallback = [this](QMenu*)
{
duint ptr = 0;
DbgMemRead(mGetSelection(), (unsigned char*)&ptr, sizeof(duint));
return DbgMemIsValidReadPtr(ptr);
};
// Menu action
if(actions & ActionDisasm)
{
builder->addAction(makeShortcutDescAction(DIcon(ArchValue("processor32", "processor64")), tr("Follow in Disassembler"), tr("Show this address in disassembler. Equivalent command \"d address\"."), std::bind(&CommonActions::followDisassemblySlot, this), "ActionFollowDisasm"), wIsDebugging);
}
if(actions & ActionDisasmData)
{
builder->addAction(makeCommandAction(DIcon("processor32"), ArchValue(tr("&Follow DWORD in Disassembler"), tr("&Follow QWORD in Disassembler")), "disasm [$]", "ActionFollowDwordQwordDisasm"), wIsValidReadPtrCallback);
}
if(actions & ActionDump)
{
builder->addAction(makeCommandDescAction(DIcon("dump"), tr("Follow in Dump"), tr("Show the address in dump. Equivalent command \"dump address\"."), "dump $"));
}
if(actions & ActionDumpData)
{
builder->addAction(makeCommandAction(DIcon("dump"), ArchValue(tr("&Follow DWORD in Current Dump"), tr("&Follow QWORD in Current Dump")), "dump [$]", "ActionFollowDwordQwordDump"), wIsValidReadPtrCallback);
}
if(actions & ActionDumpN)
{
//Follow in Dump N menu
MenuBuilder* followDumpNMenu = new MenuBuilder(this, [this](QMenu*)
{
duint ptr;
return DbgMemRead(mGetSelection(), (unsigned char*)&ptr, sizeof(ptr)) && DbgMemIsValidReadPtr(ptr);
});
const int maxDumps = 5; // TODO: get this value from CPUMultiDump
for(int i = 0; i < maxDumps; i++)
// TODO: Get dump tab names
followDumpNMenu->addAction(makeAction(tr("Dump %1").arg(i + 1), [i, this]
{
duint selectedData = mGetSelection();
if(DbgMemIsValidReadPtr(selectedData))
DbgCmdExec(QString("dump [%1], %2").arg(ToPtrString(selectedData)).arg(i + 1));
}));
builder->addMenu(makeMenu(DIcon("dump"), ArchValue(tr("Follow DWORD in Dump"), tr("Follow QWORD in Dump"))), followDumpNMenu);
}
if(actions & ActionStackDump)
{
builder->addAction(makeCommandDescAction(DIcon("stack"), tr("Follow in Stack"), tr("Show this address in stack view. Equivalent command \"sdump address\"."), "sdump $", "ActionFollowStack"), [this](QMenu*)
{
auto start = mGetSelection();
return (DbgMemIsValidReadPtr(start) && DbgMemFindBaseAddr(start, 0) == DbgMemFindBaseAddr(DbgValFromString("csp"), 0));
});
}
if(actions & ActionMemoryMap)
{
builder->addAction(makeCommandDescAction(DIcon("memmap_find_address_page"), tr("Follow in Memory Map"), tr("Show this address in memory map view. Equivalent command \"memmapdump address\"."), "memmapdump $", "ActionFollowMemMap"), wIsDebugging);
}
if(actions & ActionGraph)
{
builder->addAction(makeShortcutDescAction(DIcon("graph"), tr("Graph"), tr("Show the control flow graph of this function in CPU view. Equivalent command \"graph address\"."), std::bind(&CommonActions::graphSlot, this), "ActionGraph"));
}
if(actions & ActionBreakpoint)
{
struct ActionHolder
{
QAction* toggleBreakpointAction;
QAction* editSoftwareBreakpointAction;
QAction* setHwBreakpointAction;
QAction* removeHwBreakpointAction;
QMenu* replaceSlotMenu;
QAction* replaceSlotAction[4];
} hodl;
hodl.toggleBreakpointAction = makeShortcutAction(DIcon("breakpoint_toggle"), tr("Toggle"), std::bind(&CommonActions::toggleInt3BPActionSlot, this), "ActionToggleBreakpoint");
hodl.editSoftwareBreakpointAction = makeShortcutAction(DIcon("breakpoint_edit_alt"), tr("Edit"), std::bind(&CommonActions::editSoftBpActionSlot, this), "ActionEditBreakpoint");
hodl.setHwBreakpointAction = makeShortcutAction(DIcon("breakpoint_execute"), tr("Set Hardware on Execution"), std::bind(&CommonActions::toggleHwBpActionSlot, this), "ActionSetHwBpE");
hodl.removeHwBreakpointAction = makeShortcutAction(DIcon("breakpoint_remove"), tr("Remove Hardware"), std::bind(&CommonActions::toggleHwBpActionSlot, this), "ActionRemoveHwBp");
hodl.replaceSlotMenu = makeMenu(DIcon("breakpoint_execute"), tr("Set Hardware on Execution"));
// Replacement slot menu are only used when the breakpoints are full, so using "Unknown" as the placeholder. Might want to change this in case we display the menu when there are still free slots.
hodl.replaceSlotAction[0] = makeMenuAction(hodl.replaceSlotMenu, DIcon("breakpoint_execute_slot1"), tr("Replace Slot %1 (Unknown)").arg(1), std::bind(&CommonActions::setHwBpOnSlot0ActionSlot, this));
hodl.replaceSlotAction[1] = makeMenuAction(hodl.replaceSlotMenu, DIcon("breakpoint_execute_slot2"), tr("Replace Slot %1 (Unknown)").arg(2), std::bind(&CommonActions::setHwBpOnSlot1ActionSlot, this));
hodl.replaceSlotAction[2] = makeMenuAction(hodl.replaceSlotMenu, DIcon("breakpoint_execute_slot3"), tr("Replace Slot %1 (Unknown)").arg(3), std::bind(&CommonActions::setHwBpOnSlot2ActionSlot, this));
hodl.replaceSlotAction[3] = makeMenuAction(hodl.replaceSlotMenu, DIcon("breakpoint_execute_slot4"), tr("Replace Slot %1 (Unknown)").arg(4), std::bind(&CommonActions::setHwBpOnSlot3ActionSlot, this));
builder->addMenu(makeMenu(DIcon("breakpoint"), tr("Breakpoint")), [this, hodl](QMenu * menu)
{
auto selection = mGetSelection();
if(selection == 0)
return false;
BPXTYPE bpType = DbgGetBpxTypeAt(selection);
if((bpType & bp_normal) == bp_normal || (bpType & bp_hardware) == bp_hardware)
hodl.editSoftwareBreakpointAction->setText(tr("Edit"));
else
hodl.editSoftwareBreakpointAction->setText(tr("Set Conditional Breakpoint"));
menu->addAction(hodl.editSoftwareBreakpointAction);
menu->addAction(hodl.toggleBreakpointAction);
if((bpType & bp_hardware) == bp_hardware)
{
menu->addAction(hodl.removeHwBreakpointAction);
}
else
{
BPMAP bpList;
DbgGetBpList(bp_hardware, &bpList);
//get enabled hwbp count
int enabledCount = bpList.count;
for(int i = 0; i < bpList.count; i++)
if(!bpList.bp[i].enabled)
enabledCount--;
if(enabledCount < 4)
{
menu->addAction(hodl.setHwBreakpointAction);
}
else
{
for(int i = 0; i < bpList.count; i++)
{
if(bpList.bp[i].enabled && bpList.bp[i].slot < 4)
{
hodl.replaceSlotAction[bpList.bp[i].slot]->setText(tr("Replace Slot %1 (0x%2)").arg(bpList.bp[i].slot + 1).arg(ToPtrString(bpList.bp[i].addr)));
}
}
menu->addMenu(hodl.replaceSlotMenu);
}
if(bpList.count)
BridgeFree(bpList.bp);
}
return true;
});
}
if(actions & ActionLabel)
{
builder->addAction(makeShortcutAction(DIcon("label"), tr("Label Current Address"), std::bind(&CommonActions::setLabelSlot, this), "ActionSetLabel"), wIsDebugging);
}
if(actions & ActionComment)
{
builder->addAction(makeShortcutAction(DIcon("comment"), tr("Comment"), std::bind(&CommonActions::setCommentSlot, this), "ActionSetComment"), wIsDebugging);
}
if(actions & ActionBookmark)
{
builder->addAction(makeShortcutDescAction(DIcon("bookmark_toggle"), tr("Toggle Bookmark"), tr("Set a bookmark here, or remove bookmark. Equivalent command \"bookmarkset address\"/\"bookmarkdel address\"."), std::bind(&CommonActions::setBookmarkSlot, this), "ActionToggleBookmark"), wIsDebugging);
}
if(actions & ActionNewOrigin)
{
builder->addAction(makeShortcutDescAction(DIcon("neworigin"), tr("Set %1 Here").arg(ArchValue("EIP", "RIP")), tr("Set the next executed instruction to this address. Equivalent command \"mov cip, address\"."), std::bind(&CommonActions::setNewOriginHereActionSlot, this), "ActionSetNewOriginHere"));
}
if(actions & ActionNewThread)
{
builder->addAction(makeShortcutDescAction(DIcon("createthread"), tr("Create New Thread Here"), tr("Create a new thread at this address. Equivalent command \"createthread address, argument\"."), std::bind(&CommonActions::createThreadSlot, this), "ActionCreateNewThreadHere"));
}
if(actions & ActionWatch)
{
builder->addAction(makeCommandDescAction(DIcon("animal-dog"), ArchValue(tr("&Watch DWORD"), tr("&Watch QWORD")), tr("Add the address in the watch view. Equivalent command \"AddWatch [address], \"uint\"\"."), "AddWatch \"[$]\", \"uint\"", "ActionWatchDwordQword"));
}
}
QAction* CommonActions::makeCommandAction(const QIcon & icon, const QString & text, const char* cmd, const char* shortcut)
{
// sender() doesn't work in slots
return makeShortcutAction(icon, text, [cmd, this]()
{
DbgCmdExec(QString(cmd).replace("$", ToPtrString(mGetSelection())));
}, shortcut);
}
QAction* CommonActions::makeCommandAction(const QIcon & icon, const QString & text, const char* cmd)
{
return makeAction(icon, text, [cmd, this]()
{
DbgCmdExec(QString(cmd).replace("$", ToPtrString(mGetSelection())));
});
}
static QAction* makeDescActionHelper(QAction* action, const QString & description)
{
action->setStatusTip(description);
return action;
}
QAction* CommonActions::makeCommandDescAction(const QIcon & icon, const QString & text, const QString & description, const char* cmd)
{
return makeDescActionHelper(makeCommandAction(icon, text, cmd), description);
}
QAction* CommonActions::makeCommandDescAction(const QIcon & icon, const QString & text, const QString & description, const char* cmd, const char* shortcut)
{
return makeDescActionHelper(makeCommandAction(icon, text, cmd, shortcut), description);
}
QWidget* CommonActions::widgetparent() const
{
return dynamic_cast<QWidget*>(parent());
}
// Actions slots
// Follow in disassembly
void CommonActions::followDisassemblySlot()
{
duint cip = mGetSelection();
if(DbgMemIsValidReadPtr(cip))
DbgCmdExec(QString("dis ").append(ToPtrString(cip)));
else
GuiAddStatusBarMessage(tr("Cannot follow %1. Address is invalid.\n").arg(ToPtrString(cip)).toUtf8().constData());
}
void CommonActions::setLabelSlot()
{
duint wVA = mGetSelection();
LineEditDialog mLineEdit(widgetparent());
mLineEdit.setTextMaxLength(MAX_LABEL_SIZE - 2);
QString addr_text = ToPtrString(wVA);
char label_text[MAX_COMMENT_SIZE] = "";
if(DbgGetLabelAt((duint)wVA, SEG_DEFAULT, label_text))
mLineEdit.setText(QString(label_text));
mLineEdit.setWindowTitle(tr("Add label at ") + addr_text);
restart:
if(mLineEdit.exec() != QDialog::Accepted)
return;
QByteArray utf8data = mLineEdit.editText.toUtf8();
if(!utf8data.isEmpty() && DbgIsValidExpression(utf8data.constData()) && DbgValFromString(utf8data.constData()) != wVA)
{
QMessageBox msg(QMessageBox::Warning, tr("The label may be in use"),
tr("The label \"%1\" may be an existing label or a valid expression. Using such label might have undesired effects. Do you still want to continue?").arg(mLineEdit.editText),
QMessageBox::Yes | QMessageBox::No, widgetparent());
msg.setWindowIcon(DIcon("compile-warning"));
msg.setParent(widgetparent(), Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::No)
goto restart;
}
if(!DbgSetLabelAt(wVA, utf8data.constData()))
SimpleErrorBox(widgetparent(), tr("Error!"), tr("DbgSetLabelAt failed!"));
GuiUpdateAllViews();
}
void CommonActions::setCommentSlot()
{
if(!DbgIsDebugging())
return;
duint wVA = mGetSelection();
LineEditDialog mLineEdit(widgetparent());
mLineEdit.setTextMaxLength(MAX_COMMENT_SIZE - 2);
QString addr_text = ToPtrString(wVA);
char comment_text[MAX_COMMENT_SIZE] = "";
if(DbgGetCommentAt((duint)wVA, comment_text))
{
if(comment_text[0] == '\1') //automatic comment
mLineEdit.setText(QString(comment_text + 1));
else
mLineEdit.setText(QString(comment_text));
}
mLineEdit.setWindowTitle(tr("Add comment at ") + addr_text);
if(mLineEdit.exec() != QDialog::Accepted)
return;
QString comment = mLineEdit.editText.replace('\r', "").replace('\n', "");
if(!DbgSetCommentAt(wVA, comment.toUtf8().constData()))
SimpleErrorBox(widgetparent(), tr("Error!"), tr("DbgSetCommentAt failed!"));
static bool easter = isEaster();
if(easter && comment.toLower() == "oep")
{
QFile file(":/Default/icons/egg.wav");
if(file.open(QIODevice::ReadOnly))
{
QByteArray egg = file.readAll();
PlaySoundA(egg.data(), 0, SND_MEMORY | SND_ASYNC | SND_NODEFAULT);
}
}
GuiUpdateAllViews();
}
void CommonActions::setBookmarkSlot()
{
if(!DbgIsDebugging())
return;
duint wVA = mGetSelection();
bool result;
result = DbgSetBookmarkAt(wVA, !DbgGetBookmarkAt(wVA));
if(!result)
SimpleErrorBox(widgetparent(), tr("Error!"), tr("DbgSetBookmarkAt failed!"));
GuiUpdateAllViews();
}
// Give a warning about the selected address is not executable
bool CommonActions::WarningBoxNotExecutable(const QString & text, duint wVA) const
{
if(DbgFunctions()->IsDepEnabled() && !DbgFunctions()->MemIsCodePage(wVA, false))
{
QMessageBox msgyn(QMessageBox::Warning, tr("Address %1 is not executable").arg(ToPtrString(wVA)), text, QMessageBox::Yes | QMessageBox::No, widgetparent());
msgyn.setWindowIcon(DIcon("compile-warning"));
msgyn.setParent(widgetparent(), Qt::Dialog);
msgyn.setDefaultButton(QMessageBox::No);
msgyn.setWindowFlags(msgyn.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msgyn.exec() == QMessageBox::No)
return false;
}
return true;
}
void CommonActions::toggleInt3BPActionSlot()
{
if(!DbgIsDebugging())
return;
duint wVA = mGetSelection();
BPXTYPE wBpType = DbgGetBpxTypeAt(wVA);
QString wCmd;
if((wBpType & bp_normal) == bp_normal)
wCmd = "bc " + ToPtrString(wVA);
else
{
if(!WarningBoxNotExecutable(tr("Setting software breakpoint here may result in crash. Do you really want to continue?"), wVA))
return;
wCmd = "bp " + ToPtrString(wVA);
}
DbgCmdExec(wCmd);
//emit Disassembly::repainted();
}
// Display the edit breakpoint dialog
void CommonActions::editSoftBpActionSlot()
{
auto selection = mGetSelection();
if(selection == 0)
{
return;
}
BPXTYPE bpType = DbgGetBpxTypeAt(selection);
if((bpType & bp_hardware) == bp_hardware)
{
Breakpoints::editBP(bp_hardware, ToHexString(selection), widgetparent());
}
else if((bpType & bp_normal) == bp_normal)
{
Breakpoints::editBP(bp_normal, ToHexString(selection), widgetparent());
}
else
{
auto createCommand = QString("bp %1").arg(ToHexString(selection));
Breakpoints::editBP(bp_normal, ToHexString(selection), widgetparent(), createCommand);
}
}
void CommonActions::toggleHwBpActionSlot()
{
duint wVA = mGetSelection();
BPXTYPE wBpType = DbgGetBpxTypeAt(wVA);
QString wCmd;
if((wBpType & bp_hardware) == bp_hardware)
{
wCmd = "bphwc " + ToPtrString(wVA);
}
else
{
wCmd = "bphws " + ToPtrString(wVA);
}
DbgCmdExec(wCmd);
}
void CommonActions::setHwBpOnSlot0ActionSlot()
{
setHwBpAt(mGetSelection(), 0);
}
void CommonActions::setHwBpOnSlot1ActionSlot()
{
setHwBpAt(mGetSelection(), 1);
}
void CommonActions::setHwBpOnSlot2ActionSlot()
{
setHwBpAt(mGetSelection(), 2);
}
void CommonActions::setHwBpOnSlot3ActionSlot()
{
setHwBpAt(mGetSelection(), 3);
}
void CommonActions::setHwBpAt(duint va, int slot)
{
int wI = 0;
int wSlotIndex = -1;
BPMAP wBPList;
QString wCmd = "";
DbgGetBpList(bp_hardware, &wBPList);
// Find index of slot slot in the list
for(wI = 0; wI < wBPList.count; wI++)
{
if(wBPList.bp[wI].slot == (unsigned short)slot)
{
wSlotIndex = wI;
break;
}
}
if(wSlotIndex < 0) // Slot not used
{
wCmd = "bphws " + ToPtrString(va);
DbgCmdExec(wCmd);
}
else // Slot used
{
wCmd = "bphwc " + ToPtrString((duint)(wBPList.bp[wSlotIndex].addr));
DbgCmdExec(wCmd);
Sleep(200);
wCmd = "bphws " + ToPtrString(va);
DbgCmdExec(wCmd);
}
if(wBPList.count)
BridgeFree(wBPList.bp);
}
void CommonActions::graphSlot()
{
if(DbgCmdExecDirect(QString("graph %1").arg(ToPtrString(mGetSelection()))))
GuiFocusView(GUI_GRAPH);
}
void CommonActions::setNewOriginHereActionSlot()
{
if(!DbgIsDebugging())
return;
duint wVA = mGetSelection();
if(!WarningBoxNotExecutable(tr("Setting new origin here may result in crash. Do you really want to continue?"), wVA))
return;
QString wCmd = "cip=" + ToPtrString(wVA);
DbgCmdExec(wCmd);
}
void CommonActions::createThreadSlot()
{
duint wVA = mGetSelection();
if(!WarningBoxNotExecutable(tr("Creating new thread here may result in crash. Do you really want to continue?"), wVA))
return;
WordEditDialog argWindow(widgetparent());
argWindow.setup(tr("Argument for the new thread"), 0, sizeof(duint));
if(argWindow.exec() != QDialog::Accepted)
return;
DbgCmdExec(QString("createthread %1, %2").arg(ToPtrString(wVA)).arg(ToPtrString(argWindow.getVal())));
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/CommonActions.h | #pragma once
#include <QAction>
#include <functional>
#include "ActionHelpers.h"
class MenuBuilder;
class CommonActions : public QObject, public ActionHelperProxy
{
Q_OBJECT
public:
typedef enum
{
ActionDisasm = 1, // Follow in Disassembly
ActionDisasmMore = 1 << 1, // Follow in Disassembly (submenu)
ActionDisasmDump = 1 << 2, // Follow in Dump in Disassembly Mode
ActionDisasmDumpMore = 1 << 3, // Follow in Dump in Disassembly Mode (submenu)
ActionDisasmData = 1 << 4, // Follow DWORD in Disassembly
ActionDump = 1 << 5, // Follow in Dump
ActionDumpMore = 1 << 6, // Follow in Dump (submenu)
ActionDumpN = 1 << 7, // Follow in Dump N (submenu)
ActionDumpData = 1 << 8, // Follow DWORD in Dump
ActionStackDump = 1 << 9, // Follow in Stack
ActionMemoryMap = 1 << 10, // Follow in Memory Map
ActionGraph = 1 << 11, // Graph
ActionBreakpoint = 1 << 12, // Breakpoint
ActionMemoryBreakpoint = 1 << 13, // Memory Breakpoint
ActionMnemonicHelp = 1 << 14, // Mnemonic Help
ActionLabel = 1 << 15, // Label
ActionLabelMore = 1 << 16, // Label (submenu)
ActionComment = 1 << 17, // Comment
ActionCommentMore = 1 << 18, // Comment (submenu)
ActionBookmark = 1 << 19, // Bookmark
ActionBookmarkMore = 1 << 20, // Bookmark (submenu)
ActionFindref = 1 << 21, // Find references
ActionFindrefMore = 1 << 22, // Find references (submenu)
ActionXref = 1 << 23, // Xref
ActionXrefMore = 1 << 24, // Xref (submenu)
ActionNewOrigin = 1 << 25, // Set EIP/RIP Here
ActionNewThread = 1 << 26, // Create New Thread Here
ActionWatch = 1 << 27 // Watch DWORD
} CommonActionsList;
using GetSelectionFunc = std::function<duint()>;
explicit CommonActions(QWidget* parent, ActionHelperFuncs funcs, GetSelectionFunc getSelection);
void build(MenuBuilder* builder, int actions);
//Reserved for future use (submenu for Dump and Search with more addresses)
//void build(MenuBuilder* builder, int actions, std::function<void(QList<std::pair<QString, duint>>&, CommonActionsList)> additionalAddress);
QAction* makeCommandAction(const QIcon & icon, const QString & text, const char* cmd, const char* shortcut);
QAction* makeCommandAction(const QIcon & icon, const QString & text, const char* cmd);
QAction* makeCommandDescAction(const QIcon & icon, const QString & text, const QString & description, const char* cmd);
QAction* makeCommandDescAction(const QIcon & icon, const QString & text, const QString & description, const char* cmd, const char* shortcut);
public slots:
void followDisassemblySlot();
void setLabelSlot();
void setCommentSlot();
void setBookmarkSlot();
void toggleInt3BPActionSlot();
void editSoftBpActionSlot();
void toggleHwBpActionSlot();
void setHwBpOnSlot0ActionSlot();
void setHwBpOnSlot1ActionSlot();
void setHwBpOnSlot2ActionSlot();
void setHwBpOnSlot3ActionSlot();
void setHwBpAt(duint va, int slot);
void graphSlot();
void setNewOriginHereActionSlot();
void createThreadSlot();
private:
GetSelectionFunc mGetSelection;
bool WarningBoxNotExecutable(const QString & text, duint wVA) const;
QWidget* widgetparent() const;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/Configuration.cpp | #include "Configuration.h"
#include <QApplication>
#include <QFontInfo>
#include <QMessageBox>
#include <QIcon>
#include <QScreen>
#include <QGuiApplication>
#include <QWheelEvent>
#include "AbstractTableView.h"
Configuration* Configuration::mPtr = nullptr;
inline void insertMenuBuilderBools(QMap<QString, bool>* config, const char* id, size_t count)
{
for(size_t i = 0; i < count; i++)
config->insert(QString("Menu%1Hidden%2").arg(id).arg(i), false);
}
Configuration::Configuration() : QObject(), noMoreMsgbox(false)
{
mPtr = this;
//setup default color map
defaultColors.clear();
defaultColors.insert("AbstractTableViewSeparatorColor", QColor("#808080"));
defaultColors.insert("AbstractTableViewBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("AbstractTableViewTextColor", QColor("#000000"));
defaultColors.insert("AbstractTableViewHeaderTextColor", QColor("#000000"));
defaultColors.insert("AbstractTableViewSelectionColor", QColor("#C0C0C0"));
defaultColors.insert("DisassemblyCipColor", QColor("#FFFFFF"));
defaultColors.insert("DisassemblyCipBackgroundColor", QColor("#000000"));
defaultColors.insert("DisassemblyBreakpointColor", QColor("#000000"));
defaultColors.insert("DisassemblyBreakpointBackgroundColor", QColor("#FF0000"));
defaultColors.insert("DisassemblyHardwareBreakpointColor", QColor("#000000"));
defaultColors.insert("DisassemblyHardwareBreakpointBackgroundColor", QColor("#FF8080"));
defaultColors.insert("DisassemblyBookmarkColor", QColor("#000000"));
defaultColors.insert("DisassemblyBookmarkBackgroundColor", QColor("#FEE970"));
defaultColors.insert("DisassemblyLabelColor", QColor("#FF0000"));
defaultColors.insert("DisassemblyLabelBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("DisassemblySelectionColor", QColor("#C0C0C0"));
defaultColors.insert("DisassemblyTracedBackgroundColor", QColor("#C0FFC0"));
defaultColors.insert("DisassemblyAddressColor", QColor("#808080"));
defaultColors.insert("DisassemblyAddressBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblySelectedAddressColor", QColor("#000000"));
defaultColors.insert("DisassemblySelectedAddressBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyConditionalJumpLineTrueColor", QColor("#FF0000"));
defaultColors.insert("DisassemblyConditionalJumpLineFalseColor", QColor("#808080"));
defaultColors.insert("DisassemblyUnconditionalJumpLineColor", QColor("#FF0000"));
defaultColors.insert("DisassemblyBytesColor", QColor("#000000"));
defaultColors.insert("DisassemblyBytesBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyModifiedBytesColor", QColor("#FF0000"));
defaultColors.insert("DisassemblyModifiedBytesBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyRestoredBytesColor", QColor("#808080"));
defaultColors.insert("DisassemblyRestoredBytesBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyRelocationUnderlineColor", QColor("#000000"));
defaultColors.insert("DisassemblyCommentColor", QColor("#000000"));
defaultColors.insert("DisassemblyCommentBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyAutoCommentColor", QColor("#AA5500"));
defaultColors.insert("DisassemblyAutoCommentBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyMnemonicBriefColor", QColor("#717171"));
defaultColors.insert("DisassemblyMnemonicBriefBackgroundColor", Qt::transparent);
defaultColors.insert("DisassemblyFunctionColor", QColor("#000000"));
defaultColors.insert("DisassemblyLoopColor", QColor("#000000"));
defaultColors.insert("SideBarBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("SideBarCipLabelColor", QColor("#FFFFFF"));
defaultColors.insert("SideBarCipLabelBackgroundColor", QColor("#4040FF"));
defaultColors.insert("SideBarBulletColor", QColor("#808080"));
defaultColors.insert("SideBarBulletBreakpointColor", QColor("#FF0000"));
defaultColors.insert("SideBarBulletDisabledBreakpointColor", QColor("#00AA00"));
defaultColors.insert("SideBarBulletBookmarkColor", QColor("#FEE970"));
defaultColors.insert("SideBarCheckBoxForeColor", QColor("#000000"));
defaultColors.insert("SideBarCheckBoxBackColor", QColor("#FFFFFF"));
defaultColors.insert("SideBarConditionalJumpLineTrueColor", QColor("#FF0000"));
defaultColors.insert("SideBarConditionalJumpLineTrueBackwardsColor", QColor("#FF0000"));
defaultColors.insert("SideBarConditionalJumpLineFalseColor", QColor("#00BBFF"));
defaultColors.insert("SideBarConditionalJumpLineFalseBackwardsColor", QColor("#FFA500"));
defaultColors.insert("SideBarUnconditionalJumpLineTrueColor", QColor("#FF0000"));
defaultColors.insert("SideBarUnconditionalJumpLineTrueBackwardsColor", QColor("#FF0000"));
defaultColors.insert("SideBarUnconditionalJumpLineFalseColor", QColor("#00BBFF"));
defaultColors.insert("SideBarUnconditionalJumpLineFalseBackwardsColor", QColor("#FFA500"));
defaultColors.insert("RegistersBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("RegistersColor", QColor("#000000"));
defaultColors.insert("RegistersModifiedColor", QColor("#FF0000"));
defaultColors.insert("RegistersSelectionColor", QColor("#EEEEEE"));
defaultColors.insert("RegistersLabelColor", QColor("#000000"));
defaultColors.insert("RegistersArgumentLabelColor", Qt::darkGreen);
defaultColors.insert("RegistersExtraInfoColor", QColor("#000000"));
defaultColors.insert("RegistersHighlightReadColor", QColor("#00A000"));
defaultColors.insert("RegistersHighlightWriteColor", QColor("#B00000"));
defaultColors.insert("RegistersHighlightReadWriteColor", QColor("#808000"));
defaultColors.insert("InstructionHighlightColor", QColor("#FFFFFF"));
defaultColors.insert("InstructionHighlightBackgroundColor", QColor("#CC0000"));
defaultColors.insert("InstructionCommaColor", QColor("#000000"));
defaultColors.insert("InstructionCommaBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionPrefixColor", QColor("#000000"));
defaultColors.insert("InstructionPrefixBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionUncategorizedColor", QColor("#000000"));
defaultColors.insert("InstructionUncategorizedBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionAddressColor", QColor("#000000"));
defaultColors.insert("InstructionAddressBackgroundColor", QColor("#FFFF00"));
defaultColors.insert("InstructionValueColor", QColor("#828200"));
defaultColors.insert("InstructionValueBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMnemonicColor", QColor("#000000"));
defaultColors.insert("InstructionMnemonicBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionPushPopColor", QColor("#0000FF"));
defaultColors.insert("InstructionPushPopBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionCallColor", QColor("#000000"));
defaultColors.insert("InstructionCallBackgroundColor", QColor("#00FFFF"));
defaultColors.insert("InstructionRetColor", QColor("#000000"));
defaultColors.insert("InstructionRetBackgroundColor", QColor("#00FFFF"));
defaultColors.insert("InstructionConditionalJumpColor", QColor("#FF0000"));
defaultColors.insert("InstructionConditionalJumpBackgroundColor", QColor("#FFFF00"));
defaultColors.insert("InstructionUnconditionalJumpColor", QColor("#000000"));
defaultColors.insert("InstructionUnconditionalJumpBackgroundColor", QColor("#FFFF00"));
defaultColors.insert("InstructionUnusualColor", QColor("#000000"));
defaultColors.insert("InstructionUnusualBackgroundColor", QColor("#C00000"));
defaultColors.insert("InstructionNopColor", QColor("#808080"));
defaultColors.insert("InstructionNopBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionFarColor", QColor("#000000"));
defaultColors.insert("InstructionFarBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionInt3Color", QColor("#000000"));
defaultColors.insert("InstructionInt3BackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemorySizeColor", QColor("#000080"));
defaultColors.insert("InstructionMemorySizeBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemorySegmentColor", QColor("#FF00FF"));
defaultColors.insert("InstructionMemorySegmentBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemoryBracketsColor", QColor("#000000"));
defaultColors.insert("InstructionMemoryBracketsBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemoryStackBracketsColor", QColor("#000000"));
defaultColors.insert("InstructionMemoryStackBracketsBackgroundColor", QColor("#00FFFF"));
defaultColors.insert("InstructionMemoryBaseRegisterColor", QColor("#B03434"));
defaultColors.insert("InstructionMemoryBaseRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemoryIndexRegisterColor", QColor("#3838BC"));
defaultColors.insert("InstructionMemoryIndexRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemoryScaleColor", QColor("#B30059"));
defaultColors.insert("InstructionMemoryScaleBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMemoryOperatorColor", QColor("#F27711"));
defaultColors.insert("InstructionMemoryOperatorBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionGeneralRegisterColor", QColor("#008300"));
defaultColors.insert("InstructionGeneralRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionFpuRegisterColor", QColor("#000080"));
defaultColors.insert("InstructionFpuRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionMmxRegisterColor", QColor("#000080"));
defaultColors.insert("InstructionMmxRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionXmmRegisterColor", QColor("#000080"));
defaultColors.insert("InstructionXmmRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionYmmRegisterColor", QColor("#000080"));
defaultColors.insert("InstructionYmmRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("InstructionZmmRegisterColor", QColor("#000080"));
defaultColors.insert("InstructionZmmRegisterBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpTextColor", QColor("#000000"));
defaultColors.insert("HexDumpModifiedBytesColor", QColor("#FF0000"));
defaultColors.insert("HexDumpModifiedBytesBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpRestoredBytesColor", QColor("#808080"));
defaultColors.insert("HexDumpRestoredBytesBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpByte00Color", QColor("#008000"));
defaultColors.insert("HexDumpByte00BackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpByte7FColor", QColor("#808000"));
defaultColors.insert("HexDumpByte7FBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpByteFFColor", QColor("#800000"));
defaultColors.insert("HexDumpByteFFBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpByteIsPrintColor", QColor("#800080"));
defaultColors.insert("HexDumpByteIsPrintBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("HexDumpSelectionColor", QColor("#C0C0C0"));
defaultColors.insert("HexDumpAddressColor", QColor("#000000"));
defaultColors.insert("HexDumpAddressBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpLabelColor", QColor("#FF0000"));
defaultColors.insert("HexDumpLabelBackgroundColor", Qt::transparent);
defaultColors.insert("HexDumpUserModuleCodePointerHighlightColor", QColor("#00FF00"));
defaultColors.insert("HexDumpUserModuleDataPointerHighlightColor", QColor("#008000"));
defaultColors.insert("HexDumpSystemModuleCodePointerHighlightColor", QColor("#FF0000"));
defaultColors.insert("HexDumpSystemModuleDataPointerHighlightColor", QColor("#800000"));
defaultColors.insert("HexDumpUnknownCodePointerHighlightColor", QColor("#0000FF"));
defaultColors.insert("HexDumpUnknownDataPointerHighlightColor", QColor("#000080"));
defaultColors.insert("StackTextColor", QColor("#000000"));
defaultColors.insert("StackInactiveTextColor", QColor("#808080"));
defaultColors.insert("StackBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("StackSelectionColor", QColor("#C0C0C0"));
defaultColors.insert("StackCspColor", QColor("#FFFFFF"));
defaultColors.insert("StackCspBackgroundColor", QColor("#000000"));
defaultColors.insert("StackAddressColor", QColor("#808080"));
defaultColors.insert("StackAddressBackgroundColor", Qt::transparent);
defaultColors.insert("StackSelectedAddressColor", QColor("#000000"));
defaultColors.insert("StackSelectedAddressBackgroundColor", Qt::transparent);
defaultColors.insert("StackLabelColor", QColor("#FF0000"));
defaultColors.insert("StackLabelBackgroundColor", Qt::transparent);
defaultColors.insert("StackReturnToColor", QColor("#FF0000"));
defaultColors.insert("StackSEHChainColor", QColor("#AE81FF"));
defaultColors.insert("StackFrameColor", QColor("#000000"));
defaultColors.insert("StackFrameSystemColor", QColor("#0000FF"));
defaultColors.insert("HexEditTextColor", QColor("#000000"));
defaultColors.insert("HexEditWildcardColor", QColor("#FF0000"));
defaultColors.insert("HexEditBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("HexEditSelectionColor", QColor("#C0C0C0"));
defaultColors.insert("GraphJmpColor", QColor("#0148FB"));
defaultColors.insert("GraphBrtrueColor", QColor("#387804"));
defaultColors.insert("GraphBrfalseColor", QColor("#ED4630"));
defaultColors.insert("GraphCurrentShadowColor", QColor("#473a3a"));
defaultColors.insert("GraphRetShadowColor", QColor("#900000"));
defaultColors.insert("GraphIndirectcallShadowColor", QColor("#008080"));
defaultColors.insert("GraphBackgroundColor", Qt::transparent);
defaultColors.insert("GraphNodeColor", QColor("#000000"));
defaultColors.insert("GraphNodeBackgroundColor", Qt::transparent);
defaultColors.insert("GraphCipColor", QColor("#000000"));
defaultColors.insert("GraphBreakpointColor", QColor("#FF0000"));
defaultColors.insert("GraphDisabledBreakpointColor", QColor("#00AA00"));
defaultColors.insert("ThreadCurrentColor", QColor("#FFFFFF"));
defaultColors.insert("ThreadCurrentBackgroundColor", QColor("#000000"));
defaultColors.insert("WatchTriggeredColor", QColor("#FF0000"));
defaultColors.insert("WatchTriggeredBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("MemoryMapBreakpointColor", QColor("#000000"));
defaultColors.insert("MemoryMapBreakpointBackgroundColor", QColor("#FF0000"));
defaultColors.insert("MemoryMapCipColor", QColor("#FFFFFF"));
defaultColors.insert("MemoryMapCipBackgroundColor", QColor("#000000"));
defaultColors.insert("MemoryMapSectionTextColor", QColor("#8B671F"));
defaultColors.insert("SearchListViewHighlightColor", QColor("#FF0000"));
defaultColors.insert("SearchListViewHighlightBackgroundColor", Qt::transparent);
defaultColors.insert("StructTextColor", QColor("#000000"));
defaultColors.insert("StructBackgroundColor", QColor("#FFF8F0"));
defaultColors.insert("StructAlternateBackgroundColor", QColor("#DCD9CF"));
defaultColors.insert("LogLinkColor", QColor("#00CC00"));
defaultColors.insert("LogLinkBackgroundColor", Qt::transparent);
defaultColors.insert("BreakpointSummaryParenColor", Qt::red);
defaultColors.insert("BreakpointSummaryKeywordColor", QColor("#8B671F"));
defaultColors.insert("BreakpointSummaryStringColor", QColor("#008000"));
defaultColors.insert("PatchRelocatedByteHighlightColor", QColor("#0000DD"));
defaultColors.insert("SymbolUserTextColor", QColor("#000000"));
defaultColors.insert("SymbolSystemTextColor", QColor("#000000"));
defaultColors.insert("SymbolUnloadedTextColor", QColor("#000000"));
defaultColors.insert("SymbolLoadingTextColor", QColor("#8B671F"));
defaultColors.insert("SymbolLoadedTextColor", QColor("#008000"));
defaultColors.insert("BackgroundFlickerColor", QColor("#ff6961"));
defaultColors.insert("LinkColor", QColor("#0000ff"));
defaultColors.insert("LogColor", QColor("#000000"));
defaultColors.insert("LogBackgroundColor", QColor("#FFF8F0"));
//bool settings
QMap<QString, bool> disassemblyBool;
disassemblyBool.insert("ArgumentSpaces", false);
disassemblyBool.insert("HidePointerSizes", false);
disassemblyBool.insert("HideNormalSegments", false);
disassemblyBool.insert("MemorySpaces", false);
disassemblyBool.insert("KeepSize", false);
disassemblyBool.insert("FillNOPs", false);
disassemblyBool.insert("Uppercase", false);
disassemblyBool.insert("FindCommandEntireBlock", false);
disassemblyBool.insert("OnlyCipAutoComments", false);
disassemblyBool.insert("TabbedMnemonic", false);
disassemblyBool.insert("LongDataInstruction", false);
disassemblyBool.insert("NoHighlightOperands", false);
disassemblyBool.insert("PermanentHighlightingMode", false);
disassemblyBool.insert("0xPrefixValues", false);
disassemblyBool.insert("NoBranchDisasmPreview", false);
disassemblyBool.insert("NoCurrentModuleText", false);
disassemblyBool.insert("ShowMnemonicBrief", false);
defaultBools.insert("Disassembler", disassemblyBool);
QMap<QString, bool> engineBool;
engineBool.insert("ListAllPages", false);
engineBool.insert("ShowSuspectedCallStack", false);
defaultBools.insert("Engine", engineBool);
QMap<QString, bool> miscBool;
miscBool.insert("TransparentExceptionStepping", true);
miscBool.insert("CheckForAntiCheatDrivers", true);
defaultBools.insert("Misc", miscBool);
QMap<QString, bool> guiBool;
guiBool.insert("FpuRegistersLittleEndian", false);
guiBool.insert("SaveColumnOrder", true);
guiBool.insert("NoCloseDialog", false);
guiBool.insert("PidTidInHex", false);
guiBool.insert("SidebarWatchLabels", true);
guiBool.insert("LoadSaveTabOrder", true);
guiBool.insert("ShowGraphRva", false);
guiBool.insert("GraphZoomMode", true);
guiBool.insert("ShowExitConfirmation", false);
guiBool.insert("DisableAutoComplete", false);
guiBool.insert("CaseSensitiveAutoComplete", false);
guiBool.insert("AutoRepeatOnEnter", false);
guiBool.insert("AutoFollowInStack", true);
guiBool.insert("EnableQtHighDpiScaling", true);
guiBool.insert("Topmost", false);
//Named menu settings
insertMenuBuilderBools(&guiBool, "CPUDisassembly", 50); //CPUDisassembly
insertMenuBuilderBools(&guiBool, "CPUDump", 50); //CPUDump
insertMenuBuilderBools(&guiBool, "WatchView", 50); //Watch
insertMenuBuilderBools(&guiBool, "CallStackView", 50); //CallStackView
insertMenuBuilderBools(&guiBool, "ThreadView", 50); //Thread
insertMenuBuilderBools(&guiBool, "CPUStack", 50); //Stack
insertMenuBuilderBools(&guiBool, "SourceView", 50); //Source
insertMenuBuilderBools(&guiBool, "DisassemblerGraphView", 50); //Graph
insertMenuBuilderBools(&guiBool, "XrefBrowseDialog", 50); //XrefBrowseDialog
insertMenuBuilderBools(&guiBool, "StructWidget", 50); //StructWidget
insertMenuBuilderBools(&guiBool, "File", 50); //Main Menu : File
insertMenuBuilderBools(&guiBool, "Debug", 50); //Main Menu : Debug
insertMenuBuilderBools(&guiBool, "Option", 50); //Main Menu : Option
//"Favourites" menu cannot be customized for item hiding.
insertMenuBuilderBools(&guiBool, "Help", 50); //Main Menu : Help
insertMenuBuilderBools(&guiBool, "View", 50); //Main Menu : View
insertMenuBuilderBools(&guiBool, "TraceBrowser", 50); //TraceBrowser
defaultBools.insert("Gui", guiBool);
QMap<QString, duint> guiUint;
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "CPUDisassembly", 5);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "CPUStack", 3);
for(int i = 1; i <= 5; i++)
AbstractTableView::setupColumnConfigDefaultValue(guiUint, QString("CPUDump%1").arg(i), 4);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Watch1", 6);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "BreakpointsView", 7);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "MemoryMap", 8);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "CallStack", 7);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "SEH", 4);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Script", 3);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Thread", 14);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Handle", 5);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Window", 10);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "TcpConnection", 3);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Privilege", 2);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "LocalVarsView", 3);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Module", 5);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Symbol", 5);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "SourceView", 4);
AbstractTableView::setupColumnConfigDefaultValue(guiUint, "Trace", 7);
guiUint.insert("SIMDRegistersDisplayMode", 0);
guiUint.insert("EditFloatRegisterDefaultMode", 0);
defaultUints.insert("Gui", guiUint);
//uint settings
QMap<QString, duint> hexdumpUint;
hexdumpUint.insert("DefaultView", 0);
hexdumpUint.insert("CopyDataType", 0);
defaultUints.insert("HexDump", hexdumpUint);
QMap<QString, bool> hexdumpBool;
hexdumpBool.insert("KeepSize", false);
defaultBools.insert("HexDump", hexdumpBool);
QMap<QString, duint> disasmUint;
disasmUint.insert("MaxModuleSize", -1);
defaultUints.insert("Disassembler", disasmUint);
//font settings
QFont font("Lucida Console", 8, QFont::Normal, false);
defaultFonts.insert("AbstractTableView", font);
defaultFonts.insert("Disassembly", font);
defaultFonts.insert("HexDump", font);
defaultFonts.insert("Stack", font);
defaultFonts.insert("Registers", font);
defaultFonts.insert("HexEdit", font);
defaultFonts.insert("Application", QApplication::font());
defaultFonts.insert("Log", QFont("Courier New", 8, QFont::Normal, false));
// hotkeys settings
defaultShortcuts.insert("FileOpen", Shortcut({tr("File"), tr("Open")}, "F3", true));
defaultShortcuts.insert("FileAttach", Shortcut({tr("File"), tr("Attach")}, "Alt+A", true));
defaultShortcuts.insert("FileDetach", Shortcut({tr("File"), tr("Detach")}, "Ctrl+Alt+F2", true));
defaultShortcuts.insert("FileDbsave", Shortcut({tr("File"), tr("Save database")}, "", true));
defaultShortcuts.insert("FileDbrecovery", Shortcut({tr("File"), tr("Restore backup database")}, "", true));
defaultShortcuts.insert("FileDbload", Shortcut({tr("File"), tr("Reload database")}, "", true));
defaultShortcuts.insert("FileDbclear", Shortcut({tr("File"), tr("Clear database")}, "", true));
defaultShortcuts.insert("FileImportDatabase", Shortcut({tr("File"), tr("Import database")}, "", true));
defaultShortcuts.insert("FileExportDatabase", Shortcut({tr("File"), tr("Export database")}, "", true));
defaultShortcuts.insert("FileRestartAdmin", Shortcut({tr("File"), tr("Restart as Admin")}, "", true));
defaultShortcuts.insert("FileExit", Shortcut({tr("File"), tr("Exit")}, "Alt+X", true));
defaultShortcuts.insert("ViewCpu", Shortcut({tr("View"), tr("CPU")}, "Alt+C", true));
defaultShortcuts.insert("ViewLog", Shortcut({tr("View"), tr("Log")}, "Alt+L", true));
defaultShortcuts.insert("ViewBreakpoints", Shortcut({tr("View"), tr("Breakpoints")}, "Alt+B", true));
defaultShortcuts.insert("ViewMemoryMap", Shortcut({tr("View"), tr("Memory Map")}, "Alt+M", true));
defaultShortcuts.insert("ViewCallStack", Shortcut({tr("View"), tr("Call Stack")}, "Alt+K", true));
defaultShortcuts.insert("ViewNotes", Shortcut({tr("View"), tr("Notes")}, "Alt+N", true));
defaultShortcuts.insert("ViewSEHChain", Shortcut({tr("View"), tr("SEH")}, "", true));
defaultShortcuts.insert("ViewScript", Shortcut({tr("View"), tr("Script")}, "Alt+S", true));
defaultShortcuts.insert("ViewSymbolInfo", Shortcut({tr("View"), tr("Symbol Info")}, "Ctrl+Alt+S", true));
defaultShortcuts.insert("ViewModules", Shortcut({tr("View"), tr("Modules")}, "Alt+E", true));
defaultShortcuts.insert("ViewSource", Shortcut({tr("View"), tr("Source")}, "Ctrl+Shift+S", true));
defaultShortcuts.insert("ViewReferences", Shortcut({tr("View"), tr("References")}, "Alt+R", true));
defaultShortcuts.insert("ViewThreads", Shortcut({tr("View"), tr("Threads")}, "Alt+T", true));
defaultShortcuts.insert("ViewPatches", Shortcut({tr("View"), tr("Patches")}, "Ctrl+P", true));
defaultShortcuts.insert("ViewComments", Shortcut({tr("View"), tr("Comments")}, "Ctrl+Alt+C", true));
defaultShortcuts.insert("ViewLabels", Shortcut({tr("View"), tr("Labels")}, "Ctrl+Alt+L", true));
defaultShortcuts.insert("ViewBookmarks", Shortcut({tr("View"), tr("Bookmarks")}, "Ctrl+Alt+B", true));
defaultShortcuts.insert("ViewFunctions", Shortcut({tr("View"), tr("Functions")}, "Ctrl+Alt+F", true));
defaultShortcuts.insert("ViewVariables", Shortcut({tr("View"), tr("Variables")}, "", true));
defaultShortcuts.insert("ViewHandles", Shortcut({tr("View"), tr("Handles")}, "", true));
defaultShortcuts.insert("ViewGraph", Shortcut({tr("View"), tr("Graph")}, "Alt+G", true));
defaultShortcuts.insert("ViewPreviousTab", Shortcut({tr("View"), tr("Previous Tab")}, "Alt+Left"));
defaultShortcuts.insert("ViewNextTab", Shortcut({tr("View"), tr("Next Tab")}, "Alt+Right"));
defaultShortcuts.insert("ViewPreviousHistory", Shortcut({tr("View"), tr("Previous View")}, "Ctrl+Shift+Tab"));
defaultShortcuts.insert("ViewNextHistory", Shortcut({tr("View"), tr("Next View")}, "Ctrl+Tab"));
defaultShortcuts.insert("ViewHideTab", Shortcut({tr("View"), tr("Hide Tab")}, "Ctrl+W"));
defaultShortcuts.insert("DebugRun", Shortcut({tr("Debug"), tr("Run")}, "F9", true));
defaultShortcuts.insert("DebugeRun", Shortcut({tr("Debug"), tr("Run (pass exception)")}, "Shift+F9", true));
defaultShortcuts.insert("DebugseRun", Shortcut({tr("Debug"), tr("Run (swallow exception)")}, "Ctrl+Alt+Shift+F9", true));
defaultShortcuts.insert("DebugRunSelection", Shortcut({tr("Debug"), tr("Run until selection")}, "F4", true));
defaultShortcuts.insert("DebugRunExpression", Shortcut({tr("Debug"), tr("Run until expression")}, "Shift+F4", true));
defaultShortcuts.insert("DebugPause", Shortcut({tr("Debug"), tr("Pause")}, "F12", true));
defaultShortcuts.insert("DebugRestart", Shortcut({tr("Debug"), tr("Restart")}, "Ctrl+F2", true));
defaultShortcuts.insert("DebugClose", Shortcut({tr("Debug"), tr("Close")}, "Alt+F2", true));
defaultShortcuts.insert("DebugStepInto", Shortcut({tr("Debug"), tr("Step into")}, "F7", true));
defaultShortcuts.insert("DebugeStepInto", Shortcut({tr("Debug"), tr("Step into (pass exception)")}, "Shift+F7", true));
defaultShortcuts.insert("DebugseStepInto", Shortcut({tr("Debug"), tr("Step into (swallow exception)")}, "Ctrl+Alt+Shift+F7", true));
defaultShortcuts.insert("DebugStepIntoSource", Shortcut({tr("Debug"), tr("Step into (source)")}, "F11", true));
defaultShortcuts.insert("DebugStepOver", Shortcut({tr("Debug"), tr("Step over")}, "F8", true));
defaultShortcuts.insert("DebugeStepOver", Shortcut({tr("Debug"), tr("Step over (pass exception)")}, "Shift+F8", true));
defaultShortcuts.insert("DebugseStepOver", Shortcut({tr("Debug"), tr("Step over (swallow exception)")}, "Ctrl+Alt+Shift+F8", true));
defaultShortcuts.insert("DebugStepOverSource", Shortcut({tr("Debug"), tr("Step over (source)")}, "F10", true));
defaultShortcuts.insert("DebugRtr", Shortcut({tr("Debug"), tr("Execute till return")}, "Ctrl+F9", true));
defaultShortcuts.insert("DebugeRtr", Shortcut({tr("Debug"), tr("Execute till return (pass exception)")}, "Ctrl+Shift+F9", true));
defaultShortcuts.insert("DebugRtu", Shortcut({tr("Debug"), tr("Run to user code")}, "Alt+F9", true));
defaultShortcuts.insert("DebugSkipNextInstruction", Shortcut({tr("Debug"), tr("Skip next instruction")}, "", true));
defaultShortcuts.insert("DebugCommand", Shortcut({tr("Debug"), tr("Command")}, "Ctrl+Return", true));
defaultShortcuts.insert("DebugTraceIntoConditional", Shortcut({tr("Debug"), tr("Trace into...")}, "Ctrl+Alt+F7", true));
defaultShortcuts.insert("DebugTraceOverConditional", Shortcut({tr("Debug"), tr("Trace over...")}, "Ctrl+Alt+F8", true));
defaultShortcuts.insert("DebugEnableTraceRecordBit", Shortcut({tr("Debug"), tr("Trace coverage"), tr("Bit")}, "", true));
defaultShortcuts.insert("DebugTraceRecordNone", Shortcut({tr("Debug"), tr("Trace coverage"), tr("None")}, "", true));
defaultShortcuts.insert("DebugInstrUndo", Shortcut({tr("Debug"), tr("Undo instruction")}, "Alt+U", true));
defaultShortcuts.insert("DebugAnimateInto", Shortcut({tr("Debug"), tr("Animate into")}, "Ctrl+F7", true));
defaultShortcuts.insert("DebugAnimateOver", Shortcut({tr("Debug"), tr("Animate over")}, "Ctrl+F8", true));
defaultShortcuts.insert("DebugAnimateCommand", Shortcut({tr("Debug"), tr("Animate command")}, "", true));
defaultShortcuts.insert("DebugTraceIntoIntoTracerecord", Shortcut({tr("Debug"), tr("Step into until reaching uncovered code")}, "", true));
defaultShortcuts.insert("DebugTraceOverIntoTracerecord", Shortcut({tr("Debug"), tr("Step over until reaching uncovered code")}, "", true));
defaultShortcuts.insert("DebugTraceIntoBeyondTracerecord", Shortcut({tr("Debug"), tr("Step into until reaching covered code")}, "", true));
defaultShortcuts.insert("DebugTraceOverBeyondTracerecord", Shortcut({tr("Debug"), tr("Step over until reaching covered code")}, "", true));
defaultShortcuts.insert("PluginsScylla", Shortcut({tr("Plugins"), tr("Scylla")}, "Ctrl+I", true));
defaultShortcuts.insert("FavouritesManage", Shortcut({tr("Favourites"), tr("Manage Favourite Tools")}, "", true));
defaultShortcuts.insert("OptionsPreferences", Shortcut({tr("Options"), tr("Preferences")}, "", true));
defaultShortcuts.insert("OptionsAppearance", Shortcut({tr("Options"), tr("Appearance")}, "", true));
defaultShortcuts.insert("OptionsShortcuts", Shortcut({tr("Options"), tr("Hotkeys")}, "", true));
defaultShortcuts.insert("OptionsTopmost", Shortcut({tr("Options"), tr("Topmost")}, "Ctrl+F5", true));
defaultShortcuts.insert("OptionsReloadStylesheet", Shortcut({tr("Options"), tr("Reload style.css")}, "", true));
defaultShortcuts.insert("HelpAbout", Shortcut({tr("Help"), tr("About")}, "", true));
defaultShortcuts.insert("HelpBlog", Shortcut({tr("Help"), tr("Blog")}, "", true));
defaultShortcuts.insert("HelpDonate", Shortcut({tr("Help"), tr("Donate")}, "", true));
defaultShortcuts.insert("HelpCalculator", Shortcut({tr("Help"), tr("Calculator")}, "?"));
defaultShortcuts.insert("HelpReportBug", Shortcut({tr("Help"), tr("Report Bug")}, "", true));
defaultShortcuts.insert("HelpManual", Shortcut({tr("Help"), tr("Manual")}, "F1", true));
defaultShortcuts.insert("HelpCrashDump", Shortcut({tr("Help"), tr("Generate Crash Dump")}, "", true));
defaultShortcuts.insert("ActionFindStrings", Shortcut({tr("Actions"), tr("Find Strings")}, "", true));
defaultShortcuts.insert("ActionFindStringsModule", Shortcut({tr("Actions"), tr("Find Strings in Current Module")}, "Shift+D", true));
defaultShortcuts.insert("ActionFindIntermodularCalls", Shortcut({tr("Actions"), tr("Find Intermodular Calls")}, "", true));
defaultShortcuts.insert("ActionToggleBreakpoint", Shortcut({tr("Actions"), tr("Toggle Breakpoint")}, "F2"));
defaultShortcuts.insert("ActionEditBreakpoint", Shortcut({tr("Actions"), tr("Set Conditional Breakpoint")}, "Shift+F2"));
defaultShortcuts.insert("ActionToggleBookmark", Shortcut({tr("Actions"), tr("Toggle Bookmark")}, "Ctrl+D"));
defaultShortcuts.insert("ActionDeleteBreakpoint", Shortcut({tr("Actions"), tr("Delete Breakpoint")}, "Delete"));
defaultShortcuts.insert("ActionEnableDisableBreakpoint", Shortcut({tr("Actions"), tr("Enable/Disable Breakpoint")}, "Space"));
defaultShortcuts.insert("ActionResetHitCountBreakpoint", Shortcut({tr("Actions"), tr("Reset breakpoint hit count")}));
defaultShortcuts.insert("ActionEnableAllBreakpoints", Shortcut({tr("Actions"), tr("Enable all breakpoints")}));
defaultShortcuts.insert("ActionDisableAllBreakpoints", Shortcut({tr("Actions"), tr("Disable all breakpoints")}));
defaultShortcuts.insert("ActionRemoveAllBreakpoints", Shortcut({tr("Actions"), tr("Remove all breakpoints")}));
defaultShortcuts.insert("ActionBinaryEdit", Shortcut({tr("Actions"), tr("Binary Edit")}, "Ctrl+E"));
defaultShortcuts.insert("ActionBinaryFill", Shortcut({tr("Actions"), tr("Binary Fill")}, "F"));
defaultShortcuts.insert("ActionBinaryFillNops", Shortcut({tr("Actions"), tr("Binary Fill NOPs")}, "Ctrl+9"));
defaultShortcuts.insert("ActionBinaryCopy", Shortcut({tr("Actions"), tr("Binary Copy")}, "Shift+C"));
defaultShortcuts.insert("ActionBinaryPaste", Shortcut({tr("Actions"), tr("Binary Paste")}, "Shift+V"));
defaultShortcuts.insert("ActionBinaryPasteIgnoreSize", Shortcut({tr("Actions"), tr("Binary Paste (Ignore Size)")}, "Ctrl+Shift+V"));
defaultShortcuts.insert("ActionBinarySave", Shortcut({tr("Actions"), tr("Binary Save")}));
defaultShortcuts.insert("ActionUndoSelection", Shortcut({tr("Actions"), tr("Undo Selection")}, "Ctrl+Backspace"));
defaultShortcuts.insert("ActionSetLabel", Shortcut({tr("Actions"), tr("Set Label")}, ":"));
defaultShortcuts.insert("ActionSetLabelOperand", Shortcut({tr("Actions"), tr("Set Label for the Operand")}, "Alt+;"));
defaultShortcuts.insert("ActionSetComment", Shortcut({tr("Actions"), tr("Set Comment")}, ";"));
defaultShortcuts.insert("ActionToggleFunction", Shortcut({tr("Actions"), tr("Toggle Function")}, "Shift+F"));
defaultShortcuts.insert("ActionAddLoop", Shortcut({tr("Actions"), tr("Add Loop")}, "Shift+L"));
defaultShortcuts.insert("ActionDeleteLoop", Shortcut({tr("Actions"), tr("Delete Loop")}, "Ctrl+Shift+L"));
defaultShortcuts.insert("ActionToggleArgument", Shortcut({tr("Actions"), tr("Toggle Argument")}, "Shift+A"));
defaultShortcuts.insert("ActionAssemble", Shortcut({tr("Actions"), tr("Assemble")}, "Space"));
defaultShortcuts.insert("ActionSetNewOriginHere", Shortcut({tr("Actions"), tr("Set %1 Here").arg(ArchValue("EIP", "RIP"))}, "Ctrl+*"));
defaultShortcuts.insert("ActionGotoOrigin", Shortcut({tr("Actions"), tr("Goto Origin")}, "*"));
defaultShortcuts.insert("ActionGotoCBP", Shortcut({tr("Actions"), tr("Goto EBP/RBP")}));
defaultShortcuts.insert("ActionGotoPrevious", Shortcut({tr("Actions"), tr("Goto Previous")}, "-"));
defaultShortcuts.insert("ActionGotoNext", Shortcut({tr("Actions"), tr("Goto Next")}, "+"));
defaultShortcuts.insert("ActionGotoExpression", Shortcut({tr("Actions"), tr("Goto Expression")}, "Ctrl+G"));
defaultShortcuts.insert("ActionGotoStart", Shortcut({tr("Actions"), tr("Goto Start of Page")}, "Home"));
defaultShortcuts.insert("ActionGotoEnd", Shortcut({tr("Actions"), tr("Goto End of Page")}, "End"));
defaultShortcuts.insert("ActionGotoFunctionStart", Shortcut({tr("Actions"), tr("Goto Start of Function")}, "Ctrl+Home"));
defaultShortcuts.insert("ActionGotoFunctionEnd", Shortcut({tr("Actions"), tr("Goto End of Function")}, "Ctrl+End"));
defaultShortcuts.insert("ActionGotoFileOffset", Shortcut({tr("Actions"), tr("Goto File Offset")}, "Ctrl+Shift+G"));
defaultShortcuts.insert("ActionFindReferencesToSelectedAddress", Shortcut({tr("Actions"), tr("Find References to Selected Address")}, "Ctrl+R"));
defaultShortcuts.insert("ActionFindPattern", Shortcut({tr("Actions"), tr("Find Pattern")}, "Ctrl+B"));
defaultShortcuts.insert("ActionFindPatternInModule", Shortcut({tr("Actions"), tr("Find Pattern in Current Module")}, "Ctrl+Shift+B"));
defaultShortcuts.insert("ActionFindNamesInModule", Shortcut({tr("Actions"), tr("Find Names in Current Module")}, "Ctrl+N"));
defaultShortcuts.insert("ActionFindReferences", Shortcut({tr("Actions"), tr("Find References")}, "Ctrl+R"));
defaultShortcuts.insert("ActionXrefs", Shortcut({tr("Actions"), tr("xrefs...")}, "X"));
defaultShortcuts.insert("ActionAnalyzeSingleFunction", Shortcut({tr("Actions"), tr("Analyze Single Function")}, "A"));
defaultShortcuts.insert("ActionAnalyzeModule", Shortcut({tr("Actions"), tr("Analyze Module")}, "Ctrl+A"));
defaultShortcuts.insert("ActionHelpOnMnemonic", Shortcut({tr("Actions"), tr("Help on Mnemonic")}, "Ctrl+F1"));
defaultShortcuts.insert("ActionToggleMnemonicBrief", Shortcut({tr("Actions"), tr("Toggle Mnemonic Brief")}, "Ctrl+Shift+F1"));
defaultShortcuts.insert("ActionHighlightingMode", Shortcut({tr("Actions"), tr("Highlighting Mode")}, "H"));
defaultShortcuts.insert("ActionToggleDestinationPreview", Shortcut({tr("Actions"), tr("Enable/Disable Branch Destination Preview")}, "P"));
defaultShortcuts.insert("ActionFind", Shortcut({tr("Actions"), tr("Find")}, "Ctrl+F"));
defaultShortcuts.insert("ActionFindInModule", Shortcut({tr("Actions"), tr("Find in Current Module")}, "Ctrl+Shift+F"));
defaultShortcuts.insert("ActionToggleLogging", Shortcut({tr("Actions"), tr("Enable/Disable Logging")}, ""));
defaultShortcuts.insert("ActionAllocateMemory", Shortcut({tr("Actions"), tr("Allocate Memory")}, ""));
defaultShortcuts.insert("ActionFreeMemory", Shortcut({tr("Actions"), tr("Free Memory")}, ""));
defaultShortcuts.insert("ActionSync", Shortcut({tr("Actions"), tr("Sync")}, "S"));
defaultShortcuts.insert("ActionCopyAllRegisters", Shortcut({tr("Actions"), tr("Copy All Registers")}, ""));
defaultShortcuts.insert("ActionMarkAsUser", Shortcut({tr("Actions"), tr("Mark As User Module")}, ""));
defaultShortcuts.insert("ActionMarkAsSystem", Shortcut({tr("Actions"), tr("Mark As System Module")}, ""));
defaultShortcuts.insert("ActionMarkAsParty", Shortcut({tr("Actions"), tr("Mark As Party")}, ""));
defaultShortcuts.insert("ActionSetHwBpE", Shortcut({tr("Actions"), tr("Set Hardware Breakpoint (Execute)")}, ""));
defaultShortcuts.insert("ActionRemoveHwBp", Shortcut({tr("Actions"), tr("Remove Hardware Breakpoint")}, ""));
defaultShortcuts.insert("ActionRemoveTypeAnalysisFromModule", Shortcut({tr("Actions"), tr("Remove Type Analysis From Module")}, "Ctrl+Shift+U"));
defaultShortcuts.insert("ActionRemoveTypeAnalysisFromSelection", Shortcut({tr("Actions"), tr("Remove Type Analysis From Selection")}, "U"));
defaultShortcuts.insert("ActionTreatSelectionAsCode", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Code")}, "C"));
defaultShortcuts.insert("ActionTreatSelectionAsByte", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Byte")}, "B"));
defaultShortcuts.insert("ActionTreatSelectionAsWord", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Word")}, "W"));
defaultShortcuts.insert("ActionTreatSelectionAsDword", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Dword")}, "D"));
defaultShortcuts.insert("ActionTreatSelectionAsFword", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Fword")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsQword", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Qword")}, "Q"));
defaultShortcuts.insert("ActionTreatSelectionAsTbyte", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Tbyte")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsOword", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Oword")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsFloat", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Float")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsDouble", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("Double")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsLongDouble", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("LongDouble")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsASCII", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("ASCII")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsUNICODE", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("UNICODE")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsMMWord", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("MMWord")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsXMMWord", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("XMMWord")}, ""));
defaultShortcuts.insert("ActionTreatSelectionAsYMMWord", Shortcut({tr("Actions"), tr("Treat Selection As"), tr("YMMWord")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsCode", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Code")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsByte", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Byte")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsWord", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Word")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsDword", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Dword")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsFword", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Fword")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsQword", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Qword")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsTbyte", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Tbyte")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsOword", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Oword")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsFloat", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Float")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsDouble", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("Double")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsLongDouble", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("LongDouble")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsASCII", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("ASCII")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsUNICODE", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("UNICODE")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsMMWord", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("MMWord")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsXMMWord", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("XMMWord")}, ""));
defaultShortcuts.insert("ActionTreatSelectionHeadAsYMMWord", Shortcut({tr("Actions"), tr("Treat Selection Head As"), tr("YMMWord")}, ""));
defaultShortcuts.insert("ActionToggleRegisterValue", Shortcut({tr("Actions"), tr("Toggle Register Value")}, "Space"));
defaultShortcuts.insert("ActionClear", Shortcut({tr("Actions"), tr("Clear")}, "Ctrl+L"));
defaultShortcuts.insert("ActionCopy", Shortcut({tr("Actions"), tr("Copy")}, "Ctrl+C"));
defaultShortcuts.insert("ActionCopyAddress", Shortcut({tr("Actions"), tr("Copy Address")}, "Alt+INS"));
defaultShortcuts.insert("ActionCopyRva", Shortcut({tr("Actions"), tr("Copy RVA")}, ""));
defaultShortcuts.insert("ActionCopySymbol", Shortcut({tr("Actions"), tr("Copy Symbol")}, "Ctrl+S"));
defaultShortcuts.insert("ActionCopyLine", Shortcut({tr("Actions"), tr("Copy Line")}, ""));
defaultShortcuts.insert("ActionLoadScript", Shortcut({tr("Actions"), tr("Load Script")}, "Ctrl+O"));
defaultShortcuts.insert("ActionReloadScript", Shortcut({tr("Actions"), tr("Reload Script")}, "Ctrl+R"));
defaultShortcuts.insert("ActionUnloadScript", Shortcut({tr("Actions"), tr("Unload Script")}, "Ctrl+U"));
defaultShortcuts.insert("ActionEditScript", Shortcut({tr("Actions"), tr("Edit Script")}, ""));
defaultShortcuts.insert("ActionRunScript", Shortcut({tr("Actions"), tr("Run Script")}, "Space"));
defaultShortcuts.insert("ActionToggleBreakpointScript", Shortcut({tr("Actions"), tr("Toggle Script Breakpoint")}, "F2"));
defaultShortcuts.insert("ActionRunToCursorScript", Shortcut({tr("Actions"), tr("Run Script to Cursor")}, "Shift+F4"));
defaultShortcuts.insert("ActionStepScript", Shortcut({tr("Actions"), tr("Step Script")}, "Tab"));
defaultShortcuts.insert("ActionAbortScript", Shortcut({tr("Actions"), tr("Abort Script")}, "Esc"));
defaultShortcuts.insert("ActionExecuteCommandScript", Shortcut({tr("Actions"), tr("Execute Script Command")}, "X"));
defaultShortcuts.insert("ActionRefresh", Shortcut({tr("Actions"), tr("Refresh")}, "F5"));
defaultShortcuts.insert("ActionGraph", Shortcut({tr("Actions"), tr("Graph")}, "G"));
defaultShortcuts.insert("ActionGraphZoomToCursor", Shortcut({tr("Actions"), tr("Graph"), tr("Zoom to cursor")}, "Z"));
defaultShortcuts.insert("ActionGraphFitToWindow", Shortcut({tr("Actions"), tr("Graph"), tr("Fit To Window")}, "Shift+Z"));
defaultShortcuts.insert("ActionGraphFollowDisassembler", Shortcut({tr("Actions"), tr("Graph"), tr("Follow in disassembler")}, "Shift+Return"));
defaultShortcuts.insert("ActionGraphSaveImage", Shortcut({tr("Actions"), tr("Graph"), tr("Save as image")}, "I"));
defaultShortcuts.insert("ActionGraphToggleOverview", Shortcut({tr("Actions"), tr("Graph"), tr("Toggle overview")}, "O"));
defaultShortcuts.insert("ActionGraphToggleSummary", Shortcut({tr("Actions"), tr("Graph"), tr("Toggle summary")}, "U"));
defaultShortcuts.insert("ActionIncrementx87Stack", Shortcut({tr("Actions"), tr("Increment x87 Stack")}));
defaultShortcuts.insert("ActionDecrementx87Stack", Shortcut({tr("Actions"), tr("Decrement x87 Stack")}));
defaultShortcuts.insert("ActionRedirectLog", Shortcut({tr("Actions"), tr("Redirect Log")}));
defaultShortcuts.insert("ActionBrowseInExplorer", Shortcut({tr("Actions"), tr("Browse in Explorer")}));
defaultShortcuts.insert("ActionDownloadSymbol", Shortcut({tr("Actions"), tr("Download Symbols for This Module")}));
defaultShortcuts.insert("ActionDownloadAllSymbol", Shortcut({tr("Actions"), tr("Download Symbols for All Modules")}));
defaultShortcuts.insert("ActionCreateNewThreadHere", Shortcut({tr("Actions"), tr("Create New Thread Here")}));
defaultShortcuts.insert("ActionOpenSourceFile", Shortcut({tr("Actions"), tr("Open Source File")}));
defaultShortcuts.insert("ActionFollowMemMap", Shortcut({tr("Actions"), tr("Follow in Memory Map")}));
defaultShortcuts.insert("ActionFollowStack", Shortcut({tr("Actions"), tr("Follow in Stack")}));
defaultShortcuts.insert("ActionFollowDisasm", Shortcut({tr("Actions"), tr("Follow in Disassembler")}));
defaultShortcuts.insert("ActionFollowDwordQwordDisasm", Shortcut({tr("Actions"), tr("Follow DWORD/QWORD in Disassembler")}));
defaultShortcuts.insert("ActionFollowDwordQwordDump", Shortcut({tr("Actions"), tr("Follow DWORD/QWORD in Dump")}));
defaultShortcuts.insert("ActionFreezeStack", Shortcut({tr("Actions"), tr("Freeze the stack")}));
defaultShortcuts.insert("ActionGotoBaseOfStackFrame", Shortcut({tr("Actions"), tr("Go to Base of Stack Frame")}));
defaultShortcuts.insert("ActionGotoPrevStackFrame", Shortcut({tr("Actions"), tr("Go to Previous Stack Frame")}));
defaultShortcuts.insert("ActionGotoNextStackFrame", Shortcut({tr("Actions"), tr("Go to Next Stack Frame")}));
defaultShortcuts.insert("ActionGotoPreviousReference", Shortcut({tr("Actions"), tr("Go to Previous Reference")}, "Ctrl+K"));
defaultShortcuts.insert("ActionGotoNextReference", Shortcut({tr("Actions"), tr("Go to Next Reference")}, "Ctrl+L"));
defaultShortcuts.insert("ActionModifyValue", Shortcut({tr("Actions"), tr("Modify value")}, "Space"));
defaultShortcuts.insert("ActionWatchDwordQword", Shortcut({tr("Actions"), tr("Watch DWORD/QWORD")}));
defaultShortcuts.insert("ActionCopyFileOffset", Shortcut({tr("Actions"), tr("Copy File Offset")}));
defaultShortcuts.insert("ActionToggleRunTrace", Shortcut({tr("Actions"), tr("Start/Stop trace recording")}));
defaultShortcuts.insert("ActionCopyCroppedTable", Shortcut({tr("Actions"), tr("Copy -> Cropped Table")}));
defaultShortcuts.insert("ActionCopyTable", Shortcut({tr("Actions"), tr("Copy -> Table")}));
defaultShortcuts.insert("ActionCopyLineToLog", Shortcut({tr("Actions"), tr("Copy -> Line, To Log")}));
defaultShortcuts.insert("ActionCopyCroppedTableToLog", Shortcut({tr("Actions"), tr("Copy -> Cropped Table, To Log")}));
defaultShortcuts.insert("ActionCopyTableToLog", Shortcut({tr("Actions"), tr("Copy -> Table, To Log")}));
defaultShortcuts.insert("ActionExport", Shortcut({tr("Actions"), tr("Copy -> Export Table")}));
Shortcuts = defaultShortcuts;
load();
//because we changed the default this needs special handling for old configurations
if(Shortcuts["ViewPreviousTab"].Hotkey.toString() == Shortcuts["ViewPreviousHistory"].Hotkey.toString())
{
Shortcuts["ViewPreviousTab"].Hotkey = defaultShortcuts["ViewPreviousTab"].Hotkey;
save();
}
if(Shortcuts["ViewNextTab"].Hotkey.toString() == Shortcuts["ViewNextHistory"].Hotkey.toString())
{
Shortcuts["ViewNextTab"].Hotkey = defaultShortcuts["ViewNextTab"].Hotkey;
save();
}
}
Configuration* Configuration::instance()
{
return mPtr;
}
void Configuration::load()
{
readColors();
readBools();
readUints();
readFonts();
readShortcuts();
}
void Configuration::save()
{
writeColors();
writeBools();
writeUints();
writeFonts();
writeShortcuts();
}
void Configuration::readColors()
{
Colors = defaultColors;
//read config
for(auto it = Colors.begin(); it != Colors.end(); ++it)
it.value() = colorFromConfig(it.key());
}
void Configuration::writeColors()
{
//write config
for(auto it = Colors.begin(); it != Colors.end(); ++it)
colorToConfig(it.key(), it.value());
emit colorsUpdated();
}
void Configuration::readBools()
{
Bools = defaultBools;
//read config
for(auto itMap = Bools.begin(); itMap != Bools.end(); ++itMap)
{
const QString & category = itMap.key();
for(auto it = itMap.value().begin(); it != itMap.value().end(); it++)
{
it.value() = boolFromConfig(category, it.key());
}
}
}
void Configuration::writeBools()
{
//write config
for(auto itMap = Bools.cbegin(); itMap != Bools.cend(); ++itMap)
{
const QString & category = itMap.key();
for(auto it = itMap.value().cbegin(); it != itMap.value().cend(); it++)
{
boolToConfig(category, it.key(), it.value());
}
}
}
void Configuration::readUints()
{
Uints = defaultUints;
//read config
for(auto itMap = Uints.begin(); itMap != Uints.end(); ++itMap)
{
const QString & category = itMap.key();
for(auto it = itMap.value().begin(); it != itMap.value().end(); it++)
{
it.value() = uintFromConfig(category, it.key());
}
}
}
void Configuration::writeUints()
{
//write config
for(auto itMap = Uints.cbegin(); itMap != Uints.cend(); ++itMap)
{
const QString & category = itMap.key();
for(auto it = itMap.value().cbegin(); it != itMap.value().cend(); it++)
{
uintToConfig(category, it.key(), it.value());
}
}
}
void Configuration::readFonts()
{
Fonts = defaultFonts;
//read config
for(auto it = Fonts.begin(); it != Fonts.end(); ++it)
{
const QString & id = it.key();
QFont font = fontFromConfig(id);
QFontInfo fontInfo(font);
if(id == "Application" || fontInfo.fixedPitch())
it.value() = font;
}
}
void Configuration::writeFonts()
{
//write config
for(auto it = Fonts.cbegin(); it != Fonts.cend(); ++it)
fontToConfig(it.key(), it.value());
emit fontsUpdated();
}
void Configuration::readShortcuts()
{
Shortcuts = defaultShortcuts;
QMap<QString, Shortcut>::const_iterator it = Shortcuts.begin();
while(it != Shortcuts.end())
{
const QString & id = it.key();
QString key = shortcutFromConfig(id);
if(key != "")
{
if(key == "NOT_SET")
Shortcuts[it.key()].Hotkey = QKeySequence();
else
{
QKeySequence KeySequence(key);
Shortcuts[it.key()].Hotkey = KeySequence;
}
}
it++;
}
emit shortcutsUpdated();
}
void Configuration::writeShortcuts()
{
QMap<QString, Shortcut>::const_iterator it = Shortcuts.begin();
while(it != Shortcuts.end())
{
shortcutToConfig(it.key(), it.value().Hotkey);
it++;
}
emit shortcutsUpdated();
}
const QColor Configuration::getColor(const QString & id) const
{
if(Colors.contains(id))
return Colors.constFind(id).value();
if(noMoreMsgbox)
return Qt::black;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return Qt::black;
}
const bool Configuration::getBool(const QString & category, const QString & id) const
{
if(Bools.contains(category))
{
if(Bools[category].contains(id))
return Bools[category][id];
if(noMoreMsgbox)
return false;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category + ":" + id, QMessageBox::Retry | QMessageBox::Cancel); /* insertMenuBuilderBools */
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return false;
}
if(noMoreMsgbox)
return false;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return false;
}
void Configuration::setBool(const QString & category, const QString & id, const bool b)
{
if(Bools.contains(category))
{
if(Bools[category].contains(id))
{
Bools[category][id] = b;
return;
}
if(noMoreMsgbox)
return;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category + ":" + id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return;
}
if(noMoreMsgbox)
return;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
}
const duint Configuration::getUint(const QString & category, const QString & id) const
{
if(Uints.contains(category))
{
if(Uints[category].contains(id))
return Uints[category][id];
if(noMoreMsgbox)
return 0;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category + ":" + id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return 0;
}
if(noMoreMsgbox)
return 0;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return 0;
}
void Configuration::setUint(const QString & category, const QString & id, const duint i)
{
if(Uints.contains(category))
{
if(Uints[category].contains(id))
{
Uints[category][id] = i;
return;
}
if(noMoreMsgbox)
return;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category + ":" + id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return;
}
if(noMoreMsgbox)
return;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), category, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
}
const QFont Configuration::getFont(const QString & id) const
{
if(Fonts.contains(id))
return Fonts.constFind(id).value();
QFont ret("Lucida Console", 8, QFont::Normal, false);
ret.setFixedPitch(true);
ret.setStyleHint(QFont::Monospace);
if(noMoreMsgbox)
return ret;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
return ret;
}
const Configuration::Shortcut Configuration::getShortcut(const QString & key_id) const
{
if(Shortcuts.contains(key_id))
return Shortcuts.constFind(key_id).value();
if(!noMoreMsgbox)
{
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), key_id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
}
return Shortcut();
}
void Configuration::setShortcut(const QString & key_id, const QKeySequence key_sequence)
{
if(Shortcuts.contains(key_id))
{
Shortcuts[key_id].Hotkey = key_sequence;
return;
}
if(noMoreMsgbox)
return;
QMessageBox msg(QMessageBox::Warning, tr("NOT FOUND IN CONFIG!"), key_id, QMessageBox::Retry | QMessageBox::Cancel);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Cancel)
noMoreMsgbox = true;
}
void Configuration::setPluginShortcut(const QString & key_id, QString description, QString defaultShortcut, bool global)
{
defaultShortcuts[key_id] = Shortcut(description, defaultShortcut, global);
readShortcuts();
}
QColor Configuration::colorFromConfig(const QString & id)
{
char setting[MAX_SETTING_SIZE] = "";
if(!BridgeSettingGet("Colors", id.toUtf8().constData(), setting))
{
if(defaultColors.contains(id))
{
QColor ret = defaultColors.find(id).value();
colorToConfig(id, ret);
return ret;
}
return Qt::black; //black is default
}
if(QString(setting).toUpper() == "#XXXXXX") //support custom transparent color name
return Qt::transparent;
QColor color(setting);
if(!color.isValid())
{
if(defaultColors.contains(id))
{
QColor ret = defaultColors.find(id).value();
colorToConfig(id, ret);
return ret;
}
return Qt::black; //black is default
}
return color;
}
bool Configuration::colorToConfig(const QString & id, const QColor color)
{
QString colorName = color.name().toUpper();
if(!color.alpha())
colorName = "#XXXXXX";
return BridgeSettingSet("Colors", id.toUtf8().constData(), colorName.toUtf8().constData());
}
bool Configuration::boolFromConfig(const QString & category, const QString & id)
{
duint setting;
if(!BridgeSettingGetUint(category.toUtf8().constData(), id.toUtf8().constData(), &setting))
{
if(defaultBools.contains(category) && defaultBools[category].contains(id))
{
bool ret = defaultBools[category][id];
boolToConfig(category, id, ret);
return ret;
}
return false; //DAFUG
}
return (setting != 0);
}
bool Configuration::boolToConfig(const QString & category, const QString & id, const bool bBool)
{
return BridgeSettingSetUint(category.toUtf8().constData(), id.toUtf8().constData(), bBool);
}
duint Configuration::uintFromConfig(const QString & category, const QString & id)
{
duint setting;
if(!BridgeSettingGetUint(category.toUtf8().constData(), id.toUtf8().constData(), &setting))
{
if(defaultUints.contains(category) && defaultUints[category].contains(id))
{
setting = defaultUints[category][id];
uintToConfig(category, id, setting);
return setting;
}
return 0; //DAFUG
}
return setting;
}
bool Configuration::uintToConfig(const QString & category, const QString & id, duint i)
{
return BridgeSettingSetUint(category.toUtf8().constData(), id.toUtf8().constData(), i);
}
QFont Configuration::fontFromConfig(const QString & id)
{
char setting[MAX_SETTING_SIZE] = "";
if(!BridgeSettingGet("Fonts", id.toUtf8().constData(), setting))
{
if(defaultFonts.contains(id))
{
QFont ret = defaultFonts.find(id).value();
fontToConfig(id, ret);
return ret;
}
if(id == "Application")
return QApplication::font();
QFont ret("Lucida Console", 8, QFont::Normal, false);
ret.setFixedPitch(true);
ret.setStyleHint(QFont::Monospace);
return ret;
}
QFont font;
if(!font.fromString(setting))
{
if(defaultFonts.contains(id))
{
QFont ret = defaultFonts.find(id).value();
fontToConfig(id, ret);
return ret;
}
if(id == "Application")
return QApplication::font();
QFont ret("Lucida Console", 8, QFont::Normal, false);
ret.setFixedPitch(true);
ret.setStyleHint(QFont::Monospace);
return ret;
}
return font;
}
bool Configuration::fontToConfig(const QString & id, const QFont font)
{
return BridgeSettingSet("Fonts", id.toUtf8().constData(), font.toString().toUtf8().constData());
}
QString Configuration::shortcutFromConfig(const QString & id)
{
QString _id = QString("%1").arg(id);
char setting[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("Shortcuts", _id.toUtf8().constData(), setting))
{
return QString(setting);
}
return QString();
}
bool Configuration::shortcutToConfig(const QString & id, const QKeySequence shortcut)
{
QString _id = QString("%1").arg(id);
QString _key = "";
if(!shortcut.isEmpty())
_key = shortcut.toString(QKeySequence::NativeText);
else
_key = "NOT_SET";
return BridgeSettingSet("Shortcuts", _id.toUtf8().constData(), _key.toUtf8().constData());
}
void Configuration::registerMenuBuilder(MenuBuilder* menu, size_t count)
{
QString id = menu->getId();
for(const auto & i : NamedMenuBuilders)
if(i.type == 0 && i.builder->getId() == id)
return; //already exists
NamedMenuBuilders.append(MenuMap(menu, count));
}
void Configuration::registerMainMenuStringList(QList<QAction*>* menu)
{
NamedMenuBuilders.append(MenuMap(menu, menu->size() - 1));
}
void Configuration::zoomFont(const QString & fontName, QWheelEvent* event)
{
QPoint numDegrees = event->angleDelta() / 8;
int ticks = numDegrees.y() / 15;
QFont myFont = Fonts[fontName];
char fontSizes[] = {6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 0}; // The list of font sizes in ApperanceDialog
char* currentFontSize = strchr(fontSizes, myFont.pointSize() & 127);
if(currentFontSize)
{
currentFontSize += ticks;
if(currentFontSize > fontSizes + 11)
currentFontSize = fontSizes + 11;
else if(currentFontSize < fontSizes)
currentFontSize = fontSizes;
myFont.setPointSize(*currentFontSize);
Fonts[fontName] = myFont;
writeFonts();
GuiUpdateAllViews();
}
}
static bool IsPointVisible(QPoint pos)
{
for(const auto & i : QGuiApplication::screens())
{
QRect rt = i->geometry();
if(rt.left() <= pos.x() && rt.right() >= pos.x() && rt.top() <= pos.y() && rt.bottom() >= pos.y())
return true;
}
return false;
}
/**
* @brief Configuration::setupWindowPos Loads the position/size of a dialog.
* @param window this
*/
void Configuration::loadWindowGeometry(QWidget* window)
{
QString name = window->metaObject()->className();
char setting[MAX_SETTING_SIZE] = "";
if(!BridgeSettingGet("Gui", (name + "Geometry").toUtf8().constData(), setting))
return;
auto oldPos = window->pos();
window->restoreGeometry(QByteArray::fromBase64(QByteArray(setting)));
if(!IsPointVisible(window->pos()))
window->move(oldPos);
}
/**
* @brief Configuration::saveWindowPos Saves the position/size of a dialog.
* @param window this
*/
void Configuration::saveWindowGeometry(QWidget* window)
{
QString name = window->metaObject()->className();
BridgeSettingSet("Gui", (name + "Geometry").toUtf8().constData(), window->saveGeometry().toBase64().data());
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/Configuration.h | #pragma once
#include <QObject>
#include <QKeySequence>
#include <QMap>
#include <QColor>
#include <QFont>
#include "Imports.h"
// TODO: declare AppearanceDialog and SettingsDialog entries here, so that you only have to do it in once place
#define Config() (Configuration::instance())
#define ConfigColor(x) (Config()->getColor(x))
#define ConfigBool(x,y) (Config()->getBool(x,y))
#define ConfigUint(x,y) (Config()->getUint(x,y))
#define ConfigFont(x) (Config()->getFont(x))
#define ConfigShortcut(x) (Config()->getShortcut(x).Hotkey)
#define ConfigHScrollBarStyle() "QScrollBar:horizontal{border:1px solid grey;background:#f1f1f1;height:10px}QScrollBar::handle:horizontal{background:#aaaaaa;min-width:20px;margin:1px}QScrollBar::add-line:horizontal,QScrollBar::sub-line:horizontal{width:0;height:0}"
#define ConfigVScrollBarStyle() "QScrollBar:vertical{border:1px solid grey;background:#f1f1f1;width:10px}QScrollBar::handle:vertical{background:#aaaaaa;min-height:20px;margin:1px}QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{width:0;height:0}"
class MenuBuilder;
class QAction;
class QWheelEvent;
class Configuration : public QObject
{
Q_OBJECT
public:
//Structures
struct Shortcut
{
QString Name;
QKeySequence Hotkey;
bool GlobalShortcut;
Shortcut(QString name = QString(), QString hotkey = QString(), bool global = false)
: Name(name), Hotkey(hotkey, QKeySequence::PortableText), GlobalShortcut(global) { }
Shortcut(std::initializer_list<QString> names, QString hotkey = QString(), bool global = false)
: Shortcut(QStringList(names).join(" -> "), hotkey, global) { }
};
//Functions
Configuration();
static Configuration* instance();
void load();
void save();
void readColors();
void writeColors();
void readBools();
void writeBools();
void readUints();
void writeUints();
void readFonts();
void writeFonts();
void readShortcuts();
void writeShortcuts();
void registerMenuBuilder(MenuBuilder* menu, size_t count);
void registerMainMenuStringList(QList<QAction*>* menu);
const QColor getColor(const QString & id) const;
const bool getBool(const QString & category, const QString & id) const;
void setBool(const QString & category, const QString & id, const bool b);
const duint getUint(const QString & category, const QString & id) const;
void setUint(const QString & category, const QString & id, const duint i);
const QFont getFont(const QString & id) const;
const Shortcut getShortcut(const QString & key_id) const;
void setShortcut(const QString & key_id, const QKeySequence key_sequence);
void setPluginShortcut(const QString & key_id, QString description, QString defaultShortcut, bool global);
void loadWindowGeometry(QWidget* window);
void saveWindowGeometry(QWidget* window);
void zoomFont(const QString & fontName, QWheelEvent* event);
//default setting maps
QMap<QString, QColor> defaultColors;
QMap<QString, QMap<QString, bool>> defaultBools;
QMap<QString, QMap<QString, duint>> defaultUints;
QMap<QString, QFont> defaultFonts;
QMap<QString, Shortcut> defaultShortcuts;
//public variables
QMap<QString, QColor> Colors;
QMap<QString, QMap<QString, bool>> Bools;
QMap<QString, QMap<QString, duint>> Uints;
QMap<QString, QFont> Fonts;
QMap<QString, Shortcut> Shortcuts;
//custom menu maps
struct MenuMap
{
union
{
QList<QAction*>* mainMenuList;
MenuBuilder* builder;
};
int type;
size_t count;
MenuMap() { }
MenuMap(QList<QAction*>* mainMenuList, size_t count)
: mainMenuList(mainMenuList), type(1), count(count) { }
MenuMap(MenuBuilder* builder, size_t count)
: builder(builder), type(0), count(count) { }
};
QList<MenuMap> NamedMenuBuilders;
static Configuration* mPtr;
signals:
void colorsUpdated();
void fontsUpdated();
void guiOptionsUpdated();
void shortcutsUpdated();
void tokenizerConfigUpdated();
void disableAutoCompleteUpdated();
private:
QColor colorFromConfig(const QString & id);
bool colorToConfig(const QString & id, const QColor color);
bool boolFromConfig(const QString & category, const QString & id);
bool boolToConfig(const QString & category, const QString & id, bool bBool);
duint uintFromConfig(const QString & category, const QString & id);
bool uintToConfig(const QString & category, const QString & id, duint i);
QFont fontFromConfig(const QString & id);
bool fontToConfig(const QString & id, const QFont font);
QString shortcutFromConfig(const QString & id);
bool shortcutToConfig(const QString & id, const QKeySequence shortcut);
mutable bool noMoreMsgbox;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/EncodeMap.cpp | #include "EncodeMap.h"
EncodeMap::EncodeMap(QObject* parent)
: QObject(parent),
mBase(0),
mSize(0),
mBuffer(nullptr),
mBufferSize(0)
{
}
EncodeMap::~EncodeMap()
{
if(mBuffer)
DbgReleaseEncodeTypeBuffer(mBuffer);
}
void EncodeMap::setMemoryRegion(duint addr)
{
mBase = DbgMemFindBaseAddr(addr, &mSize);
if(!mBase)
return;
if(mBuffer)
DbgReleaseEncodeTypeBuffer(mBuffer);
mBuffer = (byte*)DbgGetEncodeTypeBuffer(addr, &mBufferSize);
}
void EncodeMap::setDataType(duint va, ENCODETYPE type)
{
setDataType(va, getEncodeTypeSize(type), type);
}
void EncodeMap::setDataType(duint va, duint size, ENCODETYPE type)
{
DbgSetEncodeType(va, size, type);
if(!mBuffer && va >= mBase && va < mBase + mSize)
setMemoryRegion(va);
}
void EncodeMap::delRange(duint start, duint size)
{
DbgDelEncodeTypeRange(start, size);
}
void EncodeMap::delSegment(duint va)
{
DbgDelEncodeTypeSegment(va);
if(mBuffer && va >= mBase && va < mBase + mSize)
{
mBuffer = nullptr;
DbgReleaseEncodeTypeBuffer(mBuffer);
}
}
ENCODETYPE EncodeMap::getDataType(duint addr)
{
if(!mBuffer || !inBufferRange(addr))
return enc_unknown;
return ENCODETYPE(mBuffer[addr - mBase]);
}
duint EncodeMap::getDataSize(duint addr, duint codesize)
{
if(!mBuffer || !inBufferRange(addr))
return codesize;
auto type = ENCODETYPE(mBuffer[addr - mBase]);
auto datasize = getEncodeTypeSize(type);
if(isCode(type))
return codesize;
else
return datasize;
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/EncodeMap.h | #pragma once
#include <QObject>
#include "Imports.h"
class EncodeMap : public QObject
{
Q_OBJECT
public:
explicit EncodeMap(QObject* parent = 0);
~EncodeMap();
void setMemoryRegion(duint va);
duint getDataSize(duint va, duint codesize);
ENCODETYPE getDataType(duint addr);
void setDataType(duint va, ENCODETYPE type);
void setDataType(duint va, duint size, ENCODETYPE type);
void delRange(duint start, duint size);
void delSegment(duint va);
static duint getEncodeTypeSize(ENCODETYPE type)
{
switch(type)
{
case enc_byte:
return 1;
case enc_word:
return 2;
case enc_dword:
return 4;
case enc_fword:
return 6;
case enc_qword:
return 8;
case enc_tbyte:
return 10;
case enc_oword:
return 16;
case enc_mmword:
return 8;
case enc_xmmword:
return 16;
case enc_ymmword:
return 32;
case enc_real4:
return 4;
case enc_real8:
return 8;
case enc_real10:
return 10;
case enc_ascii:
return 1;
case enc_unicode:
return 2;
default:
return 1;
}
}
static bool isCode(ENCODETYPE type)
{
switch(type)
{
case enc_unknown:
case enc_code:
case enc_junk:
case enc_middle:
return true;
default:
return false;
}
}
bool inBufferRange(duint addr) const
{
return addr >= mBase && addr < mBase + mBufferSize;
}
protected:
duint mBase;
duint mSize;
byte* mBuffer;
duint mBufferSize;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/FlickerThread.cpp | #include "FlickerThread.h"
#include <QStyle>
#include <Windows.h>
FlickerThread::FlickerThread(QWidget* widget, QObject* parent) : QThread(parent)
{
mWidget = widget;
setProperties();
}
void FlickerThread::setProperties(int count, int width, int delay)
{
this->count = count;
this->width = width;
this->delay = delay;
}
void FlickerThread::run()
{
QString oldStyle = mWidget->styleSheet();
for(int i = 0; i < count; i++)
{
emit setStyleSheet(QString("QWidget { border: %1px solid red; }").arg(width));
Sleep(delay);
emit setStyleSheet(oldStyle);
Sleep(delay);
}
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/FlickerThread.h | #pragma once
#include <QThread>
#include <QWidget>
class FlickerThread : public QThread
{
Q_OBJECT
public:
explicit FlickerThread(QWidget* widget, QObject* parent = 0);
void setProperties(int count = 3, int width = 2, int delay = 300);
signals:
void setStyleSheet(QString style);
private:
void run();
QWidget* mWidget;
int count;
int width;
int delay;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/HexValidator.cpp | #include "HexValidator.h"
#include <QObject>
HexValidator::HexValidator(QObject* parent) : QValidator(parent)
{
}
HexValidator::~HexValidator()
{
}
static bool isXDigit(const QChar & c)
{
return c.isDigit() || (c.toUpper() >= 'A' && c.toUpper() <= 'F');
}
void HexValidator::fixup(QString & input) const
{
for(auto i : input)
{
if(!isXDigit(i))
input.remove(i);
}
}
QValidator::State HexValidator::validate(QString & input, int & pos) const
{
Q_UNUSED(pos);
for(int i = 0; i < input.length(); i++)
{
if(!isXDigit(input[i]))
return State::Invalid;
}
return State::Acceptable;
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/HexValidator.h | #pragma once
#include <QValidator>
class HexValidator : public QValidator
{
Q_OBJECT
public:
explicit HexValidator(QObject* parent = 0);
~HexValidator();
void fixup(QString & input) const;
State validate(QString & input, int & pos) const;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/LongLongValidator.cpp | #include "LongLongValidator.h"
LongLongValidator::LongLongValidator(DataType t, QObject* parent) : QValidator(parent), dt(t)
{
}
LongLongValidator::~LongLongValidator()
{
}
void LongLongValidator::fixup(QString & input) const
{
Q_UNUSED(input);
}
QValidator::State LongLongValidator::validate(QString & input, int & pos) const
{
Q_UNUSED(pos);
bool ok = false;
if(input.isEmpty()) return State::Acceptable;
switch(dt)
{
case SignedShort:
input.toShort(&ok);
if(!ok)
{
if(input == QString('-'))
return State::Acceptable;
if(input.toULongLong(&ok) > 32767)
{
if(ok)
{
input = "32767";
return State::Acceptable;
}
}
else if(input.toLongLong(&ok) < -32768)
{
if(ok)
{
input = "-32768";
return State::Acceptable;
}
}
return State::Invalid;
}
return State::Acceptable;
case UnsignedShort:
input.toShort(&ok);
if(!ok)
{
if(input.toULongLong(&ok) > 65535)
{
if(ok)
{
input = "65535";
return State::Acceptable;
}
}
return State::Invalid;
}
return State::Acceptable;
case SignedLong:
input.toLong(&ok);
if(!ok)
{
if(input == QString('-'))
return State::Acceptable;
if(input.toULongLong(&ok) > 2147483647LL)
{
if(ok)
{
input = "2147483647";
return State::Acceptable;
}
}
else if(input.toLongLong(&ok) < -2147483648LL)
{
if(ok)
{
input = "-2147483648";
return State::Acceptable;
}
}
return State::Invalid;
}
return State::Acceptable;
case UnsignedLong:
input.toULong(&ok);
if(!ok)
{
if(input.toULongLong(&ok) > 4294967295)
if(ok)
{
input = "4294967295";
return State::Acceptable;
}
return State::Invalid;
}
return State::Acceptable;
case SignedLongLong:
input.toLongLong(&ok);
if(!ok)
return input == QChar('-') ? State::Acceptable : State::Invalid;
return State::Acceptable;
case UnsignedLongLong:
input.toULongLong(&ok);
return ok ? State::Acceptable : State::Invalid;
}
return State::Invalid;
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/LongLongValidator.h | #pragma once
#include <QValidator>
class LongLongValidator : public QValidator
{
Q_OBJECT
public:
enum DataType
{
SignedShort,
UnsignedShort,
SignedLong,
UnsignedLong,
SignedLongLong,
UnsignedLongLong
};
explicit LongLongValidator(DataType t, QObject* parent = 0);
~LongLongValidator();
void fixup(QString & input) const;
State validate(QString & input, int & pos) const;
private:
DataType dt;
}; |
C++ | x64dbg-development/src/gui/Src/Utils/MainWindowCloseThread.cpp | #include "MainWindowCloseThread.h"
#include "Imports.h"
#include "Bridge.h"
MainWindowCloseThread::MainWindowCloseThread(QObject* parent)
: QThread(parent)
{
}
void MainWindowCloseThread::run()
{
DbgExit();
Bridge::getBridge()->setDbgStopped();
emit canClose();
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/MainWindowCloseThread.h | #pragma once
#include <QThread>
class MainWindowCloseThread : public QThread
{
Q_OBJECT
public:
explicit MainWindowCloseThread(QObject* parent = nullptr);
signals:
void canClose();
private:
void run();
}; |
C++ | x64dbg-development/src/gui/Src/Utils/MenuBuilder.cpp | #include "MenuBuilder.h"
#include "Bridge.h"
#include "Configuration.h"
/**
* @brief MenuBuilder::loadFromConfig Set the menu builder to be customizable
* @param id The id of menu builder. It should be the same on every same menu.
*/
void MenuBuilder::loadFromConfig()
{
this->id = parent()->metaObject()->className(); // Set the ID first because the following subroutine will use it
Config()->registerMenuBuilder(this, _containers.size()); // Register it to the config so the customization dialog can get the text of actions here.
}
QMenu* MenuBuilder::addMenu(QMenu* submenu, BuildCallback callback)
{
addBuilder(new MenuBuilder(submenu->parent(), [submenu, callback](QMenu*)
{
submenu->clear();
return callback(submenu);
}))->addMenu(submenu);
return submenu;
}
QMenu* MenuBuilder::addMenu(QMenu* submenu, MenuBuilder* builder)
{
addBuilder(new MenuBuilder(submenu->parent(), [submenu, builder](QMenu*)
{
submenu->clear();
return builder->build(submenu);
}))->addMenu(submenu);
return submenu;
}
/**
* @brief MenuBuilder::getText Get the title of id-th element. This function is called by CustomizeMenuDialog to initialize the dialog.
* @param id The index of the element in "_containers"
* @return The title, or empty. If it is empty, that element will not appear in the CustomizeMenuDialog.
*/
QString MenuBuilder::getText(size_t id) const
{
const Container & container = _containers.at(id);
switch(container.type)
{
case Container::Action:
return container.action->text();
case Container::Menu:
return container.menu->title();
case Container::Builder:
{
if(container.builder->_containers.size() == 1)
return container.builder->getText(0); // recursively get the text inside the menu builder
else
return QString();
}
default: // separator
return QString();
}
}
/**
* @brief MenuBuilder::build Build the menu with contents stored in the menu builder
* @param menu The menu to build.
* @return true if the callback succeeds, false if the callback returns false.
*/
bool MenuBuilder::build(QMenu* menu) const
{
if(_callback && !_callback(menu))
return false;
QMenu* submenu;
if(id != 0)
submenu = new QMenu(tr("More commands"), menu);
else
submenu = nullptr;
for(size_t i = 0; i < _containers.size(); i++)
{
const Container & container = _containers.at(i);
QMenu* _menu;
if(id != 0 && container.type != Container::Separator && Config()->getBool("Gui", QString("Menu%1Hidden%2").arg(id).arg(i)))
_menu = submenu;
else
_menu = menu;
switch(container.type)
{
case Container::Separator:
_menu->addSeparator();
break;
case Container::Action:
_menu->addAction(container.action);
break;
case Container::Menu:
_menu->addMenu(container.menu);
break;
case Container::Builder:
container.builder->build(_menu);
break;
default:
break;
}
}
if(id != 0 && !submenu->actions().isEmpty())
{
menu->addSeparator();
menu->addMenu(submenu);
}
else if(submenu)
{
delete submenu;
}
return true;
} |
C/C++ | x64dbg-development/src/gui/Src/Utils/MenuBuilder.h | #pragma once
#include <QAction>
#include <QMenu>
#include <functional>
/**
* @brief The MenuBuilder class implements the dynamic context menu system for many views.
*/
class MenuBuilder : public QObject
{
Q_OBJECT
public:
typedef std::function<bool(QMenu*)> BuildCallback;
inline MenuBuilder(QObject* parent, BuildCallback callback = nullptr)
: QObject(parent),
_callback(callback)
{
}
void loadFromConfig();
inline void addSeparator()
{
_containers.push_back(Container());
}
inline QAction* addAction(QAction* action)
{
_containers.push_back(Container(action));
return action;
}
inline QAction* addAction(QAction* action, BuildCallback callback)
{
addBuilder(new MenuBuilder(action->parent(), callback))->addAction(action);
return action;
}
inline QMenu* addMenu(QMenu* menu)
{
_containers.push_back(Container(menu));
return menu;
}
QMenu* addMenu(QMenu* submenu, BuildCallback callback);
QMenu* addMenu(QMenu* submenu, MenuBuilder* builder);
inline MenuBuilder* addBuilder(MenuBuilder* builder)
{
_containers.push_back(Container(builder));
return builder;
}
QString getText(size_t id) const;
QString getId() const
{
return id;
}
bool build(QMenu* menu) const;
inline bool empty() const
{
return _containers.empty();
}
private:
struct Container
{
enum Type
{
Separator,
Action,
Menu,
Builder
};
inline Container()
: type(Separator),
action(nullptr)
{
}
inline Container(QAction* action)
: type(Action),
action(action)
{
}
inline Container(QMenu* menu)
: type(Menu),
menu(menu)
{
}
inline Container(MenuBuilder* builder)
: type(Builder),
builder(builder)
{
}
Type type;
union
{
QAction* action;
QMenu* menu;
MenuBuilder* builder;
};
};
BuildCallback _callback;
QString id;
std::vector<Container> _containers;
}; |
C/C++ | x64dbg-development/src/gui/Src/Utils/MethodInvoker.h | #pragma once
#include <functional>
#include "Bridge.h"
struct MethodInvoker
{
template<class Func>
static void invokeMethod(Func && fn)
{
using StdFunc = std::function<void()>;
auto fnPtr = new StdFunc(std::forward<Func>(fn));
GuiExecuteOnGuiThreadEx([](void* userdata)
{
auto stdFunc = (StdFunc*)userdata;
(*stdFunc)();
delete stdFunc;
}, fnPtr);
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.