language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C/C++ | x64dbg-development/src/gui/Src/Gui/ColumnReorderDialog.h | #pragma once
#include <QDialog>
class AbstractTableView;
namespace Ui
{
class ColumnReorderDialog;
}
class ColumnReorderDialog : public QDialog
{
Q_OBJECT
public:
explicit ColumnReorderDialog(AbstractTableView* parent = 0);
~ColumnReorderDialog();
private slots:
void on_upButton_clicked();
void on_downButton_clicked();
void on_addButton_clicked();
void on_hideButton_clicked();
void on_addAllButton_clicked();
void on_okButton_clicked();
private:
Ui::ColumnReorderDialog* ui;
AbstractTableView* mParent;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/ColumnReorderDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ColumnReorderDialog</class>
<widget class="QDialog" name="ColumnReorderDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>352</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<layout class="QVBoxLayout" name="verticalLayout0">
<item>
<widget class="QLabel" name="label0">
<property name="text">
<string>Displayed</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QListWidget" name="listDisplayed"/>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout1">
<item>
<widget class="QPushButton" name="addButton">
<property name="text">
<string><- &Add</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="hideButton">
<property name="text">
<string>&Hide -></string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="upButton">
<property name="text">
<string>&Up</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="downButton">
<property name="text">
<string>&Down</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="addAllButton">
<property name="text">
<string><< A&dd all</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout2">
<item>
<widget class="QLabel" name="label1">
<property name="text">
<string>Available</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QListWidget" name="listAvailable">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
</widget>
</item>
</layout>
</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="okButton">
<property name="text">
<string>&Ok</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="cancelButton">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>cancelButton</sender>
<signal>clicked()</signal>
<receiver>ColumnReorderDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>342</x>
<y>326</y>
</hint>
<hint type="destinationlabel">
<x>347</x>
<y>312</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/ComboBoxDialog.cpp | #include "ComboBoxDialog.h"
#include "ui_ComboBoxDialog.h"
#include <QLineEdit>
#include <QStringListModel>
#include <QListView>
#include <QCompleter>
ComboBoxDialog::ComboBoxDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ComboBoxDialog)
{
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true); //modal window
ui->comboBox->setInsertPolicy(QComboBox::NoInsert);
ui->comboBox->setEditable(false);
ui->comboBox->setModel(new QStringListModel(this));
ui->checkBox->hide();
bChecked = false;
ui->label->setVisible(false);
}
ComboBoxDialog::~ComboBoxDialog()
{
delete ui;
}
void ComboBoxDialog::setEditable(bool editable)
{
ui->comboBox->setEditable(editable);
if(editable)
ui->comboBox->completer()->setCompletionMode(QCompleter::PopupCompletion);
}
void ComboBoxDialog::setItems(const QStringList & items)
{
((QStringListModel*)ui->comboBox->model())->setStringList(items);
}
void ComboBoxDialog::setMinimumContentsLength(int characters)
{
ui->comboBox->setMinimumContentsLength(characters);
// For performance reasons use this policy on large models.
ui->comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
}
QString ComboBoxDialog::currentText()
{
return ui->comboBox->currentText();
}
void ComboBoxDialog::setText(const QString & text)
{
if(ui->comboBox->isEditable())
{
ui->comboBox->setEditText(text);
ui->comboBox->lineEdit()->selectAll();
}
else
{
ui->comboBox->setCurrentIndex(ui->comboBox->findText(text));
}
}
void ComboBoxDialog::setPlaceholderText(const QString & text)
{
if(ui->comboBox->isEditable())
ui->comboBox->lineEdit()->setPlaceholderText(text);
}
void ComboBoxDialog::enableCheckBox(bool bEnable)
{
if(bEnable)
ui->checkBox->show();
else
ui->checkBox->hide();
}
void ComboBoxDialog::setCheckBox(bool bSet)
{
ui->checkBox->setChecked(bSet);
bChecked = bSet;
}
void ComboBoxDialog::setCheckBoxText(const QString & text)
{
ui->checkBox->setText(text);
}
void ComboBoxDialog::on_checkBox_toggled(bool checked)
{
bChecked = checked;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ComboBoxDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class ComboBoxDialog;
}
class ComboBoxDialog : public QDialog
{
Q_OBJECT
public:
explicit ComboBoxDialog(QWidget* parent = 0);
~ComboBoxDialog();
bool bChecked;
QString currentText();
void setEditable(bool editable);
void setItems(const QStringList & items);
// Minimum number of characters that should fit into the combobox.
// Use for large models, so that the length is not computed from its items.
void setMinimumContentsLength(int characters);
void setText(const QString & text);
void setPlaceholderText(const QString & text);
void enableCheckBox(bool bEnable);
void setCheckBox(bool bSet);
void setCheckBoxText(const QString & text);
private slots:
void on_checkBox_toggled(bool checked);
private:
Ui::ComboBoxDialog* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/ComboBoxDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ComboBoxDialog</class>
<widget class="QDialog" name="ComboBoxDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>414</width>
<height>72</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Dialog</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_2">
<item>
<widget class="QComboBox" name="comboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="minimumSize">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox">
<property name="text">
<string>CheckBox</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="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>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonOk</sender>
<signal>clicked()</signal>
<receiver>ComboBoxDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>243</x>
<y>49</y>
</hint>
<hint type="destinationlabel">
<x>150</x>
<y>57</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>ComboBoxDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>320</x>
<y>51</y>
</hint>
<hint type="destinationlabel">
<x>150</x>
<y>41</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/CommandLineEdit.cpp | #include "CommandLineEdit.h"
#include "Bridge.h"
#include "Configuration.h"
CommandLineEdit::CommandLineEdit(QWidget* parent)
: HistoryLineEdit(parent),
mCurrentScriptIndex(-1)
{
// QComboBox
mCmdScriptType = new QComboBox(this);
mCmdScriptType->setSizeAdjustPolicy(QComboBox::AdjustToContents);
//Initialize QCompleter
mCompleter = new QCompleter(QStringList(), this);
mCompleter->setCaseSensitivity(Qt::CaseInsensitive);
mCompleter->setCompletionMode(QCompleter::PopupCompletion);
mCompleterModel = (QStringListModel*)mCompleter->model();
this->setCompleter(mCompleter);
loadSettings("CommandLine");
//Setup signals & slots
connect(mCompleter, SIGNAL(activated(const QString &)), this, SLOT(clear()), Qt::QueuedConnection);
connect(this, SIGNAL(textEdited(QString)), this, SLOT(autoCompleteUpdate(QString)));
connect(Bridge::getBridge(), SIGNAL(autoCompleteAddCmd(QString)), this, SLOT(autoCompleteAddCmd(QString)));
connect(Bridge::getBridge(), SIGNAL(autoCompleteDelCmd(QString)), this, SLOT(autoCompleteDelCmd(QString)));
connect(Bridge::getBridge(), SIGNAL(autoCompleteClearAll()), this, SLOT(autoCompleteClearAll()));
connect(Bridge::getBridge(), SIGNAL(registerScriptLang(SCRIPTTYPEINFO*)), this, SLOT(registerScriptType(SCRIPTTYPEINFO*)));
connect(Bridge::getBridge(), SIGNAL(unregisterScriptLang(int)), this, SLOT(unregisterScriptType(int)));
connect(mCmdScriptType, SIGNAL(currentIndexChanged(int)), this, SLOT(scriptTypeChanged(int)));
connect(mCmdScriptType, SIGNAL(activated(int)), this, SLOT(scriptTypeActivated(int)));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(fontsUpdated()));
fontsUpdated();
}
CommandLineEdit::~CommandLineEdit()
{
saveSettings("CommandLine");
}
void CommandLineEdit::keyPressEvent(QKeyEvent* event)
{
if(event->type() == QEvent::KeyPress && event->key() == Qt::Key_Tab)
{
// TAB autocompletes the command
QStringList stringList = mCompleterModel->stringList();
if(stringList.size())
{
QAbstractItemView* popup = mCompleter->popup();
QModelIndex currentModelIndex = popup->currentIndex();
// If not item selected, select first one in the list
if(currentModelIndex.row() < 0)
currentModelIndex = mCompleter->currentIndex();
// If popup list is not visible, selected next suggested command
if(!popup->isVisible())
{
for(int row = 0; row < popup->model()->rowCount(); row++)
{
QModelIndex modelIndex = popup->model()->index(row, 0);
// If the lineedit contains a suggested command, get the next suggested one
if(popup->model()->data(modelIndex) == this->text())
{
int nextModelIndexRow = (currentModelIndex.row() + 1) % popup->model()->rowCount();
currentModelIndex = popup->model()->index(nextModelIndexRow, 0);
break;
}
}
}
popup->setCurrentIndex(currentModelIndex);
popup->hide();
}
}
else if(event->type() == QEvent::KeyPress && event->modifiers() == Qt::ControlModifier)
{
int index = mCmdScriptType->currentIndex(), count = mCmdScriptType->count();
if(event->key() == Qt::Key_Up)
{
// Ctrl + Up selects the previous language
if(index > 0)
index--;
else
index = count - 1;
}
else if(event->key() == Qt::Key_Down)
{
// Ctrl + Down selects the next language
index = (index + 1) % count;
}
else
HistoryLineEdit::keyPressEvent(event);
mCmdScriptType->setCurrentIndex(index);
scriptTypeActivated(index);
}
else
HistoryLineEdit::keyPressEvent(event);
}
// Disables moving to Prev/Next child when pressing tab
bool CommandLineEdit::focusNextPrevChild(bool next)
{
Q_UNUSED(next);
return false;
}
void CommandLineEdit::execute()
{
if(mCurrentScriptIndex == -1)
return;
GUISCRIPTEXECUTE exec = mScriptInfo[mCurrentScriptIndex].execute;
QString cmd = text();
if(exec)
{
if(cmd.trimmed().isEmpty())
if(Config()->getBool("Gui", "AutoRepeatOnEnter"))
cmd = getLineFromHistory();
// Send this string directly to the user
exec(cmd.toUtf8().constData());
}
// Add this line to the history and clear text, regardless if it was executed
addLineToHistory(cmd);
emit textEdited("");
setText("");
}
QWidget* CommandLineEdit::selectorWidget()
{
return mCmdScriptType;
}
void CommandLineEdit::autoCompleteUpdate(const QString text)
{
if(mCurrentScriptIndex == -1)
return;
// No command, no completer
if(text.length() <= 0)
{
mCompleterModel->setStringList(QStringList());
}
else
{
// Save current index
QModelIndex modelIndex = mCompleter->popup()->currentIndex();
// User supplied callback
GUISCRIPTCOMPLETER complete = mScriptInfo[mCurrentScriptIndex].completeCommand;
if(complete)
{
// This will hold an array of strings allocated by BridgeAlloc
char* completionList[32];
int completionCount = _countof(completionList);
complete(text.toUtf8().constData(), completionList, &completionCount);
if(completionCount > 0)
{
QStringList stringList;
// Append to the QCompleter string list and free the data
for(int i = 0; i < completionCount; i++)
{
stringList.append(completionList[i]);
BridgeFree(completionList[i]);
}
mCompleterModel->setStringList(stringList);
}
else
{
// Otherwise set the completer to nothing
mCompleterModel->setStringList(QStringList());
}
}
else
{
// Native auto-completion
if(mCurrentScriptIndex == 0)
{
if(mDefaultCompletionsUpdated)
{
mDefaultCompletions.removeDuplicates();
mDefaultCompletionsUpdated = false;
}
mCompleterModel->setStringList(mDefaultCompletions);
}
}
// Restore index
if(mCompleter->popup()->model()->rowCount() > modelIndex.row())
mCompleter->popup()->setCurrentIndex(modelIndex);
}
}
void CommandLineEdit::autoCompleteAddCmd(const QString cmd)
{
mDefaultCompletions << cmd.split(QChar(','), QString::SkipEmptyParts);
mDefaultCompletionsUpdated = true;
}
void CommandLineEdit::autoCompleteDelCmd(const QString cmd)
{
QStringList deleteList = cmd.split(QChar(','), QString::SkipEmptyParts);
for(int i = 0; i < deleteList.size(); i++)
mDefaultCompletions.removeAll(deleteList.at(i));
mDefaultCompletionsUpdated = true;
}
void CommandLineEdit::autoCompleteClearAll()
{
// Update internal list only
mDefaultCompletions.clear();
mDefaultCompletionsUpdated = false;
}
void CommandLineEdit::registerScriptType(SCRIPTTYPEINFO* info)
{
// Must be valid pointer
if(!info)
{
Bridge::getBridge()->setResult(BridgeResult::RegisterScriptLang, 0);
return;
}
// Insert
info->id = mScriptInfo.size();
mScriptInfo.push_back(*info);
// Update
mCmdScriptType->addItem(info->name);
if(info->id == 0)
mCurrentScriptIndex = 0;
char savedType[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("Gui", "ScriptType", savedType) && strcmp(info->name, savedType) == 0)
mCmdScriptType->setCurrentIndex(info->id);
Bridge::getBridge()->setResult(BridgeResult::RegisterScriptLang, 1);
}
void CommandLineEdit::unregisterScriptType(int id)
{
// The default script type can't be unregistered
if(id <= 0)
return;
// Loop through the vector and invalidate entry (validate id)
for(int i = 0; i < mScriptInfo.size(); i++)
{
if(mScriptInfo[i].id == id)
{
mScriptInfo.removeAt(i);
mCmdScriptType->removeItem(i);
break;
}
}
// Update selected index
if(mCurrentScriptIndex > 0)
mCurrentScriptIndex--;
mCmdScriptType->setCurrentIndex(mCurrentScriptIndex);
}
void CommandLineEdit::scriptTypeChanged(int index)
{
mCurrentScriptIndex = index;
// Custom placeholder for the default commands
duint timeWastedDebugging = 0;
BridgeSettingGetUint("Engine", "TimeWastedDebugging", &timeWastedDebugging);
if(index == 0 && timeWastedDebugging < 60 * 60 * 10)
{
setPlaceholderText(tr("Commands are comma separated (like assembly instructions): mov eax, ebx"));
}
else
{
setPlaceholderText(QString());
}
// Force reset autocompletion (blank string)
emit textEdited("");
}
void CommandLineEdit::scriptTypeActivated(int index)
{
if(index >= 0 && index < mScriptInfo.size())
BridgeSettingSet("Gui", "ScriptType", mScriptInfo[index].name);
}
void CommandLineEdit::fontsUpdated()
{
setFont(ConfigFont("Log"));
mCompleter->popup()->setFont(ConfigFont("Log"));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CommandLineEdit.h | #pragma once
#include "Bridge/bridgemain.h"
#include "HistoryLineEdit.h"
#include <QAbstractItemView>
#include <QCompleter>
#include <QComboBox>
#include <QStringListModel>
class CommandLineEdit : public HistoryLineEdit
{
Q_OBJECT
public:
explicit CommandLineEdit(QWidget* parent = 0);
~CommandLineEdit();
void keyPressEvent(QKeyEvent* event);
bool focusNextPrevChild(bool next);
void execute();
QWidget* selectorWidget();
public slots:
void autoCompleteUpdate(const QString text);
void autoCompleteAddCmd(const QString cmd);
void autoCompleteDelCmd(const QString cmd);
void autoCompleteClearAll();
void registerScriptType(SCRIPTTYPEINFO* info);
void unregisterScriptType(int id);
void scriptTypeChanged(int index);
void scriptTypeActivated(int index);
void fontsUpdated();
private:
QComboBox* mCmdScriptType;
QCompleter* mCompleter;
QStringListModel* mCompleterModel;
QList<SCRIPTTYPEINFO> mScriptInfo;
QStringList mDefaultCompletions;
bool mDefaultCompletionsUpdated = false;
int mCurrentScriptIndex;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUArgumentWidget.cpp | #include "CPUArgumentWidget.h"
#include "ui_CPUArgumentWidget.h"
#include "Configuration.h"
#include "Bridge.h"
CPUArgumentWidget::CPUArgumentWidget(QWidget* parent) :
QWidget(parent),
ui(new Ui::CPUArgumentWidget),
mTable(nullptr),
mCurrentCallingConvention(-1),
mStackOffset(0),
mAllowUpdate(true)
{
ui->setupUi(this);
mTable = ui->table;
setupTable();
loadConfig();
refreshData();
ui->checkBoxLock->setToolTip(tr("Refresh is automatic."));
mFollowDisasm = new QAction(this);
connect(mFollowDisasm, SIGNAL(triggered()), this, SLOT(followDisasmSlot()));
mFollowAddrDisasm = new QAction(this);
connect(mFollowAddrDisasm, SIGNAL(triggered()), this, SLOT(followDisasmSlot()));
mFollowDump = new QAction(this);
connect(mFollowDump, SIGNAL(triggered()), this, SLOT(followDumpSlot()));
mFollowAddrDump = new QAction(this);
connect(mFollowAddrDump, SIGNAL(triggered()), this, SLOT(followDumpSlot()));
mFollowStack = new QAction(this);
connect(mFollowStack, SIGNAL(triggered()), this, SLOT(followStackSlot()));
mFollowAddrStack = new QAction(this);
connect(mFollowAddrStack, SIGNAL(triggered()), this, SLOT(followStackSlot()));
connect(Bridge::getBridge(), SIGNAL(repaintTableView()), this, SLOT(refreshData()));
connect(Bridge::getBridge(), SIGNAL(disassembleAt(dsint, dsint)), this, SLOT(disassembleAtSlot(dsint, dsint)));
}
CPUArgumentWidget::~CPUArgumentWidget()
{
delete ui;
}
void CPUArgumentWidget::updateStackOffset(bool iscall)
{
const auto & cur = mCallingConventions[mCurrentCallingConvention];
mStackOffset = cur.getStackOffset() + (iscall ? 0 : cur.getCallOffset());
}
void CPUArgumentWidget::disassembleAtSlot(dsint addr, dsint cip)
{
Q_UNUSED(addr);
if(mCurrentCallingConvention == -1) //no calling conventions
{
mTable->setRowCount(0);
mTable->reloadData();
return;
}
BASIC_INSTRUCTION_INFO disasm;
DbgDisasmFastAt(cip, &disasm);
updateStackOffset(disasm.call);
if(ui->checkBoxLock->checkState() == Qt::PartiallyChecked) //Calls
{
mAllowUpdate = disasm.call;
ui->spinArgCount->setEnabled(disasm.call);
ui->comboCallingConvention->setEnabled(disasm.call);
}
}
static QString stringFormatInline(const QString & format)
{
if(!DbgFunctions()->StringFormatInline)
return QString();
char result[MAX_SETTING_SIZE] = "";
if(DbgFunctions()->StringFormatInline(format.toUtf8().constData(), MAX_SETTING_SIZE, result))
return result;
return CPUArgumentWidget::tr("[Formatting Error]");
}
void CPUArgumentWidget::refreshData()
{
if(!mAllowUpdate) //view is locked
return;
if(mCurrentCallingConvention == -1 || !DbgIsDebugging()) //no calling conventions
{
mTable->setRowCount(0);
mTable->reloadData();
return;
}
const auto & cur = mCallingConventions[mCurrentCallingConvention];
int argCountStruct = int(cur.arguments.size());
int argCount = std::min(argCountStruct, ui->spinArgCount->value());
int stackCount = std::max(0, ui->spinArgCount->value() - argCountStruct);
mTable->setRowCount(argCount + stackCount);
mArgumentValues.clear();
for(int i = 0; i < argCount; i++)
{
const auto & curArg = cur.arguments[i];
auto data = stringFormatInline(curArg.getFormat());
auto text = defaultArgFieldFormat(defaultArgName(curArg.name, i + 1), data);
mArgumentValues.push_back(DbgValFromString(curArg.getExpression().toUtf8().constData()));
mTable->setCellContent(i, 0, text);
}
auto stackLocation = cur.getStackLocation();
for(int i = 0; i < stackCount; i++)
{
duint argOffset = mStackOffset + i * sizeof(duint);
QString expr = argOffset ? QString("%1+%2").arg(stackLocation).arg(ToHexString(argOffset)) : stackLocation;
QString format = defaultArgFormat("", QString("[%1]").arg(expr));
auto data = stringFormatInline(format);
auto text = defaultArgFieldFormat(defaultArgName("", argCount + i + 1), data);
mArgumentValues.push_back(DbgValFromString(expr.toUtf8().constData()));
mTable->setCellContent(argCount + i, 0, text);
}
mTable->reloadData();
}
static void configAction(QMenu & wMenu, const QIcon & icon, QAction* action, const QString & value, const QString & name)
{
action->setText(QApplication::translate("CPUArgumentWidget", "Follow %1 in %2").arg(value).arg(name));
action->setIcon(icon);
action->setObjectName(value);
wMenu.addAction(action);
}
void CPUArgumentWidget::contextMenuSlot(QPoint pos)
{
if(!DbgIsDebugging())
return;
auto selection = mTable->getInitialSelection();
if(int(mArgumentValues.size()) <= selection)
return;
auto value = mArgumentValues[selection];
QMenu wMenu(this);
if(DbgMemIsValidReadPtr(value))
{
duint valueAddr;
DbgMemRead(value, (unsigned char*)&valueAddr, sizeof(valueAddr));
auto valueText = ToHexString(value);
auto valueAddrText = QString("[%1]").arg(valueText);
auto inStackRange = [](duint addr)
{
auto csp = DbgValFromString("csp");
duint size;
auto base = DbgMemFindBaseAddr(csp, &size);
return addr >= base && addr < base + size;
};
configAction(wMenu, DIcon(ArchValue("processor32", "processor64")), mFollowDisasm, valueText, tr("Disassembler"));
configAction(wMenu, DIcon("dump"), mFollowDump, valueText, tr("Dump"));
if(inStackRange(value))
configAction(wMenu, DIcon("stack"), mFollowStack, valueText, tr("Stack"));
if(DbgMemIsValidReadPtr(valueAddr))
{
configAction(wMenu, DIcon(ArchValue("processor32", "processor64")), mFollowAddrDisasm, valueAddrText, tr("Disassembler"));
configAction(wMenu, DIcon("dump"), mFollowDump, valueAddrText, tr("Dump"));
if(inStackRange(valueAddr))
configAction(wMenu, DIcon("stack"), mFollowAddrStack, valueAddrText, tr("Stack"));
}
}
QMenu wCopyMenu(tr("&Copy"));
wCopyMenu.setIcon(DIcon("copy"));
mTable->setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
{
wMenu.addSeparator();
wMenu.addMenu(&wCopyMenu);
}
wMenu.exec(mTable->mapToGlobal(pos));
}
void CPUArgumentWidget::followDisasmSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(!action)
return;
DbgCmdExec(QString("disasm \"%1\"").arg(action->objectName()));
}
void CPUArgumentWidget::followDumpSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(!action)
return;
DbgCmdExec(QString("dump \"%1\"").arg(action->objectName()));
}
void CPUArgumentWidget::followStackSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(!action)
return;
DbgCmdExec(QString("sdump \"%1\"").arg(action->objectName()));
}
void CPUArgumentWidget::loadConfig()
{
#ifdef _WIN64
CallingConvention x64(tr("Default (x64 fastcall)"), 1);
x64.addArgument(Argument("", "", "rcx"));
x64.addArgument(Argument("", "", "rdx"));
x64.addArgument(Argument("", "", "r8"));
x64.addArgument(Argument("", "", "r9"));
mCallingConventions.push_back(x64);
#else
CallingConvention x32(tr("Default (stdcall)"), 5);
mCallingConventions.push_back(x32);
CallingConvention x32ebp(tr("Default (stdcall, EBP stack)"), 5, "ebp", 8, 0);
mCallingConventions.push_back(x32ebp);
CallingConvention thiscall(tr("thiscall"), 4);
thiscall.addArgument(Argument("this", "ecx", ""));
mCallingConventions.push_back(thiscall);
CallingConvention fastcall(tr("fastcall"), 3);
fastcall.addArgument(Argument("", "ecx", ""));
fastcall.addArgument(Argument("", "edx", ""));
mCallingConventions.push_back(fastcall);
CallingConvention delphi(tr("Delphi (Borland fastcall)"), 2);
delphi.addArgument(Argument("", "eax", ""));
delphi.addArgument(Argument("", "edx", ""));
delphi.addArgument(Argument("", "ecx", ""));
mCallingConventions.push_back(delphi);
#endif //_WIN64
for(auto & cur : mCallingConventions)
ui->comboCallingConvention->addItem(cur.name);
}
void CPUArgumentWidget::setupTable()
{
connect(mTable, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
mTable->enableMultiSelection(false);
mTable->setShowHeader(false);
mTable->addColumnAt(0, "", false);
mTable->reloadData();
}
void CPUArgumentWidget::on_comboCallingConvention_currentIndexChanged(int index)
{
mCurrentCallingConvention = index;
const auto & cur = mCallingConventions[index];
ui->spinArgCount->setValue(int(cur.arguments.size()) + cur.stackArgCount); //set the default argument count
if(!DbgIsDebugging())
return;
BASIC_INSTRUCTION_INFO disasm;
DbgDisasmFastAt(DbgValFromString("CIP"), &disasm);
updateStackOffset(disasm.call);
refreshData();
}
void CPUArgumentWidget::on_spinArgCount_valueChanged(int)
{
mTable->setTableOffset(0); //reset the view to the first argument (fixes an ugly issue after refreshing)
refreshData();
}
void CPUArgumentWidget::on_checkBoxLock_stateChanged(int)
{
switch(ui->checkBoxLock->checkState())
{
case Qt::Checked: //Locked, update disabled.
refreshData(); //first refresh then lock
ui->checkBoxLock->setText(tr("Locked"));
ui->checkBoxLock->setToolTip(tr("Refresh is disabled."));
ui->spinArgCount->setEnabled(false);
ui->comboCallingConvention->setEnabled(false);
mAllowUpdate = false;
break;
case Qt::PartiallyChecked://Locked, but still update when a call is encountered.
refreshData(); //first refresh then lock
ui->checkBoxLock->setText(tr("Calls"));
ui->checkBoxLock->setToolTip(tr("Refresh is only done when executing a CALL instruction."));
ui->spinArgCount->setEnabled(false);
ui->comboCallingConvention->setEnabled(false);
mAllowUpdate = false;
break;
case Qt::Unchecked://Unlocked, update enabled
ui->checkBoxLock->setText(tr("Unlocked"));
ui->checkBoxLock->setToolTip(tr("Refresh is automatic."));
ui->spinArgCount->setEnabled(true);
ui->comboCallingConvention->setEnabled(true);
mAllowUpdate = true;
refreshData(); //first lock then refresh
break;
default:
break;
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUArgumentWidget.h | #pragma once
#include <QWidget>
#include <vector>
#include "StdTable.h"
#include "StringUtil.h"
namespace Ui
{
class CPUArgumentWidget;
}
class CPUArgumentWidget : public QWidget
{
Q_OBJECT
public:
explicit CPUArgumentWidget(QWidget* parent = 0);
~CPUArgumentWidget();
static QString defaultArgFormat(const QString & format, const QString & expression)
{
if(format.length())
return format;
return QString("%1 {p:%1} {a:%1}").arg(expression).trimmed();
}
static QString defaultArgName(const QString & name, int argN)
{
if(name.length())
return name;
return QString("%1").arg(argN);
}
static QString defaultArgFieldFormat(const QString & argName, const QString & argText)
{
if(argText.length())
return QString("%1: %2").arg(argName).arg(argText);
return QString();
}
public slots:
void disassembleAtSlot(dsint addr, dsint cip);
void refreshData();
private slots:
void contextMenuSlot(QPoint pos);
void followDisasmSlot();
void followDumpSlot();
void followStackSlot();
void on_comboCallingConvention_currentIndexChanged(int index);
void on_spinArgCount_valueChanged(int arg1);
void on_checkBoxLock_stateChanged(int arg1);
private:
struct Argument
{
QString name;
QString expression32;
QString expression64;
QString format32;
QString format64;
const QString & getExpression() const
{
return ArchValue(expression32, expression64);
}
QString getFormat() const
{
return CPUArgumentWidget::defaultArgFormat(ArchValue(format32, format64), getExpression());
}
explicit Argument(const QString & name, const QString & expression32, const QString & expression64, const QString & format32 = "", const QString & format64 = "")
: name(name),
expression32(expression32),
expression64(expression64),
format32(format32),
format64(format64)
{
}
};
struct CallingConvention
{
QString name;
int stackArgCount;
QString stackLocation32;
duint stackOffset32;
duint callOffset32;
QString stackLocation64;
duint callOffset64;
duint stackOffset64;
std::vector<Argument> arguments;
const QString & getStackLocation() const
{
return ArchValue(stackLocation32, stackLocation64);
}
const duint getStackOffset() const
{
return ArchValue(stackOffset32, stackOffset64);
}
const duint & getCallOffset() const
{
return ArchValue(callOffset32, callOffset64);
}
void addArgument(const Argument & argument)
{
arguments.push_back(argument);
}
explicit CallingConvention(const QString & name,
int stackArgCount = 0,
const QString & stackLocation32 = "esp",
duint stackOffset32 = 0,
duint callOffset32 = sizeof(duint),
const QString & stackLocation64 = "rsp",
duint stackOffset64 = 0x20,
duint callOffset64 = sizeof(duint))
: name(name),
stackArgCount(stackArgCount),
stackLocation32(stackLocation32),
stackOffset32(stackOffset32),
callOffset32(callOffset32),
stackLocation64(stackLocation64),
stackOffset64(stackOffset64),
callOffset64(callOffset64)
{
}
};
Ui::CPUArgumentWidget* ui;
StdTable* mTable;
int mCurrentCallingConvention;
duint mStackOffset;
bool mAllowUpdate;
std::vector<CallingConvention> mCallingConventions;
std::vector<duint> mArgumentValues;
QAction* mFollowDisasm;
QAction* mFollowAddrDisasm;
QAction* mFollowDump;
QAction* mFollowAddrDump;
QAction* mFollowStack;
QAction* mFollowAddrStack;
void loadConfig();
void setupTable();
void updateStackOffset(bool iscall);
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/CPUArgumentWidget.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CPUArgumentWidget</class>
<widget class="QWidget" name="CPUArgumentWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>438</width>
<height>114</height>
</rect>
</property>
<property name="windowTitle">
<string>Arguments</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<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>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>3</number>
</property>
<property name="sizeConstraint">
<enum>QLayout::SetMaximumSize</enum>
</property>
<item>
<widget class="QComboBox" name="comboCallingConvention">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinArgCount"/>
</item>
<item>
<widget class="QCheckBox" name="checkBoxLock">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>66</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>Unlocked</string>
</property>
<property name="tristate">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="StdTable" name="table" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>StdTable</class>
<extends>QWidget</extends>
<header>StdTable.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/CPUDisassembly.cpp | #include <QMessageBox>
#include <QFileDialog>
#include <QFile>
#include <QDesktopServices>
#include <QClipboard>
#include "CPUDisassembly.h"
#include "main.h"
#include "CPUSideBar.h"
#include "CPUWidget.h"
#include "EncodeMap.h"
#include "CPUMultiDump.h"
#include "Configuration.h"
#include "Bridge.h"
#include "Imports.h"
#include "LineEditDialog.h"
#include "WordEditDialog.h"
#include "GotoDialog.h"
#include "HexEditDialog.h"
#include "AssembleDialog.h"
#include "StringUtil.h"
#include "XrefBrowseDialog.h"
#include "SourceViewerManager.h"
#include "MiscUtil.h"
#include "MemoryPage.h"
#include "CommonActions.h"
#include "BrowseDialog.h"
#include "Tracer/TraceBrowser.h"
CPUDisassembly::CPUDisassembly(QWidget* parent, bool isMain) : Disassembly(parent, isMain)
{
setWindowTitle("Disassembly");
// Create the action list for the right click context menu
setupRightClickContextMenu();
// Connect bridge<->disasm calls
connect(Bridge::getBridge(), SIGNAL(disassembleAt(dsint, dsint)), this, SLOT(disassembleAtSlot(dsint, dsint)));
if(mIsMain)
{
connect(Bridge::getBridge(), SIGNAL(selectionDisasmGet(SELECTIONDATA*)), this, SLOT(selectionGetSlot(SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(selectionDisasmSet(const SELECTIONDATA*)), this, SLOT(selectionSetSlot(const SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(displayWarning(QString, QString)), this, SLOT(displayWarningSlot(QString, QString)));
}
// Connect some internal signals
connect(this, SIGNAL(selectionExpanded()), this, SLOT(selectionUpdatedSlot()));
// Load configuration
mShowMnemonicBrief = ConfigBool("Disassembler", "ShowMnemonicBrief");
Initialize();
}
void CPUDisassembly::mousePressEvent(QMouseEvent* event)
{
if(event->buttons() == Qt::MiddleButton) //copy address to clipboard
{
if(!DbgIsDebugging())
return;
MessageBeep(MB_OK);
if(event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier))
copyRvaSlot();
else
copyAddressSlot();
}
else
{
mHighlightContextMenu = false;
Disassembly::mousePressEvent(event);
if(mHighlightingMode) //disable highlighting mode after clicked
{
mHighlightContextMenu = true;
mHighlightingMode = false;
reloadData();
}
}
}
void CPUDisassembly::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->button() != Qt::LeftButton)
return;
switch(getColumnIndexFromX(event->x()))
{
case 0: //address
{
dsint mSelectedVa = rvaToVa(getInitialSelection());
if(mRvaDisplayEnabled && mSelectedVa == mRvaDisplayBase)
mRvaDisplayEnabled = false;
else
{
mRvaDisplayEnabled = true;
mRvaDisplayBase = mSelectedVa;
mRvaDisplayPageBase = getBase();
}
reloadData();
}
break;
// (Opcodes) Set INT3 breakpoint
case 1:
mCommonActions->toggleInt3BPActionSlot();
break;
// (Disassembly) Assemble dialog
case 2:
{
duint assembleOnDoubleClickInt;
bool assembleOnDoubleClick = (BridgeSettingGetUint("Disassembler", "AssembleOnDoubleClick", &assembleOnDoubleClickInt) && assembleOnDoubleClickInt);
if(assembleOnDoubleClick)
{
assembleSlot();
}
else
{
duint dest = DbgGetBranchDestination(rvaToVa(getInitialSelection()));
if(DbgMemIsValidReadPtr(dest))
gotoAddress(dest);
}
}
break;
// (Comments) Set comment dialog
case 3:
mCommonActions->setCommentSlot();
break;
// Undefined area
default:
Disassembly::mouseDoubleClickEvent(event);
break;
}
}
void CPUDisassembly::addFollowReferenceMenuItem(QString name, dsint value, QMenu* menu, bool isReferences, bool isFollowInCPU)
{
foreach(QAction* action, menu->actions()) //check for duplicate action
if(action->text() == name)
return;
QAction* newAction = new QAction(name, this);
newAction->setFont(font());
menu->addAction(newAction);
if(isFollowInCPU)
newAction->setObjectName(QString("CPU|") + ToPtrString(value));
else
newAction->setObjectName(QString(isReferences ? "REF|" : "DUMP|") + ToPtrString(value));
connect(newAction, SIGNAL(triggered()), this, SLOT(followActionSlot()));
}
void CPUDisassembly::setupFollowReferenceMenu(dsint wVA, QMenu* menu, bool isReferences, bool isFollowInCPU)
{
//remove previous actions
QList<QAction*> list = menu->actions();
for(int i = 0; i < list.length(); i++)
menu->removeAction(list.at(i));
//most basic follow action
if(!isFollowInCPU)
{
if(isReferences)
menu->addAction(mReferenceSelectedAddressAction);
else
addFollowReferenceMenuItem(tr("&Selected Address"), wVA, menu, isReferences, isFollowInCPU);
}
//add follow actions
DISASM_INSTR instr;
DbgDisasmAt(wVA, &instr);
if(!isReferences) //follow in dump
{
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG & arg = instr.arg[i];
if(arg.type == arg_memory)
{
QString segment = "";
#ifdef _WIN64
if(arg.segment == SEG_GS)
segment = "gs:";
#else //x32
if(arg.segment == SEG_FS)
segment = "fs:";
#endif //_WIN64
if(arg.value != arg.constant)
{
if(DbgMemIsValidReadPtr(arg.value))
addFollowReferenceMenuItem(tr("&Address: ") + segment + QString(arg.mnemonic).toUpper().trimmed(), arg.value, menu, isReferences, isFollowInCPU);
}
if(DbgMemIsValidReadPtr(arg.constant))
addFollowReferenceMenuItem(tr("&Constant: ") + getSymbolicName(arg.constant), arg.constant, menu, isReferences, isFollowInCPU);
if(DbgMemIsValidReadPtr(arg.memvalue))
{
addFollowReferenceMenuItem(tr("&Value: ") + segment + "[" + QString(arg.mnemonic) + "]", arg.memvalue, menu, isReferences, isFollowInCPU);
//Check for switch statement
if(memcmp(instr.instruction, "jmp ", 4) == 0 && DbgMemIsValidReadPtr(arg.constant)) //todo: extend check for exact form "jmp [reg*4+disp]"
{
duint* switchTable = new duint[512];
memset(switchTable, 0, 512 * sizeof(duint));
if(DbgMemRead(arg.constant, switchTable, 512 * sizeof(duint)))
{
int index;
for(index = 0; index < 512; index++)
if(!DbgFunctions()->MemIsCodePage(switchTable[index], false))
break;
if(index >= 2 && index < 512)
for(int index2 = 0; index2 < index; index2++)
addFollowReferenceMenuItem(tr("Jump table%1: ").arg(index2) + ToHexString(switchTable[index2]), switchTable[index2], menu, isReferences, isFollowInCPU);
}
delete[] switchTable;
}
}
}
else //arg_normal
{
if(DbgMemIsValidReadPtr(arg.value))
{
QString symbolicName = getSymbolicName(arg.value);
QString mnemonic = QString(arg.mnemonic).trimmed();
if(mnemonic != ToHexString(arg.value))
mnemonic = mnemonic + ": " + symbolicName;
else
mnemonic = symbolicName;
addFollowReferenceMenuItem(mnemonic, arg.value, menu, isReferences, isFollowInCPU);
}
}
}
}
else //find references
{
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG arg = instr.arg[i];
QString constant = ToHexString(arg.constant);
if(DbgMemIsValidReadPtr(arg.constant))
addFollowReferenceMenuItem(tr("Address: ") + constant, arg.constant, menu, isReferences, isFollowInCPU);
else if(arg.constant)
addFollowReferenceMenuItem(tr("Constant: ") + constant, arg.constant, menu, isReferences, isFollowInCPU);
}
}
}
/************************************************************************************
Mouse Management
************************************************************************************/
/**
* @brief This method has been reimplemented. It manages the richt click context menu.
*
* @param[in] event Context menu event
*
* @return Nothing.
*/
void CPUDisassembly::contextMenuEvent(QContextMenuEvent* event)
{
QMenu wMenu(this);
if(!mHighlightContextMenu)
mMenuBuilder->build(&wMenu);
else if(mHighlightToken.text.length())
mHighlightMenuBuilder->build(&wMenu);
if(wMenu.actions().length())
wMenu.exec(event->globalPos());
}
/************************************************************************************
Context Menu Management
************************************************************************************/
void CPUDisassembly::setupRightClickContextMenu()
{
mMenuBuilder = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
MenuBuilder* binaryMenu = new MenuBuilder(this);
binaryMenu->addAction(makeShortcutAction(DIcon("binary_edit"), tr("&Edit"), SLOT(binaryEditSlot()), "ActionBinaryEdit"));
binaryMenu->addAction(makeShortcutAction(DIcon("binary_fill"), tr("&Fill..."), SLOT(binaryFillSlot()), "ActionBinaryFill"));
binaryMenu->addAction(makeShortcutAction(DIcon("binary_fill_nop"), tr("Fill with &NOPs"), SLOT(binaryFillNopsSlot()), "ActionBinaryFillNops"));
binaryMenu->addSeparator();
binaryMenu->addAction(makeShortcutAction(DIcon("binary_copy"), tr("&Copy"), SLOT(binaryCopySlot()), "ActionBinaryCopy"));
binaryMenu->addAction(makeShortcutAction(DIcon("binary_paste"), tr("&Paste"), SLOT(binaryPasteSlot()), "ActionBinaryPaste"), [](QMenu*)
{
return QApplication::clipboard()->mimeData()->hasText();
});
binaryMenu->addAction(makeShortcutAction(DIcon("binary_paste_ignoresize"), tr("Paste (&Ignore Size)"), SLOT(binaryPasteIgnoreSizeSlot()), "ActionBinaryPasteIgnoreSize"), [](QMenu*)
{
return QApplication::clipboard()->mimeData()->hasText();
});
mMenuBuilder->addMenu(makeMenu(DIcon("binary"), tr("&Binary")), binaryMenu);
MenuBuilder* copyMenu = new MenuBuilder(this);
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("copy_address"), tr("&Address"), SLOT(copyAddressSlot()), "ActionCopyAddress"));
copyMenu->addAction(makeShortcutAction(DIcon("copy_address"), tr("&RVA"), SLOT(copyRvaSlot()), "ActionCopyRva"));
copyMenu->addAction(makeShortcutAction(DIcon("fileoffset"), tr("&File Offset"), SLOT(copyFileOffsetSlot()), "ActionCopyFileOffset"));
copyMenu->addAction(makeAction(tr("&Header VA"), SLOT(copyHeaderVaSlot())));
copyMenu->addAction(makeAction(DIcon("copy_disassembly"), tr("Disassembly"), SLOT(copyDisassemblySlot())));
copyMenu->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
QSet<QString> labels;
if(!getLabelsFromInstruction(rvaToVa(getInitialSelection()), labels))
return false;
menu->addSeparator();
for(const auto & label : labels)
menu->addAction(makeAction(label, SLOT(labelCopySlot())));
return true;
}));
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
mMenuBuilder->addAction(makeShortcutAction(DIcon("eraser"), tr("&Restore selection"), SLOT(undoSelectionSlot()), "ActionUndoSelection"), [this](QMenu*)
{
dsint start = rvaToVa(getSelectionStart());
dsint end = rvaToVa(getSelectionEnd());
return DbgFunctions()->PatchInRange(start, end); //something patched in selected range
});
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]()
{
return rvaToVa(getInitialSelection());
});
mCommonActions->build(mMenuBuilder, CommonActions::ActionBreakpoint);
mMenuBuilder->addMenu(makeMenu(DIcon("dump"), tr("&Follow in Dump")), [this](QMenu * menu)
{
setupFollowReferenceMenu(rvaToVa(getInitialSelection()), menu, false, false);
return true;
});
mMenuBuilder->addMenu(makeMenu(DIcon("processor-cpu"), tr("&Follow in Disassembler")), [this](QMenu * menu)
{
setupFollowReferenceMenu(rvaToVa(getInitialSelection()), menu, false, true);
return menu->actions().length() != 0; //only add this menu if there is something to follow
});
mCommonActions->build(mMenuBuilder, CommonActions::ActionMemoryMap | CommonActions::ActionGraph);
mMenuBuilder->addAction(makeShortcutAction(DIcon("source"), tr("Open Source File"), SLOT(openSourceSlot()), "ActionOpenSourceFile"), [this](QMenu*)
{
return DbgFunctions()->GetSourceFromAddr(rvaToVa(getInitialSelection()), 0, 0);
});
mMenuBuilder->addMenu(makeMenu(DIcon("help"), tr("Help on Symbolic Name")), [this](QMenu * menu)
{
QSet<QString> labels;
if(!getLabelsFromInstruction(rvaToVa(getInitialSelection()), labels))
return false;
for(auto label : labels)
menu->addAction(makeAction(label, SLOT(labelHelpSlot())));
return true;
});
mMenuBuilder->addAction(makeShortcutAction(DIcon("helpmnemonic"), tr("Help on mnemonic"), SLOT(mnemonicHelpSlot()), "ActionHelpOnMnemonic"));
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;
});
mMenuBuilder->addAction(makeShortcutAction(DIcon("highlight"), tr("&Highlighting mode"), SLOT(enableHighlightingModeSlot()), "ActionHighlightingMode"));
mMenuBuilder->addAction(makeAction("Edit columns...", SLOT(editColumnDialog())));
MenuBuilder* labelMenu = new MenuBuilder(this);
labelMenu->addAction(makeShortcutAction(tr("Label Current Address"), SLOT(setLabelSlot()), "ActionSetLabel"));
QAction* labelAddress = makeShortcutAction(tr("Label"), SLOT(setLabelAddressSlot()), "ActionSetLabelOperand");
labelMenu->addAction(labelAddress, [this, labelAddress](QMenu*)
{
BASIC_INSTRUCTION_INFO instr_info;
DbgDisasmFastAt(rvaToVa(getInitialSelection()), &instr_info);
duint addr;
if(instr_info.type & TYPE_MEMORY)
addr = instr_info.memory.value;
else if(instr_info.type & TYPE_ADDR)
addr = instr_info.addr;
else if(instr_info.type & TYPE_VALUE)
addr = instr_info.value.value;
else
return false;
labelAddress->setText(tr("Label") + " " + ToPtrString(addr));
return DbgMemIsValidReadPtr(addr);
});
mMenuBuilder->addMenu(makeMenu(DIcon("label"), tr("Label")), labelMenu);
mCommonActions->build(mMenuBuilder, CommonActions::ActionComment | CommonActions::ActionBookmark);
QAction* traceCoverageDisable = makeAction(DIcon("close-all-tabs"), tr("Disable"), SLOT(traceCoverageDisableSlot()));
QAction* traceCoverageEnableBit = makeAction(DIcon("bit"), tr("Bit"), SLOT(traceCoverageBitSlot()));
QAction* traceCoverageEnableByte = makeAction(DIcon("byte"), tr("Byte"), SLOT(traceCoverageByteSlot()));
QAction* traceCoverageEnableWord = makeAction(DIcon("word"), tr("Word"), SLOT(traceCoverageWordSlot()));
QAction* traceCoverageToggleTraceRecording = makeShortcutAction(DIcon("control-record"), tr("Start trace recording"), SLOT(traceCoverageToggleTraceRecordingSlot()), "ActionToggleRunTrace");
mMenuBuilder->addMenu(makeMenu(DIcon("trace"), tr("Trace coverage")), [ = ](QMenu * menu)
{
if(DbgFunctions()->GetTraceRecordType(rvaToVa(getInitialSelection())) == TRACERECORDTYPE::TraceRecordNone)
{
menu->addAction(traceCoverageEnableBit);
menu->addAction(traceCoverageEnableByte);
menu->addAction(traceCoverageEnableWord);
}
else
menu->addAction(traceCoverageDisable);
menu->addSeparator();
if(TraceBrowser::isRecording())
{
traceCoverageToggleTraceRecording->setText(tr("Stop trace recording"));
traceCoverageToggleTraceRecording->setIcon(DIcon("control-stop"));
}
else
{
traceCoverageToggleTraceRecording->setText(tr("Start trace recording"));
traceCoverageToggleTraceRecording->setIcon(DIcon("control-record"));
}
menu->addAction(traceCoverageToggleTraceRecording);
return true;
});
mMenuBuilder->addSeparator();
MenuBuilder* analysisMenu = new MenuBuilder(this);
QAction* toggleFunctionAction = makeShortcutAction(DIcon("functions"), tr("Function"), SLOT(toggleFunctionSlot()), "ActionToggleFunction");
analysisMenu->addAction(makeShortcutAction(DIcon("analyzemodule"), tr("Analyze module"), SLOT(analyzeModuleSlot()), "ActionAnalyzeModule"));
analysisMenu->addAction(toggleFunctionAction, [this, toggleFunctionAction](QMenu*)
{
if(!DbgFunctionOverlaps(rvaToVa(getSelectionStart()), rvaToVa(getSelectionEnd())))
toggleFunctionAction->setText(tr("Add function"));
else
toggleFunctionAction->setText(tr("Delete function"));
return true;
});
QAction* toggleArgumentAction = makeShortcutAction(DIcon("arguments"), tr("Argument"), SLOT(toggleArgumentSlot()), "ActionToggleArgument");
analysisMenu->addAction(toggleArgumentAction, [this, toggleArgumentAction](QMenu*)
{
if(!DbgArgumentOverlaps(rvaToVa(getSelectionStart()), rvaToVa(getSelectionEnd())))
toggleArgumentAction->setText(tr("Add argument"));
else
toggleArgumentAction->setText(tr("Delete argument"));
return true;
});
analysisMenu->addAction(makeShortcutAction(tr("Add loop"), SLOT(addLoopSlot()), "ActionAddLoop"));
analysisMenu->addAction(makeShortcutAction(tr("Delete loop"), SLOT(deleteLoopSlot()), "ActionDeleteLoop"), [this](QMenu*)
{
return findDeepestLoopDepth(rvaToVa(getSelectionStart())) >= 0;
});
analysisMenu->addAction(makeShortcutAction(DIcon("analysis_single_function"), tr("Analyze single function"), SLOT(analyzeSingleFunctionSlot()), "ActionAnalyzeSingleFunction"));
analysisMenu->addSeparator();
analysisMenu->addAction(makeShortcutAction(DIcon("remove_analysis_from_module"), tr("Remove type analysis from module"), SLOT(removeAnalysisModuleSlot()), "ActionRemoveTypeAnalysisFromModule"));
analysisMenu->addAction(makeShortcutAction(DIcon("remove_analysis_from_selection"), tr("Remove type analysis from selection"), SLOT(removeAnalysisSelectionSlot()), "ActionRemoveTypeAnalysisFromSelection"));
analysisMenu->addSeparator();
QMenu* encodeTypeMenu = makeMenu(DIcon("treat_selection_head_as"), tr("Treat selection &head as"));
QMenu* encodeTypeRangeMenu = makeMenu(DIcon("treat_from_selection_as"), tr("Treat from &selection as"));
const char* strTable[] = {"Code", "Byte", "Word", "Dword", "Fword", "Qword", "Tbyte", "Oword", nullptr,
"Float", "Double", "Long Double", nullptr,
"ASCII", "UNICODE", nullptr,
"MMWord", "XMMWord", "YMMWord"
};
const char* shortcutTable[] = {"Code", "Byte", "Word", "Dword", "Fword", "Qword", "Tbyte", "Oword", nullptr,
"Float", "Double", "LongDouble", nullptr,
"ASCII", "UNICODE", nullptr,
"MMWord", "XMMWord", "YMMWord"
};
const char* iconTable[] = {"cmd", "byte", "word", "dword", "fword", "qword", "tbyte", "oword", nullptr,
"float", "double", "longdouble", nullptr,
"ascii", "unicode", nullptr,
"mmword", "xmm", "ymm"
};
ENCODETYPE enctypeTable[] = {enc_code, enc_byte, enc_word, enc_dword, enc_fword, enc_qword, enc_tbyte, enc_oword, enc_middle,
enc_real4, enc_real8, enc_real10, enc_middle,
enc_ascii, enc_unicode, enc_middle,
enc_mmword, enc_xmmword, enc_ymmword
};
int enctypesize = sizeof(enctypeTable) / sizeof(ENCODETYPE);
for(int i = 0; i < enctypesize; i++)
{
if(enctypeTable[i] == enc_middle)
{
encodeTypeRangeMenu->addSeparator();
encodeTypeMenu->addSeparator();
}
else
{
QAction* action;
QIcon icon;
if(iconTable[i])
icon = DIcon(QString("treat_selection_as_%1").arg(iconTable[i]));
if(shortcutTable[i])
action = makeShortcutAction(icon, tr(strTable[i]), SLOT(setEncodeTypeRangeSlot()), QString("ActionTreatSelectionAs%1").arg(shortcutTable[i]).toUtf8().constData());
else
action = makeAction(icon, tr(strTable[i]), SLOT(setEncodeTypeRangeSlot()));
action->setData(enctypeTable[i]);
encodeTypeRangeMenu->addAction(action);
if(shortcutTable[i])
action = makeShortcutAction(icon, tr(strTable[i]), SLOT(setEncodeTypeSlot()), QString("ActionTreatSelectionHeadAs%1").arg(shortcutTable[i]).toUtf8().constData());
else
action = makeAction(icon, tr(strTable[i]), SLOT(setEncodeTypeSlot()));
action->setData(enctypeTable[i]);
encodeTypeMenu->addAction(action);
}
}
analysisMenu->addMenu(encodeTypeRangeMenu);
analysisMenu->addMenu(encodeTypeMenu);
mMenuBuilder->addMenu(makeMenu(DIcon("analysis"), tr("Analysis")), analysisMenu);
mMenuBuilder->addAction(makeShortcutAction(DIcon("pdb"), tr("Download Symbols for This Module"), SLOT(downloadCurrentSymbolsSlot()), "ActionDownloadSymbol"), [this](QMenu*)
{
//only show this action in system modules (generally user modules don't have downloadable symbols)
return DbgFunctions()->ModGetParty(rvaToVa(getInitialSelection())) == 1;
});
mMenuBuilder->addSeparator();
mMenuBuilder->addAction(makeShortcutAction(DIcon("compile"), tr("Assemble"), SLOT(assembleSlot()), "ActionAssemble"));
removeAction(mMenuBuilder->addAction(makeShortcutAction(DIcon("patch"), tr("Patches"), SLOT(showPatchesSlot()), "ViewPatches"))); //prevent conflicting shortcut with the MainWindow
mMenuBuilder->addSeparator();
mCommonActions->build(mMenuBuilder, CommonActions::ActionNewOrigin | CommonActions::ActionNewThread);
MenuBuilder* gotoMenu = new MenuBuilder(this);
gotoMenu->addAction(makeShortcutAction(DIcon("cbp"), ArchValue("EIP", "RIP"), SLOT(gotoOriginSlot()), "ActionGotoOrigin"));
gotoMenu->addAction(makeShortcutAction(DIcon("previous"), tr("Previous"), SLOT(gotoPreviousSlot()), "ActionGotoPrevious"), [this](QMenu*)
{
return historyHasPrevious();
});
gotoMenu->addAction(makeShortcutAction(DIcon("next"), tr("Next"), SLOT(gotoNextSlot()), "ActionGotoNext"), [this](QMenu*)
{
return historyHasNext();
});
gotoMenu->addAction(makeShortcutAction(DIcon("geolocation-goto"), tr("Expression"), SLOT(gotoExpressionSlot()), "ActionGotoExpression"));
gotoMenu->addAction(makeShortcutAction(DIcon("fileoffset"), tr("File Offset"), SLOT(gotoFileOffsetSlot()), "ActionGotoFileOffset"), [this](QMenu*)
{
char modname[MAX_MODULE_SIZE] = "";
return DbgGetModuleAt(rvaToVa(getInitialSelection()), modname);
});
gotoMenu->addAction(makeShortcutAction(DIcon("top"), tr("Start of Page"), SLOT(gotoStartSlot()), "ActionGotoStart"));
gotoMenu->addAction(makeShortcutAction(DIcon("bottom"), tr("End of Page"), SLOT(gotoEndSlot()), "ActionGotoEnd"));
gotoMenu->addAction(makeShortcutAction(DIcon("functionstart"), tr("Start of Function"), SLOT(gotoFunctionStartSlot()), "ActionGotoFunctionStart"), [this](QMenu*)
{
return DbgFunctionGet(rvaToVa(getInitialSelection()), nullptr, nullptr);
});
gotoMenu->addAction(makeShortcutAction(DIcon("functionend"), tr("End of Function"), SLOT(gotoFunctionEndSlot()), "ActionGotoFunctionEnd"), [this](QMenu*)
{
return DbgFunctionGet(rvaToVa(getInitialSelection()), nullptr, nullptr);
});
gotoMenu->addAction(makeShortcutAction(DIcon("prevref"), tr("Previous Reference"), SLOT(gotoPreviousReferenceSlot()), "ActionGotoPreviousReference"), [](QMenu*)
{
return !!DbgEval("refsearch.count() && ($__disasm_refindex > 0 || dis.sel() != refsearch.addr($__disasm_refindex))");
});
gotoMenu->addAction(makeShortcutAction(DIcon("nextref"), tr("Next Reference"), SLOT(gotoNextReferenceSlot()), "ActionGotoNextReference"), [](QMenu*)
{
return !!DbgEval("refsearch.count() && ($__disasm_refindex < refsearch.count()|| dis.sel() != refsearch.addr($__disasm_refindex))");
});
mMenuBuilder->addMenu(makeMenu(DIcon("goto"), tr("Go to")), gotoMenu);
mMenuBuilder->addSeparator();
mMenuBuilder->addAction(makeShortcutAction(DIcon("xrefs"), tr("xrefs..."), SLOT(gotoXrefSlot()), "ActionXrefs"), [this](QMenu*)
{
return mXrefInfo.refcount > 0;
});
MenuBuilder* searchMenu = new MenuBuilder(this);
MenuBuilder* mSearchRegionMenu = new MenuBuilder(this);
MenuBuilder* mSearchModuleMenu = new MenuBuilder(this, [this](QMenu*)
{
return DbgFunctions()->ModBaseFromAddr(rvaToVa(getInitialSelection())) != 0;
});
MenuBuilder* mSearchFunctionMenu = new MenuBuilder(this, [this](QMenu*)
{
duint start, end;
return DbgFunctionGet(rvaToVa(getInitialSelection()), &start, &end);
});
MenuBuilder* mSearchAllMenu = new MenuBuilder(this);
MenuBuilder* mSearchAllUserMenu = new MenuBuilder(this);
MenuBuilder* mSearchAllSystemMenu = new MenuBuilder(this);
// Search in Current Region menu
mFindCommandRegion = makeShortcutAction(DIcon("search_for_command"), tr("C&ommand"), SLOT(findCommandSlot()), "ActionFind");
mFindConstantRegion = makeAction(DIcon("search_for_constant"), tr("&Constant"), SLOT(findConstantSlot()));
mFindStringsRegion = makeAction(DIcon("search_for_string"), tr("&String references"), SLOT(findStringsSlot()));
mFindCallsRegion = makeAction(DIcon("call"), tr("&Intermodular calls"), SLOT(findCallsSlot()));
mFindPatternRegion = makeShortcutAction(DIcon("search_for_pattern"), tr("&Pattern"), SLOT(findPatternSlot()), "ActionFindPattern");
mFindGUIDRegion = makeAction(DIcon("guid"), tr("&GUID"), SLOT(findGUIDSlot()));
mSearchRegionMenu->addAction(mFindCommandRegion);
mSearchRegionMenu->addAction(mFindConstantRegion);
mSearchRegionMenu->addAction(mFindStringsRegion);
mSearchRegionMenu->addAction(mFindCallsRegion);
mSearchRegionMenu->addAction(mFindPatternRegion);
mSearchRegionMenu->addAction(mFindGUIDRegion);
// Search in Current Module menu
mFindCommandModule = makeShortcutAction(DIcon("search_for_command"), tr("C&ommand"), SLOT(findCommandSlot()), "ActionFindInModule");
mFindConstantModule = makeAction(DIcon("search_for_constant"), tr("&Constant"), SLOT(findConstantSlot()));
mFindStringsModule = makeShortcutAction(DIcon("search_for_string"), tr("&String references"), SLOT(findStringsSlot()), "ActionFindStringsModule");
mFindCallsModule = makeAction(DIcon("call"), tr("&Intermodular calls"), SLOT(findCallsSlot()));
mFindPatternModule = makeShortcutAction(DIcon("search_for_pattern"), tr("&Pattern"), SLOT(findPatternSlot()), "ActionFindPatternInModule");
mFindGUIDModule = makeAction(DIcon("guid"), tr("&GUID"), SLOT(findGUIDSlot()));
mFindNamesModule = makeShortcutAction(DIcon("names"), tr("&Names"), SLOT(findNamesSlot()), "ActionFindNamesInModule");
mSearchModuleMenu->addAction(mFindCommandModule);
mSearchModuleMenu->addAction(mFindConstantModule);
mSearchModuleMenu->addAction(mFindStringsModule);
mSearchModuleMenu->addAction(mFindCallsModule);
mSearchModuleMenu->addAction(mFindPatternModule);
mSearchModuleMenu->addAction(mFindGUIDModule);
mSearchModuleMenu->addAction(mFindNamesModule);
// Search in Current Function menu
mFindCommandFunction = makeAction(DIcon("search_for_command"), tr("C&ommand"), SLOT(findCommandSlot()));
mFindConstantFunction = makeAction(DIcon("search_for_constant"), tr("&Constant"), SLOT(findConstantSlot()));
mFindStringsFunction = makeAction(DIcon("search_for_string"), tr("&String references"), SLOT(findStringsSlot()));
mFindCallsFunction = makeAction(DIcon("call"), tr("&Intermodular calls"), SLOT(findCallsSlot()));
mFindPatternFunction = makeAction(DIcon("search_for_pattern"), tr("&Pattern"), SLOT(findPatternSlot()));
mFindGUIDFunction = makeAction(DIcon("guid"), tr("&GUID"), SLOT(findGUIDSlot()));
mSearchFunctionMenu->addAction(mFindCommandFunction);
mSearchFunctionMenu->addAction(mFindConstantFunction);
mSearchFunctionMenu->addAction(mFindStringsFunction);
mSearchFunctionMenu->addAction(mFindCallsFunction);
mSearchFunctionMenu->addAction(mFindPatternFunction);
mSearchFunctionMenu->addAction(mFindGUIDFunction);
// Search in All User Modules menu
mFindCommandAllUser = makeAction(DIcon("search_for_command"), tr("C&ommand"), SLOT(findCommandSlot()));
mFindConstantAllUser = makeAction(DIcon("search_for_constant"), tr("&Constant"), SLOT(findConstantSlot()));
mFindStringsAllUser = makeAction(DIcon("search_for_string"), tr("&String references"), SLOT(findStringsSlot()));
mFindCallsAllUser = makeAction(DIcon("call"), tr("&Intermodular calls"), SLOT(findCallsSlot()));
mFindPatternAllUser = makeAction(DIcon("search_for_pattern"), tr("&Pattern"), SLOT(findPatternSlot()));
mFindGUIDAllUser = makeAction(DIcon("guid"), tr("&GUID"), SLOT(findGUIDSlot()));
mSearchAllUserMenu->addAction(mFindCommandAllUser);
mSearchAllUserMenu->addAction(mFindConstantAllUser);
mSearchAllUserMenu->addAction(mFindStringsAllUser);
mSearchAllUserMenu->addAction(mFindCallsAllUser);
mSearchAllUserMenu->addAction(mFindPatternAllUser);
mSearchAllUserMenu->addAction(mFindGUIDAllUser);
// Search in All System Modules menu
mFindCommandAllSystem = makeAction(DIcon("search_for_command"), tr("C&ommand"), SLOT(findCommandSlot()));
mFindConstantAllSystem = makeAction(DIcon("search_for_constant"), tr("&Constant"), SLOT(findConstantSlot()));
mFindStringsAllSystem = makeAction(DIcon("search_for_string"), tr("&String references"), SLOT(findStringsSlot()));
mFindCallsAllSystem = makeAction(DIcon("call"), tr("&Intermodular calls"), SLOT(findCallsSlot()));
mFindPatternAllSystem = makeAction(DIcon("search_for_pattern"), tr("&Pattern"), SLOT(findPatternSlot()));
mFindGUIDAllSystem = makeAction(DIcon("guid"), tr("&GUID"), SLOT(findGUIDSlot()));
mSearchAllSystemMenu->addAction(mFindCommandAllSystem);
mSearchAllSystemMenu->addAction(mFindConstantAllSystem);
mSearchAllSystemMenu->addAction(mFindStringsAllSystem);
mSearchAllSystemMenu->addAction(mFindCallsAllSystem);
mSearchAllSystemMenu->addAction(mFindPatternAllSystem);
mSearchAllSystemMenu->addAction(mFindGUIDAllSystem);
// Search in All Modules menu
mFindCommandAll = makeAction(DIcon("search_for_command"), tr("C&ommand"), SLOT(findCommandSlot()));
mFindConstantAll = makeAction(DIcon("search_for_constant"), tr("&Constant"), SLOT(findConstantSlot()));
mFindStringsAll = makeAction(DIcon("search_for_string"), tr("&String references"), SLOT(findStringsSlot()));
mFindCallsAll = makeAction(DIcon("call"), tr("&Intermodular calls"), SLOT(findCallsSlot()));
mFindPatternAll = makeAction(DIcon("search_for_pattern"), tr("&Pattern"), SLOT(findPatternSlot()));
mFindGUIDAll = makeAction(DIcon("guid"), tr("&GUID"), SLOT(findGUIDSlot()));
mSearchAllMenu->addAction(mFindCommandAll);
mSearchAllMenu->addAction(mFindConstantAll);
mSearchAllMenu->addAction(mFindStringsAll);
mSearchAllMenu->addAction(mFindCallsAll);
mSearchAllMenu->addAction(mFindPatternAll);
mSearchAllMenu->addAction(mFindGUIDAll);
searchMenu->addMenu(makeMenu(DIcon("search_current_region"), tr("Current Region")), mSearchRegionMenu);
searchMenu->addMenu(makeMenu(DIcon("search_current_module"), tr("Current Module")), mSearchModuleMenu);
QMenu* searchFunctionMenu = makeMenu(tr("Current Function"));
searchMenu->addMenu(searchFunctionMenu, mSearchFunctionMenu);
searchMenu->addMenu(makeMenu(DIcon("search_all_modules"), tr("All User Modules")), mSearchAllUserMenu);
searchMenu->addMenu(makeMenu(DIcon("search_all_modules"), tr("All System Modules")), mSearchAllSystemMenu);
searchMenu->addMenu(makeMenu(DIcon("search_all_modules"), tr("All Modules")), mSearchAllMenu);
mMenuBuilder->addMenu(makeMenu(DIcon("search-for"), tr("&Search for")), searchMenu);
mReferenceSelectedAddressAction = makeShortcutAction(tr("&Selected Address(es)"), SLOT(findReferencesSlot()), "ActionFindReferencesToSelectedAddress");
mMenuBuilder->addMenu(makeMenu(DIcon("find"), tr("Find &references to")), [this](QMenu * menu)
{
setupFollowReferenceMenu(rvaToVa(getInitialSelection()), menu, true, false);
return true;
});
// Plugins
if(mIsMain)
{
mPluginMenu = new QMenu(this);
Bridge::getBridge()->emitMenuAddToList(this, mPluginMenu, GUI_DISASM_MENU);
}
mMenuBuilder->addSeparator();
mMenuBuilder->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
DbgMenuPrepare(GUI_DISASM_MENU);
if(mIsMain)
{
menu->addActions(mPluginMenu->actions());
}
return true;
}));
// Highlight menu
mHighlightMenuBuilder = new MenuBuilder(this);
mHighlightMenuBuilder->addAction(makeAction(DIcon("copy"), tr("Copy token &text"), SLOT(copyTokenTextSlot())));
mHighlightMenuBuilder->addAction(makeAction(DIcon("copy_address"), tr("Copy token &value"), SLOT(copyTokenValueSlot())), [this](QMenu*)
{
QString text;
if(!getTokenValueText(text))
return false;
return text != mHighlightToken.text;
});
mMenuBuilder->loadFromConfig();
}
void CPUDisassembly::gotoOriginSlot()
{
if(!DbgIsDebugging())
return;
gotoAddress(DbgValFromString("cip"));
}
void CPUDisassembly::setLabelSlot()
{
if(!DbgIsDebugging())
return;
duint wVA = rvaToVa(getInitialSelection());
LineEditDialog mLineEdit(this);
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, this);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::No)
goto restart;
}
if(!DbgSetLabelAt(wVA, utf8data.constData()))
SimpleErrorBox(this, tr("Error!"), tr("DbgSetLabelAt failed!"));
GuiUpdateAllViews();
}
void CPUDisassembly::setLabelAddressSlot()
{
if(!DbgIsDebugging())
return;
BASIC_INSTRUCTION_INFO instr_info;
DbgDisasmFastAt(rvaToVa(getInitialSelection()), &instr_info);
duint addr;
if(instr_info.type & TYPE_MEMORY)
addr = instr_info.memory.value;
else if(instr_info.type & TYPE_ADDR)
addr = instr_info.addr;
else if(instr_info.type & TYPE_VALUE)
addr = instr_info.value.value;
else
return;
if(!DbgMemIsValidReadPtr(addr))
return;
LineEditDialog mLineEdit(this);
mLineEdit.setTextMaxLength(MAX_LABEL_SIZE - 2);
QString addr_text = ToPtrString(addr);
char label_text[MAX_LABEL_SIZE] = "";
if(DbgGetLabelAt(addr, 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()) != addr)
{
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, this);
msg.setWindowIcon(DIcon("compile-warning"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::No)
goto restart;
}
if(!DbgSetLabelAt(addr, utf8data.constData()))
SimpleErrorBox(this, tr("Error!"), tr("DbgSetLabelAt failed!"));
GuiUpdateAllViews();
}
void CPUDisassembly::toggleFunctionSlot()
{
if(!DbgIsDebugging())
return;
duint start = rvaToVa(getSelectionStart());
duint end = rvaToVa(getSelectionEnd());
duint function_start = 0;
duint function_end = 0;
if(!DbgFunctionOverlaps(start, end))
{
QString cmd = QString("functionadd ") + ToPtrString(start) + "," + ToPtrString(end);
DbgCmdExec(cmd);
}
else
{
for(duint i = start; i <= end; i++)
{
if(DbgFunctionGet(i, &function_start, &function_end))
break;
}
QString cmd = QString("functiondel ") + ToPtrString(function_start);
DbgCmdExec(cmd);
}
}
void CPUDisassembly::toggleArgumentSlot()
{
if(!DbgIsDebugging())
return;
duint start = rvaToVa(getSelectionStart());
duint end = rvaToVa(getSelectionEnd());
duint argument_start = 0;
duint argument_end = 0;
if(!DbgArgumentOverlaps(start, end))
{
QString start_text = ToPtrString(start);
QString end_text = ToPtrString(end);
QString cmd = "argumentadd " + start_text + "," + end_text;
DbgCmdExec(cmd);
}
else
{
for(duint i = start; i <= end; i++)
{
if(DbgArgumentGet(i, &argument_start, &argument_end))
break;
}
QString start_text = ToPtrString(argument_start);
QString cmd = "argumentdel " + start_text;
DbgCmdExec(cmd);
}
}
void CPUDisassembly::addLoopSlot()
{
if(!DbgIsDebugging())
return;
duint start = rvaToVa(getSelectionStart());
duint end = rvaToVa(getSelectionEnd());
if(start == end)
return;
auto depth = findDeepestLoopDepth(start);
DbgCmdExec(QString("loopadd %1, %2").arg(ToPtrString(start)).arg(ToPtrString(end)).arg(depth));
}
void CPUDisassembly::deleteLoopSlot()
{
if(!DbgIsDebugging())
return;
duint start = rvaToVa(getSelectionStart());
auto depth = findDeepestLoopDepth(start);
if(depth < 0)
return;
DbgCmdExec(QString("loopdel %1, .%2").arg(ToPtrString(start)).arg(depth));
}
void CPUDisassembly::assembleSlot()
{
if(!DbgIsDebugging())
return;
AssembleDialog assembleDialog(this);
do
{
dsint wRVA = getInitialSelection();
duint wVA = rvaToVa(wRVA);
unfold(wRVA);
QString addr_text = ToPtrString(wVA);
Instruction_t instr = this->DisassembleAt(wRVA);
QString actual_inst = instr.instStr;
bool assembly_error;
do
{
char error[MAX_ERROR_SIZE] = "";
assembly_error = false;
assembleDialog.setSelectedInstrVa(wVA);
if(ConfigBool("Disassembler", "Uppercase"))
actual_inst = actual_inst.toUpper().replace(QRegularExpression("0X([0-9A-F]+)"), "0x\\1");
assembleDialog.setTextEditValue(actual_inst);
assembleDialog.setWindowTitle(tr("Assemble at %1").arg(addr_text));
assembleDialog.setFillWithNopsChecked(ConfigBool("Disassembler", "FillNOPs"));
assembleDialog.setKeepSizeChecked(ConfigBool("Disassembler", "KeepSize"));
auto exec = assembleDialog.exec();
Config()->setBool("Disassembler", "FillNOPs", assembleDialog.bFillWithNopsChecked);
Config()->setBool("Disassembler", "KeepSize", assembleDialog.bKeepSizeChecked);
if(exec != QDialog::Accepted)
return;
//sanitize the expression (just simplifying it by removing excess whitespaces)
auto expression = assembleDialog.editText.simplified();
//if the instruction its unknown or is the old instruction or empty (easy way to skip from GUI) skipping
if(expression == QString("???") || expression.toLower() == instr.instStr.toLower() || expression == QString(""))
break;
if(!DbgFunctions()->AssembleAtEx(wVA, expression.toUtf8().constData(), error, assembleDialog.bFillWithNopsChecked))
{
QMessageBox msg(QMessageBox::Critical, tr("Error!"), tr("Failed to assemble instruction \" %1 \" (%2)").arg(expression).arg(error));
msg.setWindowIcon(DIcon("compile-error"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.exec();
actual_inst = expression;
assembly_error = true;
}
}
while(assembly_error);
//select next instruction after assembling
setSingleSelection(wRVA);
dsint botRVA = getTableOffset();
dsint topRVA = getInstructionRVA(getTableOffset(), getNbrOfLineToPrint() - 1);
dsint wInstrSize = getInstructionRVA(wRVA, 1) - wRVA - 1;
expandSelectionUpTo(wRVA + wInstrSize);
selectNext(false);
if(getSelectionStart() < botRVA)
setTableOffset(getSelectionStart());
else if(getSelectionEnd() >= topRVA)
setTableOffset(getInstructionRVA(getSelectionEnd(), -getNbrOfLineToPrint() + 2));
//refresh view
GuiUpdateAllViews();
}
while(1);
}
void CPUDisassembly::gotoExpressionSlot()
{
if(!DbgIsDebugging())
return;
if(!mGoto)
mGoto = new GotoDialog(this);
mGoto->setInitialExpression(ToPtrString(rvaToVa(getInitialSelection())));
if(mGoto->exec() == QDialog::Accepted)
{
duint value = DbgValFromString(mGoto->expressionText.toUtf8().constData());
gotoAddress(value);
}
}
void CPUDisassembly::gotoFileOffsetSlot()
{
if(!DbgIsDebugging())
return;
char modname[MAX_MODULE_SIZE] = "";
if(!DbgFunctions()->ModNameFromAddr(rvaToVa(getInitialSelection()), modname, true))
{
QMessageBox::critical(this, tr("Error!"), tr("Not inside a module..."));
return;
}
if(!mGotoOffset)
mGotoOffset = new GotoDialog(this);
mGotoOffset->fileOffset = true;
mGotoOffset->modName = QString(modname);
mGotoOffset->setWindowTitle(tr("Goto File Offset in ") + QString(modname));
QString offsetOfSelected;
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int, const Instruction_t & inst)
{
duint addr = rvaToVa(inst.rva);
duint offset = DbgFunctions()->VaToFileOffset(addr);
if(offset)
offsetOfSelected = ToHexString(offset);
return false;
});
if(!offsetOfSelected.isEmpty())
mGotoOffset->setInitialExpression(offsetOfSelected);
if(mGotoOffset->exec() != QDialog::Accepted)
return;
duint value = DbgValFromString(mGotoOffset->expressionText.toUtf8().constData());
value = DbgFunctions()->FileOffsetToVa(modname, value);
gotoAddress(value);
}
void CPUDisassembly::gotoStartSlot()
{
duint dest = mMemPage->getBase();
gotoAddress(dest);
}
void CPUDisassembly::gotoEndSlot()
{
duint dest = mMemPage->getBase() + mMemPage->getSize() - (getViewableRowsCount() * 16);
gotoAddress(dest);
}
void CPUDisassembly::gotoFunctionStartSlot()
{
duint start;
if(!DbgFunctionGet(rvaToVa(getInitialSelection()), &start, nullptr))
return;
gotoAddress(start);
}
void CPUDisassembly::gotoFunctionEndSlot()
{
duint end;
if(!DbgFunctionGet(rvaToVa(getInitialSelection()), nullptr, &end))
return;
gotoAddress(end);
}
void CPUDisassembly::gotoPreviousReferenceSlot()
{
auto count = DbgEval("refsearch.count()"), index = DbgEval("$__disasm_refindex"), addr = DbgEval("refsearch.addr($__disasm_refindex)");
if(count)
{
if(index > 0 && addr == rvaToVa(getInitialSelection()))
DbgValToString("$__disasm_refindex", index - 1);
gotoAddress(DbgValFromString("refsearch.addr($__disasm_refindex)"));
GuiReferenceSetSingleSelection(int(DbgEval("$__disasm_refindex")), false);
}
}
void CPUDisassembly::gotoNextReferenceSlot()
{
auto count = DbgEval("refsearch.count()"), index = DbgEval("$__disasm_refindex"), addr = DbgEval("refsearch.addr($__disasm_refindex)");
if(count)
{
if(index + 1 < count && addr == rvaToVa(getInitialSelection()))
DbgValToString("$__disasm_refindex", index + 1);
gotoAddress(DbgValFromString("refsearch.addr($__disasm_refindex)"));
GuiReferenceSetSingleSelection(int(DbgEval("$__disasm_refindex")), false);
}
}
void CPUDisassembly::gotoXrefSlot()
{
if(!DbgIsDebugging() || !mXrefInfo.refcount)
return;
if(!mXrefDlg)
mXrefDlg = new XrefBrowseDialog(this);
mXrefDlg->setup(getSelectedVa(), [this](duint addr)
{
gotoAddress(addr);
});
mXrefDlg->showNormal();
}
void CPUDisassembly::followActionSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(!action)
return;
if(action->objectName().startsWith("DUMP|"))
DbgCmdExec(QString().sprintf("dump \"%s\"", action->objectName().mid(5).toUtf8().constData()));
else if(action->objectName().startsWith("REF|"))
{
QString addrText = ToPtrString(rvaToVa(getInitialSelection()));
QString value = action->objectName().mid(4);
DbgCmdExec(QString("findref \"" + value + "\", " + addrText));
emit displayReferencesWidget();
}
else if(action->objectName().startsWith("CPU|"))
{
QString value = action->objectName().mid(4);
gotoAddress(DbgValFromString(value.toUtf8().constData()));
}
}
void CPUDisassembly::gotoPreviousSlot()
{
historyPrevious();
}
void CPUDisassembly::gotoNextSlot()
{
historyNext();
}
void CPUDisassembly::findReferencesSlot()
{
QString addrStart = ToPtrString(rvaToVa(getSelectionStart()));
QString addrEnd = ToPtrString(rvaToVa(getSelectionEnd()));
QString addrDisasm = ToPtrString(rvaToVa(getInitialSelection()));
DbgCmdExec(QString("findrefrange " + addrStart + ", " + addrEnd + ", " + addrDisasm));
emit displayReferencesWidget();
}
void CPUDisassembly::findConstantSlot()
{
int refFindType = 0;
if(sender() == mFindConstantRegion)
refFindType = 0;
else if(sender() == mFindConstantModule)
refFindType = 1;
else if(sender() == mFindConstantAll)
refFindType = 2;
else if(sender() == mFindConstantAllUser)
refFindType = 3;
else if(sender() == mFindConstantAllSystem)
refFindType = 4;
else if(sender() == mFindConstantFunction)
refFindType = -1;
WordEditDialog wordEdit(this);
wordEdit.setup(tr("Enter Constant"), 0, sizeof(dsint));
if(wordEdit.exec() != QDialog::Accepted) //cancel pressed
return;
auto addrText = ToHexString(rvaToVa(getInitialSelection()));
auto constText = ToHexString(wordEdit.getVal());
if(refFindType != -1)
DbgCmdExec(QString("findref %1, %2, 0, %3").arg(constText).arg(addrText).arg(refFindType));
else
{
duint start, end;
if(DbgFunctionGet(rvaToVa(getInitialSelection()), &start, &end))
DbgCmdExec(QString("findref %1, %2, %3, 0").arg(constText).arg(ToPtrString(start)).arg(ToPtrString(end - start)));
}
emit displayReferencesWidget();
}
void CPUDisassembly::findStringsSlot()
{
int refFindType = 0;
if(sender() == mFindStringsRegion)
refFindType = 0;
else if(sender() == mFindStringsModule)
refFindType = 1;
else if(sender() == mFindStringsAll)
refFindType = 2;
else if(sender() == mFindStringsAllUser)
refFindType = 3;
else if(sender() == mFindStringsAllSystem)
refFindType = 4;
else if(sender() == mFindStringsFunction)
{
duint start, end;
if(DbgFunctionGet(rvaToVa(getInitialSelection()), &start, &end))
DbgCmdExec(QString("strref %1, %2, 0").arg(ToPtrString(start)).arg(ToPtrString(end - start)));
return;
}
auto addrText = ToHexString(rvaToVa(getInitialSelection()));
DbgCmdExec(QString("strref %1, 0, %2").arg(addrText).arg(refFindType));
emit displayReferencesWidget();
}
void CPUDisassembly::findCallsSlot()
{
int refFindType = 0;
if(sender() == mFindCallsRegion)
refFindType = 0;
else if(sender() == mFindCallsModule)
refFindType = 1;
else if(sender() == mFindCallsAll)
refFindType = 2;
else if(sender() == mFindCallsAllUser)
refFindType = 3;
else if(sender() == mFindCallsAllSystem)
refFindType = 4;
else if(sender() == mFindCallsFunction)
refFindType = -1;
auto addrText = ToHexString(rvaToVa(getInitialSelection()));
if(refFindType != -1)
DbgCmdExec(QString("modcallfind %1, 0, %2").arg(addrText).arg(refFindType));
else
{
duint start, end;
if(DbgFunctionGet(rvaToVa(getInitialSelection()), &start, &end))
DbgCmdExec(QString("modcallfind %1, %2, 0").arg(ToPtrString(start)).arg(ToPtrString(end - start)));
}
emit displayReferencesWidget();
}
void CPUDisassembly::findPatternSlot()
{
HexEditDialog hexEdit(this);
hexEdit.showEntireBlock(true);
hexEdit.isDataCopiable(false);
hexEdit.mHexEdit->setOverwriteMode(false);
hexEdit.setWindowTitle(tr("Find Pattern..."));
if(hexEdit.exec() != QDialog::Accepted)
return;
dsint addr = rvaToVa(getSelectionStart());
if(hexEdit.entireBlock())
addr = DbgMemFindBaseAddr(addr, 0);
QString command;
if(sender() == mFindPatternRegion)
{
command = QString("findall %1, %2").arg(ToHexString(addr), hexEdit.mHexEdit->pattern());
}
else if(sender() == mFindPatternModule)
{
auto base = DbgFunctions()->ModBaseFromAddr(addr);
if(base)
command = QString("findallmem %1, %2, %3").arg(ToHexString(base), hexEdit.mHexEdit->pattern(), ToHexString(DbgFunctions()->ModSizeFromAddr(base)));
else
return;
}
else if(sender() == mFindPatternFunction)
{
duint start, end;
if(DbgFunctionGet(addr, &start, &end))
command = QString("findall %1, %2, %3").arg(ToPtrString(start), hexEdit.mHexEdit->pattern(), ToPtrString(end - start));
else
return;
}
else if(sender() == mFindPatternAll)
{
command = QString("findallmem 0, %1, &data&, module").arg(hexEdit.mHexEdit->pattern());
}
else if(sender() == mFindPatternAllUser)
{
command = QString("findallmem 0, %1, &data&, user").arg(hexEdit.mHexEdit->pattern());
}
else if(sender() == mFindPatternAllSystem)
{
command = QString("findallmem 0, %1, &data&, system").arg(hexEdit.mHexEdit->pattern());
}
if(!command.length())
throw std::runtime_error("Implementation error in findPatternSlot()");
DbgCmdExec(command);
emit displayReferencesWidget();
}
void CPUDisassembly::findGUIDSlot()
{
int refFindType = 0;
if(sender() == mFindGUIDRegion)
refFindType = 0;
else if(sender() == mFindGUIDModule)
refFindType = 1;
else if(sender() == mFindGUIDAll)
refFindType = 2;
else if(sender() == mFindGUIDAllUser)
refFindType = 3;
else if(sender() == mFindGUIDAllSystem)
refFindType = 4;
else if(sender() == mFindGUIDFunction)
refFindType = -1;
auto addrText = ToHexString(rvaToVa(getInitialSelection()));
if(refFindType == -1)
{
DbgCmdExec(QString("findguid %1, 0, %2").arg(addrText, refFindType));
}
else
{
duint start, end;
if(DbgFunctionGet(rvaToVa(getInitialSelection()), &start, &end))
DbgCmdExec(QString("findguid %1, %2, 0").arg(ToPtrString(start), ToPtrString(end - start)));
}
emit displayReferencesWidget();
}
void CPUDisassembly::findNamesSlot()
{
if(sender() == mFindNamesModule)
{
auto base = DbgFunctions()->ModBaseFromAddr(rvaToVa(getInitialSelection()));
if(!base)
return;
DbgCmdExec(QString("symfollow %1").arg(ToPtrString(base)));
}
}
void CPUDisassembly::selectionGetSlot(SELECTIONDATA* selection)
{
selection->start = rvaToVa(getSelectionStart());
selection->end = rvaToVa(getSelectionEnd());
Bridge::getBridge()->setResult(BridgeResult::SelectionGet, 1);
}
void CPUDisassembly::selectionSetSlot(const SELECTIONDATA* selection)
{
dsint selMin = getBase();
dsint selMax = selMin + getSize();
dsint start = selection->start;
dsint end = selection->end;
if(start < selMin || start >= selMax || end < selMin || end >= selMax) //selection out of range
{
Bridge::getBridge()->setResult(BridgeResult::SelectionSet, 0);
return;
}
setSingleSelection(start - selMin);
expandSelectionUpTo(end - selMin);
reloadData();
Bridge::getBridge()->setResult(BridgeResult::SelectionSet, 1);
}
void CPUDisassembly::selectionUpdatedSlot()
{
QString selStart = ToPtrString(rvaToVa(getSelectionStart()));
QString selEnd = ToPtrString(rvaToVa(getSelectionEnd()));
QString info = tr("Disassembly");
char mod[MAX_MODULE_SIZE] = "";
if(DbgFunctions()->ModNameFromAddr(rvaToVa(getSelectionStart()), mod, true))
info = QString(mod) + "";
GuiAddStatusBarMessage(QString(info + ": " + selStart + " -> " + selEnd + QString().sprintf(" (0x%.8X bytes)\n", getSelectionEnd() - getSelectionStart() + 1)).toUtf8().constData());
}
void CPUDisassembly::enableHighlightingModeSlot()
{
if(mHighlightingMode)
mHighlightingMode = false;
else
mHighlightingMode = true;
reloadData();
}
void CPUDisassembly::binaryEditSlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.setWindowTitle(tr("Edit code at %1").arg(ToPtrString(rvaToVa(selStart))));
if(hexEdit.exec() != QDialog::Accepted)
return;
dsint dataSize = hexEdit.mHexEdit->data().size();
dsint newSize = selSize > dataSize ? selSize : dataSize;
data = new byte_t[newSize];
mMemPage->read(data, selStart, newSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, newSize));
mMemPage->write(patched.constData(), selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDisassembly::binaryFillSlot()
{
HexEditDialog hexEdit(this);
hexEdit.showKeepSize(false);
hexEdit.mHexEdit->setOverwriteMode(false);
dsint selStart = getSelectionStart();
hexEdit.setWindowTitle(tr("Fill code at %1").arg(ToPtrString(rvaToVa(selStart))));
if(hexEdit.exec() != QDialog::Accepted)
return;
QString pattern = hexEdit.mHexEdit->pattern();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.mHexEdit->fill(0, QString(pattern));
QByteArray patched(hexEdit.mHexEdit->data());
mMemPage->write(patched, selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDisassembly::binaryFillNopsSlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
WordEditDialog mLineEdit(this);
mLineEdit.setup(tr("Size"), selSize, sizeof(duint));
if(mLineEdit.exec() != QDialog::Accepted || !mLineEdit.getVal())
return;
selSize = mLineEdit.getVal();
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.mHexEdit->fill(0, QString("90"));
QByteArray patched(hexEdit.mHexEdit->data());
mMemPage->write(patched, selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDisassembly::binaryCopySlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
Bridge::CopyToClipboard(hexEdit.mHexEdit->pattern(true));
}
void CPUDisassembly::binaryPasteSlot()
{
if(!QApplication::clipboard()->mimeData()->hasText())
return;
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
QClipboard* clipboard = QApplication::clipboard();
hexEdit.mHexEdit->setData(clipboard->text());
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, selSize));
if(patched.size() < selSize)
selSize = patched.size();
mMemPage->write(patched.constData(), selStart, selSize);
GuiUpdateAllViews();
}
void CPUDisassembly::undoSelectionSlot()
{
dsint start = rvaToVa(getSelectionStart());
dsint end = rvaToVa(getSelectionEnd());
if(!DbgFunctions()->PatchInRange(start, end)) //nothing patched in selected range
return;
DbgFunctions()->PatchRestoreRange(start, end);
reloadData();
}
void CPUDisassembly::binaryPasteIgnoreSizeSlot()
{
if(!QApplication::clipboard()->mimeData()->hasText())
return;
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
QClipboard* clipboard = QApplication::clipboard();
hexEdit.mHexEdit->setData(clipboard->text());
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, selSize));
delete [] data;
mMemPage->write(patched.constData(), selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDisassembly::showPatchesSlot()
{
emit showPatches();
}
void CPUDisassembly::copySelectionSlot(bool copyBytes)
{
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 CPUDisassembly::copySelectionToFileSlot(bool copyBytes)
{
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 CPUDisassembly::setSideBar(CPUSideBar* sideBar)
{
mSideBar = sideBar;
}
void CPUDisassembly::pushSelectionInto(bool copyBytes, QTextStream & stream, QTextStream* htmlStream)
{
const int addressLen = getColumnWidth(0) / getCharWidth() - 1;
const int bytesLen = getColumnWidth(1) / getCharWidth() - 1;
const int disassemblyLen = getColumnWidth(2) / getCharWidth() - 1;
if(htmlStream)
*htmlStream << QString("<table style=\"border-width:0px;border-color:#000000;font-family:%1;font-size:%2px;\">").arg(font().family().toHtmlEscaped()).arg(getRowHeight());
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
stream << "\r\n";
duint cur_addr = rvaToVa(inst.rva);
QString address = getAddrText(cur_addr, 0, addressLen > sizeof(duint) * 2 + 1);
QString bytes;
QString bytesHtml;
if(copyBytes)
RichTextPainter::htmlRichText(getRichBytes(inst, false), &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;
stream << address.leftJustified(addressLen, QChar(' '), true);
if(copyBytes)
stream << " | " + bytes.leftJustified(bytesLen, QChar(' '), true);
stream << " | " + disassembly.leftJustified(disassemblyLen, QChar(' '), true) + " |" + fullComment;
if(htmlStream)
{
*htmlStream << QString("<tr><td>%1</td><td>%2</td><td>%3</td><td>").arg(address.toHtmlEscaped(), bytesHtml, htmlDisassembly);
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>";
}
}
return true;
});
if(htmlStream)
*htmlStream << "</table>";
}
void CPUDisassembly::copySelectionSlot()
{
copySelectionSlot(true);
}
void CPUDisassembly::copySelectionToFileSlot()
{
copySelectionToFileSlot(true);
}
void CPUDisassembly::copySelectionNoBytesSlot()
{
copySelectionSlot(false);
}
void CPUDisassembly::copySelectionToFileNoBytesSlot()
{
copySelectionToFileSlot(false);
}
void CPUDisassembly::copyAddressSlot()
{
QString clipboard = "";
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
clipboard += "\r\n";
clipboard += ToPtrString(rvaToVa(inst.rva));
return true;
});
Bridge::CopyToClipboard(clipboard);
}
void CPUDisassembly::copyRvaSlot()
{
QString clipboard = "";
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
clipboard += "\r\n";
duint addr = rvaToVa(inst.rva);
duint base = DbgFunctions()->ModBaseFromAddr(addr);
if(base)
clipboard += ToHexString(addr - base);
else
{
SimpleWarningBox(this, tr("Error!"), tr("Selection not in a module..."));
return false;
}
return true;
});
Bridge::CopyToClipboard(clipboard);
}
void CPUDisassembly::copyFileOffsetSlot()
{
QString clipboard = "";
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
clipboard += "\r\n";
duint addr = rvaToVa(inst.rva);
duint offset = DbgFunctions()->VaToFileOffset(addr);
if(offset)
clipboard += ToHexString(offset);
else
{
SimpleErrorBox(this, tr("Error!"), tr("Selection not in a file..."));
return false;
}
return true;
});
Bridge::CopyToClipboard(clipboard);
}
void CPUDisassembly::copyHeaderVaSlot()
{
QString clipboard = "";
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
clipboard += "\r\n";
duint addr = rvaToVa(inst.rva);
duint base = DbgFunctions()->ModBaseFromAddr(addr);
if(base)
{
auto expr = QString("mod.headerva(0x%1)").arg(ToPtrString(addr));
clipboard += ToPtrString(DbgValFromString(expr.toUtf8().constData()));
}
else
{
SimpleWarningBox(this, tr("Error!"), tr("Selection not in a module..."));
return false;
}
return true;
});
Bridge::CopyToClipboard(clipboard);
}
void CPUDisassembly::copyDisassemblySlot()
{
QString clipboard = "";
if(getSelectionEnd() - getSelectionStart() < 2048)
{
QString clipboardHtml = QString("<div style=\"font-family: %1; font-size: %2px\">").arg(font().family()).arg(getRowHeight());
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
{
clipboard += "\r\n";
clipboardHtml += "<br/>";
}
RichTextPainter::List richText;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(inst.tokens, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, &clipboardHtml, clipboard);
return true;
});
clipboardHtml += QString("</div>");
Bridge::CopyToClipboard(clipboard, clipboardHtml);
}
else
{
prepareDataRange(getSelectionStart(), getSelectionEnd(), [&](int i, const Instruction_t & inst)
{
if(i)
{
clipboard += "\r\n";
}
RichTextPainter::List richText;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(inst.tokens, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(inst.tokens, richText, 0);
RichTextPainter::htmlRichText(richText, nullptr, clipboard);
return true;
});
Bridge::CopyToClipboard(clipboard);
}
}
void CPUDisassembly::labelCopySlot()
{
QString symbol = ((QAction*)sender())->text();
Bridge::CopyToClipboard(symbol);
}
void CPUDisassembly::findCommandSlot()
{
if(!DbgIsDebugging())
return;
int refFindType = 0;
if(sender() == mFindCommandRegion)
refFindType = 0;
else if(sender() == mFindCommandModule)
refFindType = 1;
else if(sender() == mFindCommandAll)
refFindType = 2;
else if(sender() == mFindCommandAllUser)
refFindType = 3;
else if(sender() == mFindCommandAllSystem)
refFindType = 4;
else if(sender() == mFindCommandFunction)
refFindType = -1;
LineEditDialog mLineEdit(this);
mLineEdit.enableCheckBox(refFindType == 0);
mLineEdit.setCheckBoxText(tr("Entire &Block"));
mLineEdit.setCheckBox(ConfigBool("Disassembler", "FindCommandEntireBlock"));
mLineEdit.setWindowTitle("Find Command");
if(mLineEdit.exec() != QDialog::Accepted)
return;
Config()->setBool("Disassembler", "FindCommandEntireBlock", mLineEdit.bChecked);
char error[MAX_ERROR_SIZE] = "";
unsigned char dest[16];
int asmsize = 0;
duint va = rvaToVa(getInitialSelection());
if(mLineEdit.bChecked) // entire block
va = mMemPage->getBase();
if(!DbgFunctions()->Assemble(mMemPage->getBase() + mMemPage->getSize() / 2, dest, &asmsize, mLineEdit.editText.toUtf8().constData(), error))
{
SimpleErrorBox(this, tr("Error!"), tr("Failed to assemble instruction \"") + mLineEdit.editText + "\" (" + error + ")");
return;
}
QString addr_text = ToPtrString(va);
dsint size = mMemPage->getSize();
if(refFindType != -1)
DbgCmdExec(QString("findasm \"%1\", %2, .%3, %4").arg(mLineEdit.editText).arg(addr_text).arg(size).arg(refFindType));
else
{
duint start, end;
if(DbgFunctionGet(va, &start, &end))
DbgCmdExec(QString("findasm \"%1\", %2, .%3, 0").arg(mLineEdit.editText).arg(ToPtrString(start)).arg(ToPtrString(end - start)));
}
emit displayReferencesWidget();
}
void CPUDisassembly::openSourceSlot()
{
char szSourceFile[MAX_STRING_SIZE] = "";
int line = 0;
auto sel = rvaToVa(getInitialSelection());
if(!DbgFunctions()->GetSourceFromAddr(sel, szSourceFile, &line))
return;
emit Bridge::getBridge()->loadSourceFile(szSourceFile, sel);
emit displaySourceManagerWidget();
}
void CPUDisassembly::displayWarningSlot(QString title, QString text)
{
SimpleWarningBox(this, title, text);
}
void CPUDisassembly::paintEvent(QPaintEvent* event)
{
// Hook/hack to update the sidebar at the same time as this widget.
// Ensures the two widgets are synced and prevents "draw lag"
if(mSideBar)
mSideBar->reload();
// Signal to render the original content
Disassembly::paintEvent(event);
}
int CPUDisassembly::findDeepestLoopDepth(duint addr)
{
for(int depth = 0; ; depth++)
if(!DbgLoopGet(depth, addr, nullptr, nullptr))
return depth - 1;
return -1; // unreachable
}
bool CPUDisassembly::getLabelsFromInstruction(duint addr, QSet<QString> & labels)
{
BASIC_INSTRUCTION_INFO basicinfo;
DbgDisasmFastAt(addr, &basicinfo);
std::vector<duint> values = { addr, basicinfo.addr, basicinfo.value.value, basicinfo.memory.value };
for(auto value : values)
{
char label_[MAX_LABEL_SIZE] = "";
if(DbgGetLabelAt(value, SEG_DEFAULT, label_))
{
//TODO: better cleanup of names
QString label(label_);
if(label.endsWith("A") || label.endsWith("W"))
label = label.left(label.length() - 1);
if(label.startsWith("&"))
label = label.right(label.length() - 1);
labels.insert(label);
}
}
return labels.size() != 0;
}
void CPUDisassembly::labelHelpSlot()
{
QString topic = ((QAction*)sender())->text();
char setting[MAX_SETTING_SIZE] = "";
if(!BridgeSettingGet("Misc", "HelpOnSymbolicNameUrl", setting))
{
//"execute://winhlp32.exe -k@topic ..\\win32.hlp";
strcpy_s(setting, "https://www.google.com/search?q=@topic");
BridgeSettingSet("Misc", "HelpOnSymbolicNameUrl", setting);
}
QString baseUrl(setting);
QString fullUrl = baseUrl.replace("@topic", topic);
if(fullUrl.startsWith("execute://"))
{
QString command = fullUrl.right(fullUrl.length() - 10);
QProcess::execute(command);
}
else
{
QDesktopServices::openUrl(QUrl(fullUrl));
}
}
void CPUDisassembly::traceCoverageBitSlot()
{
if(!DbgIsDebugging())
return;
duint base = mMemPage->getBase();
duint size = mMemPage->getSize();
for(duint i = base; i < base + size; i += 4096)
{
if(!(DbgFunctions()->SetTraceRecordType(i, TRACERECORDTYPE::TraceRecordBitExec)))
{
GuiAddLogMessage(tr("Failed to enable trace coverage for page %1.\n").arg(ToPtrString(i)).toUtf8().constData());
break;
}
}
DbgCmdExec("traceexecute cip");
}
void CPUDisassembly::traceCoverageByteSlot()
{
if(!DbgIsDebugging())
return;
duint base = mMemPage->getBase();
duint size = mMemPage->getSize();
for(duint i = base; i < base + size; i += 4096)
{
if(!(DbgFunctions()->SetTraceRecordType(i, TRACERECORDTYPE::TraceRecordByteWithExecTypeAndCounter)))
{
GuiAddLogMessage(tr("Failed to enable trace coverage for page %1.\n").arg(ToPtrString(i)).toUtf8().constData());
break;
}
}
DbgCmdExec("traceexecute cip");
}
void CPUDisassembly::traceCoverageWordSlot()
{
if(!DbgIsDebugging())
return;
duint base = mMemPage->getBase();
duint size = mMemPage->getSize();
for(duint i = base; i < base + size; i += 4096)
{
if(!(DbgFunctions()->SetTraceRecordType(i, TRACERECORDTYPE::TraceRecordWordWithExecTypeAndCounter)))
{
GuiAddLogMessage(tr("Failed to enable trace coverage for page %1.\n").arg(ToPtrString(i)).toUtf8().constData());
break;
}
}
DbgCmdExec("traceexecute cip");
}
void CPUDisassembly::traceCoverageDisableSlot()
{
if(!DbgIsDebugging())
return;
duint base = mMemPage->getBase();
duint size = mMemPage->getSize();
for(duint i = base; i < base + size; i += 4096)
{
if(!(DbgFunctions()->SetTraceRecordType(i, TRACERECORDTYPE::TraceRecordNone)))
{
GuiAddLogMessage(tr("Failed to disable trace coverage for page %1.\n").arg(ToPtrString(i)).toUtf8().constData());
break;
}
}
}
void CPUDisassembly::mnemonicBriefSlot()
{
mShowMnemonicBrief = !mShowMnemonicBrief;
Config()->setBool("Disassembler", "ShowMnemonicBrief", mShowMnemonicBrief);
reloadData();
}
void CPUDisassembly::mnemonicHelpSlot()
{
unsigned char data[16] = { 0xCC };
auto addr = rvaToVa(getInitialSelection());
DbgMemRead(addr, data, sizeof(data));
Zydis zydis;
zydis.Disassemble(addr, data);
DbgCmdExecDirect(QString("mnemonichelp %1").arg(zydis.Mnemonic().c_str()));
emit displayLogWidget();
}
void CPUDisassembly::analyzeSingleFunctionSlot()
{
DbgCmdExec(QString("analr %1").arg(ToHexString(rvaToVa(getInitialSelection()))));
}
void CPUDisassembly::removeAnalysisSelectionSlot()
{
if(!DbgIsDebugging())
return;
WordEditDialog mLineEdit(this);
mLineEdit.setup(tr("Size"), getSelectionSize(), sizeof(duint));
if(mLineEdit.exec() != QDialog::Accepted || !mLineEdit.getVal())
return;
mDisasm->getEncodeMap()->delRange(rvaToVa(getSelectionStart()), mLineEdit.getVal());
GuiUpdateDisassemblyView();
}
void CPUDisassembly::removeAnalysisModuleSlot()
{
if(!DbgIsDebugging())
return;
mDisasm->getEncodeMap()->delSegment(rvaToVa(getSelectionStart()));
GuiUpdateDisassemblyView();
}
void CPUDisassembly::setEncodeTypeRangeSlot()
{
if(!DbgIsDebugging())
return;
QAction* pAction = qobject_cast<QAction*>(sender());
WordEditDialog mLineEdit(this);
mLineEdit.setup(tr("Size"), getSelectionSize(), sizeof(duint));
if(mLineEdit.exec() != QDialog::Accepted || !mLineEdit.getVal())
return;
mDisasm->getEncodeMap()->setDataType(rvaToVa(getSelectionStart()), mLineEdit.getVal(), (ENCODETYPE)pAction->data().toUInt());
setSingleSelection(getSelectionStart());
GuiUpdateDisassemblyView();
}
void CPUDisassembly::setEncodeTypeSlot()
{
if(!DbgIsDebugging())
return;
QAction* pAction = qobject_cast<QAction*>(sender());
mDisasm->getEncodeMap()->setDataType(rvaToVa(getSelectionStart()), (ENCODETYPE)pAction->data().toUInt());
setSingleSelection(getSelectionStart());
GuiUpdateDisassemblyView();
}
void CPUDisassembly::analyzeModuleSlot()
{
DbgCmdExec("cfanal");
DbgCmdExec("analx");
}
void CPUDisassembly::copyTokenTextSlot()
{
Bridge::CopyToClipboard(mHighlightToken.text);
}
void CPUDisassembly::copyTokenValueSlot()
{
QString text;
if(getTokenValueText(text))
Bridge::CopyToClipboard(text);
}
bool CPUDisassembly::getTokenValueText(QString & text)
{
if(mHighlightToken.type <= ZydisTokenizer::TokenType::MnemonicUnusual)
return false;
duint value = mHighlightToken.value.value;
if(!mHighlightToken.value.size && !DbgFunctions()->ValFromString(mHighlightToken.text.toUtf8().constData(), &value))
return false;
text = ToHexString(value);
return true;
}
void CPUDisassembly::downloadCurrentSymbolsSlot()
{
char module[MAX_MODULE_SIZE] = "";
if(DbgGetModuleAt(rvaToVa(getInitialSelection()), module))
DbgCmdExec(QString("symdownload \"%0\"").arg(module));
}
void CPUDisassembly::traceCoverageToggleTraceRecordingSlot()
{
TraceBrowser::toggleTraceRecording(this);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUDisassembly.h | #pragma once
#include "Disassembly.h"
// Needed forward declaration for parent container class
class CPUSideBar;
class GotoDialog;
class XrefBrowseDialog;
class CommonActions;
class CPUDisassembly : public Disassembly
{
Q_OBJECT
public:
CPUDisassembly(QWidget* parent, bool isMain);
// Mouse management
void contextMenuEvent(QContextMenuEvent* event);
void mousePressEvent(QMouseEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event);
// Context menu management
void setupRightClickContextMenu();
void addFollowReferenceMenuItem(QString name, dsint value, QMenu* menu, bool isReferences, bool isFollowInCPU);
void setupFollowReferenceMenu(dsint wVA, QMenu* menu, bool isReferences, bool isFollowInCPU);
void copySelectionSlot(bool copyBytes);
void copySelectionToFileSlot(bool copyBytes);
void setSideBar(CPUSideBar* sideBar);
signals:
void displayReferencesWidget();
void displaySourceManagerWidget();
void showPatches();
void displayLogWidget();
void displaySymbolsWidget();
public slots:
void gotoOriginSlot();
void setLabelSlot();
void setLabelAddressSlot();
void toggleFunctionSlot();
void toggleArgumentSlot();
void addLoopSlot();
void deleteLoopSlot();
void assembleSlot();
void gotoExpressionSlot();
void gotoFileOffsetSlot();
void gotoStartSlot();
void gotoEndSlot();
void gotoFunctionStartSlot();
void gotoFunctionEndSlot();
void gotoPreviousReferenceSlot();
void gotoNextReferenceSlot();
void followActionSlot();
void gotoPreviousSlot();
void gotoNextSlot();
void gotoXrefSlot();
void findReferencesSlot();
void findConstantSlot();
void findStringsSlot();
void findCallsSlot();
void findPatternSlot();
void findGUIDSlot();
void findNamesSlot();
void selectionGetSlot(SELECTIONDATA* selection);
void selectionSetSlot(const SELECTIONDATA* selection);
void selectionUpdatedSlot();
void enableHighlightingModeSlot();
void binaryEditSlot();
void binaryFillSlot();
void binaryFillNopsSlot();
void binaryCopySlot();
void binaryPasteSlot();
void binaryPasteIgnoreSizeSlot();
void undoSelectionSlot();
void showPatchesSlot();
void copySelectionSlot();
void copySelectionToFileSlot();
void copySelectionNoBytesSlot();
void copySelectionToFileNoBytesSlot();
void copyAddressSlot();
void copyRvaSlot();
void copyFileOffsetSlot();
void copyHeaderVaSlot();
void copyDisassemblySlot();
void labelCopySlot();
void findCommandSlot();
void openSourceSlot();
void mnemonicHelpSlot();
void mnemonicBriefSlot();
void traceCoverageBitSlot();
void traceCoverageByteSlot();
void traceCoverageWordSlot();
void traceCoverageDisableSlot();
void traceCoverageToggleTraceRecordingSlot();
void displayWarningSlot(QString title, QString text);
void labelHelpSlot();
void analyzeSingleFunctionSlot();
void removeAnalysisSelectionSlot();
void removeAnalysisModuleSlot();
void setEncodeTypeSlot();
void setEncodeTypeRangeSlot();
void analyzeModuleSlot();
void copyTokenTextSlot();
void copyTokenValueSlot();
void downloadCurrentSymbolsSlot();
protected:
void paintEvent(QPaintEvent* event) override;
private:
int findDeepestLoopDepth(duint addr);
bool getLabelsFromInstruction(duint addr, QSet<QString> & labels);
bool getTokenValueText(QString & text);
void pushSelectionInto(bool copyBytes, QTextStream & stream, QTextStream* htmlStream = nullptr);
// Menus
QMenu* mHwSlotSelectMenu;
QMenu* mPluginMenu = nullptr;
// Actions
QAction* mReferenceSelectedAddressAction;
QAction* mFindCommandRegion;
QAction* mFindConstantRegion;
QAction* mFindStringsRegion;
QAction* mFindCallsRegion;
QAction* mFindPatternRegion;
QAction* mFindGUIDRegion;
QAction* mFindCommandModule;
QAction* mFindConstantModule;
QAction* mFindStringsModule;
QAction* mFindCallsModule;
QAction* mFindPatternModule;
QAction* mFindGUIDModule;
QAction* mFindNamesModule;
QAction* mFindCommandFunction;
QAction* mFindConstantFunction;
QAction* mFindStringsFunction;
QAction* mFindCallsFunction;
QAction* mFindPatternFunction;
QAction* mFindGUIDFunction;
QAction* mFindCommandAllUser;
QAction* mFindConstantAllUser;
QAction* mFindStringsAllUser;
QAction* mFindCallsAllUser;
QAction* mFindPatternAllUser;
QAction* mFindGUIDAllUser;
QAction* mFindCommandAllSystem;
QAction* mFindConstantAllSystem;
QAction* mFindStringsAllSystem;
QAction* mFindCallsAllSystem;
QAction* mFindPatternAllSystem;
QAction* mFindGUIDAllSystem;
QAction* mFindCommandAll;
QAction* mFindConstantAll;
QAction* mFindStringsAll;
QAction* mFindCallsAll;
QAction* mFindPatternAll;
QAction* mFindGUIDAll;
// Goto dialog specific
GotoDialog* mGoto = nullptr;
GotoDialog* mGotoOffset = nullptr;
XrefBrowseDialog* mXrefDlg = nullptr;
// Parent CPU window
CPUSideBar* mSideBar = nullptr;
MenuBuilder* mMenuBuilder;
MenuBuilder* mHighlightMenuBuilder;
bool mHighlightContextMenu = false;
CommonActions* mCommonActions;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUDump.cpp | #include "CPUDump.h"
#include <QMessageBox>
#include <QClipboard>
#include <QFileDialog>
#include <QToolTip>
#include "Configuration.h"
#include "Bridge.h"
#include "HexEditDialog.h"
#include "CPUMultiDump.h"
#include "GotoDialog.h"
#include "CPUDisassembly.h"
#include "CommonActions.h"
#include "WordEditDialog.h"
#include "CodepageSelectionDialog.h"
#include "MiscUtil.h"
#include "BackgroundFlickerThread.h"
CPUDump::CPUDump(CPUDisassembly* disas, CPUMultiDump* multiDump, QWidget* parent) : HexDump(parent)
{
mDisas = disas;
mMultiDump = multiDump;
duint setting;
if(BridgeSettingGetUint("Gui", "AsciiSeparator", &setting))
mAsciiSeparator = setting & 0xF;
setView((ViewEnum_t)ConfigUint("HexDump", "DefaultView"));
connect(this, SIGNAL(selectionUpdated()), this, SLOT(selectionUpdatedSlot()));
connect(this, SIGNAL(headerButtonReleased(int)), this, SLOT(headerButtonReleasedSlot(int)));
mPluginMenu = multiDump->mDumpPluginMenu;
setupContextMenu();
}
void CPUDump::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]()
{
return rvaToVa(getSelectionStart());
});
MenuBuilder* wBinaryMenu = new MenuBuilder(this);
wBinaryMenu->addAction(makeShortcutAction(DIcon("binary_edit"), tr("&Edit"), SLOT(binaryEditSlot()), "ActionBinaryEdit"));
wBinaryMenu->addAction(makeShortcutAction(DIcon("binary_fill"), tr("&Fill..."), SLOT(binaryFillSlot()), "ActionBinaryFill"));
wBinaryMenu->addSeparator();
wBinaryMenu->addAction(makeShortcutAction(DIcon("binary_copy"), tr("&Copy"), SLOT(binaryCopySlot()), "ActionBinaryCopy"));
wBinaryMenu->addAction(makeShortcutAction(DIcon("binary_paste"), tr("&Paste"), SLOT(binaryPasteSlot()), "ActionBinaryPaste"), [](QMenu*)
{
return QApplication::clipboard()->mimeData()->hasText();
});
wBinaryMenu->addAction(makeShortcutAction(DIcon("binary_paste_ignoresize"), tr("Paste (&Ignore Size)"), SLOT(binaryPasteIgnoreSizeSlot()), "ActionBinaryPasteIgnoreSize"), [](QMenu*)
{
return QApplication::clipboard()->mimeData()->hasText();
});
wBinaryMenu->addAction(makeShortcutAction(DIcon("binary_save"), tr("Save To a File"), SLOT(binarySaveToFileSlot()), "ActionBinarySave"));
mMenuBuilder->addMenu(makeMenu(DIcon("binary"), tr("B&inary")), wBinaryMenu);
MenuBuilder* wCopyMenu = new MenuBuilder(this);
wCopyMenu->addAction(mCopySelection);
wCopyMenu->addAction(mCopyAddress);
wCopyMenu->addAction(mCopyRva, [this](QMenu*)
{
return DbgFunctions()->ModBaseFromAddr(rvaToVa(getInitialSelection())) != 0;
});
wCopyMenu->addAction(makeShortcutAction(DIcon("fileoffset"), tr("&File Offset"), SLOT(copyFileOffsetSlot()), "ActionCopyFileOffset"), [this](QMenu*)
{
return DbgFunctions()->VaToFileOffset(rvaToVa(getInitialSelection())) != 0;
});
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), wCopyMenu);
mMenuBuilder->addAction(makeShortcutAction(DIcon("eraser"), tr("&Restore selection"), SLOT(undoSelectionSlot()), "ActionUndoSelection"), [this](QMenu*)
{
return DbgFunctions()->PatchInRange(rvaToVa(getSelectionStart()), rvaToVa(getSelectionEnd()));
});
mCommonActions->build(mMenuBuilder, CommonActions::ActionDisasm | CommonActions::ActionMemoryMap | CommonActions::ActionDumpData | CommonActions::ActionDumpN
| CommonActions::ActionDisasmData | CommonActions::ActionStackDump | CommonActions::ActionLabel | CommonActions::ActionWatch);
auto wIsValidReadPtrCallback = [this](QMenu*)
{
duint ptr = 0;
DbgMemRead(rvaToVa(getSelectionStart()), (unsigned char*)&ptr, sizeof(duint));
return DbgMemIsValidReadPtr(ptr);
};
mMenuBuilder->addAction(makeShortcutAction(DIcon("modify"), tr("&Modify Value"), SLOT(modifyValueSlot()), "ActionModifyValue"), [this](QMenu*)
{
auto d = mDescriptor.at(0).data;
return getSizeOf(d.itemSize) <= sizeof(duint) || (d.itemSize == 4 && d.dwordMode == FloatDword || d.itemSize == 8 && d.qwordMode == DoubleQword);
});
MenuBuilder* wBreakpointMenu = new MenuBuilder(this);
MenuBuilder* wHardwareAccessMenu = new MenuBuilder(this, [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_hardware) == 0;
});
MenuBuilder* wHardwareWriteMenu = new MenuBuilder(this, [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_hardware) == 0;
});
MenuBuilder* wMemoryAccessMenu = new MenuBuilder(this, [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_memory) == 0;
});
MenuBuilder* wMemoryReadMenu = new MenuBuilder(this, [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_memory) == 0;
});
MenuBuilder* wMemoryWriteMenu = new MenuBuilder(this, [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_memory) == 0;
});
MenuBuilder* wMemoryExecuteMenu = new MenuBuilder(this, [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_memory) == 0;
});
wHardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_byte"), tr("&Byte"), "bphws $, r, 1"));
wHardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_word"), tr("&Word"), "bphws $, r, 2"));
wHardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_dword"), tr("&Dword"), "bphws $, r, 4"));
#ifdef _WIN64
wHardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_qword"), tr("&Qword"), "bphws $, r, 8"));
#endif //_WIN64
wHardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_byte"), tr("&Byte"), "bphws $, w, 1"));
wHardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_word"), tr("&Word"), "bphws $, w, 2"));
wHardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_dword"), tr("&Dword"), "bphws $, w, 4"));
#ifdef _WIN64
wHardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_qword"), tr("&Qword"), "bphws $, w, 8"));
#endif //_WIN64
wBreakpointMenu->addMenu(makeMenu(DIcon("breakpoint_access"), tr("Hardware, &Access")), wHardwareAccessMenu);
wBreakpointMenu->addMenu(makeMenu(DIcon("breakpoint_write"), tr("Hardware, &Write")), wHardwareWriteMenu);
wBreakpointMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_execute"), tr("Hardware, &Execute"), "bphws $, x"), [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_hardware) == 0;
});
wBreakpointMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_remove"), tr("Remove &Hardware"), "bphwc $"), [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_hardware) != 0;
});
wBreakpointMenu->addSeparator();
wMemoryAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), "bpm $, 0, a"));
wMemoryAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), "bpm $, 1, a"));
wMemoryReadMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), "bpm $, 0, r"));
wMemoryReadMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), "bpm $, 1, r"));
wMemoryWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), "bpm $, 0, w"));
wMemoryWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), "bpm $, 1, w"));
wMemoryExecuteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), "bpm $, 0, x"));
wMemoryExecuteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), "bpm $, 1, x"));
wBreakpointMenu->addMenu(makeMenu(DIcon("breakpoint_memory_access"), tr("Memory, Access")), wMemoryAccessMenu);
wBreakpointMenu->addMenu(makeMenu(DIcon("breakpoint_memory_read"), tr("Memory, Read")), wMemoryReadMenu);
wBreakpointMenu->addMenu(makeMenu(DIcon("breakpoint_memory_write"), tr("Memory, Write")), wMemoryWriteMenu);
wBreakpointMenu->addMenu(makeMenu(DIcon("breakpoint_memory_execute"), tr("Memory, Execute")), wMemoryExecuteMenu);
wBreakpointMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_remove"), tr("Remove &Memory"), "bpmc $"), [this](QMenu*)
{
return (DbgGetBpxTypeAt(rvaToVa(getSelectionStart())) & bp_memory) != 0;
});
mMenuBuilder->addMenu(makeMenu(DIcon("breakpoint"), tr("&Breakpoint")), wBreakpointMenu);
mMenuBuilder->addAction(makeShortcutAction(DIcon("search-for"), tr("&Find Pattern..."), SLOT(findPattern()), "ActionFindPattern"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("find"), tr("Find &References"), SLOT(findReferencesSlot()), "ActionFindReferences"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("sync"), tr("&Sync with expression"), SLOT(syncWithExpressionSlot()), "ActionSync"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("memmap_alloc_memory"), tr("Allocate Memory"), SLOT(allocMemorySlot()), "ActionAllocateMemory"));
MenuBuilder* wGotoMenu = new MenuBuilder(this);
wGotoMenu->addAction(makeShortcutAction(DIcon("geolocation-goto"), tr("&Expression"), SLOT(gotoExpressionSlot()), "ActionGotoExpression"));
wGotoMenu->addAction(makeShortcutAction(DIcon("fileoffset"), tr("File Offset"), SLOT(gotoFileOffsetSlot()), "ActionGotoFileOffset"));
wGotoMenu->addAction(makeShortcutAction(DIcon("top"), tr("Start of Page"), SLOT(gotoStartSlot()), "ActionGotoStart"), [this](QMenu*)
{
return getSelectionStart() != 0;
});
wGotoMenu->addAction(makeShortcutAction(DIcon("bottom"), tr("End of Page"), SLOT(gotoEndSlot()), "ActionGotoEnd"));
wGotoMenu->addAction(makeShortcutAction(DIcon("previous"), tr("Previous"), SLOT(gotoPreviousSlot()), "ActionGotoPrevious"), [this](QMenu*)
{
return mHistory.historyHasPrev();
});
wGotoMenu->addAction(makeShortcutAction(DIcon("next"), tr("Next"), SLOT(gotoNextSlot()), "ActionGotoNext"), [this](QMenu*)
{
return mHistory.historyHasNext();
});
wGotoMenu->addAction(makeShortcutAction(DIcon("prevref"), tr("Previous Reference"), SLOT(gotoPreviousReferenceSlot()), "ActionGotoPreviousReference"), [](QMenu*)
{
return !!DbgEval("refsearch.count() && ($__dump_refindex > 0 || dump.sel() != refsearch.addr($__dump_refindex))");
});
wGotoMenu->addAction(makeShortcutAction(DIcon("nextref"), tr("Next Reference"), SLOT(gotoNextReferenceSlot()), "ActionGotoNextReference"), [](QMenu*)
{
return !!DbgEval("refsearch.count() && ($__dump_refindex < refsearch.count() || dump.sel() != refsearch.addr($__dump_refindex))");
});
mMenuBuilder->addMenu(makeMenu(DIcon("goto"), tr("&Go to")), wGotoMenu);
mMenuBuilder->addSeparator();
MenuBuilder* wHexMenu = new MenuBuilder(this);
wHexMenu->addAction(makeAction(DIcon("ascii"), tr("&ASCII"), SLOT(hexAsciiSlot())));
wHexMenu->addAction(makeAction(DIcon("ascii-extended"), tr("&Extended ASCII"), SLOT(hexUnicodeSlot())));
QAction* wHexLastCodepage = makeAction(DIcon("codepage"), "?", SLOT(hexLastCodepageSlot()));
wHexMenu->addAction(wHexLastCodepage, [wHexLastCodepage](QMenu*)
{
duint lastCodepage;
auto allCodecs = QTextCodec::availableCodecs();
if(!BridgeSettingGetUint("Misc", "LastCodepage", &lastCodepage) || lastCodepage >= duint(allCodecs.size()))
return false;
wHexLastCodepage->setText(QString::fromLocal8Bit(allCodecs.at(lastCodepage)));
return true;
});
wHexMenu->addAction(makeAction(DIcon("codepage"), tr("&Codepage..."), SLOT(hexCodepageSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("hex"), tr("&Hex")), wHexMenu);
MenuBuilder* wTextMenu = new MenuBuilder(this);
wTextMenu->addAction(makeAction(DIcon("ascii"), tr("&ASCII"), SLOT(textAsciiSlot())));
wTextMenu->addAction(makeAction(DIcon("ascii-extended"), tr("&Extended ASCII"), SLOT(textUnicodeSlot())));
QAction* wTextLastCodepage = makeAction(DIcon("codepage"), "?", SLOT(textLastCodepageSlot()));
wTextMenu->addAction(wTextLastCodepage, [wTextLastCodepage](QMenu*)
{
duint lastCodepage;
auto allCodecs = QTextCodec::availableCodecs();
if(!BridgeSettingGetUint("Misc", "LastCodepage", &lastCodepage) || lastCodepage >= duint(allCodecs.size()))
return false;
wTextLastCodepage->setText(QString::fromLocal8Bit(allCodecs.at(lastCodepage)));
return true;
});
wTextMenu->addAction(makeAction(DIcon("codepage"), tr("&Codepage..."), SLOT(textCodepageSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("strings"), tr("&Text")), wTextMenu);
MenuBuilder* wIntegerMenu = new MenuBuilder(this);
wIntegerMenu->addAction(makeAction(DIcon("byte"), tr("Signed byte (8-bit)"), SLOT(integerSignedByteSlot())));
wIntegerMenu->addAction(makeAction(DIcon("word"), tr("Signed short (16-bit)"), SLOT(integerSignedShortSlot())));
wIntegerMenu->addAction(makeAction(DIcon("dword"), tr("Signed long (32-bit)"), SLOT(integerSignedLongSlot())));
wIntegerMenu->addAction(makeAction(DIcon("qword"), tr("Signed long long (64-bit)"), SLOT(integerSignedLongLongSlot())));
wIntegerMenu->addAction(makeAction(DIcon("byte"), tr("Unsigned byte (8-bit)"), SLOT(integerUnsignedByteSlot())));
wIntegerMenu->addAction(makeAction(DIcon("word"), tr("Unsigned short (16-bit)"), SLOT(integerUnsignedShortSlot())));
wIntegerMenu->addAction(makeAction(DIcon("dword"), tr("Unsigned long (32-bit)"), SLOT(integerUnsignedLongSlot())));
wIntegerMenu->addAction(makeAction(DIcon("qword"), tr("Unsigned long long (64-bit)"), SLOT(integerUnsignedLongLongSlot())));
wIntegerMenu->addAction(makeAction(DIcon("word"), tr("Hex short (16-bit)"), SLOT(integerHexShortSlot())));
wIntegerMenu->addAction(makeAction(DIcon("dword"), tr("Hex long (32-bit)"), SLOT(integerHexLongSlot())));
wIntegerMenu->addAction(makeAction(DIcon("qword"), tr("Hex long long (64-bit)"), SLOT(integerHexLongLongSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("integer"), tr("&Integer")), wIntegerMenu);
MenuBuilder* wFloatMenu = new MenuBuilder(this);
wFloatMenu->addAction(makeAction(DIcon("32bit-float"), tr("&Float (32-bit)"), SLOT(floatFloatSlot())));
wFloatMenu->addAction(makeAction(DIcon("64bit-float"), tr("&Double (64-bit)"), SLOT(floatDoubleSlot())));
wFloatMenu->addAction(makeAction(DIcon("80bit-float"), tr("&Long double (80-bit)"), SLOT(floatLongDoubleSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("float"), tr("&Float")), wFloatMenu);
mMenuBuilder->addAction(makeAction(DIcon("address"), tr("&Address"), SLOT(addressAsciiSlot())));
mMenuBuilder->addAction(makeAction(DIcon("processor-cpu"), tr("&Disassembly"), SLOT(disassemblySlot())));
mMenuBuilder->addSeparator();
mMenuBuilder->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
DbgMenuPrepare(GUI_DUMP_MENU);
menu->addActions(mPluginMenu->actions());
return true;
}));
mMenuBuilder->loadFromConfig();
updateShortcuts();
}
void CPUDump::getAttention()
{
BackgroundFlickerThread* thread = new BackgroundFlickerThread(this, mBackgroundColor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void CPUDump::getColumnRichText(int col, dsint rva, RichTextPainter::List & richText)
{
if(col && !mDescriptor.at(col - 1).isData && mDescriptor.at(col - 1).itemCount) //print comments
{
RichTextPainter::CustomRichText_t curData;
curData.flags = RichTextPainter::FlagColor;
curData.textColor = mTextColor;
duint data = 0;
mMemPage->read((byte_t*)&data, rva, sizeof(duint));
char modname[MAX_MODULE_SIZE] = "";
if(!DbgGetModuleAt(data, modname))
modname[0] = '\0';
char label_text[MAX_LABEL_SIZE] = "";
char string_text[MAX_STRING_SIZE] = "";
if(DbgGetLabelAt(data, SEG_DEFAULT, label_text))
curData.text = QString(modname) + "." + QString(label_text);
else if(DbgGetStringAt(data, string_text))
curData.text = string_text;
if(!curData.text.length()) //stack comments
{
auto va = rvaToVa(rva);
duint stackSize;
duint csp = DbgValFromString("csp");
duint stackBase = DbgMemFindBaseAddr(csp, &stackSize);
STACK_COMMENT comment;
if(va >= stackBase && va < stackBase + stackSize && DbgStackCommentGet(va, &comment))
{
if(va >= csp) //active stack
{
if(*comment.color)
curData.textColor = QColor(QString(comment.color));
}
else
curData.textColor = ConfigColor("StackInactiveTextColor");
curData.text = comment.comment;
}
}
if(curData.text.length())
richText.push_back(curData);
}
else
HexDump::getColumnRichText(col, rva, richText);
}
QString CPUDump::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
// Reset byte offset when base address is reached
if(rowBase == 0 && mByteOffset != 0)
printDumpAt(mMemPage->getBase(), false, false);
if(!col) //address
{
char label[MAX_LABEL_SIZE] = "";
dsint cur_addr = rvaToVa((rowBase + rowOffset) * getBytePerRowCount() - mByteOffset);
QColor background;
if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label)) //label
{
background = ConfigColor("HexDumpLabelBackgroundColor");
painter->setPen(ConfigColor("HexDumpLabelColor")); //TODO: config
}
else
{
background = ConfigColor("HexDumpAddressBackgroundColor");
painter->setPen(ConfigColor("HexDumpAddressColor")); //TODO: config
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background color
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, makeAddrText(cur_addr));
return QString();
}
return HexDump::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
}
void CPUDump::contextMenuEvent(QContextMenuEvent* event)
{
QMenu wMenu(this);
mMenuBuilder->build(&wMenu);
wMenu.exec(event->globalPos());
}
void CPUDump::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->button() != Qt::LeftButton || !DbgIsDebugging())
return;
switch(getColumnIndexFromX(event->x()))
{
case 0: //address
{
//very ugly way to calculate the base of the current row (no clue why it works)
dsint deltaRowBase = getInitialSelection() % getBytePerRowCount() + mByteOffset;
if(deltaRowBase >= getBytePerRowCount())
deltaRowBase -= getBytePerRowCount();
dsint mSelectedVa = rvaToVa(getInitialSelection() - deltaRowBase);
if(mRvaDisplayEnabled && mSelectedVa == mRvaDisplayBase)
mRvaDisplayEnabled = false;
else
{
mRvaDisplayEnabled = true;
mRvaDisplayBase = mSelectedVa;
mRvaDisplayPageBase = mMemPage->getBase();
}
reloadData();
}
break;
default:
{
auto d = mDescriptor.at(0).data;
if(getSizeOf(d.itemSize) <= sizeof(duint) || (d.itemSize == 4 && d.dwordMode == FloatDword || d.itemSize == 8 && d.qwordMode == DoubleQword))
modifyValueSlot();
else
binaryEditSlot();
}
break;
}
}
static QString getTooltipForVa(duint va, int depth)
{
duint ptr = 0;
if(!DbgMemRead(va, &ptr, sizeof(duint)))
return QString();
QString tooltip;
/* TODO: if this is enabled, make sure the context menu items also work
// If the VA is not a valid pointer, try to align it
if(!DbgMemIsValidReadPtr(ptr))
{
va -= va % sizeof(duint);
DbgMemRead(va, &ptr, sizeof(duint));
}*/
// Check if its a pointer
switch(DbgGetEncodeTypeAt(va, 1))
{
// Get information about the pointer type
case enc_unknown:
default:
if(DbgMemIsValidReadPtr(ptr) && depth >= 0)
{
tooltip = QString("[%1] = %2").arg(ToPtrString(ptr), getTooltipForVa(ptr, depth - 1));
}
// If not a pointer, hide tooltips
else
{
bool isCodePage;
isCodePage = DbgFunctions()->MemIsCodePage(va, false);
char disassembly[GUI_MAX_DISASSEMBLY_SIZE];
if(isCodePage)
{
if(GuiGetDisassembly(va, disassembly))
tooltip = QString::fromUtf8(disassembly);
else
tooltip = "";
}
else
tooltip = QString("[%1] = %2").arg(ToPtrString(va)).arg(ToPtrString(ptr));
if(DbgFunctions()->ModGetParty(va) == 1)
tooltip += " (" + (isCodePage ? CPUDump::tr("System Code") : CPUDump::tr("System Data")) + ")";
else
tooltip += " (" + (isCodePage ? CPUDump::tr("User Code") : CPUDump::tr("User Data")) + ")";
}
break;
case enc_code:
char disassembly[GUI_MAX_DISASSEMBLY_SIZE];
if(GuiGetDisassembly(va, disassembly))
tooltip = QString::fromUtf8(disassembly);
else
tooltip = "";
if(DbgFunctions()->ModGetParty(va) == 1)
tooltip += " (" + CPUDump::tr("System Code") + ")";
else
tooltip += " (" + CPUDump::tr("User Code") + ")";
break;
case enc_real4:
tooltip = ToFloatString(&va) + CPUDump::tr(" (Real4)");
break;
case enc_real8:
double numd;
DbgMemRead(va, &numd, sizeof(double));
tooltip = ToDoubleString(&numd) + CPUDump::tr(" (Real8)");
break;
case enc_byte:
tooltip = ToByteString(va) + CPUDump::tr(" (BYTE)");
break;
case enc_word:
tooltip = ToWordString(va) + CPUDump::tr(" (WORD)");
break;
case enc_dword:
tooltip = QString("%1").arg((unsigned int)va, 8, 16, QChar('0')).toUpper() + CPUDump::tr(" (DWORD)");
break;
case enc_qword:
#ifdef _WIN64
tooltip = QString("%1").arg((unsigned long long)va, 16, 16, QChar('0')).toUpper() + CPUDump::tr(" (QWORD)");
#else //x86
unsigned long long qword;
qword = 0;
DbgMemRead(va, &qword, 8);
tooltip = QString("%1").arg((unsigned long long)qword, 16, 16, QChar('0')).toUpper() + CPUDump::tr(" (QWORD)");
#endif //_WIN64
break;
case enc_ascii:
case enc_unicode:
char str[MAX_STRING_SIZE];
if(DbgGetStringAt(va, str))
tooltip = QString::fromUtf8(str) + CPUDump::tr(" (String)");
else
tooltip = CPUDump::tr("(Unknown String)");
break;
}
return tooltip;
}
void CPUDump::mouseMoveEvent(QMouseEvent* event)
{
// Get mouse pointer relative position
int x = event->x();
int y = event->y();
// Get HexDump own RVA address, then VA in memory
auto va = rvaToVa(getItemStartingAddress(x, y));
// Read VA
QToolTip::showText(event->globalPos(), getTooltipForVa(va, 4));
HexDump::mouseMoveEvent(event);
}
void CPUDump::modifyValueSlot()
{
dsint addr = getSelectionStart();
auto d = mDescriptor.at(0).data;
if(d.itemSize == 4 && d.dwordMode == FloatDword || d.itemSize == 8 && d.qwordMode == DoubleQword)
{
auto size = std::min(getSizeOf(mDescriptor.at(0).data.itemSize), sizeof(double));
if(size == 4)
{
float value;
mMemPage->read(&value, addr, size);
QString current = QString::number(value);
QString newvalue;
if(SimpleInputBox(this, tr("Modify value"), current, newvalue, current))
{
bool ok;
value = newvalue.toFloat(&ok);
if(ok)
mMemPage->write(&value, addr, size);
else
SimpleErrorBox(this, tr("Error"), tr("The input text is not a number!"));
}
}
else if(size == 8)
{
double value;
mMemPage->read(&value, addr, size);
QString current = QString::number(value);
QString newvalue;
if(SimpleInputBox(this, tr("Modify value"), current, newvalue, current))
{
bool ok;
value = newvalue.toDouble(&ok);
if(ok)
mMemPage->write(&value, addr, size);
else
SimpleErrorBox(this, tr("Error"), tr("The input text is not a number!"));
}
}
}
else
{
auto size = std::min(getSizeOf(mDescriptor.at(0).data.itemSize), sizeof(dsint));
WordEditDialog wEditDialog(this);
dsint value = 0;
mMemPage->read(&value, addr, size);
wEditDialog.setup(tr("Modify value"), value, (int)size);
if(wEditDialog.exec() != QDialog::Accepted)
return;
value = wEditDialog.getVal();
mMemPage->write(&value, addr, size);
}
GuiUpdateAllViews();
}
void CPUDump::gotoExpressionSlot()
{
if(!DbgIsDebugging())
return;
if(!mGoto)
mGoto = new GotoDialog(this);
mGoto->setWindowTitle(tr("Enter expression to follow in Dump..."));
mGoto->setInitialExpression(ToPtrString(rvaToVa(getInitialSelection())));
if(mGoto->exec() == QDialog::Accepted)
{
duint value = DbgValFromString(mGoto->expressionText.toUtf8().constData());
DbgCmdExec(QString().sprintf("dump %p", value));
}
}
void CPUDump::gotoFileOffsetSlot()
{
if(!DbgIsDebugging())
return;
char modname[MAX_MODULE_SIZE] = "";
if(!DbgFunctions()->ModNameFromAddr(rvaToVa(getSelectionStart()), modname, true))
{
SimpleErrorBox(this, tr("Error!"), tr("Not inside a module..."));
return;
}
if(!mGotoOffset)
mGotoOffset = new GotoDialog(this);
mGotoOffset->fileOffset = true;
mGotoOffset->modName = QString(modname);
mGotoOffset->setWindowTitle(tr("Goto File Offset in %1").arg(QString(modname)));
duint addr = rvaToVa(getInitialSelection());
duint offset = DbgFunctions()->VaToFileOffset(addr);
if(offset)
mGotoOffset->setInitialExpression(ToHexString(offset));
if(mGotoOffset->exec() != QDialog::Accepted)
return;
duint value = DbgValFromString(mGotoOffset->expressionText.toUtf8().constData());
value = DbgFunctions()->FileOffsetToVa(modname, value);
DbgCmdExec(QString().sprintf("dump \"%p\"", value));
}
void CPUDump::gotoStartSlot()
{
duint dest = mMemPage->getBase();
DbgCmdExec(QString().sprintf("dump \"%p\"", dest));
}
void CPUDump::gotoEndSlot()
{
duint dest = mMemPage->getBase() + mMemPage->getSize() - (getViewableRowsCount() * getBytePerRowCount());
DbgCmdExec(QString().sprintf("dump \"%p\"", dest));
}
void CPUDump::gotoPreviousReferenceSlot()
{
auto count = DbgEval("refsearch.count()"), index = DbgEval("$__dump_refindex"), addr = DbgEval("refsearch.addr($__dump_refindex)");
if(count)
{
if(index > 0 && addr == rvaToVa(getInitialSelection()))
DbgValToString("$__dump_refindex", index - 1);
DbgCmdExec("dump refsearch.addr($__dump_refindex)");
GuiReferenceSetSingleSelection(int(DbgEval("$__dump_refindex")), false);
}
}
void CPUDump::gotoNextReferenceSlot()
{
auto count = DbgEval("refsearch.count()"), index = DbgEval("$__dump_refindex"), addr = DbgEval("refsearch.addr($__dump_refindex)");
if(count)
{
if(index + 1 < count && addr == rvaToVa(getInitialSelection()))
DbgValToString("$__dump_refindex", index + 1);
DbgCmdExec("dump refsearch.addr($__dump_refindex)");
GuiReferenceSetSingleSelection(int(DbgEval("$__dump_refindex")), false);
}
}
void CPUDump::hexAsciiSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewHexAscii);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //hex byte
wColDesc.itemCount = 16;
wColDesc.separator = mAsciiSeparator ? mAsciiSeparator : 4;
dDesc.itemSize = Byte;
dDesc.byteMode = HexByte;
wColDesc.data = dDesc;
appendResetDescriptor(8 + charwidth * 47, tr("Hex"), false, wColDesc);
wColDesc.isData = true; //ascii byte
wColDesc.itemCount = 16;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(8 + charwidth * 16, tr("ASCII"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::hexUnicodeSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewHexUnicode);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //hex byte
wColDesc.itemCount = 16;
wColDesc.separator = mAsciiSeparator ? mAsciiSeparator : 4;
dDesc.itemSize = Byte;
dDesc.byteMode = HexByte;
wColDesc.data = dDesc;
appendResetDescriptor(8 + charwidth * 47, tr("Hex"), false, wColDesc);
wColDesc.isData = true; //unicode short
wColDesc.itemCount = 8;
wColDesc.separator = 0;
dDesc.itemSize = Word;
dDesc.wordMode = UnicodeWord;
wColDesc.data = dDesc;
appendDescriptor(8 + charwidth * 8, tr("UNICODE"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::hexCodepageSlot()
{
CodepageSelectionDialog dialog(this);
if(dialog.exec() != QDialog::Accepted)
return;
auto codepage = dialog.getSelectedCodepage();
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //hex byte
wColDesc.itemCount = 16;
wColDesc.separator = mAsciiSeparator ? mAsciiSeparator : 4;
dDesc.itemSize = Byte;
dDesc.byteMode = HexByte;
wColDesc.data = dDesc;
appendResetDescriptor(8 + charwidth * 47, tr("Hex"), false, wColDesc);
wColDesc.isData = true; //text (in code page)
wColDesc.itemCount = 16;
wColDesc.separator = 0;
wColDesc.textCodec = QTextCodec::codecForName(codepage);
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, codepage, false, wColDesc);
reloadData();
}
void CPUDump::hexLastCodepageSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewHexCodepage);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
duint lastCodepage;
auto allCodecs = QTextCodec::availableCodecs();
if(!BridgeSettingGetUint("Misc", "LastCodepage", &lastCodepage) || lastCodepage >= duint(allCodecs.size()))
return;
wColDesc.isData = true; //hex byte
wColDesc.itemCount = 16;
wColDesc.separator = mAsciiSeparator ? mAsciiSeparator : 4;
dDesc.itemSize = Byte;
dDesc.byteMode = HexByte;
wColDesc.data = dDesc;
appendResetDescriptor(8 + charwidth * 47, tr("Hex"), false, wColDesc);
wColDesc.isData = true; //text (in code page)
wColDesc.itemCount = 16;
wColDesc.separator = 0;
wColDesc.textCodec = QTextCodec::codecForName(allCodecs.at(lastCodepage));
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, allCodecs.at(lastCodepage), false, wColDesc);
reloadData();
}
void CPUDump::textLastCodepageSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewTextCodepage);
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
duint lastCodepage;
auto allCodecs = QTextCodec::availableCodecs();
if(!BridgeSettingGetUint("Misc", "LastCodepage", &lastCodepage) || lastCodepage >= duint(allCodecs.size()))
return;
wColDesc.isData = true; //text (in code page)
wColDesc.itemCount = 64;
wColDesc.separator = 0;
wColDesc.textCodec = QTextCodec::codecForName(allCodecs.at(lastCodepage));
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendResetDescriptor(0, allCodecs.at(lastCodepage), false, wColDesc);
reloadData();
}
void CPUDump::textAsciiSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewTextAscii);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //ascii byte
wColDesc.itemCount = 64;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendResetDescriptor(8 + charwidth * 64, tr("ASCII"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::textUnicodeSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewTextUnicode);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //unicode short
wColDesc.itemCount = 64;
wColDesc.separator = 0;
dDesc.itemSize = Word;
dDesc.wordMode = UnicodeWord;
wColDesc.data = dDesc;
appendResetDescriptor(8 + charwidth * 64, tr("UNICODE"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::textCodepageSlot()
{
CodepageSelectionDialog dialog(this);
if(dialog.exec() != QDialog::Accepted)
return;
auto codepage = dialog.getSelectedCodepage();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //text (in code page)
wColDesc.itemCount = 64;
wColDesc.separator = 0;
wColDesc.textCodec = QTextCodec::codecForName(codepage);
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendResetDescriptor(0, codepage, false, wColDesc);
reloadData();
}
void CPUDump::integerSignedByteSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerSignedByte);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //signed short
wColDesc.itemCount = 8;
wColDesc.separator = 0;
wColDesc.data.itemSize = Byte;
wColDesc.data.wordMode = SignedDecWord;
appendResetDescriptor(8 + charwidth * 40, tr("Signed byte (8-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerSignedShortSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerSignedShort);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //signed short
wColDesc.itemCount = 8;
wColDesc.separator = 0;
wColDesc.data.itemSize = Word;
wColDesc.data.wordMode = SignedDecWord;
appendResetDescriptor(8 + charwidth * 55, tr("Signed short (16-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerSignedLongSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerSignedLong);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //signed long
wColDesc.itemCount = 4;
wColDesc.separator = 0;
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = SignedDecDword;
appendResetDescriptor(8 + charwidth * 47, tr("Signed long (32-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerSignedLongLongSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerSignedLongLong);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //signed long long
wColDesc.itemCount = 2;
wColDesc.separator = 0;
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = SignedDecQword;
appendResetDescriptor(8 + charwidth * 41, tr("Signed long long (64-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerUnsignedByteSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerUnsignedByte);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //unsigned short
wColDesc.itemCount = 8;
wColDesc.separator = 0;
wColDesc.data.itemSize = Byte;
wColDesc.data.wordMode = UnsignedDecWord;
appendResetDescriptor(8 + charwidth * 32, tr("Unsigned byte (8-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerUnsignedShortSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerUnsignedShort);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //unsigned short
wColDesc.itemCount = 8;
wColDesc.separator = 0;
wColDesc.data.itemSize = Word;
wColDesc.data.wordMode = UnsignedDecWord;
appendResetDescriptor(8 + charwidth * 47, tr("Unsigned short (16-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerUnsignedLongSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerUnsignedLong);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //unsigned long
wColDesc.itemCount = 4;
wColDesc.separator = 0;
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = UnsignedDecDword;
appendResetDescriptor(8 + charwidth * 43, tr("Unsigned long (32-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerUnsignedLongLongSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerUnsignedLongLong);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //unsigned long long
wColDesc.itemCount = 2;
wColDesc.separator = 0;
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = UnsignedDecQword;
appendResetDescriptor(8 + charwidth * 41, tr("Unsigned long long (64-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerHexShortSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerHexShort);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //hex short
wColDesc.itemCount = 8;
wColDesc.separator = 0;
wColDesc.data.itemSize = Word;
wColDesc.data.wordMode = HexWord;
appendResetDescriptor(8 + charwidth * 39, tr("Hex short (16-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerHexLongSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerHexLong);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //hex long
wColDesc.itemCount = 4;
wColDesc.separator = 0;
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = HexDword;
appendResetDescriptor(8 + charwidth * 35, tr("Hex long (32-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::integerHexLongLongSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewIntegerHexLongLong);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //hex long long
wColDesc.itemCount = 2;
wColDesc.separator = 0;
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = HexQword;
appendResetDescriptor(8 + charwidth * 33, tr("Hex long long (64-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::floatFloatSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewFloatFloat);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //float dword
wColDesc.itemCount = 4;
wColDesc.separator = 0;
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = FloatDword;
appendResetDescriptor(8 + charwidth * 55, tr("Float (32-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::floatDoubleSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewFloatDouble);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //float qword
wColDesc.itemCount = 2;
wColDesc.separator = 0;
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = DoubleQword;
appendResetDescriptor(8 + charwidth * 47, tr("Double (64-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::floatLongDoubleSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewFloatLongDouble);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //float qword
wColDesc.itemCount = 2;
wColDesc.separator = 0;
wColDesc.data.itemSize = Tword;
wColDesc.data.twordMode = FloatTword;
appendResetDescriptor(8 + charwidth * 59, tr("Long double (80-bit)"), false, wColDesc);
wColDesc.isData = false; //empty column
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, "", false, wColDesc);
reloadData();
}
void CPUDump::addressAsciiSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewAddressAscii);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //void*
wColDesc.itemCount = 1;
wColDesc.separator = 0;
#ifdef _WIN64
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = HexQword;
#else
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = HexDword;
#endif
appendResetDescriptor(8 + charwidth * 2 * sizeof(duint), tr("Value"), false, wColDesc);
wColDesc.isData = true;
wColDesc.separator = 0;
#ifdef _WIN64
wColDesc.itemCount = 8;
#else
wColDesc.itemCount = 4;
#endif
wColDesc.data.itemSize = Byte;
wColDesc.data.byteMode = AsciiByte;
wColDesc.columnSwitch = [this]()
{
this->setView(ViewAddressUnicode);
};
appendDescriptor(8 + charwidth * wColDesc.itemCount, tr("ASCII"), true, wColDesc);
wColDesc.isData = false; //comments
wColDesc.itemCount = 1;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, tr("Comments"), false, wColDesc);
reloadData();
}
void CPUDump::addressUnicodeSlot()
{
Config()->setUint("HexDump", "DefaultView", (duint)ViewAddressUnicode);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
wColDesc.isData = true; //void*
wColDesc.itemCount = 1;
wColDesc.separator = 0;
#ifdef _WIN64
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = HexQword;
#else
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = HexDword;
#endif
appendResetDescriptor(8 + charwidth * 2 * sizeof(duint), tr("Value"), false, wColDesc);
wColDesc.isData = true;
wColDesc.separator = 0;
#ifdef _WIN64
wColDesc.itemCount = 4;
#else
wColDesc.itemCount = 2;
#endif
wColDesc.data.itemSize = Word;
wColDesc.data.wordMode = UnicodeWord;
wColDesc.columnSwitch = [this]()
{
this->setView(ViewAddressAscii);
};
appendDescriptor(8 + charwidth * wColDesc.itemCount, tr("UNICODE"), true, wColDesc);
wColDesc.isData = false; //comments
wColDesc.itemCount = 1;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(0, tr("Comments"), false, wColDesc);
reloadData();
}
void CPUDump::disassemblySlot()
{
SELECTIONDATA selection;
selectionGet(&selection);
emit showDisassemblyTab(selection.start, selection.end, rvaToVa(getTableOffsetRva()));
}
void CPUDump::selectionGet(SELECTIONDATA* selection)
{
selection->start = rvaToVa(getSelectionStart());
selection->end = rvaToVa(getSelectionEnd());
Bridge::getBridge()->setResult(BridgeResult::SelectionGet, 1);
}
void CPUDump::selectionSet(const SELECTIONDATA* selection)
{
dsint selMin = mMemPage->getBase();
dsint selMax = selMin + mMemPage->getSize();
dsint start = selection->start;
dsint end = selection->end;
if(start < selMin || start >= selMax || end < selMin || end >= selMax) //selection out of range
{
Bridge::getBridge()->setResult(BridgeResult::SelectionSet, 0);
return;
}
setSingleSelection(start - selMin);
expandSelectionUpTo(end - selMin);
reloadData();
Bridge::getBridge()->setResult(BridgeResult::SelectionSet, 1);
}
void CPUDump::findReferencesSlot()
{
QString addrStart = ToPtrString(rvaToVa(getSelectionStart()));
QString addrEnd = ToPtrString(rvaToVa(getSelectionEnd()));
QString addrDisasm = ToPtrString(mDisas->rvaToVa(mDisas->getSelectionStart()));
DbgCmdExec(QString("findrefrange " + addrStart + ", " + addrEnd + ", " + addrDisasm));
emit displayReferencesWidget();
}
void CPUDump::binaryEditSlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.setWindowTitle(tr("Edit data at %1").arg(ToPtrString(rvaToVa(selStart))));
if(hexEdit.exec() != QDialog::Accepted)
return;
dsint dataSize = hexEdit.mHexEdit->data().size();
dsint newSize = selSize > dataSize ? selSize : dataSize;
data = new byte_t[newSize];
mMemPage->read(data, selStart, newSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, newSize));
mMemPage->write(patched.constData(), selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDump::binaryFillSlot()
{
HexEditDialog hexEdit(this);
hexEdit.showKeepSize(false);
hexEdit.mHexEdit->setOverwriteMode(false);
dsint selStart = getSelectionStart();
hexEdit.setWindowTitle(tr("Fill data at %1").arg(ToPtrString(rvaToVa(selStart))));
if(hexEdit.exec() != QDialog::Accepted)
return;
QString pattern = hexEdit.mHexEdit->pattern();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.mHexEdit->fill(0, QString(pattern));
QByteArray patched(hexEdit.mHexEdit->data());
mMemPage->write(patched, selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDump::binaryCopySlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
Bridge::CopyToClipboard(hexEdit.mHexEdit->pattern(true));
}
void CPUDump::binaryPasteSlot()
{
if(!QApplication::clipboard()->mimeData()->hasText())
return;
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
QClipboard* clipboard = QApplication::clipboard();
hexEdit.mHexEdit->setData(clipboard->text());
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, selSize));
if(patched.size() < selSize)
selSize = patched.size();
mMemPage->write(patched.constData(), selStart, selSize);
GuiUpdateAllViews();
}
void CPUDump::binaryPasteIgnoreSizeSlot()
{
if(!QApplication::clipboard()->mimeData()->hasText())
return;
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
QClipboard* clipboard = QApplication::clipboard();
hexEdit.mHexEdit->setData(clipboard->text());
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, selSize));
delete [] data;
mMemPage->write(patched.constData(), selStart, patched.size());
GuiUpdateAllViews();
}
void CPUDump::binarySaveToFileSlot()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save to file"), QDir::currentPath(), tr("All files (*.*)"));
if(fileName.length())
{
// Get starting selection and selection size, then convert selStart to VA
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
// Prepare command
fileName = QDir::toNativeSeparators(fileName);
QString cmd = QString("savedata \"%1\",%2,%3").arg(fileName, ToHexString(rvaToVa(selStart)), ToHexString(selSize));
DbgCmdExec(cmd);
}
}
void CPUDump::findPattern()
{
HexEditDialog hexEdit(this);
hexEdit.showEntireBlock(true);
hexEdit.isDataCopiable(false);
hexEdit.mHexEdit->setOverwriteMode(false);
hexEdit.setWindowTitle(tr("Find Pattern..."));
if(hexEdit.exec() != QDialog::Accepted)
return;
dsint addr = rvaToVa(getSelectionStart());
if(hexEdit.entireBlock())
addr = DbgMemFindBaseAddr(addr, 0);
QString addrText = ToPtrString(addr);
DbgCmdExec(QString("findall " + addrText + ", " + hexEdit.mHexEdit->pattern() + ", &data&"));
emit displayReferencesWidget();
}
void CPUDump::copyFileOffsetSlot()
{
duint addr = rvaToVa(getInitialSelection());
duint offset = DbgFunctions()->VaToFileOffset(addr);
if(offset)
{
QString addrText = ToHexString(offset);
Bridge::CopyToClipboard(addrText);
}
else
QMessageBox::warning(this, tr("Error!"), tr("Selection not in a file..."));
}
void CPUDump::undoSelectionSlot()
{
dsint start = rvaToVa(getSelectionStart());
dsint end = rvaToVa(getSelectionEnd());
if(!DbgFunctions()->PatchInRange(start, end)) //nothing patched in selected range
return;
DbgFunctions()->PatchRestoreRange(start, end);
reloadData();
}
void CPUDump::selectionUpdatedSlot()
{
QString selStart = ToPtrString(rvaToVa(getSelectionStart()));
QString selEnd = ToPtrString(rvaToVa(getSelectionEnd()));
QString info = tr("Dump");
char mod[MAX_MODULE_SIZE] = "";
if(DbgFunctions()->ModNameFromAddr(rvaToVa(getSelectionStart()), mod, true))
info = QString(mod) + "";
GuiAddStatusBarMessage(QString(info + ": " + selStart + " -> " + selEnd + QString().sprintf(" (0x%.8X bytes)\n", getSelectionEnd() - getSelectionStart() + 1)).toUtf8().constData());
}
void CPUDump::syncWithExpressionSlot()
{
if(!DbgIsDebugging())
return;
GotoDialog gotoDialog(this, true);
gotoDialog.setWindowTitle(tr("Enter expression to sync with..."));
gotoDialog.setInitialExpression(mSyncAddrExpression);
if(gotoDialog.exec() != QDialog::Accepted)
return;
mSyncAddrExpression = gotoDialog.expressionText;
updateDumpSlot();
}
void CPUDump::allocMemorySlot()
{
WordEditDialog mLineEdit(this);
mLineEdit.setup(tr("Size"), 0x1000, sizeof(duint));
if(mLineEdit.exec() == QDialog::Accepted)
{
duint memsize = mLineEdit.getVal();
if(memsize == 0) // 1GB
{
SimpleWarningBox(this, tr("Warning"), tr("You're trying to allocate a zero-sized buffer just now."));
return;
}
if(memsize > 1024 * 1024 * 1024)
{
SimpleErrorBox(this, tr("Error"), tr("The size of buffer you're trying to allocate exceeds 1GB. Please check your expression to ensure nothing is wrong."));
return;
}
DbgCmdExecDirect(QString("alloc %1").arg(ToPtrString(memsize)));
duint addr = DbgValFromString("$result");
if(addr != 0)
{
DbgCmdExec("Dump $result");
}
else
{
SimpleErrorBox(this, tr("Error"), tr("Memory allocation failed!"));
return;
}
}
}
void CPUDump::setView(ViewEnum_t view)
{
switch(view)
{
case ViewHexAscii:
hexAsciiSlot();
break;
case ViewHexUnicode:
hexUnicodeSlot();
break;
case ViewTextAscii:
textAsciiSlot();
break;
case ViewTextUnicode:
textUnicodeSlot();
break;
case ViewIntegerSignedByte:
integerSignedByteSlot();
break;
case ViewIntegerSignedShort:
integerSignedShortSlot();
break;
case ViewIntegerSignedLong:
integerSignedLongSlot();
break;
case ViewIntegerSignedLongLong:
integerSignedLongLongSlot();
break;
case ViewIntegerUnsignedByte:
integerUnsignedByteSlot();
break;
case ViewIntegerUnsignedShort:
integerUnsignedShortSlot();
break;
case ViewIntegerUnsignedLong:
integerUnsignedLongSlot();
break;
case ViewIntegerUnsignedLongLong:
integerUnsignedLongLongSlot();
break;
case ViewIntegerHexShort:
integerHexShortSlot();
break;
case ViewIntegerHexLong:
integerHexLongSlot();
break;
case ViewIntegerHexLongLong:
integerHexLongLongSlot();
break;
case ViewFloatFloat:
floatFloatSlot();
break;
case ViewFloatDouble:
floatDoubleSlot();
break;
case ViewFloatLongDouble:
floatLongDoubleSlot();
break;
case ViewAddress:
case ViewAddressAscii:
addressAsciiSlot();
break;
case ViewAddressUnicode:
addressUnicodeSlot();
break;
case ViewHexCodepage:
hexLastCodepageSlot();
break;
case ViewTextCodepage:
textLastCodepageSlot();
break;
default:
hexAsciiSlot();
break;
}
}
void CPUDump::headerButtonReleasedSlot(int colIndex)
{
auto callback = mDescriptor[colIndex].columnSwitch;
if(callback)
callback();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUDump.h | #pragma once
#include "HexDump.h"
//forward declaration
class CPUMultiDump;
class CPUDisassembly;
class GotoDialog;
class CommonActions;
class CPUDump : public HexDump
{
Q_OBJECT
public:
explicit CPUDump(CPUDisassembly* disas, CPUMultiDump* multiDump, QWidget* parent = 0);
void getColumnRichText(int col, dsint rva, RichTextPainter::List & richText) override;
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h);
void setupContextMenu();
void getAttention();
void contextMenuEvent(QContextMenuEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);
signals:
void displayReferencesWidget();
void showDisassemblyTab(duint selectionStart, duint selectionEnd, duint firstAddress);
public slots:
void modifyValueSlot();
void gotoExpressionSlot();
void gotoFileOffsetSlot();
void gotoStartSlot();
void gotoEndSlot();
void gotoPreviousReferenceSlot();
void gotoNextReferenceSlot();
void hexAsciiSlot();
void hexUnicodeSlot();
void hexCodepageSlot();
void hexLastCodepageSlot();
void textAsciiSlot();
void textUnicodeSlot();
void textCodepageSlot();
void textLastCodepageSlot();
void integerSignedByteSlot();
void integerSignedShortSlot();
void integerSignedLongSlot();
void integerSignedLongLongSlot();
void integerUnsignedByteSlot();
void integerUnsignedShortSlot();
void integerUnsignedLongSlot();
void integerUnsignedLongLongSlot();
void integerHexShortSlot();
void integerHexLongSlot();
void integerHexLongLongSlot();
void floatFloatSlot();
void floatDoubleSlot();
void floatLongDoubleSlot();
void addressUnicodeSlot();
void addressAsciiSlot();
void disassemblySlot();
void selectionGet(SELECTIONDATA* selection);
void selectionSet(const SELECTIONDATA* selection);
void binaryEditSlot();
void binaryFillSlot();
void binaryCopySlot();
void binaryPasteSlot();
void binaryPasteIgnoreSizeSlot();
void binarySaveToFileSlot();
void findPattern();
void copyFileOffsetSlot();
void undoSelectionSlot();
void findReferencesSlot();
void selectionUpdatedSlot();
void syncWithExpressionSlot();
void allocMemorySlot();
void headerButtonReleasedSlot(int colIndex);
private:
MenuBuilder* mMenuBuilder;
CommonActions* mCommonActions;
QMenu* mPluginMenu;
QMenu* mFollowInDumpMenu;
QList<QAction*> mFollowInDumpActions;
GotoDialog* mGoto = nullptr;
GotoDialog* mGotoOffset = nullptr;
CPUDisassembly* mDisas;
CPUMultiDump* mMultiDump;
int mAsciiSeparator = 0;
enum ViewEnum_t
{
ViewHexAscii = 0,
ViewHexUnicode,
ViewTextAscii,
ViewTextUnicode,
ViewIntegerSignedShort,
ViewIntegerSignedLong,
ViewIntegerSignedLongLong,
ViewIntegerUnsignedShort,
ViewIntegerUnsignedLong,
ViewIntegerUnsignedLongLong,
ViewIntegerHexShort,
ViewIntegerHexLong,
ViewIntegerHexLongLong,
ViewFloatFloat,
ViewFloatDouble,
ViewFloatLongDouble,
ViewAddress,
ViewIntegerSignedByte,
ViewIntegerUnsignedByte,
ViewAddressAscii,
ViewAddressUnicode,
ViewHexCodepage,
ViewTextCodepage
};
void setView(ViewEnum_t view);
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUInfoBox.cpp | #include "CPUInfoBox.h"
#include "Configuration.h"
#include "WordEditDialog.h"
#include "XrefBrowseDialog.h"
#include "Bridge.h"
#include "QBeaEngine.h"
CPUInfoBox::CPUInfoBox(QWidget* parent) : StdTable(parent)
{
setWindowTitle("InfoBox");
enableMultiSelection(false);
setShowHeader(false);
addColumnAt(0, "", true);
setRowCount(4);
setCellContent(0, 0, "");
setCellContent(1, 0, "");
setCellContent(2, 0, "");
setCellContent(3, 0, "");
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
int height = getHeight();
setMinimumHeight(height);
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChanged(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(addInfoLine(QString)), this, SLOT(addInfoLine(QString)));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(doubleClickedSlot()));
curAddr = 0;
// Deselect any row (visual reasons only)
setSingleSelection(-1);
int maxModuleSize = (int)ConfigUint("Disassembler", "MaxModuleSize");
mDisasm = new QBeaEngine(maxModuleSize);
setupContextMenu();
}
CPUInfoBox::~CPUInfoBox()
{
delete mDisasm;
}
void CPUInfoBox::setupContextMenu()
{
mCopyAddressAction = makeAction(tr("Address"), SLOT(copyAddress()));
mCopyRvaAction = makeAction(tr("RVA"), SLOT(copyRva()));
mCopyOffsetAction = makeAction(tr("File Offset"), SLOT(copyOffset()));
mCopyLineAction = makeAction(tr("Copy Line"), SLOT(copyLineSlot()));
setupShortcuts();
}
int CPUInfoBox::getHeight()
{
return ((getRowHeight() + 1) * 4);
}
void CPUInfoBox::setInfoLine(int line, QString text)
{
if(line < 0 || line > 3)
return;
setCellContent(line, 0, text);
reloadData();
}
QString CPUInfoBox::getInfoLine(int line)
{
if(line < 0 || line > 3)
return QString();
return getCellContent(line, 0);
}
void CPUInfoBox::addInfoLine(const QString & infoLine)
{
auto rowCount = getRowCount();
setRowCount(rowCount + 1);
setCellContent(rowCount, 0, infoLine);
reloadData();
}
void CPUInfoBox::clear()
{
// Set all 4 lines to empty strings
setRowCount(4);
setInfoLine(0, "");
setInfoLine(1, "");
setInfoLine(2, "");
setInfoLine(3, "");
}
QString CPUInfoBox::formatSSEOperand(const QByteArray & data, unsigned char vectorType)
{
QString hex;
bool isXMMdecoded = false;
switch(vectorType)
{
case Zydis::VETFloat32:
if(data.size() == 32)
{
hex = composeRegTextYMM(data.constData(), 1);
isXMMdecoded = true;
}
else if(data.size() == 16)
{
hex = composeRegTextXMM(data.constData(), 1);
isXMMdecoded = true;
}
else if(data.size() == 4)
{
hex = ToFloatString(data.constData());
isXMMdecoded = true;
}
break;
case Zydis::VETFloat64:
if(data.size() == 32)
{
hex = composeRegTextYMM(data.constData(), 2);
isXMMdecoded = true;
}
else if(data.size() == 16)
{
hex = composeRegTextXMM(data.constData(), 2);
isXMMdecoded = true;
}
else if(data.size() == 8)
{
hex = ToDoubleString(data.constData());
isXMMdecoded = true;
}
break;
default:
isXMMdecoded = false;
break;
}
if(!isXMMdecoded)
{
hex.reserve(data.size() * 3);
for(int k = 0; k < data.size(); k++)
{
if(k)
hex.append(' ');
hex.append(ToByteString(data[k]));
}
}
return hex;
}
void CPUInfoBox::disasmSelectionChanged(dsint parVA)
{
curAddr = parVA;
curRva = -1;
curOffset = -1;
if(!DbgIsDebugging() || !DbgMemIsValidReadPtr(parVA))
return;
// Rather than using clear() or setInfoLine(), only reset the first three cells to reduce flicker
setRowCount(4);
setCellContent(0, 0, "");
setCellContent(1, 0, "");
setCellContent(2, 0, "");
Instruction_t wInst;
unsigned char instructiondata[MAX_DISASM_BUFFER];
DbgMemRead(parVA, &instructiondata, MAX_DISASM_BUFFER);
wInst = mDisasm->DisassembleAt(instructiondata, MAX_DISASM_BUFFER, 0, parVA);
DISASM_INSTR instr; //Fix me: these disasm methods are so messy
DbgDisasmAt(parVA, &instr);
BASIC_INSTRUCTION_INFO basicinfo;
DbgDisasmFastAt(parVA, &basicinfo);
int start = 0;
bool commentThis = !ConfigBool("Disassembler", "OnlyCipAutoComments") || parVA == DbgValFromString("cip");
if(wInst.branchType == Instruction_t::Conditional && commentThis) //jump
{
bool taken = DbgIsJumpGoingToExecute(parVA);
if(taken)
setInfoLine(0, tr("Jump is taken"));
else
setInfoLine(0, tr("Jump is not taken"));
start = 1;
}
bool bUpper = ConfigBool("Disassembler", "Uppercase");
for(int i = 0, j = start; i < instr.argcount && j < 2; i++)
{
const DISASM_ARG & arg = instr.arg[i];
QString argMnemonic = QString(arg.mnemonic);
if(bUpper)
argMnemonic = argMnemonic.toUpper();
if(arg.type == arg_memory)
{
bool ok;
argMnemonic.toULongLong(&ok, 16);
QString valText = DbgMemIsValidReadPtr(arg.value) ? ToPtrString(arg.value) : ToHexString(arg.value);
auto valTextSym = getSymbolicNameStr(arg.value);
if(!valTextSym.contains(valText))
valText = QString("%1 %2").arg(valText, valTextSym);
else
valText = valTextSym;
argMnemonic = !ok ? QString("%1]=[%2").arg(argMnemonic).arg(valText) : valText;
QString sizeName = "";
bool knownsize = true;
switch(basicinfo.memory.size)
{
case size_byte:
sizeName = "byte ptr ";
break;
case size_word:
sizeName = "word ptr ";
break;
case size_dword:
sizeName = "dword ptr ";
break;
#ifdef _WIN64
case size_qword:
sizeName = "qword ptr ";
break;
#endif //_WIN64
case size_xmmword:
knownsize = false;
sizeName = "xmmword ptr ";
break;
case size_ymmword:
knownsize = false;
sizeName = "ymmword ptr ";
break;
default:
knownsize = false;
break;
}
sizeName += [](SEGMENTREG seg)
{
switch(seg)
{
case SEG_ES:
return "es:";
case SEG_DS:
return "ds:";
case SEG_FS:
return "fs:";
case SEG_GS:
return "gs:";
case SEG_CS:
return "cs:";
case SEG_SS:
return "ss:";
default:
return "";
}
}(arg.segment);
if(bUpper)
sizeName = sizeName.toUpper();
if(!DbgMemIsValidReadPtr(arg.value))
{
setInfoLine(j, sizeName + "[" + argMnemonic + "]=???");
}
else if(knownsize && wInst.vectorElementType[i] == Zydis::VETDefault) // MOVSD/MOVSS instruction
{
QString addrText = getSymbolicNameStr(arg.memvalue);
setInfoLine(j, sizeName + "[" + argMnemonic + "]=" + addrText);
}
else
{
QByteArray data;
data.resize(basicinfo.memory.size);
memset(data.data(), 0, data.size());
if(DbgMemRead(arg.value, data.data(), data.size()))
{
setInfoLine(j, sizeName + "[" + argMnemonic + "]=" + formatSSEOperand(data, wInst.vectorElementType[i]));
}
else
{
setInfoLine(j, sizeName + "[" + argMnemonic + "]=???");
}
}
j++;
}
else
{
QString valText;
auto symbolicName = getSymbolicNameStr(arg.value);
if(!symbolicName.contains(valText))
valText = QString("%1 (%2)").arg(symbolicName, valText);
else
valText = symbolicName;
QString mnemonic(arg.mnemonic);
bool ok;
mnemonic.toULongLong(&ok, 16);
if(ok) //skip certain numbers
{
if(ToHexString(arg.value) == symbolicName)
continue;
setInfoLine(j, symbolicName);
}
else if(!mnemonic.startsWith("xmm") &&
!mnemonic.startsWith("ymm") &&
!mnemonic.startsWith("zmm") && //TODO: properly handle display of AVX-512 registers
!mnemonic.startsWith("k") && //TODO: properly handle display of AVX-512 registers
!mnemonic.startsWith("st"))
{
setInfoLine(j, mnemonic + "=" + valText);
j++;
}
else if(mnemonic.startsWith("xmm") || mnemonic.startsWith("ymm") || mnemonic.startsWith("st"))
{
REGDUMP registers;
DbgGetRegDumpEx(®isters, sizeof(registers));
if(mnemonic == "xmm0")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[0], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm1")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[1], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm2")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[2], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm3")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[3], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm4")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[4], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm5")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[5], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm6")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[6], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm7")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[7], 16), wInst.vectorElementType[i]);
#ifdef _WIN64
else if(mnemonic == "xmm8")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[8], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm9")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[9], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm10")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[10], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm11")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[11], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm12")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[12], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm13")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[13], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm14")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[14], 16), wInst.vectorElementType[i]);
else if(mnemonic == "xmm15")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.XmmRegisters[15], 16), wInst.vectorElementType[i]);
#endif //_WIN64
else if(mnemonic == "ymm0")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[0], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm1")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[1], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm2")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[2], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm3")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[3], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm4")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[4], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm5")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[5], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm6")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[6], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm7")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[7], 32), wInst.vectorElementType[i]);
#ifdef _WIN64
else if(mnemonic == "ymm8")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[8], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm9")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[9], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm10")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[10], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm11")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[11], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm12")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[12], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm13")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[13], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm14")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[14], 32), wInst.vectorElementType[i]);
else if(mnemonic == "ymm15")
valText = formatSSEOperand(QByteArray((const char*)®isters.regcontext.YmmRegisters[15], 32), wInst.vectorElementType[i]);
#endif //_WIN64
else if(mnemonic == "st0")
valText = ToLongDoubleString(®isters.x87FPURegisters[registers.x87StatusWordFields.TOP & 7]);
else if(mnemonic == "st1")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 1) & 7]);
else if(mnemonic == "st2")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 2) & 7]);
else if(mnemonic == "st3")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 3) & 7]);
else if(mnemonic == "st4")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 4) & 7]);
else if(mnemonic == "st5")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 5) & 7]);
else if(mnemonic == "st6")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 6) & 7]);
else if(mnemonic == "st7")
valText = ToLongDoubleString(®isters.x87FPURegisters[(registers.x87StatusWordFields.TOP + 7) & 7]);
setInfoLine(j, mnemonic + "=" + valText);
j++;
}
}
}
if(getInfoLine(0) == getInfoLine(1)) //check for duplicate info line
setInfoLine(1, "");
// check references details
// code extracted from ExtraInfo plugin by torusrxxx
XREF_INFO xrefInfo;
xrefInfo.refcount = 0;
xrefInfo.references = nullptr;
if(DbgXrefGet(parVA, &xrefInfo) && xrefInfo.refcount > 0)
{
QString output;
std::vector<XREF_RECORD*> data;
for(duint i = 0; i < xrefInfo.refcount; i++)
data.push_back(&xrefInfo.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);
});
int t = XREF_NONE;
duint i;
for(i = 0; i < xrefInfo.refcount && i < 10; i++)
{
if(t != data[i]->type)
{
switch(data[i]->type)
{
case XREF_JMP:
output += tr("Jump from ");
break;
case XREF_CALL:
output += tr("Call from ");
break;
default:
output += tr("Reference from ");
break;
}
t = data[i]->type;
}
char clabel[MAX_LABEL_SIZE] = "";
DbgGetLabelAt(data[i]->addr, SEG_DEFAULT, clabel);
if(*clabel)
output += QString(clabel);
else
{
duint start;
if(DbgFunctionGet(data[i]->addr, &start, nullptr) && DbgGetLabelAt(start, SEG_DEFAULT, clabel) && start != data[i]->addr)
output += QString("%1+%2").arg(clabel).arg(ToHexString(data[i]->addr - start));
else
output += QString("%1").arg(ToHexString(data[i]->addr));
}
if(i != xrefInfo.refcount - 1)
output += ", ";
}
data.clear();
if(xrefInfo.refcount > 10)
output += "...";
setInfoLine(2, output);
}
// Set last line
//
// Format: SECTION:VA MODULE:$RVA :#FILE_OFFSET FUNCTION, Accessed %u times
QString info;
// Section
char section[MAX_SECTION_SIZE * 5];
if(DbgFunctions()->SectionFromAddr(parVA, section))
info += QString(section) + ":";
// VA
info += ToPtrString(parVA);
// Module name, RVA, and file offset
char mod[MAX_MODULE_SIZE];
if(DbgFunctions()->ModNameFromAddr(parVA, mod, true))
{
dsint modbase = DbgFunctions()->ModBaseFromAddr(parVA);
// Append modname
info += " " + QString(mod);
// Module RVA
curRva = parVA - modbase;
if(modbase)
info += QString(":$%1").arg(ToHexString(curRva));
// File offset
curOffset = DbgFunctions()->VaToFileOffset(parVA);
info += QString(" #%1").arg(ToHexString(curOffset));
}
// Function/label name
char label[MAX_LABEL_SIZE];
if(DbgGetLabelAt(parVA, SEG_DEFAULT, label))
info += QString(" <%1>").arg(label);
else
{
duint start;
if(DbgFunctionGet(parVA, &start, nullptr) && DbgGetLabelAt(start, SEG_DEFAULT, label) && start != parVA)
info += QString(" <%1+%2>").arg(label).arg(ToHexString(parVA - start));
}
auto tracedCount = DbgFunctions()->GetTraceRecordHitCount(parVA);
if(tracedCount != 0)
{
info += ", " + tr("Accessed %n time(s)", nullptr, tracedCount);
}
setInfoLine(3, info);
DbgSelChanged(GUI_DISASSEMBLY, parVA);
}
void CPUInfoBox::dbgStateChanged(DBGSTATE state)
{
if(state == stopped)
clear();
}
/**
* @brief CPUInfoBox::followActionSlot Called when follow or watch action is clicked
*/
void CPUInfoBox::followActionSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action && action->objectName().startsWith("DUMP|"))
DbgCmdExec(QString("dump \"%1\"").arg(action->objectName().mid(5)));
else if(action && action->objectName().startsWith("WATCH|"))
DbgCmdExec(QString("AddWatch \"[%1]\"").arg(action->objectName().mid(6)));
}
void CPUInfoBox::modifySlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action)
{
duint addrVal = 0;
DbgFunctions()->ValFromString(action->objectName().toUtf8().constData(), &addrVal);
WordEditDialog wEditDialog(this);
dsint value = 0;
DbgMemRead(addrVal, &value, sizeof(dsint));
wEditDialog.setup(tr("Modify Value"), value, sizeof(dsint));
if(wEditDialog.exec() != QDialog::Accepted)
return;
value = wEditDialog.getVal();
DbgMemWrite(addrVal, &value, sizeof(dsint));
GuiUpdateAllViews();
}
}
void CPUInfoBox::findXReferencesSlot()
{
if(!DbgIsDebugging())
return;
if(!mXrefDlg)
mXrefDlg = new XrefBrowseDialog(this);
mXrefDlg->setup(curAddr, [](duint address)
{
DbgCmdExec(QString("disasm %1").arg(ToPtrString(address)));
});
mXrefDlg->showNormal();
}
void CPUInfoBox::addModifyValueMenuItem(QMenu* menu, QString name, duint value)
{
foreach(QAction* action, menu->actions()) //check for duplicate action
if(action->text() == name)
return;
QAction* newAction = new QAction(name, menu);
menu->addAction(newAction);
newAction->setObjectName(ToPtrString(value));
connect(newAction, SIGNAL(triggered()), this, SLOT(modifySlot()));
}
void CPUInfoBox::setupModifyValueMenu(QMenu* menu, duint wVA)
{
menu->setIcon(DIcon("modify"));
//add follow actions
DISASM_INSTR instr;
DbgDisasmAt(wVA, &instr);
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG arg = instr.arg[i];
if(arg.type == arg_memory)
{
QString segment = "";
#ifdef _WIN64
if(arg.segment == SEG_GS)
segment = "gs:";
#else //x32
if(arg.segment == SEG_FS)
segment = "fs:";
#endif //_WIN64
if(DbgMemIsValidReadPtr(arg.value))
addModifyValueMenuItem(menu, tr("&Address: ") + segment + QString(arg.mnemonic).toUpper().trimmed(), arg.value);
if(arg.value != arg.constant)
{
QString constant = QString("%1").arg(ToHexString(arg.constant));
if(DbgMemIsValidReadPtr(arg.constant))
addModifyValueMenuItem(menu, tr("&Constant: ") + constant, arg.constant);
}
if(DbgMemIsValidReadPtr(arg.memvalue))
addModifyValueMenuItem(menu, tr("&Value: ") + segment + "[" + QString(arg.mnemonic).toUpper().trimmed() + "]", arg.memvalue);
}
else
{
if(DbgMemIsValidReadPtr(arg.value))
addModifyValueMenuItem(menu, "&Value: [" + QString(arg.mnemonic).toUpper().trimmed() + "]", arg.value);
}
}
}
/**
* @brief CPUInfoBox::addFollowMenuItem Add a follow action to the menu
* @param menu The menu to which the follow action adds
* @param name The user-friendly name of the action
* @param value The VA of the address
*/
void CPUInfoBox::addFollowMenuItem(QMenu* menu, QString name, duint value)
{
foreach(QAction* action, menu->actions()) //check for duplicate action
if(action->text() == name)
return;
QAction* newAction = new QAction(name, menu);
menu->addAction(newAction);
newAction->setObjectName(QString("DUMP|") + ToPtrString(value));
connect(newAction, SIGNAL(triggered()), this, SLOT(followActionSlot()));
}
/**
* @brief CPUInfoBox::setupFollowMenu Set up a follow menu.
* @param menu The menu to create
* @param wVA The selected VA
*/
void CPUInfoBox::setupFollowMenu(QMenu* menu, duint wVA)
{
menu->setIcon(DIcon("dump"));
//most basic follow action
addFollowMenuItem(menu, tr("&Selected Address"), wVA);
//add follow actions
DISASM_INSTR instr;
DbgDisasmAt(wVA, &instr);
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG arg = instr.arg[i];
if(arg.type == arg_memory)
{
QString segment = "";
#ifdef _WIN64
if(arg.segment == SEG_GS)
segment = "gs:";
#else //x32
if(arg.segment == SEG_FS)
segment = "fs:";
#endif //_WIN64
if(DbgMemIsValidReadPtr(arg.value))
addFollowMenuItem(menu, tr("&Address: ") + segment + QString(arg.mnemonic).toUpper().trimmed(), arg.value);
if(arg.value != arg.constant)
{
QString constant = QString("%1").arg(ToHexString(arg.constant));
if(DbgMemIsValidReadPtr(arg.constant))
addFollowMenuItem(menu, tr("&Constant: ") + constant, arg.constant);
}
if(DbgMemIsValidReadPtr(arg.memvalue))
addFollowMenuItem(menu, tr("&Value: ") + segment + "[" + QString(arg.mnemonic) + "]", arg.memvalue);
}
else
{
if(DbgMemIsValidReadPtr(arg.value))
addFollowMenuItem(menu, QString(arg.mnemonic).toUpper().trimmed(), arg.value);
}
}
}
/**
* @brief CPUInfoBox::addFollowMenuItem Add a follow action to the menu
* @param menu The menu to which the follow action adds
* @param name The user-friendly name of the action
* @param value The VA of the address
*/
void CPUInfoBox::addWatchMenuItem(QMenu* menu, QString name, duint value)
{
foreach(QAction* action, menu->actions()) //check for duplicate action
if(action->text() == name)
return;
QAction* newAction = new QAction(name, menu);
menu->addAction(newAction);
newAction->setObjectName(QString("WATCH|") + ToPtrString(value));
connect(newAction, SIGNAL(triggered()), this, SLOT(followActionSlot()));
}
/**
* @brief CPUInfoBox::setupFollowMenu Set up a follow menu.
* @param menu The menu to create
* @param wVA The selected VA
*/
void CPUInfoBox::setupWatchMenu(QMenu* menu, duint wVA)
{
menu->setIcon(DIcon("animal-dog"));
//most basic follow action
addWatchMenuItem(menu, tr("&Selected Address"), wVA);
//add follow actions
DISASM_INSTR instr;
DbgDisasmAt(wVA, &instr);
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG arg = instr.arg[i];
if(arg.type == arg_memory)
{
QString segment = "";
#ifdef _WIN64
if(arg.segment == SEG_GS)
segment = "gs:";
#else //x32
if(arg.segment == SEG_FS)
segment = "fs:";
#endif //_WIN64
if(DbgMemIsValidReadPtr(arg.value))
addWatchMenuItem(menu, tr("&Address: ") + segment + QString(arg.mnemonic).toUpper().trimmed(), arg.value);
if(arg.value != arg.constant)
{
QString constant = QString("%1").arg(ToHexString(arg.constant));
if(DbgMemIsValidReadPtr(arg.constant))
addWatchMenuItem(menu, tr("&Constant: ") + constant, arg.constant);
}
if(DbgMemIsValidReadPtr(arg.memvalue))
addWatchMenuItem(menu, tr("&Value: ") + segment + "[" + QString(arg.mnemonic) + "]", arg.memvalue);
}
else
{
if(DbgMemIsValidReadPtr(arg.value))
addWatchMenuItem(menu, QString(arg.mnemonic).toUpper().trimmed(), arg.value);
}
}
}
int CPUInfoBox::followInDump(dsint wVA)
{
// Copy pasta from setupFollowMenu for now
int tableOffset = getInitialSelection();
QString cellContent = this->getCellContent(tableOffset, 0);
// No text in row that was clicked
if(cellContent.length() == 0)
return -1;
// Last line of infoBox => Current Address(EIP) in disassembly
if(tableOffset == 2)
{
DbgCmdExec(QString("dump %1").arg(ToPtrString(wVA)));
return 0;
}
DISASM_INSTR instr;
DbgDisasmAt(wVA, &instr);
if(instr.type == instr_branch && cellContent.contains("Jump"))
{
DbgCmdExec(QString("dump %1").arg(ToPtrString(instr.arg[0].value)));
return 0;
}
// Loop through all instruction arguments
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG arg = instr.arg[i];
if(arg.type == arg_memory)
{
if(DbgMemIsValidReadPtr(arg.value))
{
if(cellContent.contains(arg.mnemonic))
{
DbgCmdExec(QString("dump %1").arg(ToPtrString(arg.value)));
return 0;
}
}
}
}
return 0;
}
void CPUInfoBox::contextMenuSlot(QPoint pos)
{
QMenu wMenu(this); //create context menu
QMenu wFollowMenu(tr("&Follow in Dump"), this);
setupFollowMenu(&wFollowMenu, curAddr);
wMenu.addMenu(&wFollowMenu);
QMenu wModifyValueMenu(tr("&Modify Value"), this);
setupModifyValueMenu(&wModifyValueMenu, curAddr);
if(!wModifyValueMenu.isEmpty())
wMenu.addMenu(&wModifyValueMenu);
QMenu wWatchMenu(tr("&Watch"), this);
setupWatchMenu(&wWatchMenu, curAddr);
wMenu.addMenu(&wWatchMenu);
if(!getInfoLine(2).isEmpty())
wMenu.addAction(makeAction(DIcon("xrefs"), tr("&Show References"), SLOT(findXReferencesSlot())));
QMenu wCopyMenu(tr("&Copy"), this);
setupCopyMenu(&wCopyMenu);
if(DbgIsDebugging())
{
wCopyMenu.addAction(mCopyAddressAction);
if(curRva != -1)
wCopyMenu.addAction(mCopyRvaAction);
if(curOffset != -1)
wCopyMenu.addAction(mCopyOffsetAction);
}
if(wCopyMenu.actions().length())
{
wMenu.addSeparator();
wMenu.addMenu(&wCopyMenu);
}
wMenu.exec(mapToGlobal(pos)); //execute context menu
}
void CPUInfoBox::copyAddress()
{
Bridge::CopyToClipboard(ToPtrString(curAddr));
}
void CPUInfoBox::copyRva()
{
Bridge::CopyToClipboard(ToHexString(curRva));
}
void CPUInfoBox::copyOffset()
{
Bridge::CopyToClipboard(ToHexString(curOffset));
}
void CPUInfoBox::doubleClickedSlot()
{
followInDump(curAddr);
}
void CPUInfoBox::setupShortcuts()
{
mCopyLineAction->setShortcut(ConfigShortcut("ActionCopyLine"));
addAction(mCopyLineAction);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUInfoBox.h | #pragma once
#include "StdTable.h"
class WordEditDialog;
class XrefBrowseDialog;
class QBeaEngine;
class CPUInfoBox : public StdTable
{
Q_OBJECT
public:
explicit CPUInfoBox(QWidget* parent = 0);
~CPUInfoBox();
int getHeight();
void addFollowMenuItem(QMenu* menu, QString name, duint value);
void setupFollowMenu(QMenu* menu, duint wVA);
void addModifyValueMenuItem(QMenu* menu, QString name, duint value);
void setupModifyValueMenu(QMenu* menu, duint wVA);
void addWatchMenuItem(QMenu* menu, QString name, duint value);
void setupWatchMenu(QMenu* menu, duint wVA);
int followInDump(dsint wVA);
static QString formatSSEOperand(const QByteArray & data, unsigned char vectorType);
public slots:
void disasmSelectionChanged(dsint parVA);
void dbgStateChanged(DBGSTATE state);
void contextMenuSlot(QPoint pos);
void followActionSlot();
void modifySlot();
void findXReferencesSlot();
void copyAddress();
void copyRva();
void copyOffset();
void doubleClickedSlot();
void addInfoLine(const QString & infoLine);
private:
dsint curAddr;
dsint curRva;
dsint curOffset;
void setInfoLine(int line, QString text);
QString getInfoLine(int line);
void clear();
void setupContextMenu();
void setupShortcuts();
XrefBrowseDialog* mXrefDlg = nullptr;
QBeaEngine* mDisasm;
QAction* mCopyAddressAction;
QAction* mCopyRvaAction;
QAction* mCopyOffsetAction;
QAction* mCopyLineAction;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUMultiDump.cpp | #include "CPUMultiDump.h"
#include "CPUDump.h"
#include "CPUDisassembly.h"
#include "WatchView.h"
#include "LocalVarsView.h"
#include "StructWidget.h"
#include "Bridge.h"
#include <QInputDialog>
#include <QMessageBox>
#include <QTabBar>
CPUMultiDump::CPUMultiDump(CPUDisassembly* disas, int nbCpuDumpTabs, QWidget* parent)
: MHTabWidget(parent, true)
{
setWindowTitle("CPUMultiDump");
mMaxCPUDumpTabs = nbCpuDumpTabs;
mInitAllDumpTabs = false;
mDumpPluginMenu = new QMenu(this);
mDumpPluginMenu->setIcon(DIcon("plugin"));
Bridge::getBridge()->emitMenuAddToList(this, mDumpPluginMenu, GUI_DUMP_MENU);
for(uint i = 0; i < mMaxCPUDumpTabs; i++)
{
CPUDump* cpuDump = new CPUDump(disas, this);
//cpuDump->loadColumnFromConfig(QString("CPUDump%1").arg(i + 1)); //TODO: needs a workaround because the columns change
connect(cpuDump, SIGNAL(displayReferencesWidget()), this, SLOT(displayReferencesWidgetSlot()));
connect(cpuDump, SIGNAL(showDisassemblyTab(duint, duint, duint)), this, SLOT(showDisassemblyTabSlot(duint, duint, duint)));
auto nativeTitle = QString("Dump ") + QString::number(i + 1);
this->addTabEx(cpuDump, DIcon("dump"), tr("Dump ") + QString::number(i + 1), nativeTitle);
cpuDump->setWindowTitle(nativeTitle);
}
mCurrentCPUDump = dynamic_cast<CPUDump*>(currentWidget());
mWatch = new WatchView(this);
//mMaxCPUDumpTabs++;
auto nativeTitle = QString("Watch 1");
this->addTabEx(mWatch, DIcon("animal-dog"), tr("Watch ") + QString::number(1), nativeTitle);
mWatch->setWindowTitle(nativeTitle);
mWatch->loadColumnFromConfig("Watch1");
mLocalVars = new LocalVarsView(this);
this->addTabEx(mLocalVars, DIcon("localvars"), tr("Locals"), "Locals");
mStructWidget = new StructWidget(this);
this->addTabEx(mStructWidget, DIcon("struct"), mStructWidget->windowTitle(), "Struct");
connect(this, SIGNAL(currentChanged(int)), this, SLOT(updateCurrentTabSlot(int)));
connect(tabBar(), SIGNAL(OnDoubleClickTabIndex(int)), this, SLOT(openChangeTabTitleDialogSlot(int)));
connect(Bridge::getBridge(), SIGNAL(dumpAt(dsint)), this, SLOT(printDumpAtSlot(dsint)));
connect(Bridge::getBridge(), SIGNAL(dumpAtN(duint, int)), this, SLOT(printDumpAtNSlot(duint, int)));
connect(Bridge::getBridge(), SIGNAL(selectionDumpGet(SELECTIONDATA*)), this, SLOT(selectionGetSlot(SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(selectionDumpSet(const SELECTIONDATA*)), this, SLOT(selectionSetSlot(const SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChangedSlot(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(focusDump()), this, SLOT(focusCurrentDumpSlot()));
connect(Bridge::getBridge(), SIGNAL(getDumpAttention()), this, SLOT(getDumpAttention()));
connect(mCurrentCPUDump, SIGNAL(selectionUpdated()), mCurrentCPUDump, SLOT(selectionUpdatedSlot()));
}
CPUDump* CPUMultiDump::getCurrentCPUDump()
{
return mCurrentCPUDump;
}
// Only get tab names for all dump tabs!
void CPUMultiDump::getTabNames(QList<QString> & names)
{
names.clear();
int i;
int index;
// placeholders
for(i = 0; i < getMaxCPUTabs(); i++)
names.push_back(QString("Dump %1").arg(i + 1));
// enumerate all tabs
for(i = 0; i < QTabWidget::count(); i++)
{
if(!getNativeName(i).startsWith("Dump "))
continue;
index = getNativeName(i).mid(5).toInt() - 1;
if(index < getMaxCPUTabs())
names[index] = this->tabBar()->tabText(i);
}
// enumerate all detached windows
for(i = 0; i < windows().count(); i++)
{
QString nativeName = dynamic_cast<MHDetachedWindow*>(windows()[i]->parent())->mNativeName;
if(nativeName.startsWith("Dump "))
{
index = nativeName.mid(5).toInt() - 1;
if(index < getMaxCPUTabs())
names[index] = dynamic_cast<MHDetachedWindow*>(windows()[i]->parent())->windowTitle();
}
}
}
int CPUMultiDump::getMaxCPUTabs()
{
return mMaxCPUDumpTabs;
}
void CPUMultiDump::saveWindowSettings()
{
mStructWidget->saveWindowSettings();
}
void CPUMultiDump::loadWindowSettings()
{
mStructWidget->loadWindowSettings();
}
int CPUMultiDump::GetDumpWindowIndex(int dump)
{
QString dumpNativeName = QString("Dump ") + QString::number(dump);
for(int i = 0; i < count(); i++)
{
if(getNativeName(i) == dumpNativeName)
return i;
}
return 2147483647;
}
int CPUMultiDump::GetWatchWindowIndex()
{
QString watchNativeName = QString("Watch 1");
for(int i = 0; i < count(); i++)
{
if(getNativeName(i) == watchNativeName)
return i;
}
return 2147483647;
}
void CPUMultiDump::SwitchToDumpWindow()
{
if(!mCurrentCPUDump)
setCurrentIndex(GetDumpWindowIndex(1));
}
void CPUMultiDump::SwitchToWatchWindow()
{
if(mCurrentCPUDump)
setCurrentIndex(GetWatchWindowIndex());
}
void CPUMultiDump::updateCurrentTabSlot(int tabIndex)
{
CPUDump* t = qobject_cast<CPUDump*>(widget(tabIndex));
mCurrentCPUDump = t;
}
void CPUMultiDump::printDumpAtSlot(dsint parVa)
{
if(mInitAllDumpTabs)
{
CPUDump* cpuDump = NULL;
for(int i = 0; i < count(); i++)
{
if(!getNativeName(i).startsWith("Dump "))
continue;
cpuDump = qobject_cast<CPUDump*>(widget(i));
if(cpuDump)
{
cpuDump->mHistory.historyClear();
cpuDump->mHistory.addVaToHistory(parVa);
cpuDump->printDumpAt(parVa);
}
}
mInitAllDumpTabs = false;
}
else
{
SwitchToDumpWindow();
mCurrentCPUDump->printDumpAt(parVa);
mCurrentCPUDump->mHistory.addVaToHistory(parVa);
}
}
void CPUMultiDump::printDumpAtNSlot(duint parVa, int index)
{
int tabindex = GetDumpWindowIndex(index);
if(tabindex == 2147483647)
return;
CPUDump* current = qobject_cast<CPUDump*>(widget(tabindex));
if(!current)
return;
setCurrentIndex(tabindex);
current->printDumpAt(parVa);
current->mHistory.addVaToHistory(parVa);
}
void CPUMultiDump::selectionGetSlot(SELECTIONDATA* selectionData)
{
SwitchToDumpWindow();
mCurrentCPUDump->selectionGet(selectionData);
}
void CPUMultiDump::selectionSetSlot(const SELECTIONDATA* selectionData)
{
SwitchToDumpWindow();
mCurrentCPUDump->selectionSet(selectionData);
}
void CPUMultiDump::dbgStateChangedSlot(DBGSTATE dbgState)
{
if(dbgState == initialized)
mInitAllDumpTabs = true;
}
void CPUMultiDump::openChangeTabTitleDialogSlot(int tabIndex)
{
bool bUserPressedOk;
QString sCurrentTabName = tabBar()->tabText(tabIndex);
QString sNewTabName = QInputDialog::getText(this, tr("Change Tab %1 Name").arg(tabIndex + 1), tr("Tab Name"), QLineEdit::Normal, sCurrentTabName, &bUserPressedOk, Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
if(bUserPressedOk)
{
if(sNewTabName.length() != 0)
tabBar()->setTabText(tabIndex, sNewTabName);
}
}
void CPUMultiDump::displayReferencesWidgetSlot()
{
emit displayReferencesWidget();
}
void CPUMultiDump::focusCurrentDumpSlot()
{
SwitchToDumpWindow();
mCurrentCPUDump->setFocus();
}
void CPUMultiDump::showDisassemblyTabSlot(duint selectionStart, duint selectionEnd, duint firstAddress)
{
Q_UNUSED(firstAddress); // TODO: implement setTableOffset(firstAddress)
if(!mDisassembly)
{
mDisassembly = new CPUDisassembly(this, false);
this->addTabEx(mDisassembly, DIcon(ArchValue("processor32", "processor64")), tr("Disassembly"), "DumpDisassembly");
}
// Set CIP
auto clearHistory = mDisassembly->getBase() == 0;
mDisassembly->disassembleAtSlot(selectionStart, Bridge::getBridge()->mLastCip);
if(clearHistory)
mDisassembly->historyClear();
// Make the address visisble in memory
mDisassembly->disassembleAt(selectionStart, true, -1);
// Set selection to match the dump
mDisassembly->setSingleSelection(selectionStart - mDisassembly->getBase());
mDisassembly->expandSelectionUpTo(selectionEnd - mDisassembly->getBase());
// Show the tab
setCurrentWidget(mDisassembly);
}
void CPUMultiDump::getDumpAttention()
{
mCurrentCPUDump->getAttention();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUMultiDump.h | #pragma once
#include <QWidget>
#include "TabWidget.h"
#include "Bridge.h"
class CPUDump;
class WatchView;
class StructWidget;
class CPUDisassembly;
class LocalVarsView;
class CPUMultiDump : public MHTabWidget
{
Q_OBJECT
public:
explicit CPUMultiDump(CPUDisassembly* disas, int nbCpuDumpTabs = 1, QWidget* parent = 0);
CPUDump* getCurrentCPUDump();
void getTabNames(QList<QString> & names);
int getMaxCPUTabs();
QMenu* mDumpPluginMenu;
void saveWindowSettings();
void loadWindowSettings();
signals:
void displayReferencesWidget();
public slots:
void updateCurrentTabSlot(int tabIndex);
void printDumpAtSlot(dsint parVa);
void printDumpAtNSlot(duint parVa, int index);
void selectionGetSlot(SELECTIONDATA* selectionData);
void selectionSetSlot(const SELECTIONDATA* selectionData);
void dbgStateChangedSlot(DBGSTATE dbgState);
void openChangeTabTitleDialogSlot(int tabIndex);
void displayReferencesWidgetSlot();
void focusCurrentDumpSlot();
void showDisassemblyTabSlot(duint selectionStart, duint selectionEnd, duint firstAddress);
void getDumpAttention();
private:
CPUDump* mCurrentCPUDump;
bool mInitAllDumpTabs;
uint mMaxCPUDumpTabs;
WatchView* mWatch;
LocalVarsView* mLocalVars;
StructWidget* mStructWidget;
CPUDisassembly* mDisassembly = nullptr;
int GetDumpWindowIndex(int dump);
int GetWatchWindowIndex();
void SwitchToDumpWindow();
void SwitchToWatchWindow();
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPURegistersView.cpp | #include <QListWidget>
#include "MiscUtil.h"
#include "CPUWidget.h"
#include "CPUDisassembly.h"
#include "CPUMultiDump.h"
#include "Configuration.h"
#include "WordEditDialog.h"
#include "LineEditDialog.h"
#include "EditFloatRegister.h"
#include "SelectFields.h"
#include "CPURegistersView.h"
#include "ldconvert.h"
CPURegistersView::CPURegistersView(CPUWidget* parent) : RegistersView(parent), mParent(parent)
{
// precreate ContextMenu Actions
wCM_Modify = new QAction(DIcon("register_edit"), tr("Modify value"), this);
wCM_Modify->setShortcut(QKeySequence(Qt::Key_Enter));
wCM_Increment = new QAction(DIcon("register_inc"), tr("Increment value"), this);
wCM_Increment->setShortcut(QKeySequence(Qt::Key_Plus));
wCM_Decrement = new QAction(DIcon("register_dec"), tr("Decrement value"), this);
wCM_Decrement->setShortcut(QKeySequence(Qt::Key_Minus));
wCM_Zero = new QAction(DIcon("register_zero"), tr("Zero value"), this);
wCM_Zero->setShortcut(QKeySequence(Qt::Key_0));
wCM_ToggleValue = setupAction(DIcon("register_toggle"), tr("Toggle"));
wCM_Undo = setupAction(DIcon("undo"), tr("Undo"));
wCM_CopyPrevious = setupAction(DIcon("undo"), "");
wCM_FollowInDisassembly = new QAction(DIcon(QString("processor%1").arg(ArchValue("32", "64"))), tr("Follow in Disassembler"), this);
wCM_FollowInDump = new QAction(DIcon("dump"), tr("Follow in Dump"), this);
wCM_FollowInStack = new QAction(DIcon("stack"), tr("Follow in Stack"), this);
wCM_FollowInMemoryMap = new QAction(DIcon("memmap_find_address_page"), tr("Follow in Memory Map"), this);
wCM_RemoveHardware = new QAction(DIcon("breakpoint_remove"), tr("&Remove hardware breakpoint"), this);
wCM_Incrementx87Stack = setupAction(DIcon("arrow-small-down"), tr("Increment x87 Stack"));
wCM_Decrementx87Stack = setupAction(DIcon("arrow-small-up"), tr("Decrement x87 Stack"));
wCM_Highlight = setupAction(DIcon("highlight"), tr("Highlight"));
// foreign messages
connect(Bridge::getBridge(), SIGNAL(updateRegisters()), this, SLOT(updateRegistersSlot()));
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(displayCustomContextMenuSlot(QPoint)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(debugStateChangedSlot(DBGSTATE)));
connect(parent->getDisasmWidget(), SIGNAL(selectionChanged(dsint)), this, SLOT(disasmSelectionChangedSlot(dsint)));
// context menu actions
connect(wCM_Incrementx87Stack, SIGNAL(triggered()), this, SLOT(onIncrementx87StackAction()));
connect(wCM_Decrementx87Stack, SIGNAL(triggered()), this, SLOT(onDecrementx87StackAction()));
connect(wCM_Modify, SIGNAL(triggered()), this, SLOT(onModifyAction()));
connect(wCM_Increment, SIGNAL(triggered()), this, SLOT(onIncrementAction()));
connect(wCM_Decrement, SIGNAL(triggered()), this, SLOT(onDecrementAction()));
connect(wCM_Zero, SIGNAL(triggered()), this, SLOT(onZeroAction()));
connect(wCM_ToggleValue, SIGNAL(triggered()), this, SLOT(onToggleValueAction()));
connect(wCM_Undo, SIGNAL(triggered()), this, SLOT(onUndoAction()));
connect(wCM_CopyPrevious, SIGNAL(triggered()), this, SLOT(onCopyPreviousAction()));
connect(wCM_FollowInDisassembly, SIGNAL(triggered()), this, SLOT(onFollowInDisassembly()));
connect(wCM_FollowInDump, SIGNAL(triggered()), this, SLOT(onFollowInDump()));
connect(wCM_FollowInStack, SIGNAL(triggered()), this, SLOT(onFollowInStack()));
connect(wCM_FollowInMemoryMap, SIGNAL(triggered()), this, SLOT(onFollowInMemoryMap()));
connect(wCM_RemoveHardware, SIGNAL(triggered()), this, SLOT(onRemoveHardware()));
connect(wCM_Highlight, SIGNAL(triggered()), this, SLOT(onHighlightSlot()));
refreshShortcutsSlot();
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcutsSlot()));
}
void CPURegistersView::refreshShortcutsSlot()
{
wCM_ToggleValue->setShortcut(ConfigShortcut("ActionToggleRegisterValue"));
wCM_Highlight->setShortcut(ConfigShortcut("ActionHighlightingMode"));
wCM_Incrementx87Stack->setShortcut(ConfigShortcut("ActionIncrementx87Stack"));
wCM_Decrementx87Stack->setShortcut(ConfigShortcut("ActionDecrementx87Stack"));
RegistersView::refreshShortcutsSlot();
}
void CPURegistersView::mousePressEvent(QMouseEvent* event)
{
if(!isActive)
return;
if(event->y() < yTopSpacing - mButtonHeight)
{
onChangeFPUViewAction();
}
else
{
// get mouse position
const int y = (event->y() - yTopSpacing) / (double)mRowHeight;
const int x = event->x() / (double)mCharWidth;
REGISTER_NAME r;
// do we find a corresponding register?
if(identifyRegister(y, x, &r))
{
Disassembly* CPUDisassemblyView = mParent->getDisasmWidget();
if(CPUDisassemblyView->isHighlightMode())
{
if(mGPR.contains(r) && r != REGISTER_NAME::EFLAGS)
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::GeneralRegister, mRegisterMapping.constFind(r).value()));
else if(mFPUMMX.contains(r))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::MmxRegister, mRegisterMapping.constFind(r).value()));
else if(mFPUXMM.contains(r))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::XmmRegister, mRegisterMapping.constFind(r).value()));
else if(mFPUYMM.contains(r))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::YmmRegister, mRegisterMapping.constFind(r).value()));
else if(mSEGMENTREGISTER.contains(r))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::MemorySegment, mRegisterMapping.constFind(r).value()));
else
mSelected = r;
}
else
mSelected = r;
emit refresh();
}
else
mSelected = UNKNOWN;
}
}
void CPURegistersView::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, disasm CIP
DbgCmdExec("disasm cip");
// is current register general purposes register or FPU register?
else if(mMODIFYDISPLAY.contains(mSelected))
wCM_Modify->trigger();
else if(mBOOLDISPLAY.contains(mSelected)) // is flag ?
wCM_ToggleValue->trigger(); //toggle flag value
else if(mCANSTOREADDRESS.contains(mSelected))
wCM_FollowInDisassembly->trigger(); //follow in disassembly
else if(mSelected == ArchValue(FS, GS)) // double click on FS or GS, follow TEB in dump
DbgCmdExec("dump teb()");
}
void CPURegistersView::keyPressEvent(QKeyEvent* event)
{
if(isActive && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return))
wCM_Modify->trigger();
else if(isActive && (event->key() == Qt::Key_Plus))
wCM_Increment->trigger();
else if(isActive && (event->key() == Qt::Key_Minus))
wCM_Decrement->trigger();
else if(isActive && (event->key() == Qt::Key_0))
wCM_Zero->trigger();
else
RegistersView::keyPressEvent(event);
}
void CPURegistersView::debugStateChangedSlot(DBGSTATE state)
{
if(state == stopped)
{
updateRegistersSlot();
isActive = false;
}
else
{
isActive = true;
}
}
void CPURegistersView::updateRegistersSlot()
{
// read registers
REGDUMP z;
DbgGetRegDumpEx(&z, sizeof(REGDUMP));
// update gui
setRegisters(&z);
}
void CPURegistersView::ModifyFields(const QString & title, STRING_VALUE_TABLE_t* table, SIZE_T size)
{
SelectFields mSelectFields(this);
QListWidget* mQListWidget = mSelectFields.GetList();
QStringList items;
unsigned int i;
for(i = 0; i < size; i++)
items << QApplication::translate("RegistersView_ConstantsOfRegisters", table[i].string) + QString(" (%1)").arg(table[i].value, 0, 16);
mQListWidget->addItems(items);
mSelectFields.setWindowTitle(title);
if(mSelectFields.exec() != QDialog::Accepted)
return;
if(mQListWidget->selectedItems().count() != 1)
return;
//QListWidgetItem* item = mQListWidget->takeItem(mQListWidget->currentRow());
QString itemText = mQListWidget->item(mQListWidget->currentRow())->text();
duint value;
for(i = 0; i < size; i++)
{
if(QApplication::translate("RegistersView_ConstantsOfRegisters", table[i].string) + QString(" (%1)").arg(table[i].value, 0, 16) == itemText)
break;
}
value = table[i].value;
setRegister(mSelected, (duint)value);
//delete item;
}
extern STRING_VALUE_TABLE_t MxCsrRCValueStringTable[4];
extern STRING_VALUE_TABLE_t ControlWordRCValueStringTable[4];
extern STRING_VALUE_TABLE_t StatusWordTOPValueStringTable[8];
extern STRING_VALUE_TABLE_t ControlWordPCValueStringTable[4];
extern STRING_VALUE_TABLE_t TagWordValueStringTable[4];
#define MODIFY_FIELDS_DISPLAY(prefix, title, table) ModifyFields(prefix + QChar(' ') + QString(title), (STRING_VALUE_TABLE_t *) & table, SIZE_TABLE(table) )
static void editSIMDRegister(CPURegistersView* parent, int bits, const QString & title, char* data, RegistersView::REGISTER_NAME mSelected)
{
EditFloatRegister mEditFloat(bits, parent);
mEditFloat.setWindowTitle(title);
mEditFloat.loadData(data);
mEditFloat.show();
mEditFloat.selectAllText();
if(mEditFloat.exec() == QDialog::Accepted)
parent->setRegister(mSelected, (duint)mEditFloat.getData());
}
/**
* @brief This function displays the appropriate edit dialog according to selected register
* @return Nothing.
*/
void CPURegistersView::displayEditDialog()
{
if(mFPU.contains(mSelected))
{
if(mTAGWORD.contains(mSelected))
MODIFY_FIELDS_DISPLAY(tr("Edit"), "Tag " + mRegisterMapping.constFind(mSelected).value(), TagWordValueStringTable);
else if(mSelected == MxCsr_RC)
MODIFY_FIELDS_DISPLAY(tr("Edit"), "MxCsr_RC", MxCsrRCValueStringTable);
else if(mSelected == x87CW_RC)
MODIFY_FIELDS_DISPLAY(tr("Edit"), "x87CW_RC", ControlWordRCValueStringTable);
else if(mSelected == x87CW_PC)
MODIFY_FIELDS_DISPLAY(tr("Edit"), "x87CW_PC", ControlWordPCValueStringTable);
else if(mSelected == x87SW_TOP)
{
MODIFY_FIELDS_DISPLAY(tr("Edit"), "x87SW_TOP", StatusWordTOPValueStringTable);
// if(mFpuMode == false)
updateRegistersSlot();
}
else if(mFPUYMM.contains(mSelected))
editSIMDRegister(this, 256, tr("Edit YMM register"), registerValue(&wRegDumpStruct, mSelected), mSelected);
else if(mFPUXMM.contains(mSelected))
editSIMDRegister(this, 128, tr("Edit XMM register"), registerValue(&wRegDumpStruct, mSelected), mSelected);
else if(mFPUMMX.contains(mSelected))
editSIMDRegister(this, 64, tr("Edit MMX register"), registerValue(&wRegDumpStruct, mSelected), mSelected);
else
{
bool errorinput = false;
LineEditDialog mLineEdit(this);
mLineEdit.setText(GetRegStringValueFromValue(mSelected, registerValue(&wRegDumpStruct, mSelected)));
mLineEdit.setWindowTitle(tr("Edit FPU register"));
mLineEdit.setWindowIcon(DIcon("log"));
mLineEdit.setCursorPosition(0);
auto sizeRegister = int(GetSizeRegister(mSelected));
if(sizeRegister == 10)
mLineEdit.setFpuMode();
mLineEdit.ForceSize(sizeRegister * 2);
do
{
errorinput = false;
mLineEdit.show();
mLineEdit.selectAllText();
if(mLineEdit.exec() != QDialog::Accepted)
return; //pressed cancel
else
{
bool ok = false;
duint fpuvalue;
if(mUSHORTDISPLAY.contains(mSelected))
fpuvalue = (duint) mLineEdit.editText.toUShort(&ok, 16);
else if(mDWORDDISPLAY.contains(mSelected))
fpuvalue = mLineEdit.editText.toUInt(&ok, 16);
else if(mFPUx87_80BITSDISPLAY.contains(mSelected))
{
QString editTextLower = mLineEdit.editText.toLower();
if(sizeRegister == 10 && (mLineEdit.editText.contains(QChar('.')) || editTextLower == "nan" || editTextLower == "inf"
|| editTextLower == "+inf" || editTextLower == "-inf"))
{
char number[10];
str2ld(mLineEdit.editText.toUtf8().constData(), number);
setRegister(mSelected, reinterpret_cast<duint>(number));
return;
}
else
{
QByteArray pArray = mLineEdit.editText.toLocal8Bit();
if(pArray.size() == sizeRegister * 2)
{
char* pData = (char*) calloc(1, sizeof(char) * sizeRegister);
if(pData != NULL)
{
ok = true;
char actual_char[3];
for(int i = 0; i < sizeRegister; i++)
{
memset(actual_char, 0, sizeof(actual_char));
memcpy(actual_char, (char*) pArray.data() + (i * 2), 2);
if(! isxdigit(actual_char[0]) || ! isxdigit(actual_char[1]))
{
ok = false;
break;
}
pData[i] = (char)strtol(actual_char, NULL, 16);
}
if(ok)
{
if(!ConfigBool("Gui", "FpuRegistersLittleEndian")) // reverse byte order if it is big-endian
{
pArray = ByteReverse(QByteArray(pData, sizeRegister));
setRegister(mSelected, reinterpret_cast<duint>(pArray.constData()));
}
else
setRegister(mSelected, reinterpret_cast<duint>(pData));
}
free(pData);
if(ok)
return;
}
}
}
}
if(!ok)
{
errorinput = true;
SimpleWarningBox(this, tr("ERROR CONVERTING TO HEX"), tr("ERROR CONVERTING TO HEX"));
}
else
setRegister(mSelected, fpuvalue);
}
}
while(errorinput);
}
}
else if(mSelected == LastError)
{
bool errorinput = false;
LineEditDialog mLineEdit(this);
LASTERROR* error = (LASTERROR*)registerValue(&wRegDumpStruct, LastError);
mLineEdit.setText(QString::number(error->code, 16));
mLineEdit.setWindowTitle(tr("Set Last Error"));
mLineEdit.setCursorPosition(0);
do
{
errorinput = true;
mLineEdit.show();
mLineEdit.selectAllText();
if(mLineEdit.exec() != QDialog::Accepted)
return;
if(DbgIsValidExpression(mLineEdit.editText.toUtf8().constData()))
errorinput = false;
}
while(errorinput);
setRegister(LastError, DbgValFromString(mLineEdit.editText.toUtf8().constData()));
}
else if(mSelected == LastStatus)
{
bool statusinput = false;
LineEditDialog mLineEdit(this);
LASTSTATUS* status = (LASTSTATUS*)registerValue(&wRegDumpStruct, LastStatus);
mLineEdit.setText(QString::number(status->code, 16));
mLineEdit.setWindowTitle(tr("Set Last Status"));
mLineEdit.setCursorPosition(0);
do
{
statusinput = true;
mLineEdit.show();
mLineEdit.selectAllText();
if(mLineEdit.exec() != QDialog::Accepted)
return;
if(DbgIsValidExpression(mLineEdit.editText.toUtf8().constData()))
statusinput = false;
}
while(statusinput);
setRegister(LastStatus, DbgValFromString(mLineEdit.editText.toUtf8().constData()));
}
else
{
WordEditDialog wEditDial(this);
wEditDial.setup(tr("Edit"), (* ((duint*) registerValue(&wRegDumpStruct, mSelected))), sizeof(dsint));
if(wEditDial.exec() == QDialog::Accepted) //OK button clicked
setRegister(mSelected, wEditDial.getVal());
}
}
void CPURegistersView::CreateDumpNMenu(QMenu* dumpMenu)
{
QList<QString> names;
CPUMultiDump* multiDump = mParent->getDumpWidget();
dumpMenu->setIcon(DIcon("dump"));
int maxDumps = multiDump->getMaxCPUTabs();
multiDump->getTabNames(names);
for(int i = 0; i < maxDumps; i++)
{
QAction* action = new QAction(names.at(i), this);
connect(action, SIGNAL(triggered()), this, SLOT(onFollowInDumpN()));
dumpMenu->addAction(action);
action->setData(i + 1);
}
}
void CPURegistersView::onIncrementx87StackAction()
{
if(mFPUx87_80BITSDISPLAY.contains(mSelected))
setRegister(x87SW_TOP, ((* ((duint*) registerValue(&wRegDumpStruct, x87SW_TOP))) + 1) % 8);
}
void CPURegistersView::onDecrementx87StackAction()
{
if(mFPUx87_80BITSDISPLAY.contains(mSelected))
setRegister(x87SW_TOP, ((* ((duint*) registerValue(&wRegDumpStruct, x87SW_TOP))) - 1) % 8);
}
void CPURegistersView::onModifyAction()
{
if(mMODIFYDISPLAY.contains(mSelected))
displayEditDialog();
}
void CPURegistersView::onIncrementAction()
{
if(mINCREMENTDECREMET.contains(mSelected))
{
duint value = *((duint*) registerValue(&wRegDumpStruct, mSelected));
setRegister(mSelected, value + 1);
}
}
void CPURegistersView::onDecrementAction()
{
if(mINCREMENTDECREMET.contains(mSelected))
{
duint value = *((duint*) registerValue(&wRegDumpStruct, mSelected));
setRegister(mSelected, value - 1);
}
}
void CPURegistersView::onZeroAction()
{
if(mINCREMENTDECREMET.contains(mSelected))
setRegister(mSelected, 0);
}
void CPURegistersView::onToggleValueAction()
{
if(mBOOLDISPLAY.contains(mSelected))
{
int value = (int)(* (bool*) registerValue(&wRegDumpStruct, mSelected));
setRegister(mSelected, value ^ 1);
}
}
void CPURegistersView::onUndoAction()
{
if(mUNDODISPLAY.contains(mSelected))
{
if(mFPUMMX.contains(mSelected) || mFPUXMM.contains(mSelected) || mFPUYMM.contains(mSelected) || mFPUx87_80BITSDISPLAY.contains(mSelected))
setRegister(mSelected, (duint)registerValue(&wCipRegDumpStruct, mSelected));
else
setRegister(mSelected, *(duint*)registerValue(&wCipRegDumpStruct, mSelected));
}
}
void CPURegistersView::onCopyPreviousAction()
{
Bridge::CopyToClipboard(wCM_CopyPrevious->data().toString());
}
void CPURegistersView::onHighlightSlot()
{
Disassembly* CPUDisassemblyView = mParent->getDisasmWidget();
if(mGPR.contains(mSelected) && mSelected != REGISTER_NAME::EFLAGS)
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::GeneralRegister, mRegisterMapping.constFind(mSelected).value()));
else if(mSEGMENTREGISTER.contains(mSelected))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::MemorySegment, mRegisterMapping.constFind(mSelected).value()));
else if(mFPUMMX.contains(mSelected))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::MmxRegister, mRegisterMapping.constFind(mSelected).value()));
else if(mFPUXMM.contains(mSelected))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::XmmRegister, mRegisterMapping.constFind(mSelected).value()));
else if(mFPUYMM.contains(mSelected))
CPUDisassemblyView->hightlightToken(ZydisTokenizer::SingleToken(ZydisTokenizer::TokenType::YmmRegister, mRegisterMapping.constFind(mSelected).value()));
CPUDisassemblyView->reloadData();
}
void CPURegistersView::onFollowInDisassembly()
{
if(mCANSTOREADDRESS.contains(mSelected))
{
QString addr = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, mSelected))), mRegisterPlaces[mSelected].valuesize, 16, QChar('0')).toUpper();
if(DbgMemIsValidReadPtr((* ((duint*) registerValue(&wRegDumpStruct, mSelected)))))
DbgCmdExec(QString().sprintf("disasm \"%s\"", addr.toUtf8().constData()));
}
}
void CPURegistersView::onFollowInDump()
{
if(mCANSTOREADDRESS.contains(mSelected))
{
QString addr = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, mSelected))), mRegisterPlaces[mSelected].valuesize, 16, QChar('0')).toUpper();
if(DbgMemIsValidReadPtr((* ((duint*) registerValue(&wRegDumpStruct, mSelected)))))
DbgCmdExec(QString().sprintf("dump \"%s\"", addr.toUtf8().constData()));
}
}
void CPURegistersView::onFollowInDumpN()
{
if(mCANSTOREADDRESS.contains(mSelected))
{
QString addr = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, mSelected))), mRegisterPlaces[mSelected].valuesize, 16, QChar('0')).toUpper();
if(DbgMemIsValidReadPtr((* ((duint*) registerValue(&wRegDumpStruct, mSelected)))))
{
QAction* action = qobject_cast<QAction*>(sender());
int numDump = action->data().toInt();
DbgCmdExec(QString("dump %1, .%2").arg(addr).arg(numDump));
}
}
}
void CPURegistersView::onFollowInStack()
{
if(mCANSTOREADDRESS.contains(mSelected))
{
QString addr = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, mSelected))), mRegisterPlaces[mSelected].valuesize, 16, QChar('0')).toUpper();
if(DbgMemIsValidReadPtr((* ((duint*) registerValue(&wRegDumpStruct, mSelected)))))
DbgCmdExec(QString().sprintf("sdump \"%s\"", addr.toUtf8().constData()));
}
}
void CPURegistersView::onFollowInMemoryMap()
{
if(mCANSTOREADDRESS.contains(mSelected))
{
QString addr = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, mSelected))), mRegisterPlaces[mSelected].valuesize, 16, QChar('0')).toUpper();
if(DbgMemIsValidReadPtr((* ((duint*) registerValue(&wRegDumpStruct, mSelected)))))
DbgCmdExec(QString().sprintf("memmapdump \"%s\"", addr.toUtf8().constData()));
}
}
void CPURegistersView::onRemoveHardware()
{
if(mSelected == DR0 || mSelected == DR1 || mSelected == DR2 || mSelected == DR3)
{
QString addr = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, mSelected))), mRegisterPlaces[mSelected].valuesize, 16, QChar('0')).toUpper();
DbgCmdExec(QString().sprintf("bphc \"%s\"", addr.toUtf8().constData()));
}
}
void CPURegistersView::displayCustomContextMenuSlot(QPoint pos)
{
if(!isActive)
return;
QMenu wMenu(this);
QMenu* followInDumpNMenu = nullptr;
setupSIMDModeMenu();
if(mSelected != UNKNOWN)
{
if(mMODIFYDISPLAY.contains(mSelected))
{
wMenu.addAction(wCM_Modify);
}
if(mINCREMENTDECREMET.contains(mSelected))
{
wMenu.addAction(wCM_Increment);
wMenu.addAction(wCM_Decrement);
wMenu.addAction(wCM_Zero);
}
if(mCANSTOREADDRESS.contains(mSelected))
{
duint addr = (* ((duint*) registerValue(&wRegDumpStruct, mSelected)));
if(DbgMemIsValidReadPtr(addr))
{
wMenu.addAction(wCM_FollowInDump);
followInDumpNMenu = new QMenu(tr("Follow in &Dump"), &wMenu);
CreateDumpNMenu(followInDumpNMenu);
wMenu.addMenu(followInDumpNMenu);
wMenu.addAction(wCM_FollowInDisassembly);
wMenu.addAction(wCM_FollowInMemoryMap);
duint size = 0;
duint base = DbgMemFindBaseAddr(DbgValFromString("csp"), &size);
if(addr >= base && addr < base + size)
wMenu.addAction(wCM_FollowInStack);
}
}
if(mSelected == DR0 || mSelected == DR1 || mSelected == DR2 || mSelected == DR3)
{
if(* ((duint*) registerValue(&wRegDumpStruct, mSelected)) != 0)
wMenu.addAction(wCM_RemoveHardware);
}
wMenu.addAction(wCM_CopyToClipboard);
if(mFPUx87_80BITSDISPLAY.contains(mSelected))
{
wMenu.addAction(wCM_CopyFloatingPointValueToClipboard);
}
if(mLABELDISPLAY.contains(mSelected))
{
QString symbol = getRegisterLabel(mSelected);
if(symbol != "")
wMenu.addAction(wCM_CopySymbolToClipboard);
}
wMenu.addAction(wCM_CopyAll);
if((mGPR.contains(mSelected) && mSelected != REGISTER_NAME::EFLAGS) || mSEGMENTREGISTER.contains(mSelected) || mFPUMMX.contains(mSelected) || mFPUXMM.contains(mSelected) || mFPUYMM.contains(mSelected))
{
wMenu.addAction(wCM_Highlight);
}
if(mUNDODISPLAY.contains(mSelected) && CompareRegisters(mSelected, &wRegDumpStruct, &wCipRegDumpStruct) != 0)
{
wMenu.addAction(wCM_Undo);
wCM_CopyPrevious->setData(GetRegStringValueFromValue(mSelected, registerValue(&wCipRegDumpStruct, mSelected)));
wCM_CopyPrevious->setText(tr("Copy old value: %1").arg(wCM_CopyPrevious->data().toString()));
wMenu.addAction(wCM_CopyPrevious);
}
if(mBOOLDISPLAY.contains(mSelected))
{
wMenu.addAction(wCM_ToggleValue);
}
if(mFPUx87_80BITSDISPLAY.contains(mSelected))
{
wMenu.addAction(wCM_Incrementx87Stack);
wMenu.addAction(wCM_Decrementx87Stack);
}
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
{
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);
wMenu.addSeparator();
QAction* wHwbpCsp = wMenu.addAction(DIcon("breakpoint"), tr("Set Hardware Breakpoint on %1").arg(ArchValue("ESP", "RSP")));
QAction* wAction = wMenu.exec(this->mapToGlobal(pos));
if(wAction == wHwbpCsp)
DbgCmdExec("bphws csp,rw");
}
}
void CPURegistersView::setRegister(REGISTER_NAME reg, duint value)
{
// is register-id known?
if(mRegisterMapping.contains(reg))
{
// map x87st0 to x87r0
QString wRegName;
if(reg >= x87st0 && reg <= x87st7)
wRegName = QString().sprintf("st%d", reg - x87st0);
else
// map "cax" to "eax" or "rax"
wRegName = mRegisterMapping.constFind(reg).value();
// flags need to '_' infront
if(mFlags.contains(reg))
wRegName = "_" + wRegName;
// we change the value (so highlight it)
mRegisterUpdates.insert(reg);
// tell everything the compiler
if(mFPU.contains(reg))
wRegName = "_" + wRegName;
DbgValToString(wRegName.toUtf8().constData(), value);
// force repaint
emit refresh();
}
}
void CPURegistersView::disasmSelectionChangedSlot(dsint va)
{
mHighlightRegs = mParent->getDisasmWidget()->DisassembleAt(va - mParent->getDisasmWidget()->getBase()).regsReferenced;
emit refresh();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPURegistersView.h | #pragma once
#include "RegistersView.h"
class CPURegistersView : public RegistersView
{
Q_OBJECT
public:
CPURegistersView(CPUWidget* parent = 0);
public slots:
void setRegister(REGISTER_NAME reg, duint value);
void updateRegistersSlot();
virtual void debugStateChangedSlot(DBGSTATE state);
virtual void mousePressEvent(QMouseEvent* event);
virtual void mouseDoubleClickEvent(QMouseEvent* event);
virtual void keyPressEvent(QKeyEvent* event);
virtual void refreshShortcutsSlot();
virtual void displayCustomContextMenuSlot(QPoint pos);
protected slots:
void onIncrementx87StackAction();
void onDecrementx87StackAction();
void onModifyAction();
void onIncrementAction();
void onDecrementAction();
void onZeroAction();
void onToggleValueAction();
void onUndoAction();
void onCopyPreviousAction();
void onFollowInDisassembly();
void onFollowInDump();
void onFollowInDumpN();
void onFollowInStack();
void onFollowInMemoryMap();
void onRemoveHardware();
void onHighlightSlot();
void ModifyFields(const QString & title, STRING_VALUE_TABLE_t* table, SIZE_T size);
void disasmSelectionChangedSlot(dsint va);
private:
void CreateDumpNMenu(QMenu* dumpMenu);
void displayEditDialog();
CPUWidget* mParent;
// context menu actions
QAction* mFollowInDump;
QAction* wCM_Modify;
QAction* wCM_Increment;
QAction* wCM_Decrement;
QAction* wCM_Zero;
QAction* wCM_ToggleValue;
QAction* wCM_CopyPrevious;
QAction* wCM_Undo;
QAction* wCM_FollowInDisassembly;
QAction* wCM_FollowInDump;
QAction* wCM_FollowInStack;
QAction* wCM_FollowInMemoryMap;
QAction* wCM_RemoveHardware;
QAction* wCM_Incrementx87Stack;
QAction* wCM_Decrementx87Stack;
QAction* wCM_Highlight;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUSideBar.cpp | #include "CPUSideBar.h"
#include "Configuration.h"
#include "Breakpoints.h"
#include "CPUDisassembly.h"
#include "CachedFontMetrics.h"
#include <QToolTip>
CPUSideBar::CPUSideBar(CPUDisassembly* Ptr, QWidget* parent) : QAbstractScrollArea(parent)
{
setWindowTitle("SideBar");
topVA = -1;
selectedVA = -1;
viewableRows = 0;
mFontMetrics = nullptr;
mDisas = Ptr;
mInstrBuffer = mDisas->instructionsBuffer();
memset(®Dump, 0, sizeof(REGDUMP));
updateSlots();
this->setMouseTracking(true);
}
CPUSideBar::~CPUSideBar()
{
delete mFontMetrics;
}
void CPUSideBar::updateSlots()
{
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateColors()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(updateFonts()));
connect(Bridge::getBridge(), SIGNAL(foldDisassembly(duint, duint)), this, SLOT(foldDisassembly(duint, duint)));
// Init all other updates once
updateColors();
updateFonts();
}
void CPUSideBar::updateColors()
{
mBackgroundColor = ConfigColor("SideBarBackgroundColor");
mConditionalJumpLineFalseColor = ConfigColor("SideBarConditionalJumpLineFalseColor");
mUnconditionalJumpLineFalseColor = ConfigColor("SideBarUnconditionalJumpLineFalseColor");
mConditionalJumpLineTrueColor = ConfigColor("SideBarConditionalJumpLineTrueColor");
mUnconditionalJumpLineTrueColor = ConfigColor("SideBarUnconditionalJumpLineTrueColor");
mConditionalJumpLineFalseBackwardsColor = ConfigColor("SideBarConditionalJumpLineFalseBackwardsColor");
mUnconditionalJumpLineFalseBackwardsColor = ConfigColor("SideBarUnconditionalJumpLineFalseBackwardsColor");
mConditionalJumpLineTrueBackwardsColor = ConfigColor("SideBarConditionalJumpLineTrueBackwardsColor");
mUnconditionalJumpLineTrueBackwardsColor = ConfigColor("SideBarUnconditionalJumpLineTrueBackwardsColor");
mBulletBreakpointColor = ConfigColor("SideBarBulletBreakpointColor");
mBulletBookmarkColor = ConfigColor("SideBarBulletBookmarkColor");
mBulletColor = ConfigColor("SideBarBulletColor");
mBulletDisabledBreakpointColor = ConfigColor("SideBarBulletDisabledBreakpointColor");
mCipLabelColor = ConfigColor("SideBarCipLabelColor");
mCipLabelBackgroundColor = ConfigColor("SideBarCipLabelBackgroundColor");
mChkBoxForeColor = ConfigColor("SideBarCheckBoxForeColor");
mChkBoxBackColor = ConfigColor("SideBarCheckBoxBackColor");
mUnconditionalPen = QPen(mUnconditionalJumpLineFalseColor, 1, Qt::SolidLine);
mConditionalPen = QPen(mConditionalJumpLineFalseColor, 1, Qt::DashLine);
mUnconditionalBackwardsPen = QPen(mUnconditionalJumpLineFalseBackwardsColor, 1, Qt::SolidLine);
mConditionalBackwardsPen = QPen(mConditionalJumpLineFalseBackwardsColor, 1, Qt::DashLine);
}
void CPUSideBar::updateFonts()
{
mDefaultFont = mDisas->font();
this->setFont(mDefaultFont);
delete mFontMetrics;
mFontMetrics = new CachedFontMetrics(this, mDefaultFont);
fontWidth = mFontMetrics->width(' ');
fontHeight = mFontMetrics->height();
mBulletYOffset = 2;
mBulletRadius = fontHeight - 2 * mBulletYOffset;
}
QSize CPUSideBar::sizeHint() const
{
return QSize(40, this->viewport()->height());
}
void CPUSideBar::debugStateChangedSlot(DBGSTATE state)
{
if(state == stopped)
{
reload(); //clear
}
}
void CPUSideBar::reload()
{
fontHeight = mDisas->getRowHeight();
viewport()->update();
}
void CPUSideBar::changeTopmostAddress(dsint i)
{
topVA = i;
DbgGetRegDumpEx(®Dump, sizeof(REGDUMP));
reload();
}
void CPUSideBar::setViewableRows(int rows)
{
viewableRows = rows;
}
void CPUSideBar::setSelection(dsint selVA)
{
if(selVA != selectedVA)
{
selectedVA = selVA;
reload();
}
}
bool CPUSideBar::isJump(int i) const
{
if(i < 0 || i >= mInstrBuffer->size())
return false;
const Instruction_t & instr = mInstrBuffer->at(i);
Instruction_t::BranchType branchType = instr.branchType;
if(branchType == Instruction_t::Unconditional || branchType == Instruction_t::Conditional)
{
duint start = mDisas->getBase();
duint end = start + mDisas->getSize();
duint addr = DbgGetBranchDestination(start + instr.rva);
if(!addr)
return false;
return addr >= start && addr < end; //do not draw jumps that go out of the section
}
return false;
}
void CPUSideBar::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter painter(this->viewport());
// Paints background
painter.fillRect(painter.viewport(), mBackgroundColor);
// Don't draw anything if there aren't any instructions to draw
if(mInstrBuffer->size() == 0)
return;
if(mCodeFoldingManager.isFolded(regDump.regcontext.cip))
{
mCodeFoldingManager.expandFoldSegment(regDump.regcontext.cip);
mDisas->reloadData();
}
int jumpoffset = 0;
duint last_va = mInstrBuffer->last().rva + mDisas->getBase();
duint first_va = mInstrBuffer->first().rva + mDisas->getBase();
QVector<std::pair<QString, duint>> regLabel;
auto appendReg = [®Label, last_va, first_va](const QString & name, duint value)
{
if(value >= first_va && value <= last_va)
regLabel.append(std::make_pair(name, value));
};
#ifdef _WIN64
appendReg("RIP", regDump.regcontext.cip);
appendReg("RAX", regDump.regcontext.cax);
appendReg("RCX", regDump.regcontext.ccx);
appendReg("RDX", regDump.regcontext.cdx);
appendReg("RBX", regDump.regcontext.cbx);
appendReg("RSP", regDump.regcontext.csp);
appendReg("RBP", regDump.regcontext.cbp);
appendReg("RSI", regDump.regcontext.csi);
appendReg("RDI", regDump.regcontext.cdi);
appendReg("R8", regDump.regcontext.r8);
appendReg("R9", regDump.regcontext.r9);
appendReg("R10", regDump.regcontext.r10);
appendReg("R11", regDump.regcontext.r11);
appendReg("R12", regDump.regcontext.r12);
appendReg("R13", regDump.regcontext.r13);
appendReg("R14", regDump.regcontext.r14);
appendReg("R15", regDump.regcontext.r15);
#else //x86
appendReg("EIP", regDump.regcontext.cip);
appendReg("EAX", regDump.regcontext.cax);
appendReg("ECX", regDump.regcontext.ccx);
appendReg("EDX", regDump.regcontext.cdx);
appendReg("EBX", regDump.regcontext.cbx);
appendReg("ESP", regDump.regcontext.csp);
appendReg("EBP", regDump.regcontext.cbp);
appendReg("ESI", regDump.regcontext.csi);
appendReg("EDI", regDump.regcontext.cdi);
#endif //_WIN64
if(ConfigBool("Gui", "SidebarWatchLabels"))
{
BridgeList<WATCHINFO> WatchList;
DbgGetWatchList(&WatchList);
for(int i = 0; i < WatchList.Count(); i++)
{
if(WatchList[i].varType == WATCHVARTYPE::TYPE_UINT || WatchList[i].varType == WATCHVARTYPE::TYPE_ASCII || WatchList[i].varType == WATCHVARTYPE::TYPE_UNICODE)
{
appendReg(QString(WatchList[i].WatchName), WatchList[i].value);
}
}
}
std::vector<JumpLine> jumpLines;
std::vector<LabelArrow> labelArrows;
for(int line = 0; line < viewableRows; line++)
{
if(line >= mInstrBuffer->size()) //at the end of the page it will crash otherwise
break;
const Instruction_t & instr = mInstrBuffer->at(line);
duint instrVA = instr.rva + mDisas->getBase();
duint instrVAEnd = instrVA + instr.length;
// draw bullet
drawBullets(&painter, line, DbgGetBpxTypeAt(instrVA) != bp_none, DbgIsBpDisabled(instrVA), DbgGetBookmarkAt(instrVA));
if(isJump(line)) //handle jumps
{
duint baseAddr = mDisas->getBase();
duint destVA = DbgGetBranchDestination(baseAddr + instr.rva);
JumpLine jmp;
jmp.isJumpGoingToExecute = DbgIsJumpGoingToExecute(instrVA);
jmp.isSelected = (selectedVA == instrVA || selectedVA == destVA);
jmp.isConditional = instr.branchType == Instruction_t::Conditional;
jmp.line = line;
/*
if(mDisas->currentEIP() != mInstrBuffer->at(line).rva) //create a setting for this
isJumpGoingToExecute=false;
*/
jumpoffset++;
// Do not draw jumps that leave the memory range
if(destVA >= mDisas->getBase() + mDisas->getSize() || destVA < mDisas->getBase())
continue;
if(destVA <= last_va && destVA >= first_va)
{
int destLine = line;
while(destLine > -1 && destLine < mInstrBuffer->size())
{
duint va = mInstrBuffer->at(destLine).rva + mDisas->getBase();
if(destVA > instrVA) //jump goes down
{
duint vaEnd = va + mInstrBuffer->at(destLine).length - 1;
if(vaEnd >= destVA)
break;
destLine++;
}
else //jump goes up
{
if(va <= destVA)
break;
destLine--;
}
}
jmp.destLine = destLine;
}
else if(destVA > last_va)
jmp.destLine = viewableRows + 6;
else if(destVA < first_va)
jmp.destLine = -6;
jumpLines.emplace_back(jmp);
}
QString regLabelText;
for(auto i = regLabel.cbegin(); i != regLabel.cend(); i++)
{
if(i->second >= instrVA && i->second < instrVAEnd)
regLabelText += i->first + " ";
}
if(regLabelText.size())
{
regLabelText.chop(1);
labelArrows.push_back(drawLabel(&painter, line, regLabelText));
}
if(isFoldingGraphicsPresent(line) == 1)
{
if(mCodeFoldingManager.isFoldStart(instrVA))
drawFoldingCheckbox(&painter, line * fontHeight, mCodeFoldingManager.isFolded(instrVA));
else
drawFoldingCheckbox(&painter, line * fontHeight, false);
}
else if(mCodeFoldingManager.isFoldBody(instrVA))
{
painter.setPen(QColor(Qt::black));
painter.drawLine(QPointF(viewport()->width() - fontHeight / 2 - mBulletXOffset - mBulletRadius, line * fontHeight), QPointF(viewport()->width() - fontHeight / 2 - mBulletXOffset - mBulletRadius, (line + 1) * fontHeight));
if(mCodeFoldingManager.isFoldEnd(instrVA + instr.length - 1))
painter.drawLine(QPointF(viewport()->width() - fontHeight / 2 - mBulletXOffset - mBulletRadius, (line + 1) * fontHeight), QPointF(viewport()->width(), (line + 1) * fontHeight));
}
}
if(jumpLines.size())
{
AllocateJumpOffsets(jumpLines, labelArrows);
for(auto i : jumpLines)
drawJump(&painter, i.line, i.destLine, i.jumpOffset, i.isConditional, i.isJumpGoingToExecute, i.isSelected);
}
else
{
for(auto i = labelArrows.begin(); i != labelArrows.end(); i++)
i->endX = viewport()->width() - 1 - 11 - (isFoldingGraphicsPresent(i->line) != 0 ? mBulletRadius + fontHeight : 0);
}
drawLabelArrows(&painter, labelArrows);
}
void CPUSideBar::mouseReleaseEvent(QMouseEvent* e)
{
// Don't care if we are not debugging
if(!DbgIsDebugging())
return;
// get clicked line
const int x = e->pos().x();
const int y = e->pos().y();
const int line = y / fontHeight;
if(line >= mInstrBuffer->size())
return;
const int width = viewport()->width();
const int bulletRadius = fontHeight / 2 + 1; //14/2=7
const int bulletX = width - mBulletXOffset;
//const int bulletY = line * fontHeight + mBulletYOffset;
const bool CheckBoxPresent = isFoldingGraphicsPresent(line);
if(x > bulletX + bulletRadius)
return;
// calculate virtual address of clicked line
duint wVA = mInstrBuffer->at(line).rva + mDisas->getBase();
if(CheckBoxPresent)
{
if(x > width - fontHeight - mBulletXOffset - mBulletRadius && x < width - mBulletXOffset - mBulletRadius)
{
if(e->button() == Qt::LeftButton)
{
duint start, end;
const Instruction_t* instr = &mInstrBuffer->at(line);
const dsint SelectionStart = mDisas->getSelectionStart();
const dsint SelectionEnd = mDisas->getSelectionEnd();
if(mCodeFoldingManager.isFoldStart(wVA))
{
mCodeFoldingManager.setFolded(wVA, !mCodeFoldingManager.isFolded(wVA));
}
else if(instr->rva == SelectionStart && (SelectionEnd - SelectionStart + 1) != instr->length)
{
bool success = mCodeFoldingManager.addFoldSegment(wVA, mDisas->getSelectionEnd() - mDisas->getSelectionStart());
if(!success)
GuiAddLogMessage(tr("Cannot fold selection.\n").toUtf8().constData());
}
else if((DbgArgumentGet(wVA, &start, &end) || DbgFunctionGet(wVA, &start, &end)) && wVA == start)
{
bool success = mCodeFoldingManager.addFoldSegment(wVA, end - start);
if(!success)
GuiAddLogMessage(tr("Cannot fold selection.\n").toUtf8().constData());
}
else
GuiAddLogMessage(tr("Cannot fold selection.\n").toUtf8().constData());
}
else if(e->button() == Qt::RightButton)
{
mCodeFoldingManager.delFoldSegment(wVA);
}
mDisas->reloadData();
viewport()->update();
}
}
if(x < bulletX - mBulletRadius)
return;
//if(y < bulletY - mBulletRadius || y > bulletY + bulletRadius)
// return;
if(e->button() == Qt::LeftButton)
{
QString wCmd;
// create --> disable --> delete --> create --> ...
switch(Breakpoints::BPState(bp_normal, wVA))
{
case bp_enabled:
// breakpoint exists and is enabled --> disable breakpoint
wCmd = "bd ";
break;
case bp_disabled:
// is disabled --> delete or enable
if(Breakpoints::BPTrival(bp_normal, wVA))
wCmd = "bc ";
else
wCmd = "be ";
break;
case bp_non_existent:
// no breakpoint was found --> create breakpoint
wCmd = "bp ";
break;
}
wCmd += ToPtrString(wVA);
DbgCmdExec(wCmd);
}
}
void CPUSideBar::mouseDoubleClickEvent(QMouseEvent* event)
{
const int line = event->y() / fontHeight;
if(line >= mInstrBuffer->size())
return;
const bool CheckBoxPresent = isFoldingGraphicsPresent(line);
if(CheckBoxPresent)
{
if(event->x() > width() - fontHeight - mBulletXOffset - mBulletRadius && event->x() < width() - mBulletXOffset - mBulletRadius)
{
if(event->button() == Qt::LeftButton)
{
duint wVA = mInstrBuffer->at(line).rva + mDisas->getBase();
duint start = mCodeFoldingManager.getFoldBegin(wVA);
duint end = mCodeFoldingManager.getFoldEnd(wVA);
if(mCodeFoldingManager.isFolded(wVA) || (start <= regDump.regcontext.cip && end >= regDump.regcontext.cip))
{
mDisas->setSingleSelection(start - mDisas->getBase());
mDisas->expandSelectionUpTo(end - mDisas->getBase());
mDisas->setFocus();
}
}
}
}
}
void CPUSideBar::mouseMoveEvent(QMouseEvent* event)
{
if(!DbgIsDebugging() || !mInstrBuffer->size())
{
QAbstractScrollArea::mouseMoveEvent(event);
QToolTip::hideText();
setCursor(QCursor(Qt::ArrowCursor));
return;
}
const QPoint & mousePos = event->pos();
const QPoint & globalMousePos = event->globalPos();
const int width = viewport()->width();
const int mLine = mousePos.y() / fontHeight;
const bool lineInBounds = mLine > 0 && mLine < mInstrBuffer->size();
const int mBulletX = width - mBulletXOffset;
const int mBulletY = mLine * fontHeight + mBulletYOffset;
const int mouseBulletXOffset = abs(mBulletX - mousePos.x());
const int mouseBulletYOffset = abs(mBulletY - mousePos.y());
// calculate virtual address of clicked line
duint wVA = 0;
if(lineInBounds)
wVA = mInstrBuffer->at(mLine).rva + mDisas->getBase();
// check if mouse is on a code folding box
if(mousePos.x() > width - fontHeight - mBulletXOffset - mBulletRadius && mousePos.x() < width - mBulletXOffset - mBulletRadius)
{
if(isFoldingGraphicsPresent(mLine))
{
if(mCodeFoldingManager.isFolded(wVA))
{
QToolTip::showText(globalMousePos, tr("Click to unfold, right click to delete."));
}
else
{
if(mCodeFoldingManager.isFoldStart(wVA))
QToolTip::showText(globalMousePos, tr("Click to fold, right click to delete."));
else
QToolTip::showText(globalMousePos, tr("Click to fold."));
}
}
}
// if (mouseCursor not on a bullet) or (mLine not in bounds)
else if((mouseBulletXOffset > mBulletRadius || mouseBulletYOffset > mBulletRadius) || !lineInBounds)
{
QToolTip::hideText();
setCursor(QCursor(Qt::ArrowCursor));
}
else
{
switch(Breakpoints::BPState(bp_normal, wVA))
{
case bp_enabled:
QToolTip::showText(globalMousePos, tr("Breakpoint Enabled"));
break;
case bp_disabled:
QToolTip::showText(globalMousePos, tr("Breakpoint Disabled"));
break;
case bp_non_existent:
QToolTip::showText(globalMousePos, tr("Breakpoint Not Set"));
break;
}
setCursor(QCursor(Qt::PointingHandCursor));
}
}
void CPUSideBar::drawJump(QPainter* painter, int startLine, int endLine, int jumpoffset, bool conditional, bool isexecute, bool isactive)
{
painter->save();
// Pixel adjustment to make drawing lines even
int pixel_y_offs = 0;
int y_start = fontHeight * (1 + startLine) - 0.5 * fontHeight - pixel_y_offs;
int y_end = fontHeight * (1 + endLine) - 0.5 * fontHeight;
int y_diff = y_end >= y_start ? 1 : -1;
if(conditional)
{
if(y_diff > 0)
painter->setPen(mConditionalPen);
else
painter->setPen(mConditionalBackwardsPen);
}
else //JMP
{
if(y_diff > 0)
painter->setPen(mUnconditionalPen);
else
painter->setPen(mUnconditionalBackwardsPen);
}
if(isactive) //selected
{
QPen activePen = painter->pen();
// Active/selected jumps use a bold line (2px wide)
activePen.setWidth(2);
// Adjust for 2px line
pixel_y_offs = 0;
// Use a different color to highlight jumps that will execute
if(isexecute)
{
if(conditional)
{
if(y_diff > 0)
activePen.setColor(mConditionalJumpLineTrueColor);
else
activePen.setColor(mConditionalJumpLineTrueBackwardsColor);
}
else
{
if(y_diff > 0)
activePen.setColor(mUnconditionalJumpLineTrueColor);
else
activePen.setColor(mUnconditionalJumpLineTrueBackwardsColor);
}
}
// Update the painter itself with the new pen style
painter->setPen(activePen);
}
// Cache variables
const int viewportWidth = viewport()->width();
const int viewportHeight = viewport()->height();
const int JumpPadding = 11;
int x = viewportWidth - jumpoffset * JumpPadding - 15 - fontHeight;
int x_right = viewportWidth - 12;
// special handling of self-jumping
if(startLine == endLine)
{
y_start -= fontHeight / 4;
y_end += fontHeight / 4;
}
// Horizontal (<----)
if(!isFoldingGraphicsPresent(startLine) != 0)
painter->drawLine(x_right, y_start, x, y_start);
else
painter->drawLine(x_right - mBulletRadius - fontHeight, y_start, x, y_start);
// Vertical
painter->drawLine(x, y_start, x, y_end);
// Specialized pen for solid lines only, keeping other styles
QPen solidLine = painter->pen();
solidLine.setStyle(Qt::SolidLine);
// Draw the arrow
if(!isactive) //selected
{
// Horizontal (---->)
if(isFoldingGraphicsPresent(endLine) != 0)
painter->drawLine(x, y_end, x_right - mBulletRadius - fontHeight, y_end);
else
painter->drawLine(x, y_end, x_right, y_end);
if(endLine == viewableRows + 6)
{
int y = viewportHeight - 1;
if(y > y_start)
{
painter->setPen(solidLine);
QPoint wPoints[] =
{
QPoint(x - 3, y - 3),
QPoint(x, y),
QPoint(x + 3, y - 3),
};
painter->drawPolyline(wPoints, 3);
}
}
else if(endLine == -6)
{
int y = 0;
painter->setPen(solidLine);
QPoint wPoints[] =
{
QPoint(x - 3, y + 3),
QPoint(x, y),
QPoint(x + 3, y + 3),
};
painter->drawPolyline(wPoints, 3);
}
else
{
if(isFoldingGraphicsPresent(endLine) != 0)
x_right -= mBulletRadius + fontHeight;
painter->setPen(solidLine);
QPoint wPoints[] =
{
QPoint(x_right - 3, y_end - 3),
QPoint(x_right, y_end),
QPoint(x_right - 3, y_end + 3),
};
painter->drawPolyline(wPoints, 3);
}
}
else
{
if(endLine == viewableRows + 6)
{
int y = viewportHeight - 1;
x--;
painter->setPen(solidLine);
QPoint wPoints[] =
{
QPoint(x - 3, y - 3),
QPoint(x, y),
QPoint(x + 3, y - 3),
};
painter->drawPolyline(wPoints, 3);
}
else if(endLine == -6)
{
int y = 0;
painter->setPen(solidLine);
QPoint wPoints[] =
{
QPoint(x - 3, y + 3),
QPoint(x, y),
QPoint(x + 3, y + 3),
};
painter->drawPolyline(wPoints, 3);
}
else
{
if(isFoldingGraphicsPresent(endLine) != 0)
drawStraightArrow(painter, x, y_end, x_right - mBulletRadius - fontHeight, y_end);
else
drawStraightArrow(painter, x, y_end, x_right, y_end);
}
}
painter->restore();
}
void CPUSideBar::drawBullets(QPainter* painter, int line, bool isbp, bool isbpdisabled, bool isbookmark)
{
painter->save();
if(isbp)
painter->setBrush(QBrush(mBulletBreakpointColor));
else if(isbookmark)
painter->setBrush(QBrush(mBulletBookmarkColor));
else
painter->setBrush(QBrush(mBulletColor));
painter->setPen(mBackgroundColor);
const int x = viewport()->width() - mBulletXOffset; //initial x
const int y = line * fontHeight; //initial y
painter->setRenderHint(QPainter::Antialiasing, true);
if(isbpdisabled) //disabled breakpoint
painter->setBrush(QBrush(mBulletDisabledBreakpointColor));
painter->drawEllipse(x, y + mBulletYOffset, mBulletRadius, mBulletRadius);
painter->restore();
}
CPUSideBar::LabelArrow CPUSideBar::drawLabel(QPainter* painter, int Line, const QString & Text)
{
painter->save();
const int LineCoordinate = fontHeight * (1 + Line);
const QColor & IPLabel = mCipLabelColor;
const QColor & IPLabelBG = mCipLabelBackgroundColor;
int width = mFontMetrics->width(Text);
int x = 1;
int y = LineCoordinate - fontHeight;
QRect rect(x, y, width, fontHeight - 1);
// Draw rectangle
painter->setBrush(IPLabelBG);
painter->setPen(IPLabelBG);
painter->drawRect(rect);
// Draw text inside the rectangle
painter->setPen(IPLabel);
painter->drawText(rect, Qt::AlignHCenter | Qt::AlignVCenter, Text);
// Draw arrow
/*y = fontHeight * (1 + Line) - 0.5 * fontHeight;
painter->setPen(QPen(IPLabelBG, 2.0));
painter->setBrush(QBrush(IPLabelBG));
drawStraightArrow(painter, rect.right() + 2, y, this->viewport()->width() - x - 11 - (isFoldingGraphicsPresent(Line) != 0 ? mBulletRadius + fontHeight : 0), y);*/
LabelArrow labelArrow;
labelArrow.line = Line;
labelArrow.startX = rect.right() + 2;
labelArrow.endX = 0;
painter->restore();
return labelArrow;
}
void CPUSideBar::drawLabelArrows(QPainter* painter, const std::vector<LabelArrow> & labelArrows)
{
if(!labelArrows.empty())
{
painter->save();
painter->setPen(QPen(mCipLabelBackgroundColor, 2.0));
for(auto i : labelArrows)
{
if(i.startX < i.endX)
{
int y = fontHeight * (1 + i.line) - 0.5 * fontHeight;
drawStraightArrow(painter, i.startX, y, i.endX, y);
}
}
painter->restore();
}
}
void CPUSideBar::drawFoldingCheckbox(QPainter* painter, int y, bool state)
{
int x = viewport()->width() - fontHeight - mBulletXOffset - mBulletRadius;
painter->save();
painter->setBrush(QBrush(mChkBoxBackColor));
painter->setPen(QColor(mChkBoxForeColor));
QRect rect(x, y, fontHeight, fontHeight);
painter->drawRect(rect);
painter->drawLine(QPointF(x + fontHeight / 4, y + fontHeight / 2), QPointF(x + 3 * fontHeight / 4, y + fontHeight / 2));
if(state) // "+"
painter->drawLine(QPointF(x + fontHeight / 2, y + fontHeight / 4), QPointF(x + fontHeight / 2, y + 3 * fontHeight / 4));
painter->restore();
}
void CPUSideBar::drawStraightArrow(QPainter* painter, int x1, int y1, int x2, int y2)
{
painter->drawLine(x1, y1, x2, y2);
const int ArrowSizeX = 4;// Width of arrow tip in pixels
const int ArrowSizeY = 4;// Height of arrow tip in pixels
// X and Y values adjusted so that the arrow itself is symmetrical on 2px
painter->drawLine(x2 - 1, y2 - 1, x2 - ArrowSizeX, y2 - ArrowSizeY);// Arrow top
painter->drawLine(x2 - 1, y2, x2 - ArrowSizeX, y2 + ArrowSizeY - 1);// Arrow bottom
}
void CPUSideBar::AllocateJumpOffsets(std::vector<JumpLine> & jumpLines, std::vector<LabelArrow> & labelArrows)
{
unsigned int* numLines = new unsigned int[viewableRows * 2]; // Low:jump offsets of the vertical jumping line, High:jump offsets of the horizontal jumping line.
memset(numLines, 0, sizeof(unsigned int) * viewableRows * 2);
// preprocessing
for(size_t i = 0; i < jumpLines.size(); i++)
{
JumpLine & jmp = jumpLines.at(i);
jmp.jumpOffset = abs(jmp.destLine - jmp.line);
}
// Sort jumpLines so that longer jumps are put at the back.
std::sort(jumpLines.begin(), jumpLines.end(), [](const JumpLine & op1, const JumpLine & op2)
{
return op2.jumpOffset > op1.jumpOffset;
});
// Allocate jump offsets
for(size_t i = 0; i < jumpLines.size(); i++)
{
JumpLine & jmp = jumpLines.at(i);
unsigned int maxJmpOffset = 0;
if(jmp.line < jmp.destLine)
{
for(int j = jmp.line; j <= jmp.destLine && j < viewableRows; j++)
{
if(numLines[j] > maxJmpOffset)
maxJmpOffset = numLines[j];
}
}
else
{
for(int j = jmp.line; j >= jmp.destLine && j >= 0; j--)
{
if(numLines[j] > maxJmpOffset)
maxJmpOffset = numLines[j];
}
}
jmp.jumpOffset = maxJmpOffset + 1;
if(jmp.line < jmp.destLine)
{
for(int j = jmp.line; j <= jmp.destLine && j < viewableRows; j++)
numLines[j] = jmp.jumpOffset;
}
else
{
for(int j = jmp.line; j >= jmp.destLine && j >= 0; j--)
numLines[j] = jmp.jumpOffset;
}
if(jmp.line >= 0 && jmp.line < viewableRows)
numLines[jmp.line + viewableRows] = jmp.jumpOffset;
if(jmp.destLine >= 0 && jmp.destLine < viewableRows)
numLines[jmp.destLine + viewableRows] = jmp.jumpOffset;
}
// set label arrows according to jump offsets
auto viewportWidth = viewport()->width();
const int JumpPadding = 11;
for(auto i = labelArrows.begin(); i != labelArrows.end(); i++)
{
if(numLines[i->line + viewableRows] != 0)
i->endX = viewportWidth - numLines[i->line + viewableRows] * JumpPadding - 15 - fontHeight; // This expression should be consistent with drawJump
else
i->endX = viewportWidth - 1 - 11 - (isFoldingGraphicsPresent(i->line) != 0 ? mBulletRadius + fontHeight : 0);
}
delete[] numLines;
}
int CPUSideBar::isFoldingGraphicsPresent(int line)
{
if(line < 0 || line >= mInstrBuffer->size()) //There couldn't be a folding box out of viewport
return 0;
const Instruction_t* instr = &mInstrBuffer->at(line);
if(instr == nullptr) //Selection out of a memory page
return 0;
auto wVA = instr->rva + mDisas->getBase();
if(mCodeFoldingManager.isFoldStart(wVA)) //Code is already folded
return 1;
const dsint SelectionStart = mDisas->getSelectionStart();
const dsint SelectionEnd = mDisas->getSelectionEnd();
duint start, end;
if((DbgArgumentGet(wVA, &start, &end) || DbgFunctionGet(wVA, &start, &end)) && wVA == start)
{
return end - start + 1 != instr->length ? 1 : 0;
}
else if(instr->rva >= duint(SelectionStart) && instr->rva < duint(SelectionEnd))
{
if(instr->rva == SelectionStart)
return (SelectionEnd - SelectionStart + 1) != instr->length ? 1 : 0;
}
return 0;
}
CodeFoldingHelper* CPUSideBar::getCodeFoldingManager()
{
return &mCodeFoldingManager;
}
void CPUSideBar::foldDisassembly(duint startAddress, duint length)
{
mCodeFoldingManager.addFoldSegment(startAddress, length);
}
void* CPUSideBar::operator new(size_t size)
{
return _aligned_malloc(size, 16);
}
void CPUSideBar::operator delete(void* p)
{
_aligned_free(p);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUSideBar.h | #pragma once
#include <QAbstractScrollArea>
#include <QPen>
#include "QBeaEngine.h"
#include "CodeFolding.h"
#include "Imports.h"
class CPUDisassembly;
class CPUSideBar : public QAbstractScrollArea
{
Q_OBJECT
QPair<dsint, dsint> mHighlightedJump;
public:
// Constructors
explicit CPUSideBar(CPUDisassembly* Ptr, QWidget* parent = 0);
~CPUSideBar();
QSize sizeHint() const;
void drawStraightArrow(QPainter* painter, int x1, int y1, int x2, int y2);
void drawFoldingCheckbox(QPainter* painter, int y, bool state);
CodeFoldingHelper* getCodeFoldingManager();
static void* operator new(size_t size);
static void operator delete(void* p);
signals:
void folded();
public slots:
// Configuration
void updateSlots();
void updateColors();
void updateFonts();
void debugStateChangedSlot(DBGSTATE state);
void reload();
void changeTopmostAddress(dsint i);
void setViewableRows(int rows);
void setSelection(dsint selVA);
void foldDisassembly(duint startAddress, duint length);
protected:
void paintEvent(QPaintEvent* event);
void mouseReleaseEvent(QMouseEvent* e);
void mouseMoveEvent(QMouseEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event);
void drawBullets(QPainter* painter, int line, bool ispb, bool isbpdisabled, bool isbookmark);
bool isJump(int i) const;
void drawJump(QPainter* painter, int startLine, int endLine, int jumpoffset, bool conditional, bool isexecute, bool isactive);
int isFoldingGraphicsPresent(int line);
CodeFoldingHelper mCodeFoldingManager;
private:
CachedFontMetrics* mFontMetrics;
dsint topVA;
dsint selectedVA;
QFont mDefaultFont;
int fontWidth, fontHeight;
int viewableRows;
int mBulletRadius;
int mBulletYOffset = 10;
const int mBulletXOffset = 10;
CPUDisassembly* mDisas;
QList<Instruction_t>* mInstrBuffer;
REGDUMP regDump;
struct JumpLine
{
int line = 0;
int destLine = 0;
unsigned int jumpOffset = 0;
bool isSelected = false;
bool isConditional = false;
bool isJumpGoingToExecute = false;
};
struct LabelArrow
{
int line = 0;
int startX = 0;
int endX = 0;
};
void AllocateJumpOffsets(std::vector<JumpLine> & jumpLines, std::vector<LabelArrow> & labelArrows);
LabelArrow drawLabel(QPainter* painter, int Line, const QString & Text);
void drawLabelArrows(QPainter* painter, const std::vector<LabelArrow> & labelArrows);
// Configuration
QColor mBackgroundColor;
QColor mConditionalJumpLineFalseColor;
QColor mUnconditionalJumpLineFalseColor;
QColor mConditionalJumpLineTrueColor;
QColor mUnconditionalJumpLineTrueColor;
QColor mConditionalJumpLineFalseBackwardsColor;
QColor mUnconditionalJumpLineFalseBackwardsColor;
QColor mConditionalJumpLineTrueBackwardsColor;
QColor mUnconditionalJumpLineTrueBackwardsColor;
QColor mBulletBreakpointColor;
QColor mBulletBookmarkColor;
QColor mBulletColor;
QColor mBulletDisabledBreakpointColor;
QColor mChkBoxForeColor;
QColor mChkBoxBackColor;
QColor mCipLabelColor;
QColor mCipLabelBackgroundColor;
QPen mUnconditionalPen;
QPen mConditionalPen;
QPen mUnconditionalBackwardsPen;
QPen mConditionalBackwardsPen;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUStack.cpp | #include "CPUStack.h"
#include "CPUDump.h"
#include <QClipboard>
#include "Configuration.h"
#include "Bridge.h"
#include "CommonActions.h"
#include "HexEditDialog.h"
#include "WordEditDialog.h"
#include "CPUMultiDump.h"
#include "GotoDialog.h"
CPUStack::CPUStack(CPUMultiDump* multiDump, QWidget* parent) : HexDump(parent)
{
setWindowTitle("Stack");
setShowHeader(false);
int charwidth = getCharWidth();
ColumnDescriptor wColDesc;
DataDescriptor dDesc;
mMultiDump = multiDump;
mForceColumn = 1;
wColDesc.isData = true; //void*
wColDesc.itemCount = 1;
wColDesc.separator = 0;
#ifdef _WIN64
wColDesc.data.itemSize = Qword;
wColDesc.data.qwordMode = HexQword;
#else
wColDesc.data.itemSize = Dword;
wColDesc.data.dwordMode = HexDword;
#endif
appendDescriptor(10 + charwidth * 2 * sizeof(duint), "void*", false, wColDesc);
wColDesc.isData = false; //comments
wColDesc.itemCount = 0;
wColDesc.separator = 0;
dDesc.itemSize = Byte;
dDesc.byteMode = AsciiByte;
wColDesc.data = dDesc;
appendDescriptor(2000, tr("Comments"), false, wColDesc);
setupContextMenu();
mGoto = 0;
// Slots
connect(Bridge::getBridge(), SIGNAL(stackDumpAt(duint, duint)), this, SLOT(stackDumpAt(duint, duint)));
connect(Bridge::getBridge(), SIGNAL(selectionStackGet(SELECTIONDATA*)), this, SLOT(selectionGet(SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(selectionStackSet(const SELECTIONDATA*)), this, SLOT(selectionSet(const SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChangedSlot(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(focusStack()), this, SLOT(setFocus()));
connect(Bridge::getBridge(), SIGNAL(updateDump()), this, SLOT(updateSlot()));
connect(this, SIGNAL(selectionUpdated()), this, SLOT(selectionUpdatedSlot()));
Initialize();
}
void CPUStack::updateColors()
{
HexDump::updateColors();
mBackgroundColor = ConfigColor("StackBackgroundColor");
mTextColor = ConfigColor("StackTextColor");
mSelectionColor = ConfigColor("StackSelectionColor");
mStackReturnToColor = ConfigColor("StackReturnToColor");
mStackSEHChainColor = ConfigColor("StackSEHChainColor");
mUserStackFrameColor = ConfigColor("StackFrameColor");
mSystemStackFrameColor = ConfigColor("StackFrameSystemColor");
}
void CPUStack::updateFonts()
{
setFont(ConfigFont("Stack"));
invalidateCachedFont();
}
void CPUStack::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]()
{
return rvaToVa(getSelectionStart());
});
//Realign
mMenuBuilder->addAction(makeAction(DIcon("align-stack-pointer"), tr("Align Stack Pointer"), SLOT(realignSlot())), [this](QMenu*)
{
return (mCsp & (sizeof(duint) - 1)) != 0;
});
// Modify
mMenuBuilder->addAction(makeAction(DIcon("modify"), tr("Modify"), SLOT(modifySlot())));
auto binaryMenu = new MenuBuilder(this);
//Binary->Edit
binaryMenu->addAction(makeShortcutAction(DIcon("binary_edit"), tr("&Edit"), SLOT(binaryEditSlot()), "ActionBinaryEdit"));
//Binary->Fill
binaryMenu->addAction(makeShortcutAction(DIcon("binary_fill"), tr("&Fill..."), SLOT(binaryFillSlot()), "ActionBinaryFill"));
//Binary->Separator
binaryMenu->addSeparator();
//Binary->Copy
binaryMenu->addAction(makeShortcutAction(DIcon("binary_copy"), tr("&Copy"), SLOT(binaryCopySlot()), "ActionBinaryCopy"));
//Binary->Paste
binaryMenu->addAction(makeShortcutAction(DIcon("binary_paste"), tr("&Paste"), SLOT(binaryPasteSlot()), "ActionBinaryPaste"));
//Binary->Paste (Ignore Size)
binaryMenu->addAction(makeShortcutAction(DIcon("binary_paste_ignoresize"), tr("Paste (&Ignore Size)"), SLOT(binaryPasteIgnoreSizeSlot()), "ActionBinaryPasteIgnoreSize"));
mMenuBuilder->addMenu(makeMenu(DIcon("binary"), tr("B&inary")), binaryMenu);
auto copyMenu = new MenuBuilder(this);
copyMenu->addAction(mCopySelection);
copyMenu->addAction(mCopyAddress);
copyMenu->addAction(mCopyRva, [this](QMenu*)
{
return DbgFunctions()->ModBaseFromAddr(rvaToVa(getInitialSelection())) != 0;
});
//Copy->DWORD/QWORD
QString ptrName = ArchValue(tr("&DWORD"), tr("&QWORD"));
copyMenu->addAction(makeAction(ptrName, SLOT(copyPtrColumnSlot())));
//Copy->Comments
copyMenu->addAction(makeAction(tr("&Comments"), SLOT(copyCommentsColumnSlot())));
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
//Breakpoint (hardware access) menu
auto hardwareAccessMenu = makeMenu(DIcon("breakpoint_access"), tr("Hardware, Access"));
hardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_byte"), tr("&Byte"), "bphws $, r, 1"));
hardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_word"), tr("&Word"), "bphws $, r, 2"));
hardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_dword"), tr("&Dword"), "bphws $, r, 4"));
#ifdef _WIN64
hardwareAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_qword"), tr("&Qword"), "bphws $, r, 8"));
#endif //_WIN64
//Breakpoint (hardware write) menu
auto hardwareWriteMenu = makeMenu(DIcon("breakpoint_write"), tr("Hardware, Write"));
hardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_byte"), tr("&Byte"), "bphws $, w, 1"));
hardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_word"), tr("&Word"), "bphws $, w, 2"));
hardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_dword"), tr("&Dword"), "bphws $, w, 4"));
#ifdef _WIN64
hardwareWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_qword"), tr("&Qword"), "bphws $, r, 8"));
#endif //_WIN64
//Breakpoint (remove hardware)
auto hardwareRemove = mCommonActions->makeCommandAction(DIcon("breakpoint_remove"), tr("Remove &Hardware"), "bphwc $");
//Breakpoint (memory access) menu
auto memoryAccessMenu = makeMenu(DIcon("breakpoint_memory_access"), tr("Memory, Access"));
memoryAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), "bpm $, 0, a"));
memoryAccessMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), "bpm $, 1, a"));
//Breakpoint (memory write) menu
auto memoryWriteMenu = makeMenu(DIcon("breakpoint_memory_write"), tr("Memory, Write"));
memoryWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), "bpm $, 0, w"));
memoryWriteMenu->addAction(mCommonActions->makeCommandAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore on hit"), "bpm $, 1, w"));
//Breakpoint (remove memory) menu
auto memoryRemove = mCommonActions->makeCommandAction(DIcon("breakpoint_remove"), tr("Remove &Memory"), "bpmc $");
//Breakpoint menu
auto breakpointMenu = new MenuBuilder(this);
//Breakpoint menu
breakpointMenu->addBuilder(new MenuBuilder(this, [ = ](QMenu * menu)
{
duint selectedAddr = rvaToVa(getInitialSelection());
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;
}));
mMenuBuilder->addMenu(makeMenu(DIcon("breakpoint"), tr("Brea&kpoint")), breakpointMenu);
// Restore Selection
mMenuBuilder->addAction(makeShortcutAction(DIcon("eraser"), tr("&Restore selection"), SLOT(undoSelectionSlot()), "ActionUndoSelection"), [this](QMenu*)
{
dsint start = rvaToVa(getSelectionStart());
dsint end = rvaToVa(getSelectionEnd());
return DbgFunctions()->PatchInRange(start, end);
});
//Find Pattern
mMenuBuilder->addAction(makeShortcutAction(DIcon("search-for"), tr("&Find Pattern..."), SLOT(findPattern()), "ActionFindPattern"));
//Follow CSP
mMenuBuilder->addAction(makeShortcutAction(DIcon("neworigin"), ArchValue(tr("Follow E&SP"), tr("Follow R&SP")), SLOT(gotoCspSlot()), "ActionGotoOrigin"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("cbp"), ArchValue(tr("Follow E&BP"), tr("Follow R&BP")), SLOT(gotoCbpSlot()), "ActionGotoCBP"), [](QMenu*)
{
return DbgMemIsValidReadPtr(DbgValFromString("cbp"));
});
auto gotoMenu = new MenuBuilder(this);
//Go to Expression
gotoMenu->addAction(makeShortcutAction(DIcon("geolocation-goto"), tr("Go to &Expression"), SLOT(gotoExpressionSlot()), "ActionGotoExpression"));
//Go to Base of Stack Frame
gotoMenu->addAction(makeShortcutAction(DIcon("neworigin"), tr("Go to Base of Stack Frame"), SLOT(gotoFrameBaseSlot()), "ActionGotoBaseOfStackFrame"));
//Go to Previous Frame
gotoMenu->addAction(makeShortcutAction(DIcon("previous"), tr("Go to Previous Stack Frame"), SLOT(gotoPreviousFrameSlot()), "ActionGotoPrevStackFrame"));
//Go to Next Frame
gotoMenu->addAction(makeShortcutAction(DIcon("next"), tr("Go to Next Stack Frame"), SLOT(gotoNextFrameSlot()), "ActionGotoNextStackFrame"));
//Go to Previous
gotoMenu->addAction(makeShortcutAction(DIcon("previous"), tr("Go to Previous"), SLOT(gotoPreviousSlot()), "ActionGotoPrevious"), [this](QMenu*)
{
return mHistory.historyHasPrev();
});
//Go to Next
gotoMenu->addAction(makeShortcutAction(DIcon("next"), tr("Go to Next"), SLOT(gotoNextSlot()), "ActionGotoNext"), [this](QMenu*)
{
return mHistory.historyHasNext();
});
mMenuBuilder->addMenu(makeMenu(DIcon("goto"), tr("&Go to")), gotoMenu);
//Freeze the stack
mMenuBuilder->addAction(mFreezeStack = makeShortcutAction(DIcon("freeze"), tr("Freeze the stack"), SLOT(freezeStackSlot()), "ActionFreezeStack"));
mFreezeStack->setCheckable(true);
//Follow in Memory Map
mCommonActions->build(mMenuBuilder, CommonActions::ActionMemoryMap | CommonActions::ActionDump | CommonActions::ActionDumpData);
//Follow in Stack
auto followStackName = ArchValue(tr("Follow DWORD in &Stack"), tr("Follow QWORD in &Stack"));
mFollowStack = makeAction(DIcon("stack"), followStackName, SLOT(followStackSlot()));
mFollowStack->setShortcutContext(Qt::WidgetShortcut);
mFollowStack->setShortcut(QKeySequence("enter"));
mMenuBuilder->addAction(mFollowStack, [this](QMenu*)
{
duint ptr;
if(!DbgMemRead(rvaToVa(getInitialSelection()), (unsigned char*)&ptr, sizeof(ptr)))
return false;
duint stackBegin = mMemPage->getBase();
duint stackEnd = stackBegin + mMemPage->getSize();
return ptr >= stackBegin && ptr < stackEnd;
});
//Follow in Disassembler
auto disasmIcon = DIcon(ArchValue("processor32", "processor64"));
mFollowDisasm = makeAction(disasmIcon, ArchValue(tr("&Follow DWORD in Disassembler"), tr("&Follow QWORD in Disassembler")), SLOT(followDisasmSlot()));
mFollowDisasm->setShortcutContext(Qt::WidgetShortcut);
mFollowDisasm->setShortcut(QKeySequence("enter"));
mMenuBuilder->addAction(mFollowDisasm, [this](QMenu*)
{
duint ptr;
return DbgMemRead(rvaToVa(getInitialSelection()), (unsigned char*)&ptr, sizeof(ptr)) && DbgMemIsValidReadPtr(ptr);
});
//Follow PTR in Dump
auto followDumpName = ArchValue(tr("Follow DWORD in &Dump"), tr("Follow QWORD in &Dump"));
mCommonActions->build(mMenuBuilder, CommonActions::ActionDumpN | CommonActions::ActionWatch);
mMenuBuilder->addAction(makeAction("Edit columns...", SLOT(editColumnDialog())));
mPluginMenu = new QMenu(this);
Bridge::getBridge()->emitMenuAddToList(this, mPluginMenu, GUI_STACK_MENU);
mMenuBuilder->addSeparator();
mMenuBuilder->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
DbgMenuPrepare(GUI_STACK_MENU);
menu->addActions(mPluginMenu->actions());
return true;
}));
mMenuBuilder->loadFromConfig();
}
void CPUStack::updateFreezeStackAction()
{
if(bStackFrozen)
mFreezeStack->setText(tr("Unfreeze the stack"));
else
mFreezeStack->setText(tr("Freeze the stack"));
mFreezeStack->setChecked(bStackFrozen);
}
void CPUStack::getColumnRichText(int col, dsint rva, RichTextPainter::List & richText)
{
// Compute VA
duint wVa = rvaToVa(rva);
bool wActiveStack = (wVa >= mCsp); //inactive stack
STACK_COMMENT comment;
RichTextPainter::CustomRichText_t curData;
curData.underline = false;
curData.flags = RichTextPainter::FlagColor;
curData.textColor = mTextColor;
if(col && mDescriptor.at(col - 1).isData == true) //paint stack data
{
HexDump::getColumnRichText(col, rva, richText);
if(!wActiveStack)
{
QColor inactiveColor = ConfigColor("StackInactiveTextColor");
for(int i = 0; i < int(richText.size()); i++)
{
richText[i].flags = RichTextPainter::FlagColor;
richText[i].textColor = inactiveColor;
}
}
}
else if(col && DbgStackCommentGet(wVa, &comment)) //paint stack comments
{
if(wActiveStack)
{
if(*comment.color)
{
if(comment.color[0] == '!')
{
if(strcmp(comment.color, "!sehclr") == 0)
curData.textColor = mStackSEHChainColor;
else if(strcmp(comment.color, "!rtnclr") == 0)
curData.textColor = mStackReturnToColor;
else
curData.textColor = mTextColor;
}
else
curData.textColor = QColor(QString(comment.color));
}
else
curData.textColor = mTextColor;
}
else
curData.textColor = ConfigColor("StackInactiveTextColor");
curData.text = comment.comment;
richText.push_back(curData);
}
else
HexDump::getColumnRichText(col, rva, richText);
}
QString CPUStack::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
// Compute RVA
int wBytePerRowCount = getBytePerRowCount();
dsint wRva = (rowBase + rowOffset) * wBytePerRowCount - mByteOffset;
duint wVa = rvaToVa(wRva);
bool wIsSelected = isSelected(wRva);
if(wIsSelected) //highlight if selected
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor));
if(col == 0) // paint stack address
{
QColor background;
char labelText[MAX_LABEL_SIZE] = "";
if(DbgGetLabelAt(wVa, SEG_DEFAULT, labelText)) //label
{
if(wVa == mCsp) //CSP
{
background = ConfigColor("StackCspBackgroundColor");
painter->setPen(QPen(ConfigColor("StackCspColor")));
}
else //no CSP
{
background = ConfigColor("StackLabelBackgroundColor");
painter->setPen(ConfigColor("StackLabelColor"));
}
}
else //no label
{
if(wVa == mCsp) //CSP
{
background = ConfigColor("StackCspBackgroundColor");
painter->setPen(QPen(ConfigColor("StackCspColor")));
}
else if(wIsSelected) //selected normal address
{
background = ConfigColor("StackSelectedAddressBackgroundColor");
painter->setPen(QPen(ConfigColor("StackSelectedAddressColor"))); //black address (DisassemblySelectedAddressColor)
}
else //normal address
{
background = ConfigColor("StackAddressBackgroundColor");
painter->setPen(QPen(ConfigColor("StackAddressColor")));
}
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background when defined
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, makeAddrText(wVa));
return QString();
}
else if(col == 1) // paint stack data
{
if(mCallstack.size())
{
int stackFrameBitfield = 0; // 0:none, 1:top of stack frame, 2:bottom of stack frame, 4:middle of stack frame
int party = 0;
if(wVa >= mCallstack[0].addr)
{
for(size_t i = 0; i < mCallstack.size() - 1; i++)
{
if(wVa >= mCallstack[i].addr && wVa < mCallstack[i + 1].addr)
{
stackFrameBitfield |= (mCallstack[i].addr == wVa) ? 1 : 0;
stackFrameBitfield |= (mCallstack[i + 1].addr == wVa + sizeof(duint)) ? 2 : 0;
if(stackFrameBitfield == 0)
stackFrameBitfield = 4;
party = mCallstack[i].party;
break;
}
}
// draw stack frame
if(stackFrameBitfield == 0)
return HexDump::paintContent(painter, rowBase, rowOffset, 1, x, y, w, h);
else
{
int height = getRowHeight();
int halfHeight = height / 2;
int width = 5;
int offset = 2;
auto result = HexDump::paintContent(painter, rowBase, rowOffset, 1, x + (width - 2), y, w - (width - 2), h);
if(party == mod_user)
painter->setPen(QPen(mUserStackFrameColor, 2));
else
painter->setPen(QPen(mSystemStackFrameColor, 2));
if((stackFrameBitfield & 1) != 0)
{
painter->drawLine(x + width, y + halfHeight / 2, x + offset, y + halfHeight / 2);
painter->drawLine(x + offset, y + halfHeight / 2, x + offset, y + halfHeight);
}
else
painter->drawLine(x + offset, y, x + offset, y + halfHeight);
if((stackFrameBitfield & 2) != 0)
{
painter->drawLine(x + width, y + height / 4 * 3, x + offset, y + height / 4 * 3);
painter->drawLine(x + offset, y + height / 4 * 3, x + offset, y + halfHeight);
}
else
painter->drawLine(x + offset, y + height, x + offset, y + halfHeight);
return result;
}
}
else
return HexDump::paintContent(painter, rowBase, rowOffset, 1, x, y, w, h);
}
else
return HexDump::paintContent(painter, rowBase, rowOffset, 1, x, y, w, h);
}
else
return HexDump::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
}
void CPUStack::contextMenuEvent(QContextMenuEvent* event)
{
QMenu wMenu(this); //create context menu
mMenuBuilder->build(&wMenu);
wMenu.exec(event->globalPos());
}
void CPUStack::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->button() != Qt::LeftButton || !DbgIsDebugging())
return;
switch(getColumnIndexFromX(event->x()))
{
case 0: //address
{
//very ugly way to calculate the base of the current row (no clue why it works)
dsint deltaRowBase = getInitialSelection() % getBytePerRowCount() + mByteOffset;
if(deltaRowBase >= getBytePerRowCount())
deltaRowBase -= getBytePerRowCount();
dsint mSelectedVa = rvaToVa(getInitialSelection() - deltaRowBase);
if(mRvaDisplayEnabled && mSelectedVa == mRvaDisplayBase)
mRvaDisplayEnabled = false;
else
{
mRvaDisplayEnabled = true;
mRvaDisplayBase = mSelectedVa;
mRvaDisplayPageBase = mMemPage->getBase();
}
reloadData();
}
break;
case 1: // value
{
modifySlot();
}
break;
default:
{
duint wVa = rvaToVa(getInitialSelection());
STACK_COMMENT comment;
if(DbgStackCommentGet(wVa, &comment) && strcmp(comment.color, "!rtnclr") == 0)
followDisasmSlot();
}
break;
}
}
void CPUStack::wheelEvent(QWheelEvent* event)
{
if(event->modifiers() == Qt::NoModifier)
AbstractTableView::wheelEvent(event);
else if(event->modifiers() == Qt::ControlModifier) // Zoom
Config()->zoomFont("Stack", event);
}
void CPUStack::stackDumpAt(duint addr, duint csp)
{
if(DbgMemIsValidReadPtr(addr))
mHistory.addVaToHistory(addr);
mCsp = csp;
// Get the callstack
DBGCALLSTACK callstack;
memset(&callstack, 0, sizeof(DBGCALLSTACK));
DbgFunctions()->GetCallStack(&callstack);
mCallstack.resize(callstack.total);
if(mCallstack.size())
{
// callstack data highest >> lowest
std::qsort(callstack.entries, callstack.total, sizeof(DBGCALLSTACKENTRY), [](const void* a, const void* b)
{
auto p = (const DBGCALLSTACKENTRY*)a;
auto q = (const DBGCALLSTACKENTRY*)b;
if(p->addr < q->addr)
return -1;
else
return 1;
});
for(size_t i = 0; i < mCallstack.size(); i++)
{
mCallstack[i].addr = callstack.entries[i].addr;
mCallstack[i].party = DbgFunctions()->ModGetParty(callstack.entries[i].to);
}
BridgeFree(callstack.entries);
}
bool isInvisible;
isInvisible = (addr < mMemPage->va(getTableOffsetRva())) || (addr >= mMemPage->va(getTableOffsetRva() + getViewableRowsCount() * getBytePerRowCount()));
printDumpAt(addr, true, true, isInvisible || addr == csp);
}
void CPUStack::updateSlot()
{
if(!DbgIsDebugging())
return;
// Get the callstack
DBGCALLSTACK callstack;
memset(&callstack, 0, sizeof(DBGCALLSTACK));
DbgFunctions()->GetCallStack(&callstack);
mCallstack.resize(callstack.total);
if(mCallstack.size())
{
// callstack data highest >> lowest
std::qsort(callstack.entries, callstack.total, sizeof(DBGCALLSTACKENTRY), [](const void* a, const void* b)
{
auto p = (const DBGCALLSTACKENTRY*)a;
auto q = (const DBGCALLSTACKENTRY*)b;
if(p->addr < q->addr)
return -1;
else
return 1;
});
for(size_t i = 0; i < mCallstack.size(); i++)
{
mCallstack[i].addr = callstack.entries[i].addr;
mCallstack[i].party = DbgFunctions()->ModGetParty(callstack.entries[i].to);
}
BridgeFree(callstack.entries);
}
}
void CPUStack::disasmSelectionChanged(dsint parVA)
{
// When the selected instruction is changed, select the argument that is in the stack.
DISASM_INSTR instr;
if(!DbgIsDebugging() || !DbgMemIsValidReadPtr(parVA))
return;
DbgDisasmAt(parVA, &instr);
duint underlineStart = 0;
duint underlineEnd = 0;
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG & arg = instr.arg[i];
if(arg.type == arg_memory)
{
if(arg.value >= mMemPage->getBase() && arg.value < mMemPage->getBase() + mMemPage->getSize())
{
if(Config()->getBool("Gui", "AutoFollowInStack"))
{
//TODO: When the stack is unaligned?
stackDumpAt(arg.value & (~(sizeof(void*) - 1)), mCsp);
}
else
{
BASIC_INSTRUCTION_INFO info;
DbgDisasmFastAt(parVA, &info);
underlineStart = arg.value;
underlineEnd = mUnderlineRangeStartVa + info.memory.size - 1;
}
break;
}
}
}
if(mUnderlineRangeStartVa != underlineStart || mUnderlineRangeEndVa != underlineEnd)
{
mUnderlineRangeStartVa = underlineStart;
mUnderlineRangeEndVa = underlineEnd;
reloadData();
}
}
void CPUStack::gotoCspSlot()
{
DbgCmdExec("sdump csp");
}
void CPUStack::gotoCbpSlot()
{
DbgCmdExec("sdump cbp");
}
int CPUStack::getCurrentFrame(const std::vector<CPUStack::CPUCallStack> & mCallstack, duint wVA)
{
if(mCallstack.size())
for(size_t i = 0; i < mCallstack.size() - 1; i++)
if(wVA >= mCallstack[i].addr && wVA < mCallstack[i + 1].addr)
return int(i);
return -1;
}
void CPUStack::gotoFrameBaseSlot()
{
int frame = getCurrentFrame(mCallstack, rvaToVa(getInitialSelection()));
if(frame != -1)
DbgCmdExec(QString("sdump \"%1\"").arg(ToPtrString(mCallstack[frame].addr)));
}
void CPUStack::gotoNextFrameSlot()
{
int frame = getCurrentFrame(mCallstack, rvaToVa(getInitialSelection()));
if(frame != -1 && frame + 1 < int(mCallstack.size()))
DbgCmdExec(QString("sdump \"%1\"").arg(ToPtrString(mCallstack[frame + 1].addr)));
}
void CPUStack::gotoPreviousFrameSlot()
{
int frame = getCurrentFrame(mCallstack, rvaToVa(getInitialSelection()));
if(frame > 0)
DbgCmdExec(QString("sdump \"%1\"").arg(ToPtrString(mCallstack[frame - 1].addr)));
}
void CPUStack::gotoExpressionSlot()
{
if(!DbgIsDebugging())
return;
duint size = 0;
duint base = DbgMemFindBaseAddr(mCsp, &size);
if(!mGoto)
mGoto = new GotoDialog(this);
mGoto->validRangeStart = base;
mGoto->validRangeEnd = base + size;
mGoto->setWindowTitle(tr("Enter expression to follow in Stack..."));
mGoto->setInitialExpression(ToPtrString(rvaToVa(getInitialSelection())));
if(mGoto->exec() == QDialog::Accepted)
{
duint value = DbgValFromString(mGoto->expressionText.toUtf8().constData());
DbgCmdExec(QString().sprintf("sdump %p", value));
}
}
void CPUStack::selectionGet(SELECTIONDATA* selection)
{
selection->start = rvaToVa(getSelectionStart());
selection->end = rvaToVa(getSelectionEnd());
Bridge::getBridge()->setResult(BridgeResult::SelectionGet, 1);
}
void CPUStack::selectionSet(const SELECTIONDATA* selection)
{
dsint selMin = mMemPage->getBase();
dsint selMax = selMin + mMemPage->getSize();
dsint start = selection->start;
dsint end = selection->end;
if(start < selMin || start >= selMax || end < selMin || end >= selMax) //selection out of range
{
Bridge::getBridge()->setResult(BridgeResult::SelectionSet, 0);
return;
}
setSingleSelection(start - selMin);
expandSelectionUpTo(end - selMin);
reloadData();
Bridge::getBridge()->setResult(BridgeResult::SelectionSet, 1);
}
void CPUStack::selectionUpdatedSlot()
{
duint selectedData;
if(mMemPage->read((byte_t*)&selectedData, getInitialSelection(), sizeof(duint)))
if(DbgMemIsValidReadPtr(selectedData)) //data is a pointer
{
duint stackBegin = mMemPage->getBase();
duint stackEnd = stackBegin + mMemPage->getSize();
if(selectedData >= stackBegin && selectedData < stackEnd) //data is a pointer to stack address
{
disconnect(SIGNAL(enterPressedSignal()));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followStackSlot()));
mFollowDisasm->setShortcut(QKeySequence(""));
mFollowStack->setShortcut(QKeySequence("enter"));
}
else
{
disconnect(SIGNAL(enterPressedSignal()));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followDisasmSlot()));
mFollowStack->setShortcut(QKeySequence(""));
mFollowDisasm->setShortcut(QKeySequence("enter"));
}
}
}
void CPUStack::followDisasmSlot()
{
duint selectedData;
if(mMemPage->read((byte_t*)&selectedData, getInitialSelection(), sizeof(duint)))
if(DbgMemIsValidReadPtr(selectedData)) //data is a pointer
{
QString addrText = ToPtrString(selectedData);
DbgCmdExec(QString("disasm " + addrText));
}
}
void CPUStack::followStackSlot()
{
duint selectedData;
if(mMemPage->read((byte_t*)&selectedData, getInitialSelection(), sizeof(duint)))
if(DbgMemIsValidReadPtr(selectedData)) //data is a pointer
{
QString addrText = ToPtrString(selectedData);
DbgCmdExec(QString("sdump " + addrText));
}
}
void CPUStack::binaryEditSlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.setWindowTitle(tr("Edit data at %1").arg(ToPtrString(rvaToVa(selStart))));
if(hexEdit.exec() != QDialog::Accepted)
return;
dsint dataSize = hexEdit.mHexEdit->data().size();
dsint newSize = selSize > dataSize ? selSize : dataSize;
data = new byte_t[newSize];
mMemPage->read(data, selStart, newSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, newSize));
mMemPage->write(patched.constData(), selStart, patched.size());
GuiUpdateAllViews();
}
void CPUStack::binaryFillSlot()
{
HexEditDialog hexEdit(this);
hexEdit.showKeepSize(false);
hexEdit.mHexEdit->setOverwriteMode(false);
dsint selStart = getSelectionStart();
hexEdit.setWindowTitle(tr("Fill data at %1").arg(ToPtrString(rvaToVa(selStart))));
if(hexEdit.exec() != QDialog::Accepted)
return;
QString pattern = hexEdit.mHexEdit->pattern();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
hexEdit.mHexEdit->fill(0, QString(pattern));
QByteArray patched(hexEdit.mHexEdit->data());
mMemPage->write(patched, selStart, patched.size());
GuiUpdateAllViews();
}
void CPUStack::binaryCopySlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
hexEdit.mHexEdit->setData(QByteArray((const char*)data, selSize));
delete [] data;
Bridge::CopyToClipboard(hexEdit.mHexEdit->pattern(true));
}
void CPUStack::binaryPasteSlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
QClipboard* clipboard = QApplication::clipboard();
hexEdit.mHexEdit->setData(clipboard->text());
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, selSize));
if(patched.size() < selSize)
selSize = patched.size();
mMemPage->write(patched.constData(), selStart, selSize);
GuiUpdateAllViews();
}
void CPUStack::binaryPasteIgnoreSizeSlot()
{
HexEditDialog hexEdit(this);
dsint selStart = getSelectionStart();
dsint selSize = getSelectionEnd() - selStart + 1;
QClipboard* clipboard = QApplication::clipboard();
hexEdit.mHexEdit->setData(clipboard->text());
byte_t* data = new byte_t[selSize];
mMemPage->read(data, selStart, selSize);
QByteArray patched = hexEdit.mHexEdit->applyMaskedData(QByteArray((const char*)data, selSize));
delete [] data;
mMemPage->write(patched.constData(), selStart, patched.size());
GuiUpdateAllViews();
}
void CPUStack::findPattern()
{
HexEditDialog hexEdit(this);
hexEdit.showEntireBlock(true);
hexEdit.isDataCopiable(false);
hexEdit.mHexEdit->setOverwriteMode(false);
hexEdit.setWindowTitle(tr("Find Pattern..."));
if(hexEdit.exec() != QDialog::Accepted)
return;
dsint addr = rvaToVa(getSelectionStart());
if(hexEdit.entireBlock())
addr = DbgMemFindBaseAddr(addr, 0);
QString addrText = ToPtrString(addr);
DbgCmdExec(QString("findall " + addrText + ", " + hexEdit.mHexEdit->pattern() + ", &data&"));
emit displayReferencesWidget();
}
void CPUStack::undoSelectionSlot()
{
dsint start = rvaToVa(getSelectionStart());
dsint end = rvaToVa(getSelectionEnd());
if(!DbgFunctions()->PatchInRange(start, end)) //nothing patched in selected range
return;
DbgFunctions()->PatchRestoreRange(start, end);
reloadData();
}
void CPUStack::modifySlot()
{
dsint addr = getInitialSelection();
WordEditDialog wEditDialog(this);
dsint value = 0;
mMemPage->read(&value, addr, sizeof(dsint));
wEditDialog.setup(tr("Modify"), value, sizeof(dsint));
if(wEditDialog.exec() != QDialog::Accepted)
return;
value = wEditDialog.getVal();
mMemPage->write(&value, addr, sizeof(dsint));
GuiUpdateAllViews();
}
void CPUStack::realignSlot()
{
#ifdef _WIN64
mCsp &= ~0x7;
#else //x86
mCsp &= ~0x3;
#endif //_WIN64
DbgValToString("csp", mCsp);
GuiUpdateAllViews();
}
void CPUStack::freezeStackSlot()
{
if(bStackFrozen)
DbgCmdExec(QString("setfreezestack 0"));
else
DbgCmdExec(QString("setfreezestack 1"));
bStackFrozen = !bStackFrozen;
updateFreezeStackAction();
if(!bStackFrozen)
gotoCspSlot();
}
void CPUStack::dbgStateChangedSlot(DBGSTATE state)
{
if(state == initialized)
{
bStackFrozen = false;
updateFreezeStackAction();
}
}
void CPUStack::copyPtrColumnSlot()
{
const duint wordSize = sizeof(duint);
dsint selStart = getSelectionStart();
dsint selLen = getSelectionEnd() - selStart + 1;
duint wordCount = selLen / wordSize;
duint* data = new duint[wordCount];
mMemPage->read((byte_t*)data, selStart, wordCount * wordSize);
QString clipboard;
for(duint i = 0; i < wordCount; i++)
{
if(i > 0)
clipboard += "\r\n";
clipboard += ToPtrString(data[i]);
}
delete [] data;
Bridge::CopyToClipboard(clipboard);
}
void CPUStack::copyCommentsColumnSlot()
{
int commentsColumn = 2;
const duint wordSize = sizeof(duint);
dsint selStart = getSelectionStart();
dsint selLen = getSelectionEnd() - selStart + 1;
QString clipboard;
for(dsint i = 0; i < selLen; i += wordSize)
{
RichTextPainter::List richText;
getColumnRichText(commentsColumn, selStart + i, richText);
QString colText;
for(auto & r : richText)
colText += r.text;
if(i > 0)
clipboard += "\r\n";
clipboard += colText;
}
Bridge::CopyToClipboard(clipboard);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUStack.h | #pragma once
#include "HexDump.h"
//forward declaration
class CPUMultiDump;
class GotoDialog;
class CommonActions;
class CPUStack : public HexDump
{
Q_OBJECT
public:
explicit CPUStack(CPUMultiDump* multiDump, QWidget* parent = 0);
// Configuration
virtual void updateColors();
virtual void updateFonts();
void getColumnRichText(int col, dsint rva, RichTextPainter::List & richText) override;
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
void contextMenuEvent(QContextMenuEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event);
void wheelEvent(QWheelEvent* event) override;
void setupContextMenu();
void updateFreezeStackAction();
signals:
void displayReferencesWidget();
public slots:
void stackDumpAt(duint addr, duint csp);
void gotoCspSlot();
void gotoCbpSlot();
void gotoExpressionSlot();
void gotoPreviousFrameSlot();
void gotoNextFrameSlot();
void gotoFrameBaseSlot();
void selectionGet(SELECTIONDATA* selection);
void selectionSet(const SELECTIONDATA* selection);
void selectionUpdatedSlot();
void followDisasmSlot();
void followStackSlot();
void binaryEditSlot();
void binaryFillSlot();
void binaryCopySlot();
void binaryPasteSlot();
void findPattern();
void binaryPasteIgnoreSizeSlot();
void undoSelectionSlot();
void modifySlot();
void realignSlot();
void freezeStackSlot();
void dbgStateChangedSlot(DBGSTATE state);
void disasmSelectionChanged(dsint parVA);
void updateSlot();
void copyPtrColumnSlot();
void copyCommentsColumnSlot();
private:
duint mCsp = 0;
bool bStackFrozen = false;
QAction* mFreezeStack;
QAction* mFollowStack;
QAction* mFollowDisasm;
QMenu* mPluginMenu;
GotoDialog* mGoto;
CPUMultiDump* mMultiDump;
QColor mUserStackFrameColor;
QColor mSystemStackFrameColor;
QColor mStackReturnToColor;
QColor mStackSEHChainColor;
struct CPUCallStack
{
duint addr;
int party;
};
MenuBuilder* mMenuBuilder;
CommonActions* mCommonActions;
std::vector<CPUCallStack> mCallstack;
static int CPUStack::getCurrentFrame(const std::vector<CPUStack::CPUCallStack> & mCallstack, duint wVA);
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CPUWidget.cpp | #include "CPUWidget.h"
#include "ui_CPUWidget.h"
#include <QDesktopWidget>
#include <QTabWidget>
#include <QVBoxLayout>
#include "CPUSideBar.h"
#include "CPUDisassembly.h"
#include "CPUMultiDump.h"
#include "CPUStack.h"
#include "CPURegistersView.h"
#include "CPUInfoBox.h"
#include "CPUArgumentWidget.h"
#include "DisassemblerGraphView.h"
#include "Configuration.h"
#include "TabWidget.h"
CPUWidget::CPUWidget(QWidget* parent) : QWidget(parent), ui(new Ui::CPUWidget)
{
ui->setupUi(this);
setDefaultDisposition();
setStyleSheet("AbstractTableView:focus, CPURegistersView:focus, CPUSideBar:focus { border: 1px solid #000000; }");
mDisas = new CPUDisassembly(this, true);
mSideBar = new CPUSideBar(mDisas);
mDisas->setSideBar(mSideBar);
mArgumentWidget = new CPUArgumentWidget(this);
mGraph = new DisassemblerGraphView(this);
connect(mDisas, SIGNAL(tableOffsetChanged(dsint)), mSideBar, SLOT(changeTopmostAddress(dsint)));
connect(mDisas, SIGNAL(viewableRowsChanged(int)), mSideBar, SLOT(setViewableRows(int)));
connect(mDisas, SIGNAL(selectionChanged(dsint)), mSideBar, SLOT(setSelection(dsint)));
connect(mGraph, SIGNAL(detachGraph()), this, SLOT(detachGraph()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), mSideBar, SLOT(debugStateChangedSlot(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(updateSideBar()), mSideBar, SLOT(reload()));
connect(Bridge::getBridge(), SIGNAL(updateArgumentView()), mArgumentWidget, SLOT(refreshData()));
connect(Bridge::getBridge(), SIGNAL(focusDisasm()), this, SLOT(setDisasmFocus()));
connect(Bridge::getBridge(), SIGNAL(focusGraph()), this, SLOT(setGraphFocus()));
mDisas->setCodeFoldingManager(mSideBar->getCodeFoldingManager());
ui->mTopLeftUpperHSplitter->setCollapsible(0, true); //allow collapsing of the side bar
ui->mTopLeftUpperLeftFrameLayout->addWidget(mSideBar);
ui->mTopLeftUpperRightFrameLayout->addWidget(mDisas);
ui->mTopLeftUpperRightFrameLayout->addWidget(mGraph);
mGraph->hide();
disasMode = 0;
mGraphWindow = nullptr;
ui->mTopLeftVSplitter->setCollapsible(1, true); //allow collapsing of the InfoBox
connect(ui->mTopLeftVSplitter, SIGNAL(splitterMoved(int, int)), this, SLOT(splitterMoved(int, int)));
mInfo = new CPUInfoBox();
ui->mTopLeftLowerFrameLayout->addWidget(mInfo);
int height = mInfo->getHeight();
ui->mTopLeftLowerFrame->setMinimumHeight(height + 2);
connect(mDisas, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
mDump = new CPUMultiDump(mDisas, 5, this); //dump widget
ui->mBotLeftFrameLayout->addWidget(mDump);
mGeneralRegs = new CPURegistersView(this);
mGeneralRegs->setFixedWidth(1000);
mGeneralRegs->ShowFPU(true);
QScrollArea* upperScrollArea = new QScrollArea(this);
upperScrollArea->setFrameShape(QFrame::NoFrame);
upperScrollArea->setWidget(mGeneralRegs);
upperScrollArea->setWidgetResizable(true);
QPushButton* button_changeview = new QPushButton("", this);
connect(button_changeview, SIGNAL(clicked()), mGeneralRegs, SLOT(onChangeFPUViewAction()));
mGeneralRegs->SetChangeButton(button_changeview);
ui->mTopRightVSplitter->setCollapsible(1, true); //allow collapsing of the ArgumentWidget
connect(ui->mTopRightVSplitter, SIGNAL(splitterMoved(int, int)), this, SLOT(splitterMoved(int, int)));
ui->mTopRightUpperFrameLayout->addWidget(button_changeview);
ui->mTopRightUpperFrameLayout->addWidget(upperScrollArea);
ui->mTopHSplitter->setCollapsible(1, true); // allow collapsing of the RegisterView
ui->mTopRightLowerFrameLayout->addWidget(mArgumentWidget);
mStack = new CPUStack(mDump, 0); //stack widget
ui->mBotRightFrameLayout->addWidget(mStack);
connect(mDisas, SIGNAL(selectionChanged(dsint)), mStack, SLOT(disasmSelectionChanged(dsint)));
mDisas->setAccessibleName(tr("Disassembly"));
mStack->setAccessibleName(tr("Stack"));
upperScrollArea->setAccessibleName(tr("Registers"));
mDump->setAccessibleName(tr("Dump"));
mArgumentWidget->setAccessibleName(tr("Arguments"));
mSideBar->setAccessibleName(tr("Sidebar"));
mInfo->setAccessibleName(tr("InfoBox"));
// load column config
mDisas->loadColumnFromConfig("CPUDisassembly");
mStack->loadColumnFromConfig("CPUStack");
}
inline void saveSplitter(QSplitter* splitter, QString name)
{
BridgeSettingSet("Main Window Settings", (name + "Geometry").toUtf8().constData(), splitter->saveGeometry().toBase64().data());
BridgeSettingSet("Main Window Settings", (name + "State").toUtf8().constData(), splitter->saveState().toBase64().data());
}
inline void loadSplitter(QSplitter* splitter, QString name)
{
char setting[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("Main Window Settings", (name + "Geometry").toUtf8().constData(), setting))
splitter->restoreGeometry(QByteArray::fromBase64(QByteArray(setting)));
if(BridgeSettingGet("Main Window Settings", (name + "State").toUtf8().constData(), setting))
splitter->restoreState(QByteArray::fromBase64(QByteArray(setting)));
splitter->splitterMoved(1, 0);
}
void CPUWidget::saveWindowSettings()
{
saveSplitter(ui->mVSplitter, "mVSplitter");
saveSplitter(ui->mTopHSplitter, "mTopHSplitter");
saveSplitter(ui->mTopLeftVSplitter, "mTopLeftVSplitter");
if(disasMode == 1 && mDisasmSidebarSplitterStatus.size() > 0) // restore correct sidebar state
ui->mTopLeftUpperHSplitter->restoreState(mDisasmSidebarSplitterStatus);
saveSplitter(ui->mTopLeftUpperHSplitter, "mTopLeftUpperHSplitter");
saveSplitter(ui->mTopRightVSplitter, "mTopRightVSplitter");
saveSplitter(ui->mBotHSplitter, "mBotHSplitter");
mDump->saveWindowSettings();
}
void CPUWidget::loadWindowSettings()
{
loadSplitter(ui->mVSplitter, "mVSplitter");
loadSplitter(ui->mTopHSplitter, "mTopHSplitter");
loadSplitter(ui->mTopLeftVSplitter, "mTopLeftVSplitter");
loadSplitter(ui->mTopLeftUpperHSplitter, "mTopLeftUpperHSplitter");
loadSplitter(ui->mTopRightVSplitter, "mTopRightVSplitter");
loadSplitter(ui->mBotHSplitter, "mBotHSplitter");
mDump->loadWindowSettings();
}
CPUWidget::~CPUWidget()
{
delete mGraphWindow;
delete ui;
}
void CPUWidget::setDefaultDisposition()
{
// This is magic, don't touch it...
// Vertical Splitter
ui->mVSplitter->setStretchFactor(0, 48);
ui->mVSplitter->setStretchFactor(1, 62);
// Top Horizontal Splitter
ui->mTopHSplitter->setStretchFactor(0, 77);
ui->mTopHSplitter->setStretchFactor(1, 23);
// Bottom Horizontal Splitter
ui->mBotHSplitter->setStretchFactor(0, 60);
ui->mBotHSplitter->setStretchFactor(1, 40);
// Top Right Vertical Splitter
ui->mTopRightVSplitter->setStretchFactor(0, 87);
ui->mTopRightVSplitter->setStretchFactor(1, 13);
// Top Left Vertical Splitter
ui->mTopLeftVSplitter->setStretchFactor(0, 99);
ui->mTopLeftVSplitter->setStretchFactor(1, 1);
// Top Left Upper Horizontal Splitter
ui->mTopLeftUpperHSplitter->setStretchFactor(0, 36);
ui->mTopLeftUpperHSplitter->setStretchFactor(1, 64);
}
void CPUWidget::setDisasmFocus()
{
if(disasMode == 1)
{
mGraph->hide();
mDisas->show();
mSideBar->show();
ui->mTopLeftUpperHSplitter->restoreState(mDisasmSidebarSplitterStatus);
disasMode = 0;
connect(mDisas, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
disconnect(mGraph, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
}
else if(disasMode == 2)
{
activateWindow();
}
mDisas->setFocus();
}
void CPUWidget::setGraphFocus()
{
if(disasMode == 0)
{
mDisasmSidebarSplitterStatus = ui->mTopLeftUpperHSplitter->saveState();
mDisas->hide();
mSideBar->hide();
mGraph->show();
// Hide the sidebar area
ui->mTopLeftUpperHSplitter->setSizes(QList<int>({0, 100}));
disasMode = 1;
disconnect(mDisas, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
connect(mGraph, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
}
else if(disasMode == 2)
{
mGraph->activateWindow();
}
mGraph->setFocus();
}
void CPUWidget::detachGraph()
{
if(mGraphWindow == nullptr)
{
mGraphWindow = new MHDetachedWindow(this);
mGraphWindow->setWindowModality(Qt::NonModal);
// Find Widget and connect
connect(mGraphWindow, SIGNAL(OnClose(QWidget*)), this, SLOT(attachGraph(QWidget*)));
mGraphWindow->setWindowTitle(tr("Graph"));
mGraphWindow->setWindowIcon(mGraph->windowIcon());
mGraphWindow->mNativeName = "";
mGraph->setParent(mGraphWindow);
ui->mTopLeftUpperRightFrameLayout->removeWidget(mGraph);
// Create and show
mGraphWindow->show();
mGraphWindow->setCentralWidget(mGraph);
// Needs to be done explicitly
mGraph->showNormal();
QRect screenGeometry = QApplication::desktop()->screenGeometry();
int w = 640;
int h = 480;
int x = (screenGeometry.width() - w) / 2;
int y = (screenGeometry.height() - h) / 2;
mGraphWindow->showNormal();
mGraphWindow->setGeometry(x, y, w, h);
mGraphWindow->showNormal();
disasMode = 2;
mDisas->show();
mSideBar->show();
// restore the sidebar splitter so that the sidebar is visible
ui->mTopLeftUpperHSplitter->restoreState(mDisasmSidebarSplitterStatus);
connect(mDisas, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
connect(mGraph, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
}
}
void CPUWidget::attachGraph(QWidget* widget)
{
Q_UNUSED(widget);
mGraph->setParent(this);
ui->mTopLeftUpperRightFrameLayout->addWidget(mGraph);
mGraph->hide();
mGraphWindow->close();
disconnect(mGraph, SIGNAL(selectionChanged(dsint)), mInfo, SLOT(disasmSelectionChanged(dsint)));
delete mGraphWindow;
mGraphWindow = nullptr;
disasMode = 0;
}
//This is used in run to selection
duint CPUWidget::getSelectionVa()
{
if(disasMode < 2)
return disasMode == 0 ? mDisas->getSelectedVa() : mGraph->get_cursor_pos();
else
return !mGraph->hasFocus() ? mDisas->getSelectedVa() : mGraph->get_cursor_pos();
}
CPUSideBar* CPUWidget::getSidebarWidget()
{
return mSideBar;
}
CPUDisassembly* CPUWidget::getDisasmWidget()
{
return mDisas;
}
DisassemblerGraphView* CPUWidget::getGraphWidget()
{
return mGraph;
}
CPUMultiDump* CPUWidget::getDumpWidget()
{
return mDump;
}
CPUInfoBox* CPUWidget::getInfoBoxWidget()
{
return mInfo;
}
CPUStack* CPUWidget::getStackWidget()
{
return mStack;
}
void CPUWidget::splitterMoved(int pos, int index)
{
Q_UNUSED(pos);
Q_UNUSED(index);
auto splitter = qobject_cast<QSplitter*>(sender());
if(splitter == nullptr) {} // ???
else if(splitter->sizes().at(1) == 0)
{
splitter->handle(1)->setCursor(Qt::UpArrowCursor);
splitter->setStyleSheet("QSplitter::handle:vertical { border-top: 2px solid grey; }");
}
else
{
splitter->handle(1)->setCursor(Qt::SplitVCursor);
splitter->setStyleSheet("");
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CPUWidget.h | #pragma once
#include <QWidget>
#include "Bridge.h"
class QVBoxLayout;
class CPUSideBar;
class CPUDisassembly;
class CPUMultiDump;
class CPUStack;
class CPURegistersView;
class CPUInfoBox;
class CPUArgumentWidget;
class DisassemblerGraphView;
class MHDetachedWindow;
namespace Ui
{
class CPUWidget;
}
class CPUWidget : public QWidget
{
Q_OBJECT
public:
explicit CPUWidget(QWidget* parent = 0);
~CPUWidget();
// Misc
void setDefaultDisposition();
void saveWindowSettings();
void loadWindowSettings();
duint getSelectionVa();
// Widget getters
CPUSideBar* getSidebarWidget();
CPUDisassembly* getDisasmWidget();
DisassemblerGraphView* getGraphWidget();
CPUMultiDump* getDumpWidget();
CPUStack* getStackWidget();
CPUInfoBox* getInfoBoxWidget();
public slots:
void setDisasmFocus();
void setGraphFocus();
protected:
CPUSideBar* mSideBar;
CPUDisassembly* mDisas;
DisassemblerGraphView* mGraph;
MHDetachedWindow* mGraphWindow;
CPUMultiDump* mDump;
CPUStack* mStack;
CPURegistersView* mGeneralRegs;
CPUInfoBox* mInfo;
CPUArgumentWidget* mArgumentWidget;
int disasMode;
private:
Ui::CPUWidget* ui;
QByteArray mDisasmSidebarSplitterStatus;
private slots:
void splitterMoved(int pos, int index);
void attachGraph(QWidget* widget);
void detachGraph();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/CPUWidget.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CPUWidget</class>
<widget class="QWidget" name="CPUWidget">
<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="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QSplitter" name="mTopLeftUpperHSplitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QFrame" name="mTopLeftUpperLeftFrame">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mTopLeftUpperLeftFrameLayout">
<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="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>
<widget class="QFrame" name="mTopLeftLowerFrame">
<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="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="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="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 class="QSplitter" name="mBotHSplitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QFrame" name="mBotLeftFrame">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mBotLeftFrameLayout">
<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="mBotRightFrame">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="mBotRightFrameLayout">
<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>
</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++ | x64dbg-development/src/gui/Src/Gui/CustomizeMenuDialog.cpp | #include "CustomizeMenuDialog.h"
#include "ui_CustomizeMenuDialog.h"
#include "MenuBuilder.h"
#include "Configuration.h"
CustomizeMenuDialog::CustomizeMenuDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::CustomizeMenuDialog)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
ui->setupUi(this);
for(const Configuration::MenuMap & i : Config()->NamedMenuBuilders)
{
QString viewName;
MenuBuilder* builder = nullptr;
QList<QAction*>* mainMenuList = nullptr;
QString id;
if(i.type == 1)
{
mainMenuList = i.mainMenuList;
id = mainMenuList->first()->text();
}
else if(i.type == 0)
{
builder = i.builder;
id = builder->getId();
}
else //invalid or unsupported type.Continue
continue;
//Get localized string for the name of individual views
if(id == "CPUDisassembly")
viewName = tr("Disassembler");
else if(id == "CPUDump")
viewName = tr("Dump");
else if(id == "WatchView")
viewName = tr("Watch");
else if(id == "CallStackView")
viewName = tr("Call Stack");
else if(id == "ThreadView")
viewName = tr("Threads");
else if(id == "DisassemblerGraphView")
viewName = tr("Graph");
else if(id == "XrefBrowseDialog")
viewName = tr("Xref Browser");
else if(id == "StructWidget")
viewName = tr("Struct");
else if(id == "CPUStack")
viewName = tr("Stack");
else if(id == "SourceView")
viewName = tr("Source");
else if(id == "File")
viewName = tr("File");
else if(id == "Debug")
viewName = tr("Debug");
else if(id == "Option")
viewName = tr("Option");
else if(id == "Favourite")
viewName = tr("Favourite");
else if(id == "Help")
viewName = tr("Help");
else if(id == "View")
viewName = tr("View");
else if(id == "TraceBrowser")
viewName = tr("Trace disassembler");
else
continue;
// Add Parent Node
QTreeWidgetItem* parentItem = new QTreeWidgetItem(ui->treeWidget);
parentItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
parentItem->setText(0, viewName);
// Add Children nodes
for(size_t j = 0; j < i.count; j++)
{
// Get localized name of menu item by communicating with the menu
QString text;
if(i.type == 0)
text = builder->getText(j);
else if(i.type == 1)
text = mainMenuList->at(int(j + 1))->text();
// Add a child node only if it has a non-empty name
if(!text.isEmpty())
{
QTreeWidgetItem* menuItem = new QTreeWidgetItem(parentItem, 0);
menuItem->setText(0, text.replace(QChar('&'), ""));
QString configString = QString("Menu%1Hidden%2").arg(id).arg(j);
menuItem->setCheckState(0, Config()->getBool("Gui", configString) ? Qt::Checked : Qt::Unchecked);
menuItem->setData(0, Qt::UserRole, QVariant(configString));
menuItem->setFlags(Qt::ItemIsSelectable | Qt::ItemNeverHasChildren | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
}
}
ui->treeWidget->addTopLevelItem(parentItem);
}
connect(ui->btnOk, SIGNAL(clicked()), this, SLOT(onOk()));
connect(ui->btnDisselectAll, SIGNAL(clicked()), this, SLOT(onDisselectAll()));
}
void CustomizeMenuDialog::onOk()
{
for(int i = ui->treeWidget->topLevelItemCount(); i != 0; i--)
{
const QTreeWidgetItem* parentItem = ui->treeWidget->topLevelItem(i - 1);
for(int j = parentItem->childCount(); j != 0; j--)
{
const QTreeWidgetItem* childItem = parentItem->child(j - 1);
Config()->setBool("Gui", childItem->data(0, Qt::UserRole).toString(), childItem->checkState(0) == Qt::Checked);
}
}
emit accept();
}
void CustomizeMenuDialog::onDisselectAll()
{
for(int i = ui->treeWidget->topLevelItemCount(); i != 0; i--)
{
const QTreeWidgetItem* parentItem = ui->treeWidget->topLevelItem(i - 1);
for(int j = parentItem->childCount(); j != 0; j--)
{
parentItem->child(j - 1)->setCheckState(0, Qt::Unchecked);
}
}
}
CustomizeMenuDialog::~CustomizeMenuDialog()
{
delete ui;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CustomizeMenuDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class CustomizeMenuDialog;
}
class CustomizeMenuDialog : public QDialog
{
Q_OBJECT
public:
explicit CustomizeMenuDialog(QWidget* parent = 0);
~CustomizeMenuDialog();
public slots:
void onOk();
void onDisselectAll();
private:
Ui::CustomizeMenuDialog* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/CustomizeMenuDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CustomizeMenuDialog</class>
<widget class="QDialog" name="CustomizeMenuDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>446</width>
<height>431</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Customize which menu item will be shown in the "More commands" submenu</string>
</property>
</widget>
</item>
<item>
<widget class="QTreeWidget" name="treeWidget">
<property name="columnCount">
<number>1</number>
</property>
<attribute name="headerVisible">
<bool>false</bool>
</attribute>
<column>
<property name="text">
<string notr="true">1</string>
</property>
</column>
</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="btnDisselectAll">
<property name="text">
<string>Disselect All</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnOk">
<property name="text">
<string>&OK</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>
<resources/>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>CustomizeMenuDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>526</x>
<y>519</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>270</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/DebugStatusLabel.cpp | #include "DebugStatusLabel.h"
#include <QTextDocument>
#include <QStyle>
#include <QMetaEnum>
DebugStatusLabel::DebugStatusLabel(QStatusBar* parent) : QLabel(parent)
{
mStatusTexts[0] = tr("Initialized");
mStatusTexts[1] = tr("Paused");
mStatusTexts[2] = tr("Running");
mStatusTexts[3] = tr("Terminated");
QFontMetrics fm(this->font());
int maxWidth = 0;
for(size_t i = 0; i < _countof(mStatusTexts); i++)
{
int width = fm.width(mStatusTexts[i]);
if(width > maxWidth)
maxWidth = width;
}
this->setTextFormat(Qt::RichText); //rich text
this->setFixedHeight(fm.height() + 5);
this->setAlignment(Qt::AlignCenter);
this->setFixedWidth(maxWidth + 10);
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(debugStateChangedSlot(DBGSTATE)));
}
QString DebugStatusLabel::state() const
{
return this->mState;
}
void DebugStatusLabel::debugStateChangedSlot(DBGSTATE state)
{
const char* states[4] = { "initialized", "paused", "running", "stopped" };
this->setText(mStatusTexts[state]);
this->mState = states[state];
if(state == stopped)
{
GuiUpdateWindowTitle("");
}
this->style()->unpolish(this);
this->style()->polish(this);
this->update();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/DebugStatusLabel.h | #pragma once
#include <QLabel>
#include <QStatusBar>
#include "Bridge.h"
class DebugStatusLabel : public QLabel
{
Q_OBJECT
public:
Q_PROPERTY(QString state READ state NOTIFY stateChanged)
explicit DebugStatusLabel(QStatusBar* parent = 0);
QString state() const;
public slots:
void debugStateChangedSlot(DBGSTATE state);
signals:
void stateChanged();
private:
QString mStatusTexts[4];
QString mState;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/DisassemblerGraphView.cpp | #include "DisassemblerGraphView.h"
#include "MenuBuilder.h"
#include "CachedFontMetrics.h"
#include "QBeaEngine.h"
#include "GotoDialog.h"
#include "XrefBrowseDialog.h"
#include <vector>
#include <QPainter>
#include <QScrollBar>
#include <QClipboard>
#include <QApplication>
#include <QMimeData>
#include <QFileDialog>
#include <QMessageBox>
#include "CommonActions.h"
#include "StringUtil.h"
#include "MiscUtil.h"
#include <QMainWindow>
DisassemblerGraphView::DisassemblerGraphView(QWidget* parent)
: QAbstractScrollArea(parent),
mFontMetrics(nullptr),
currentGraph(duint(0)),
disasm(ConfigUint("Disassembler", "MaxModuleSize")),
mCip(0),
mGoto(nullptr),
syncOrigin(false),
forceCenter(false),
layoutType(LayoutType::Medium),
mHistoryLock(false),
mXrefDlg(nullptr)
{
this->status = "Loading...";
//Start disassembly view at the entry point of the binary
resetGraph();
//Initialize zoom values
this->graphZoomMode = ConfigBool("Gui", "GraphZoomMode");
this->zoomLevel = 1;
this->zoomLevelOld = 1;
this->zoomStep = 0.1;
this->zoomOverviewValue = 0.5; //text is hidden
this->zoomMaximum = 1;
//zoomScrollThreshold (relative to viewport size) adds fixed free space around the graph in order to make it free to move/scale
//0.9 makes at least 10% of the graph allways visible regardless of scroll value
//0.5 - at least half of the graph
//0 - no margins ()
//this->zoomScrollThreshold = 1; // default now
//TODO: implement ^^^
this->initFont();
//Initialize scroll bars
this->width = 0;
this->height = 0;
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
this->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
this->horizontalScrollBar()->setSingleStep(this->charWidth);
this->verticalScrollBar()->setSingleStep(this->charHeight);
this->setWindowIcon(DIcon("graph"));
//QSize areaSize = this->viewport()->size(); <-\
//this->adjustSize(areaSize.width(), areaSize.height()); <-- useless at this point (?)
//Setup context menu
setupContextMenu();
//Connect to bridge
connect(Bridge::getBridge(), SIGNAL(loadGraph(BridgeCFGraphList*, duint)), this, SLOT(loadGraphSlot(BridgeCFGraphList*, duint)));
connect(Bridge::getBridge(), SIGNAL(graphAt(duint)), this, SLOT(graphAtSlot(duint)));
connect(Bridge::getBridge(), SIGNAL(updateGraph()), this, SLOT(updateGraphSlot()));
connect(Bridge::getBridge(), SIGNAL(selectionGraphGet(SELECTIONDATA*)), this, SLOT(selectionGetSlot(SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(disassembleAt(dsint, dsint)), this, SLOT(disassembleAtSlot(dsint, dsint)));
connect(Bridge::getBridge(), SIGNAL(getCurrentGraph(BridgeCFGraphList*)), this, SLOT(getCurrentGraphSlot(BridgeCFGraphList*)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChangedSlot(DBGSTATE)));
//Connect to config
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(colorsUpdatedSlot()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(fontsUpdatedSlot()));
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(shortcutsUpdatedSlot()));
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(tokenizerConfigUpdatedSlot()));
//colorsUpdatedSlot(); <-- already called somewhere
}
DisassemblerGraphView::~DisassemblerGraphView() {}
void DisassemblerGraphView::resetGraph()
{
this->function = 0;
this->ready = false;
this->viewportReady = false;
this->desired_pos = nullptr;
this->mHighlightToken = ZydisTokenizer::SingleToken();
this->mHighlightingModeEnabled = false;
this->cur_instr = 0;
this->scroll_base_x = 0;
this->scroll_base_y = 0;
this->scroll_mode = false;
this->drawOverview = false;
this->onlySummary = false;
this->blocks.clear();
this->saveGraph = false;
this->analysis = Analysis();
this->currentGraph = BridgeCFGraph(0);
this->currentBlockMap.clear();
this->syncOrigin = false;
}
void DisassemblerGraphView::initFont()
{
setFont(ConfigFont("Disassembly"));
QFontMetricsF metrics(this->font());
this->baseline = int(metrics.ascent());
this->charWidth = metrics.width('X');
this->charHeight = metrics.height();
this->charOffset = 0;
if(mFontMetrics)
delete mFontMetrics;
mFontMetrics = new CachedFontMetrics(this, font());
}
void DisassemblerGraphView::adjustSize(int viewportWidth, int viewportHeight, QPoint mousePosition, bool fitToWindow)
{
//bugfix - resize event (during several initial calls) may reset correct adjustment already made
if(viewportHeight < 30)
return;
//When zoom mode is enabled, graph turns to a free scallable object with ability to zoom in/out on any point (like IDA)
if(graphZoomMode)
{
qreal graphWidth = this->width;
qreal graphHeight = this->height;
int hScrollRange;
int vScrollRange;
renderWidth = graphWidth * zoomLevel;
renderHeight = graphHeight * zoomLevel;
renderXOfs = viewportWidth;
renderYOfs = viewportHeight;
//Adjust scroll bar range
hScrollRange = renderWidth + viewportWidth;
vScrollRange = renderHeight + viewportHeight;
QPointF deltaMouseReal;
QPointF deltaMouseDiff;
//Addition to scrool position depending on viewport offset
qreal zoomStepReal; //real step which may differ from default step
if(zoomDirection > 0)
{
zoomStepReal = (zoomLevel - zoomLevelOld) / zoomLevel;
zoomStepReal /= (1 - zoomStepReal);
}
else
{
zoomStepReal = (zoomLevelOld - zoomLevel) / zoomLevelOld;
}
qreal deltaXOfs = renderXOfs * zoomStepReal * zoomDirection;
qreal deltaYOfs = renderYOfs * zoomStepReal * zoomDirection;
QPoint scrollPositionOld = QPoint(horizontalScrollBar()->value(), verticalScrollBar()->value());
horizontalScrollBar()->setPageStep(viewportWidth);
horizontalScrollBar()->setRange(0, hScrollRange);
verticalScrollBar()->setPageStep(viewportHeight);
verticalScrollBar()->setRange(0, vScrollRange);
if(!mousePosition.isNull()) //Adjust to cursor position
{
deltaMouseReal = mousePosition / zoomLevelOld + scrollPositionOld / zoomLevelOld;
deltaMouseDiff = deltaMouseReal * zoomLevel - deltaMouseReal * zoomLevelOld;
horizontalScrollBar()->setValue(qRound(scrollPositionOld.x() + deltaMouseDiff.x() - deltaXOfs));
verticalScrollBar()->setValue(qRound(scrollPositionOld.y() + deltaMouseDiff.y() - deltaYOfs));
}
else if(fitToWindow) //Fit to window or 50/50
{
horizontalScrollBar()->setValue(hScrollRange / 2);
verticalScrollBar()->setValue(vScrollRange / 2);
}
}
else //zoom mode is disabled
{
this->renderWidth = this->width;
this->renderHeight = this->height;
this->renderXOfs = 0;
this->renderYOfs = 0;
if(this->renderWidth < viewportWidth)
{
this->renderXOfs = (viewportWidth - this->renderWidth) / 2;
this->renderWidth = viewportWidth;
}
if(this->renderHeight < viewportHeight)
{
this->renderYOfs = (viewportHeight - this->renderHeight) / 2;
this->renderHeight = viewportHeight;
}
//Update scroll bar information
this->horizontalScrollBar()->setPageStep(viewportWidth);
this->horizontalScrollBar()->setRange(0, this->renderWidth - viewportWidth);
this->verticalScrollBar()->setPageStep(viewportHeight);
this->verticalScrollBar()->setRange(0, this->renderHeight - viewportHeight);
}
}
void DisassemblerGraphView::showEvent(QShowEvent* event)
{
//before graph tab is shown for the first time the viewport has uninitialized width and height
if(!this->viewportReady)
this->viewportReady = true;
event->ignore();
}
void DisassemblerGraphView::resizeEvent(QResizeEvent* event)
{
adjustSize(event->size().width(), event->size().height());
}
duint DisassemblerGraphView::get_cursor_pos()
{
if(this->cur_instr == 0)
return this->function;
return this->cur_instr;
}
void DisassemblerGraphView::set_cursor_pos(duint addr)
{
if(!this->navigate(addr))
{
//TODO: show in hex editor?
}
}
std::tuple<duint, duint> DisassemblerGraphView::get_selection_range()
{
return std::make_tuple<duint, duint>(get_cursor_pos(), get_cursor_pos());
}
void DisassemblerGraphView::set_selection_range(std::tuple<duint, duint> range)
{
this->set_cursor_pos(std::get<0>(range));
}
void DisassemblerGraphView::copy_address()
{
QClipboard* clipboard = QApplication::clipboard();
clipboard->clear();
QMimeData mime;
mime.setText(QString().sprintf("0x%p", this->get_cursor_pos()));
clipboard->setMimeData(&mime);
}
void DisassemblerGraphView::zoomIn(QPoint mousePosition)
{
zoomLevelOld = zoomLevel;
if(zoomLevel == zoomMaximum)
{
return;
}
//unlike addition, multiplication (by 1/x, x<1) makes zooming more smooth
zoomLevel /= (1 - zoomStep * zoomBoost);
if(zoomLevel > zoomMaximum)
{
zoomLevel = zoomMaximum;
}
auto areaSize = viewport()->size();
adjustSize(areaSize.width(), areaSize.height(), mousePosition);
this->viewport()->update();
}
void DisassemblerGraphView::zoomOut(QPoint mousePosition)
{
zoomLevelOld = zoomLevel;
if(zoomLevel == zoomMinimum)
{
return;
}
//unlike subtraction, multiplication makes zooming more smooth
zoomLevel *= (1 - zoomStep * zoomBoost);
if(zoomLevel < zoomMinimum)
{
zoomLevel = zoomMinimum;
}
auto areaSize = viewport()->size();
adjustSize(areaSize.width(), areaSize.height(), mousePosition);
this->viewport()->update();
}
void DisassemblerGraphView::paintNormal(QPainter & p, QRect & viewportRect, int xofs, int yofs)
{
//Translate the painter
auto dbgfunctions = DbgFunctions();
QPoint translation(this->renderXOfs - xofs, this->renderYOfs - yofs);
p.translate(translation);
viewportRect.translate(-translation.x(), -translation.y());
//Render each node
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
bool blockSelected = false;
for(const Instr & instr : block.block.instrs)
{
if(instr.addr == this->cur_instr)
{
blockSelected = true;
}
}
duint pathTaken = 0;
if(blockSelected)
{
auto lastInstrAddr = block.block.instrs.back().addr;
pathTaken = DbgIsJumpGoingToExecute(lastInstrAddr) ? block.block.true_path : block.block.false_path;
// When there is only one destination true_path and false_path are not set
if(pathTaken == 0 && !block.block.exits.empty())
pathTaken = block.block.exits.front();
}
//Ignore blocks that are not in view
if(viewportRect.intersects(QRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (2 * this->charWidth), block.height - (2 * this->charWidth))))
{
//Render shadow
p.setPen(QColor(0, 0, 0, 0));
if(block.block.terminal)
p.setBrush(retShadowColor);
else if(block.block.indirectcall)
p.setBrush(indirectcallShadowColor);
else
p.setBrush(QColor(0, 0, 0, 128));
p.drawRect(block.x + this->charWidth + 4, block.y + this->charWidth + 4,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
//Render node background
p.setPen(graphNodeColor);
p.setBrush(graphNodeBackgroundColor);
p.drawRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
//Print current instruction background
if(this->cur_instr != 0)
{
int y = block.y + (2 * this->charWidth) + (int(block.block.header_text.lines.size()) * this->charHeight);
for(Instr & instr : block.block.instrs)
{
if(y > viewportRect.y() - int(instr.text.lines.size()) * this->charHeight && y < viewportRect.bottom())
{
auto selected = instr.addr == this->cur_instr;
auto traceCount = dbgfunctions->GetTraceRecordHitCount(instr.addr);
if(selected && traceCount)
{
p.fillRect(QRect(block.x + this->charWidth + 3, y, block.width - (10 + 2 * this->charWidth),
int(instr.text.lines.size()) * this->charHeight), disassemblyTracedSelectionColor);
}
else if(selected)
{
p.fillRect(QRect(block.x + this->charWidth + 3, y, block.width - (10 + 2 * this->charWidth),
int(instr.text.lines.size()) * this->charHeight), disassemblySelectionColor);
}
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(disassemblyTracedColor.blue() > 160)
colorDiff *= -1;
p.fillRect(QRect(block.x + this->charWidth + 3, y, block.width - (10 + 2 * this->charWidth), int(instr.text.lines.size()) * this->charHeight),
QColor(disassemblyTracedColor.red(),
disassemblyTracedColor.green(),
std::max(0, std::min(256, disassemblyTracedColor.blue() + colorDiff))));
}
}
y += int(instr.text.lines.size()) * this->charHeight;
}
}
//Render node text
auto x = block.x + (2 * this->charWidth);
auto y = block.y + (2 * this->charWidth);
for(auto & line : block.block.header_text.lines)
{
if(y > viewportRect.y() - this->charHeight && y < viewportRect.bottom())
{
RichTextPainter::paintRichText(&p, x, y, block.width, this->charHeight, 0, line, mFontMetrics);
}
y += this->charHeight;
}
for(Instr & instr : block.block.instrs)
{
for(auto & line : instr.text.lines)
{
if(y > viewportRect.y() - this->charHeight && y < viewportRect.bottom())
{
int rectSize = qRound(this->charWidth);
if(rectSize % 2)
rectSize++;
// Assume charWidth <= charHeight
QRectF bpRect(x - rectSize / 3.0, y + (this->charHeight - rectSize) / 2.0, rectSize, rectSize);
bool isbp = DbgGetBpxTypeAt(instr.addr) != bp_none;
bool isbookmark = DbgGetBookmarkAt(instr.addr);
bool isbpdisabled = DbgIsBpDisabled(instr.addr);
bool iscip = instr.addr == mCip;
if(isbp || isbpdisabled)
{
if(iscip)
{
// Left half is cip
bpRect.setWidth(bpRect.width() / 2);
p.fillRect(bpRect, mCipColor);
// Right half is breakpoint
bpRect.translate(bpRect.width(), 0);
}
p.fillRect(bpRect, isbp ? mBreakpointColor : mDisabledBreakpointColor);
}
else if(isbookmark)
{
if(iscip)
{
// Left half is cip
bpRect.setWidth(bpRect.width() / 2);
p.fillRect(bpRect, mCipColor);
// Right half is breakpoint
bpRect.translate(bpRect.width(), 0);
}
p.fillRect(bpRect, mBookmarkBackgroundColor);
}
else if(iscip)
p.fillRect(bpRect, mCipColor);
RichTextPainter::paintRichText(&p, x + this->charWidth, y, block.width - this->charWidth, this->charHeight, 0, line, mFontMetrics);
}
y += this->charHeight;
}
}
}
// Render edges
for(DisassemblerEdge & edge : block.edges)
{
QPen pen(edge.color);
if(blockSelected)
{
if(edge.dest != nullptr && edge.dest->block.entry == pathTaken)
{
pen.setWidth(3);
}
else
{
pen.setStyle(Qt::DashLine);
}
}
p.setPen(pen);
p.setBrush(edge.color);
p.drawPolyline(edge.polyline);
pen.setStyle(Qt::SolidLine);
pen.setWidth(1);
p.setPen(pen);
p.drawConvexPolygon(edge.arrow);
}
}
}
void DisassemblerGraphView::paintOverview(QPainter & p, QRect & viewportRect, int xofs, int yofs)
{
// Scale and translate painter
auto dbgfunctions = DbgFunctions();
qreal sx = qreal(viewportRect.width()) / qreal(this->renderWidth);
qreal sy = qreal(viewportRect.height()) / qreal(this->renderHeight);
qreal s = qMin(sx, sy);
this->overviewScale = s;
if(sx < sy)
{
this->overviewXOfs = this->renderXOfs * s;
this->overviewYOfs = this->renderYOfs * s + (qreal(this->renderHeight) * sy - qreal(this->renderHeight) * s) / 2;
}
else if(sy < sx)
{
this->overviewXOfs = this->renderXOfs * s + (qreal(this->renderWidth) * sx - qreal(this->renderWidth) * s) / 2;
this->overviewYOfs = this->renderYOfs * s;
}
else
{
this->overviewXOfs = this->renderXOfs;
this->overviewYOfs = this->renderYOfs;
}
p.translate(this->overviewXOfs, this->overviewYOfs);
p.scale(s, s);
// Scaled pen
QPen pen;
qreal penWidth = 1.0 / s;
pen.setWidthF(penWidth);
//Render each node
duint cipBlock = 0;
auto found = currentBlockMap.find(mCip);
if(found != currentBlockMap.end())
cipBlock = found->second;
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
// Render edges
for(DisassemblerEdge & edge : block.edges)
{
pen.setColor(edge.color);
p.setPen(pen);
p.setBrush(edge.color);
p.drawPolyline(edge.polyline);
p.drawConvexPolygon(edge.arrow);
}
//Get block metadata
auto traceCount = dbgfunctions->GetTraceRecordHitCount(block.block.entry);
auto isCip = block.block.entry == cipBlock;
//Render shadow
p.setPen(QColor(0, 0, 0, 0));
if((isCip || traceCount) && block.block.terminal)
p.setBrush(retShadowColor);
else if((isCip || traceCount) && block.block.indirectcall)
p.setBrush(indirectcallShadowColor);
else if(isCip)
p.setBrush(QColor(0, 0, 0, 0));
else
p.setBrush(QColor(0, 0, 0, 128));
p.drawRect(block.x + this->charWidth + 4, block.y + this->charWidth + 4,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
//Render node background
pen.setColor(graphNodeColor);
p.setPen(pen);
if(isCip)
p.setBrush(mCipColor);
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(disassemblyTracedColor.blue() > 160)
colorDiff *= -1;
p.setBrush(QColor(disassemblyTracedColor.red(),
disassemblyTracedColor.green(),
std::max(0, std::min(256, disassemblyTracedColor.blue() + colorDiff))));
}
else if(block.block.terminal)
p.setBrush(retShadowColor);
else if(block.block.indirectcall)
p.setBrush(indirectcallShadowColor);
else
p.setBrush(disassemblyBackgroundColor);
p.drawRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
}
// Draw viewport selection
if(s < 1.0)
{
QPoint translation(this->renderXOfs - xofs, this->renderYOfs - yofs);
viewportRect.translate(-translation.x(), -translation.y());
p.setPen(QPen(graphNodeColor, penWidth, Qt::DotLine));
p.setBrush(Qt::transparent);
p.drawRect(viewportRect);
}
}
void DisassemblerGraphView::paintZoom(QPainter & p, QRect & viewportRect, int xofs, int yofs)
{
//Based on paintNormal and paintOverview (depending on zoom level)
auto dbgfunctions = DbgFunctions();
QPoint translation(this->renderXOfs - xofs, this->renderYOfs - yofs);
p.translate(translation);
p.scale(zoomLevel, zoomLevel);
//Adjust imaginary viewport rect at new zoom level
viewportRect.setWidth(viewportRect.width() / zoomLevel);
viewportRect.setHeight(viewportRect.height() / zoomLevel);
viewportRect.translate(-translation.x() / zoomLevel, -translation.y() / zoomLevel);
//Current block
duint cipBlock = 0;
auto found = currentBlockMap.find(mCip);
if(found != currentBlockMap.end())
cipBlock = found->second;
//Scaled pen
QPen pen;
qreal penWidth = 1 / zoomLevel;
pen.setColor(graphNodeColor);
pen.setWidthF(penWidth);
//Render each node
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
bool blockSelected = false;
for(const Instr & instr : block.block.instrs)
{
if(instr.addr == this->cur_instr)
{
blockSelected = true;
}
}
//Ignore blocks that are not in view
if(viewportRect.intersects(QRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (2 * this->charWidth), block.height - (2 * this->charWidth))))
{
//Get block metadata
auto isCip = block.block.entry == cipBlock;
auto traceCount = dbgfunctions->GetTraceRecordHitCount(block.block.entry);
if(zoomLevel > zoomOverviewValue) //Normal mode
{
//Render shadow
p.setPen(QColor(0, 0, 0, 0));
if(isCip)
p.setBrush(graphCurrentShadowColor);
else if(block.block.terminal)
p.setBrush(retShadowColor);
else if(block.block.indirectcall)
p.setBrush(indirectcallShadowColor);
else
p.setBrush(QColor(0, 0, 0, 100));
p.drawRect(block.x + this->charWidth + 4, block.y + this->charWidth + 4,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
//Node background
pen.setColor(graphNodeColor);
p.setPen(pen);
p.setBrush(graphNodeBackgroundColor);
p.drawRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
//Print current instruction background
if(this->cur_instr != 0)
{
int y = block.y + (2 * this->charWidth) + (int(block.block.header_text.lines.size()) * this->charHeight);
for(Instr & instr : block.block.instrs)
{
if(y > viewportRect.y() - int(instr.text.lines.size()) * this->charHeight && y < viewportRect.bottom())
{
auto selected = instr.addr == this->cur_instr;
auto traceCount = dbgfunctions->GetTraceRecordHitCount(instr.addr);
if(selected && traceCount)
{
p.fillRect(QRect(block.x + this->charWidth + 3, y, block.width - (10 + 2 * this->charWidth),
int(instr.text.lines.size()) * this->charHeight), disassemblyTracedSelectionColor);
}
else if(selected)
{
p.fillRect(QRect(block.x + this->charWidth + 3, y, block.width - (10 + 2 * this->charWidth),
int(instr.text.lines.size()) * this->charHeight), disassemblySelectionColor);
}
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(disassemblyTracedColor.blue() > 160)
colorDiff *= -1;
p.fillRect(QRect(block.x + this->charWidth + 3, y, block.width - (10 + 2 * this->charWidth), int(instr.text.lines.size()) * this->charHeight),
QColor(disassemblyTracedColor.red(),
disassemblyTracedColor.green(),
std::max(0, std::min(256, disassemblyTracedColor.blue() + colorDiff))));
}
}
y += int(instr.text.lines.size()) * this->charHeight;
}
}
//Render node text
auto x = block.x + (2 * this->charWidth);
auto y = block.y + (2 * this->charWidth);
for(auto & line : block.block.header_text.lines)
{
if(y > viewportRect.y() - this->charHeight && y < viewportRect.bottom())
{
RichTextPainter::paintRichText(&p, x, y, block.width, this->charHeight, 0, line, mFontMetrics);
}
y += this->charHeight;
}
for(Instr & instr : block.block.instrs)
{
for(auto & line : instr.text.lines)
{
if(y > viewportRect.y() - this->charHeight && y < viewportRect.bottom())
{
int rectSize = qRound(this->charWidth);
if(rectSize % 2)
rectSize++;
// Assume charWidth <= charHeight
QRectF bpRect(x - rectSize / 3.0, y + (this->charHeight - rectSize) / 2.0, rectSize, rectSize);
bool isbp = DbgGetBpxTypeAt(instr.addr) != bp_none;
bool isbpdisabled = DbgIsBpDisabled(instr.addr);
bool iscip = instr.addr == mCip;
if(isbp || isbpdisabled)
{
if(iscip)
{
// Left half is cip
bpRect.setWidth(bpRect.width() / 2);
p.fillRect(bpRect, mCipColor);
// Right half is breakpoint
bpRect.translate(bpRect.width(), 0);
}
p.fillRect(bpRect, isbp ? mBreakpointColor : mDisabledBreakpointColor);
}
else if(iscip)
p.fillRect(bpRect, mCipColor);
RichTextPainter::paintRichText(&p, x + this->charWidth, y, block.width - this->charWidth, this->charHeight, 0, line, mFontMetrics);
}
y += this->charHeight;
}
}
}
else //Overview mode
{
pen.setColor(graphNodeColor);
p.setPen(pen);
if(isCip)
p.setBrush(graphCurrentShadowColor);
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(disassemblyTracedColor.blue() > 160)
colorDiff *= -1;
p.setBrush(QColor(disassemblyTracedColor.red(),
disassemblyTracedColor.green(),
std::max(0, std::min(256, disassemblyTracedColor.blue() + colorDiff))));
}
else if(block.block.terminal)
p.setBrush(retShadowColor);
else if(block.block.indirectcall)
p.setBrush(indirectcallShadowColor);
else
p.setBrush(graphNodeBackgroundColor);
p.drawRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (4 + 2 * this->charWidth), block.height - (4 + 2 * this->charWidth));
}
}
// Render edges
for(DisassemblerEdge & edge : block.edges)
{
pen.setWidthF(penWidth);
pen.setColor(edge.color);
p.setPen(pen);
if(blockSelected)
pen.setStyle(Qt::DashLine);
p.setPen(pen);
p.setBrush(edge.color);
p.drawPolyline(edge.polyline);
pen.setStyle(Qt::SolidLine);
p.setPen(pen);
p.drawConvexPolygon(edge.arrow);
}
}
}
void DisassemblerGraphView::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter p(this->viewport());
p.setFont(this->font());
int xofs = this->horizontalScrollBar()->value();
int yofs = this->verticalScrollBar()->value();
//Render background
QRect viewportRect(this->viewport()->rect().topLeft(), this->viewport()->rect().bottomRight() - QPoint(1, 1));
p.setBrush(backgroundColor);
p.drawRect(viewportRect);
p.setBrush(Qt::black);
if(!this->ready || !DbgIsDebugging())
{
p.setPen(graphNodeColor);
p.drawText(viewportRect, Qt::AlignCenter | Qt::AlignVCenter, tr("Use Graph command or menu action to draw control flow graph here..."));
return;
}
if(!graphZoomMode)
{
if(drawOverview)
paintOverview(p, viewportRect, xofs, yofs);
else
paintNormal(p, viewportRect, xofs, yofs);
}
else
{
paintZoom(p, viewportRect, xofs, yofs);
}
// while selecting a token to highlight, draw a thin 2px red border around the viewport
if(!saveGraph && mHighlightingModeEnabled)
{
QPainter p(this->viewport());
QPen pen(Qt::red);
pen.setWidth(2);
p.setPen(pen);
p.setBrush(Qt::NoBrush); // don't fill the background
QRect viewportRect = this->viewport()->rect();
viewportRect.adjust(1, 1, -1, -1);
p.drawRect(viewportRect);
}
if(saveGraph)
{
//TODO: speed up large graph saving or show gif loader so it won't look like it has crashed
//Image corresponds to the current zoom level
saveGraph = false;
QString path = QFileDialog::getSaveFileName(this, tr("Save as image"), "", tr("PNG file (*.png);;BMP file (*.bmp)"));
if(path.isEmpty())
return;
QSize size = this->viewport()->size();
QPoint scrollbarPos = QPoint(this->horizontalScrollBar()->value(), this->verticalScrollBar()->value());
// expand to full render Rectangle
this->viewport()->resize(this->renderWidth, this->renderHeight);
if(graphZoomMode)
{
adjustSize(this->renderWidth, this->renderHeight, QPoint(), true); //set scrollbars to 50%
}
//save viewport to image
QRect completeRenderRect = QRect(0, 0, this->renderWidth, this->renderHeight);
QImage img(completeRenderRect.size(), QImage::Format_ARGB32);
QPainter painter(&img);
this->viewport()->render(&painter);
img.save(path);
//restore changes made to viewport for full render saving
this->viewport()->resize(size);
if(graphZoomMode)
{
this->horizontalScrollBar()->setValue(scrollbarPos.x());
this->verticalScrollBar()->setValue(scrollbarPos.y());
}
}
}
void DisassemblerGraphView::wheelEvent(QWheelEvent* event)
{
if(!DbgIsDebugging())
return;
if(event->modifiers() & Qt::ControlModifier && graphZoomMode)
{
QPoint numDegrees = event->angleDelta() / 8;
QPoint numSteps = numDegrees / 15;
QPoint mousePosition = event->pos();
zoomBoost = 1;
//Speed up zooming on large graphs by Ctrl+Shift
if(event->modifiers() & Qt::ShiftModifier)
zoomBoost = 2;
if(numSteps.y() > 0)
{
zoomDirection = 1;
zoomIn(mousePosition);
}
else if(numSteps.y() < 0)
{
zoomDirection = -1;
zoomOut(mousePosition);
}
event->accept();
}
else if(event->modifiers() == Qt::ControlModifier)
{
Config()->zoomFont("Disassembly", event);
}
else
{
QAbstractScrollArea::wheelEvent(event);
}
}
bool DisassemblerGraphView::isMouseEventInBlock(QMouseEvent* event)
{
//Convert coordinates to system used in blocks
int xofs = this->horizontalScrollBar()->value();
int yofs = this->verticalScrollBar()->value();
int x = (event->x() + xofs - this->renderXOfs) / zoomLevel;
int y = (event->y() + yofs - this->renderYOfs) / zoomLevel;
// Check each block for hits
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
//Compute coordinate relative to text area in block
int blockx = x - (block.x + (2 * this->charWidth));
int blocky = y - (block.y + (2 * this->charWidth));
//Check to see if click is within bounds of block
if((blockx < 0) || (blockx > (block.width - 4 * this->charWidth)))
continue;
if((blocky < 0) || (blocky > (block.height - 4 * this->charWidth)))
continue;
return true;
}
return false;
}
duint DisassemblerGraphView::getInstrForMouseEvent(QMouseEvent* event)
{
//Convert coordinates to system used in blocks
int xofs = this->horizontalScrollBar()->value();
int yofs = this->verticalScrollBar()->value();
int x = (event->x() + xofs - this->renderXOfs) / zoomLevel;
int y = (event->y() + yofs - this->renderYOfs) / zoomLevel;
//Check each block for hits
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
//Compute coordinate relative to text area in block
int blockx = x - (block.x + (2 * this->charWidth));
int blocky = y - (block.y + (2 * this->charWidth));
//Check to see if click is within bounds of block
if((blockx < 0) || (blockx > (block.width - 4 * this->charWidth)))
continue;
if((blocky < 0) || (blocky > (block.height - 4 * this->charWidth)))
continue;
//Compute row within text
int row = int(blocky / this->charHeight);
//Determine instruction for this row
int cur_row = int(block.block.header_text.lines.size());
if(row < cur_row)
return block.block.entry;
for(Instr & instr : block.block.instrs)
{
if(row < cur_row + int(instr.text.lines.size()))
return instr.addr;
cur_row += int(instr.text.lines.size());
}
}
return 0;
}
bool DisassemblerGraphView::getTokenForMouseEvent(QMouseEvent* event, ZydisTokenizer::SingleToken & tokenOut)
{
//Convert coordinates to system used in blocks
int xofs = this->horizontalScrollBar()->value();
int yofs = this->verticalScrollBar()->value();
int x = (event->x() + xofs - this->renderXOfs) / zoomLevel;
int y = (event->y() + yofs - this->renderYOfs) / zoomLevel;
//Check each block for hits
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
//Compute coordinate relative to text area in block
int blockx = x - (block.x + (2 * this->charWidth));
int blocky = y - (block.y + (2 * this->charWidth));
//Check to see if click is within bounds of block
if((blockx < 0) || (blockx > (block.width - 4 * this->charWidth)))
continue;
if((blocky < 0) || (blocky > (block.height - 4 * this->charWidth)))
continue;
//Compute row and column within text
int col = int(blockx / this->charWidth);
int row = int(blocky / this->charHeight);
//Check tokens to see if one was clicked
int selectedCodeRow = row - block.block.header_text.lines.size();
if(selectedCodeRow < 0)
return false; // skip the header
int rowIndex = 0;
for(auto & instr : block.block.instrs)
{
int lineCount = instr.text.lines.size();
if(rowIndex + lineCount > selectedCodeRow)
{
// instruction found, try to get the row and precise token from it
size_t instrRow = selectedCodeRow - rowIndex;
if(instrRow < instr.text.lineTokens.size())
{
auto & instrToken = instr.text.lineTokens.at(instrRow);
int x = 1 + instrToken.x; // skip the breakpoint/CIP mark and potential RVA prefix
for(auto & token : instrToken.tokens)
{
auto tokenLength = token.text.size();
if(col >= x && col < x + tokenLength)
{
tokenOut = token;
return true;
}
x += tokenLength;
}
}
return false; // selected area doesn't have associated tokens
}
rowIndex += lineCount;
}
}
return false;
}
bool DisassemblerGraphView::find_instr(duint addr, Instr & instrOut)
{
for(auto & blockIt : this->blocks)
for(Instr & instr : blockIt.second.block.instrs)
if(instr.addr == addr)
{
instrOut = instr;
return true;
}
return false;
}
void DisassemblerGraphView::mousePressEvent(QMouseEvent* event)
{
if(!DbgIsDebugging() || !this->ready)
return;
bool inBlock = this->isMouseEventInBlock(event);
//Save click state for actions that need to maintain cursor position and can be triggered whether via menu or by key
//TODO: transfer this to setupContextMenu() somehow
if(event->button() == Qt::RightButton)
{
this->lastRightClickPosition.pos = event->pos();
this->lastRightClickPosition.inBlock = inBlock;
}
if(drawOverview)
{
if(event->button() == Qt::LeftButton)
{
//Enter scrolling mode
this->scroll_base_x = event->x();
this->scroll_base_y = event->y();
this->scroll_mode = true;
this->setCursor(Qt::ClosedHandCursor);
this->viewport()->grabMouse();
//Scroll to the cursor
this->horizontalScrollBar()->setValue(((event->x() - this->overviewXOfs) / this->overviewScale) - this->viewport()->width() / 2);
this->verticalScrollBar()->setValue(((event->y() - this->overviewYOfs) / this->overviewScale) - this->viewport()->height() / 2);
}
else if(event->button() == Qt::RightButton)
{
QMenu wMenu(this);
mMenuBuilder->build(&wMenu);
wMenu.exec(event->globalPos()); //execute context menu
}
}
else if(event->button() & (Qt::LeftButton | Qt::RightButton))
{
// the highlighting behaviour mostly mimics that of CPUDisassembly
auto oldHighlightToken = mHighlightToken;
if((event->button() == Qt::RightButton || inBlock) && mHighlightingModeEnabled)
mHighlightToken = ZydisTokenizer::SingleToken();
bool overrideCtxMenu = mHighlightingModeEnabled; // "intercept" the standard ctx menu
if(inBlock)
{
//Check for click on a token and highlight it
ZydisTokenizer::SingleToken currentToken;
if(this->getTokenForMouseEvent(event, currentToken))
{
bool isHighlightable = ZydisTokenizer::IsHighlightableToken(currentToken);
if(isHighlightable && (mPermanentHighlightingMode || mHighlightingModeEnabled))
{
bool isEqual = ZydisTokenizer::TokenEquals(&oldHighlightToken, ¤tToken);
if(isEqual && event->button() == Qt::LeftButton)
// on LMB, deselect an already highlighted token
mHighlightToken = ZydisTokenizer::SingleToken();
else
mHighlightToken = currentToken;
}
}
//Update current instruction when the highlighting mode is off
duint instr = this->getInstrForMouseEvent(event);
if(instr != 0 && !mHighlightingModeEnabled)
{
this->cur_instr = instr;
emit selectionChanged(instr);
}
this->viewport()->update();
}
if(event->button() == Qt::LeftButton && !inBlock)
{
//Left click outside any block, enter scrolling mode
this->scroll_base_x = event->x();
this->scroll_base_y = event->y();
this->scroll_mode = true;
this->setCursor(Qt::ClosedHandCursor);
this->viewport()->grabMouse();
}
else
{
// preserve the Highlighting mode only when scrolling with LMB
mHighlightingModeEnabled = false;
}
// if the highlighting has changed, show it on the current graph
if(!ZydisTokenizer::TokenEquals(&oldHighlightToken, &mHighlightToken))
for(auto & blockIt : this->blocks)
for(auto & instr : blockIt.second.block.instrs)
instr.text.updateHighlighting(mHighlightToken,
mInstructionHighlightColor,
mInstructionHighlightBackgroundColor);
if(event->button() == Qt::RightButton)
{
if(overrideCtxMenu && !mHighlightToken.text.isEmpty())
{
// show the "copy highlighted token" context menu
QMenu wMenu(this);
mHighlightMenuBuilder->build(&wMenu);
wMenu.exec(event->globalPos());
lastRightClickPosition.pos = {};
}
else if(!overrideCtxMenu)
{
showContextMenu(event);
}
}
}
}
void DisassemblerGraphView::mouseMoveEvent(QMouseEvent* event)
{
if(this->scroll_mode)
{
int x_delta = this->scroll_base_x - event->x();
int y_delta = this->scroll_base_y - event->y();
if(drawOverview)
{
x_delta = -x_delta / this->overviewScale;
y_delta = -y_delta / this->overviewScale;
}
this->scroll_base_x = event->x();
this->scroll_base_y = event->y();
this->horizontalScrollBar()->setValue(this->horizontalScrollBar()->value() + x_delta);
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + y_delta);
}
}
void DisassemblerGraphView::mouseReleaseEvent(QMouseEvent* event)
{
// Bring the user back to disassembly if the user is stuck in an empty graph view (Alt+G)
if((!this->ready || !DbgIsDebugging()) && (event->button() == Qt::LeftButton || event->button() == Qt::BackButton))
GuiFocusView(GUI_DISASSEMBLY);
this->viewport()->update();
if(event->button() == Qt::ForwardButton)
gotoNextSlot();
else if(event->button() == Qt::BackButton)
gotoPreviousSlot();
if(event->button() != Qt::LeftButton)
return;
if(this->scroll_mode)
{
this->scroll_mode = false;
this->setCursor(Qt::ArrowCursor);
this->viewport()->releaseMouse();
}
}
void DisassemblerGraphView::mouseDoubleClickEvent(QMouseEvent* event)
{
if(drawOverview)
{
toggleOverviewSlot();
}
else if(!graphZoomMode || (zoomLevel > zoomOverviewValue))
{
duint instr = this->getInstrForMouseEvent(event);
//Add address to history
if(!mHistoryLock)
mHistory.addVaToHistory(instr);
DbgCmdExec(QString("graph dis.branchdest(%1), silent").arg(ToPtrString(instr)));
}
}
void DisassemblerGraphView::prepareGraphNode(DisassemblerBlock & block)
{
int width = 0;
int height = 0;
for(auto & line : block.block.header_text.lines)
{
int lw = 0;
for(auto & part : line)
lw += mFontMetrics->width(part.text);
if(lw > width)
width = lw;
height += 1;
}
for(Instr & instr : block.block.instrs)
{
for(auto & line : instr.text.lines)
{
int lw = 0;
for(auto & part : line)
lw += mFontMetrics->width(part.text);
if(lw > width)
width = lw;
height += 1;
}
}
int extra = 4 * this->charWidth + 4;
block.width = width + extra + this->charWidth;
block.height = (height * this->charHeight) + extra;
}
void DisassemblerGraphView::adjustGraphLayout(DisassemblerBlock & block, int col, int row)
{
block.col += col;
block.row += row;
for(duint edge : block.new_exits)
this->adjustGraphLayout(this->blocks[edge], col, row);
}
void DisassemblerGraphView::computeGraphLayout(DisassemblerBlock & block)
{
//Compute child node layouts and arrange them horizontally
int col = 0;
int row_count = 1;
int childColumn = 0;
bool singleChild = block.new_exits.size() == 1;
for(size_t i = 0; i < block.new_exits.size(); i++)
{
duint edge = block.new_exits[i];
this->computeGraphLayout(this->blocks[edge]);
if((this->blocks[edge].row_count + 1) > row_count)
row_count = this->blocks[edge].row_count + 1;
childColumn = this->blocks[edge].col;
}
if(this->layoutType != LayoutType::Wide && block.new_exits.size() == 2)
{
DisassemblerBlock & left = this->blocks[block.new_exits[0]];
DisassemblerBlock & right = this->blocks[block.new_exits[1]];
if(left.new_exits.size() == 0)
{
left.col = right.col - 2;
int add = left.col < 0 ? - left.col : 0;
this->adjustGraphLayout(right, add, 1);
this->adjustGraphLayout(left, add, 1);
col = right.col_count + add;
}
else if(right.new_exits.size() == 0)
{
this->adjustGraphLayout(left, 0, 1);
this->adjustGraphLayout(right, left.col + 2, 1);
col = std::max(left.col_count, right.col + 2);
}
else
{
this->adjustGraphLayout(left, 0, 1);
this->adjustGraphLayout(right, left.col_count, 1);
col = left.col_count + right.col_count;
}
block.col_count = std::max(2, col);
if(layoutType == LayoutType::Medium)
block.col = (left.col + right.col) / 2;
else
block.col = singleChild ? childColumn : (col - 2) / 2;
}
else
{
for(duint edge : block.new_exits)
{
this->adjustGraphLayout(this->blocks[edge], col, 1);
col += this->blocks[edge].col_count;
}
if(col >= 2)
{
//Place this node centered over the child nodes
block.col = singleChild ? childColumn : (col - 2) / 2;
block.col_count = col;
}
else
{
//No child nodes, set single node's width (nodes are 2 columns wide to allow
//centering over a branch)
block.col = 0;
block.col_count = 2;
}
}
block.row = 0;
block.row_count = row_count;
}
bool DisassemblerGraphView::isEdgeMarked(EdgesVector & edges, int row, int col, int index)
{
if(index >= int(edges[row][col].size()))
return false;
return edges[row][col][index];
}
void DisassemblerGraphView::markEdge(EdgesVector & edges, int row, int col, int index, bool used)
{
while(int(edges[row][col].size()) <= index)
edges[row][col].push_back(false);
edges[row][col][index] = used;
}
int DisassemblerGraphView::findHorizEdgeIndex(EdgesVector & edges, int row, int min_col, int max_col)
{
//Find a valid index
int i = 0;
while(true)
{
bool valid = true;
for(int col = min_col; col < max_col + 1; col++)
if(isEdgeMarked(edges, row, col, i))
{
valid = false;
break;
}
if(valid)
break;
i++;
}
//Mark chosen index as used
for(int col = min_col; col < max_col + 1; col++)
this->markEdge(edges, row, col, i);
return i;
}
int DisassemblerGraphView::findVertEdgeIndex(EdgesVector & edges, int col, int min_row, int max_row)
{
//Find a valid index
int i = 0;
while(true)
{
bool valid = true;
for(int row = min_row; row < max_row + 1; row++)
if(isEdgeMarked(edges, row, col, i))
{
valid = false;
break;
}
if(valid)
break;
i++;
}
//Mark chosen index as used
for(int row = min_row; row < max_row + 1; row++)
this->markEdge(edges, row, col, i);
return i;
}
DisassemblerGraphView::DisassemblerEdge DisassemblerGraphView::routeEdge(EdgesVector & horiz_edges, EdgesVector & vert_edges, Matrix<bool> & edge_valid, DisassemblerBlock & start, DisassemblerBlock & end, QColor color)
{
DisassemblerEdge edge;
edge.color = color;
edge.dest = &end;
//Find edge index for initial outgoing line
int i = 0;
while(true)
{
if(!this->isEdgeMarked(vert_edges, start.row + 1, start.col + 1, i))
break;
i += 1;
}
this->markEdge(vert_edges, start.row + 1, start.col + 1, i);
edge.addPoint(start.row + 1, start.col + 1);
edge.start_index = i;
bool horiz = false;
//Find valid column for moving vertically to the target node
int min_row, max_row;
if(end.row < (start.row + 1))
{
min_row = end.row;
max_row = start.row + 1;
}
else
{
min_row = start.row + 1;
max_row = end.row;
}
int col = start.col + 1;
if(min_row != max_row)
{
auto checkColumn = [min_row, max_row, &edge_valid](int column)
{
if(column < 0 || column >= int(edge_valid[min_row].size()))
return false;
for(int row = min_row; row < max_row; row++)
{
if(!edge_valid[row][column])
{
return false;
}
}
return true;
};
if(!checkColumn(col))
{
if(checkColumn(end.col + 1))
{
col = end.col + 1;
}
else
{
int ofs = 0;
while(true)
{
col = start.col + 1 - ofs;
if(checkColumn(col))
{
break;
}
col = start.col + 1 + ofs;
if(checkColumn(col))
{
break;
}
ofs += 1;
}
}
}
}
if(col != (start.col + 1))
{
//Not in same column, need to generate a line for moving to the correct column
int min_col, max_col;
if(col < (start.col + 1))
{
min_col = col;
max_col = start.col + 1;
}
else
{
min_col = start.col + 1;
max_col = col;
}
int index = this->findHorizEdgeIndex(horiz_edges, start.row + 1, min_col, max_col);
edge.addPoint(start.row + 1, col, index);
horiz = true;
}
if(end.row != (start.row + 1))
{
//Not in same row, need to generate a line for moving to the correct row
if(col == (start.col + 1))
this->markEdge(vert_edges, start.row + 1, start.col + 1, i, false);
int index = this->findVertEdgeIndex(vert_edges, col, min_row, max_row);
if(col == (start.col + 1))
edge.start_index = index;
edge.addPoint(end.row, col, index);
horiz = false;
}
if(col != (end.col + 1))
{
//Not in ending column, need to generate a line for moving to the correct column
int min_col, max_col;
if(col < (end.col + 1))
{
min_col = col;
max_col = end.col + 1;
}
else
{
min_col = end.col + 1;
max_col = col;
}
int index = this->findHorizEdgeIndex(horiz_edges, end.row, min_col, max_col);
edge.addPoint(end.row, end.col + 1, index);
horiz = true;
}
//If last line was horizontal, choose the ending edge index for the incoming edge
if(horiz)
{
int index = this->findVertEdgeIndex(vert_edges, end.col + 1, end.row, end.row);
edge.points[int(edge.points.size()) - 1].index = index;
}
return edge;
}
template<class T>
static void removeFromVec(std::vector<T> & vec, T elem)
{
vec.erase(std::remove(vec.begin(), vec.end(), elem), vec.end());
}
template<class T>
static void initVec(std::vector<T> & vec, size_t size, T value)
{
vec.resize(size);
for(size_t i = 0; i < size; i++)
vec[i] = value;
}
void DisassemblerGraphView::renderFunction(Function & func)
{
//puts("Starting renderFunction");
//Create render nodes
this->blocks.clear();
if(func.entry == 0)
{
this->ready = false;
return;
}
for(Block & block : func.blocks)
{
this->blocks[block.entry] = DisassemblerBlock(block);
this->prepareGraphNode(this->blocks[block.entry]);
}
//puts("Create render nodes");
//Populate incoming lists
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
for(auto & edge : block.block.exits)
this->blocks[edge].incoming.push_back(block.block.entry);
}
//puts("Populate incoming lists");
//Construct acyclic graph where each node is used as an edge exactly once
std::unordered_set<duint> visited;
visited.insert(func.entry);
std::queue<duint> queue;
queue.push(this->blocks[func.entry].block.entry);
std::vector<duint> blockOrder;
bool changed = true;
while(changed)
{
changed = false;
//First pick nodes that have single entry points
while(!queue.empty())
{
DisassemblerBlock & block = this->blocks[queue.front()];
queue.pop();
blockOrder.push_back(block.block.entry);
for(duint edge : block.block.exits)
{
if(visited.count(edge))
continue;
//If node has no more unseen incoming edges, add it to the graph layout now
if(int(this->blocks[edge].incoming.size()) == 1)
{
removeFromVec(this->blocks[edge].incoming, block.block.entry);
block.new_exits.push_back(edge);
queue.push(this->blocks[edge].block.entry);
visited.insert(edge);
changed = true;
}
else
{
removeFromVec(this->blocks[edge].incoming, block.block.entry);
}
}
}
//No more nodes satisfy constraints, pick a node to continue constructing the graph
duint best = 0;
int best_edges;
duint best_parent;
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
if(!visited.count(block.block.entry))
continue;
for(duint edge : block.block.exits)
{
if(visited.count(edge))
continue;
if((best == 0) || (int(this->blocks[edge].incoming.size()) < best_edges) || (
(int(this->blocks[edge].incoming.size()) == best_edges) && (edge < best)))
{
best = edge;
best_edges = int(this->blocks[edge].incoming.size());
best_parent = block.block.entry;
}
}
}
if(best != 0)
{
DisassemblerBlock & best_parentb = this->blocks[best_parent];
removeFromVec(this->blocks[best].incoming, best_parentb.block.entry);
best_parentb.new_exits.push_back(best);
visited.insert(best);
queue.push(best);
changed = true;
}
}
//puts("Construct acyclic graph where each node is used as an edge exactly once");
//Compute graph layout from bottom up
this->computeGraphLayout(this->blocks[func.entry]);
//Optimize layout to be more compact
/*std::vector<DisassemblerBlock> rowBlocks;
for(auto blockIt : this->blocks)
rowBlocks.push_back(blockIt.second);
std::sort(rowBlocks.begin(), rowBlocks.end(), [](DisassemblerBlock & a, DisassemblerBlock & b)
{
if(a.row < b.row)
return true;
if(a.row == b.row)
return a.col < b.col;
return false;
});
std::vector<std::vector<DisassemblerBlock>> rowMap;
for(DisassemblerBlock & block : rowBlocks)
{
if(block.row == rowMap.size())
rowMap.push_back(std::vector<DisassemblerBlock>());
rowMap[block.row].push_back(block);
}
int median = this->blocks[func.entry].col;
for(auto & blockVec : rowMap)
{
int len = int(blockVec.size());
if(len == 1)
continue;
int bestidx = 0;
int bestdist = median;
for(int i = 0; i < len; i++)
{
auto & block = blockVec[i];
int dist = std::abs(block.col - median);
if(dist < bestdist)
{
bestdist = dist;
bestidx = i;
}
}
for(int j = bestidx - 1; j > -1; j--)
blockVec[j].col = blockVec[j + 1].col - 2;
for(int j = bestidx + 1; j < len; j++)
blockVec[j].col = blockVec[j - 1].col + 2;
}
for(auto & blockVec : rowMap)
for(DisassemblerBlock & block : blockVec)
blocks[block.block.entry] = block;*/
//puts("Compute graph layout from bottom up");
//Prepare edge routing
EdgesVector horiz_edges, vert_edges;
horiz_edges.resize(this->blocks[func.entry].row_count + 1);
vert_edges.resize(this->blocks[func.entry].row_count + 1);
Matrix<bool> edge_valid;
edge_valid.resize(this->blocks[func.entry].row_count + 1);
for(int row = 0; row < this->blocks[func.entry].row_count + 1; row++)
{
horiz_edges[row].resize(this->blocks[func.entry].col_count + 1);
vert_edges[row].resize(this->blocks[func.entry].col_count + 1);
initVec(edge_valid[row], this->blocks[func.entry].col_count + 1, true);
for(int col = 0; col < this->blocks[func.entry].col_count + 1; col++)
{
horiz_edges[row][col].clear();
vert_edges[row][col].clear();
}
}
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
edge_valid[block.row][block.col + 1] = false;
}
//puts("Prepare edge routing");
//Perform edge routing
for(duint blockId : blockOrder)
{
DisassemblerBlock & block = blocks[blockId];
DisassemblerBlock & start = block;
for(duint edge : block.block.exits)
{
DisassemblerBlock & end = this->blocks[edge];
QColor color = jmpColor;
if(edge == block.block.true_path)
color = brtrueColor;
else if(edge == block.block.false_path)
color = brfalseColor;
start.edges.push_back(this->routeEdge(horiz_edges, vert_edges, edge_valid, start, end, color));
}
}
//puts("Perform edge routing");
//Compute edge counts for each row and column
std::vector<int> col_edge_count, row_edge_count;
initVec(col_edge_count, this->blocks[func.entry].col_count + 1, 0);
initVec(row_edge_count, this->blocks[func.entry].row_count + 1, 0);
for(int row = 0; row < this->blocks[func.entry].row_count + 1; row++)
{
for(int col = 0; col < this->blocks[func.entry].col_count + 1; col++)
{
if(int(horiz_edges[row][col].size()) > row_edge_count[row])
row_edge_count[row] = int(horiz_edges[row][col].size());
if(int(vert_edges[row][col].size()) > col_edge_count[col])
col_edge_count[col] = int(vert_edges[row][col].size());
}
}
//puts("Compute edge counts for each row and column");
//Compute row and column sizes
std::vector<int> col_width, row_height;
initVec(col_width, this->blocks[func.entry].col_count + 1, 0);
initVec(row_height, this->blocks[func.entry].row_count + 1, 0);
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
if((int(block.width / 2)) > col_width[block.col])
col_width[block.col] = int(block.width / 2);
if((int(block.width / 2)) > col_width[block.col + 1])
col_width[block.col + 1] = int(block.width / 2);
if(int(block.height) > row_height[block.row])
row_height[block.row] = int(block.height);
}
//puts("Compute row and column sizes");
//Compute row and column positions
std::vector<int> col_x, row_y;
initVec(col_x, this->blocks[func.entry].col_count, 0);
initVec(row_y, this->blocks[func.entry].row_count, 0);
initVec(this->col_edge_x, this->blocks[func.entry].col_count + 1, 0);
initVec(this->row_edge_y, this->blocks[func.entry].row_count + 1, 0);
int x = 16;
for(int i = 0; i < this->blocks[func.entry].col_count; i++)
{
this->col_edge_x[i] = x;
x += 8 * col_edge_count[i];
col_x[i] = x;
x += col_width[i];
}
int y = 16;
for(int i = 0; i < this->blocks[func.entry].row_count; i++)
{
this->row_edge_y[i] = y;
y += 8 * row_edge_count[i];
row_y[i] = y;
y += row_height[i];
}
this->col_edge_x[this->blocks[func.entry].col_count] = x;
this->row_edge_y[this->blocks[func.entry].row_count] = y;
this->width = x + 16 + (8 * col_edge_count[this->blocks[func.entry].col_count]);
this->height = y + 16 + (8 * row_edge_count[this->blocks[func.entry].row_count]);
//puts("Compute row and column positions");
//Compute node positions
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
block.x = int(
(col_x[block.col] + col_width[block.col] + 4 * col_edge_count[block.col + 1]) - (block.width / 2));
if((block.x + block.width) > (
col_x[block.col] + col_width[block.col] + col_width[block.col + 1] + 8 * col_edge_count[
block.col + 1]))
{
block.x = int((col_x[block.col] + col_width[block.col] + col_width[block.col + 1] + 8 * col_edge_count[
block.col + 1]) - block.width);
}
block.y = row_y[block.row];
}
//puts("Compute node positions");
//Precompute coordinates for edges
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
for(DisassemblerEdge & edge : block.edges)
{
auto start = edge.points[0];
auto start_col = start.col;
auto last_index = edge.start_index;
auto last_pt = QPoint(this->col_edge_x[start_col] + (8 * last_index) + 4,
block.y + block.height + 4 - (2 * this->charWidth));
QPolygonF pts;
pts.append(last_pt);
for(int i = 0; i < int(edge.points.size()); i++)
{
auto end = edge.points[i];
auto end_row = end.row;
auto end_col = end.col;
auto last_index = end.index;
QPoint new_pt;
if(start_col == end_col)
new_pt = QPoint(last_pt.x(), this->row_edge_y[end_row] + (8 * last_index) + 4);
else
new_pt = QPoint(this->col_edge_x[end_col] + (8 * last_index) + 4, last_pt.y());
pts.push_back(new_pt);
last_pt = new_pt;
start_col = end_col;
}
auto new_pt = QPoint(last_pt.x(), edge.dest->y + this->charWidth - 1);
pts.push_back(QPoint(new_pt.x(), new_pt.y() - 6));
edge.polyline = pts;
pts.clear();
pts.append(QPoint(new_pt.x() - 3, new_pt.y() - 6));
pts.append(QPoint(new_pt.x() + 3, new_pt.y() - 6));
pts.append(new_pt);
edge.arrow = pts;
}
}
//puts("Precompute coordinates for edges");
//Adjust scroll bars for new size
QSize areaSize;
if(this->viewportReady)
{
areaSize = this->viewport()->size();
}
else
{
//before graph tab is shown for the first time the viewport is kind of 98x28 so setting the parent size almost fixes this problem
areaSize = this->parentWidget()->size() - QSize(20, 20);
}
qreal sx = qreal(areaSize.width()) / qreal(this->width);
qreal sy = qreal(areaSize.height()) / qreal(this->height);
zoomMinimum = qMin(qMin(sx, sy) * (1 - zoomStep), 0.05); //if graph is very lagre
this->adjustSize(areaSize.width(), areaSize.height());
puts("Adjust scroll bars for new size");
if(this->desired_pos)
{
//There was a position saved, navigate to it
this->horizontalScrollBar()->setValue(this->desired_pos[0]);
this->verticalScrollBar()->setValue(this->desired_pos[1]);
}
else if(this->cur_instr != 0)
{
this->show_cur_instr(this->forceCenter);
this->forceCenter = false;
}
else
{
//Ensure start node is visible
auto start_x = this->blocks[func.entry].x + this->renderXOfs + int(this->blocks[func.entry].width / 2);
this->horizontalScrollBar()->setValue(start_x - int(areaSize.width() / 2));
this->verticalScrollBar()->setValue(0);
}
this->ready = true;
this->viewport()->update(0, 0, areaSize.width(), areaSize.height());
//puts("Finished");
}
void DisassemblerGraphView::show_cur_instr(bool force)
{
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
auto row = int(block.block.header_text.lines.size());
for(Instr & instr : block.block.instrs)
{
if(this->cur_instr == instr.addr)
{
//Don't update the view for blocks that are already fully in view
int xofs = this->horizontalScrollBar()->value();
int yofs = this->verticalScrollBar()->value();
QRect viewportRect = this->viewport()->rect();
if(!viewportReady)
{
//before being shown for the first time viewport is kind of 98x28 so setting the parent size almost fixes this problem
viewportRect.setSize(this->parentWidget()->size() - QSize(20, 20));
}
QPoint translation(this->renderXOfs - xofs, this->renderYOfs - yofs);
//Adjust scaled viewport
viewportRect.setWidth(viewportRect.width() / zoomLevel);
viewportRect.setHeight(viewportRect.height() / zoomLevel);
viewportRect.translate(-translation.x() / zoomLevel, -translation.y() / zoomLevel);
if(force || !viewportRect.contains(QRect(block.x + this->charWidth, block.y + this->charWidth,
block.width - (2 * this->charWidth), block.height - (2 * this->charWidth))))
{
auto x = (block.x + int(block.width / 2)) * zoomLevel;
auto y = (block.y + (2 * this->charWidth) + int((row + 0.5) * this->charHeight)) * zoomLevel;
this->horizontalScrollBar()->setValue(x + this->renderXOfs -
int(this->horizontalScrollBar()->pageStep() / 2));
this->verticalScrollBar()->setValue(y + this->renderYOfs -
int(this->verticalScrollBar()->pageStep() / 2));
}
return;
}
row += int(instr.text.lines.size());
}
}
}
bool DisassemblerGraphView::navigate(duint addr)
{
//Add address to history
if(!mHistoryLock)
mHistory.addVaToHistory(addr);
//Check to see if address is within current function
for(auto & blockIt : this->blocks)
{
DisassemblerBlock & block = blockIt.second;
if(block.block.entry > addr) //optimize it
continue;
auto row = int(block.block.header_text.lines.size());
for(Instr & instr : block.block.instrs)
{
if((addr >= instr.addr) && (addr < (instr.addr + int(instr.opcode.size()))))
{
this->cur_instr = instr.addr;
this->show_cur_instr();
this->viewport()->update();
emit selectionChanged(addr);
return true;
}
row += int(instr.text.lines.size());
}
}
//Check other functions for this address
duint func, instr;
if(this->analysis.find_instr(addr, func, instr))
{
this->function = func;
this->cur_instr = instr;
this->ready = false;
this->desired_pos = nullptr;
this->viewport()->update();
emit selectionChanged(addr);
return true;
}
return false;
}
void DisassemblerGraphView::fontChanged()
{
this->initFont();
if(this->ready)
{
//Rerender function to update layout
this->renderFunction(this->analysis.functions[this->function]);
}
}
void DisassemblerGraphView::setGraphLayout(DisassemblerGraphView::LayoutType layout)
{
this->layoutType = layout;
if(this->ready)
{
this->renderFunction(this->analysis.functions[this->function]);
}
}
void DisassemblerGraphView::tokenizerConfigUpdatedSlot()
{
disasm.UpdateConfig();
mPermanentHighlightingMode = ConfigBool("Disassembler", "PermanentHighlightingMode");
loadCurrentGraph();
}
void DisassemblerGraphView::loadCurrentGraph()
{
if(ConfigBool("Gui", "GraphZoomMode"))
{
graphZoomMode = true;
drawOverview = false;
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
else
{
graphZoomMode = false;
zoomLevel = 1;
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}
bool showGraphRva = ConfigBool("Gui", "ShowGraphRva");
Analysis anal;
anal.entry = currentGraph.entryPoint;
anal.ready = true;
{
Function func;
func.entry = currentGraph.entryPoint;
func.ready = true;
{
for(const auto & nodeIt : currentGraph.nodes)
{
const BridgeCFNode & node = nodeIt.second;
Block block;
block.entry = node.instrs.empty() ? node.start : node.instrs[0].addr;
block.exits = node.exits;
block.false_path = node.brfalse;
block.true_path = node.brtrue;
block.terminal = node.terminal;
block.indirectcall = node.indirectcall;
auto headerRich = Text::makeRich(getSymbolicName(block.entry), mLabelColor, mLabelBackgroundColor);
block.header_text = Text();
block.header_text.addLine({headerRich}, {});
{
Instr instr;
for(const BridgeCFInstruction & nodeInstr : node.instrs)
{
auto addr = nodeInstr.addr;
currentBlockMap[addr] = block.entry;
Instruction_t instrTok = disasm.DisassembleAt((byte_t*)nodeInstr.data, sizeof(nodeInstr.data), 0, addr, false);
RichTextPainter::List richText;
auto zydisTokens = instrTok.tokens;
ZydisTokenizer::TokenToRichText(zydisTokens, richText, nullptr);
// add rva to node instruction text
if(showGraphRva)
{
QString rvaText = QString().number(instrTok.rva, 16).toUpper().trimmed() + " ";
auto rvaRich = Text::makeRich(rvaText, mAddressColor, mAddressBackgroundColor);
richText.insert(richText.begin(), rvaRich);
zydisTokens.x += rvaText.length(); // pad tokens for the highlighting mode
}
auto size = instrTok.length;
instr.addr = addr;
instr.opcode.resize(size);
for(int j = 0; j < size; j++)
instr.opcode[j] = nodeInstr.data[j];
QString comment;
bool autoComment = false;
RichTextPainter::CustomRichText_t commentText;
commentText.underline = false;
char label[MAX_LABEL_SIZE] = "";
if(GetCommentFormat(addr, comment, &autoComment))
{
if(autoComment)
{
commentText.textColor = mAutoCommentColor;
commentText.textBackground = mAutoCommentBackgroundColor;
}
else //user comment
{
commentText.textColor = mCommentColor;
commentText.textBackground = mCommentBackgroundColor;
}
commentText.text = QString("; ") + comment;
//add to text
}
else if(DbgGetLabelAt(addr, SEG_DEFAULT, label) && addr != block.entry) // label but no comment
{
commentText.textColor = mLabelColor;
commentText.textBackground = mLabelBackgroundColor;
commentText.text = QString("; ") + label;
}
commentText.flags = commentText.textBackground.alpha() ? RichTextPainter::FlagAll : RichTextPainter::FlagColor;
if(commentText.text.length())
{
RichTextPainter::CustomRichText_t spaceText;
spaceText.underline = false;
spaceText.flags = RichTextPainter::FlagNone;
spaceText.text = " ";
richText.push_back(spaceText);
richText.push_back(commentText);
}
instr.text = Text();
instr.text.addLine(richText, zydisTokens);
instr.text.updateHighlighting(mHighlightToken, mInstructionHighlightColor, mInstructionHighlightBackgroundColor);
//The summary contains calls, rets, user comments and string references
if(!onlySummary ||
instrTok.branchType == Instruction_t::Call ||
instrTok.instStr.startsWith("ret", Qt::CaseInsensitive) ||
(!commentText.text.isEmpty() && !autoComment) ||
commentText.text.contains('\"'))
block.instrs.push_back(instr);
}
}
func.blocks.push_back(block);
}
}
anal.functions.insert({func.entry, func});
}
this->analysis = anal;
this->function = this->analysis.entry;
this->renderFunction(this->analysis.functions[this->function]);
}
void DisassemblerGraphView::loadGraphSlot(BridgeCFGraphList* graphList, duint addr)
{
auto nodeCount = graphList->nodes.count;
if(nodeCount > 5000) //TODO: add configuration
{
auto title = tr("Large number of nodes");
auto message = tr("The graph you are trying to render has a large number of nodes (%1). This can cause x64dbg to hang or crash. It is recommended to save your data before you continue.\n\nDo you want to continue rendering this graph?").arg(nodeCount);
if(QMessageBox::question(this, title, message, QMessageBox::Yes, QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
{
Bridge::getBridge()->setResult(BridgeResult::LoadGraph, 0);
return;
}
}
currentGraph = BridgeCFGraph(graphList, true);
currentBlockMap.clear();
this->cur_instr = addr ? addr : this->function;
this->forceCenter = true;
loadCurrentGraph();
Bridge::getBridge()->setResult(BridgeResult::LoadGraph, 1);
}
void DisassemblerGraphView::graphAtSlot(duint addr)
{
Bridge::getBridge()->setResult(BridgeResult::GraphAt, this->navigate(addr) ? this->currentGraph.entryPoint : 0);
}
void DisassemblerGraphView::updateGraphSlot()
{
if(!DbgIsDebugging())
{
//happens mostly when debugging process has been terminated
this->ready = false;
zoomLevel = 1;
zoomLevelOld = 1;
}
this->viewport()->update();
}
void DisassemblerGraphView::addReferenceAction(QMenu* menu, duint addr, const QString & description)
{
if(!DbgMemIsValidReadPtr(addr))
return;
auto addrText = ToPtrString(addr);
for(QAction* action : menu->actions())
if(action->data() == addrText)
return;
QAction* action = new QAction(menu);
action->setFont(font());
action->setData(addrText);
if(description.isEmpty())
action->setText(getSymbolicName(addr));
else
action->setText(description);
connect(action, SIGNAL(triggered()), this, SLOT(followActionSlot()));
menu->addAction(action);
}
duint DisassemblerGraphView::zoomActionHelper()
{
if(!graphZoomMode || graphZoomMode && lastRightClickPosition.pos.isNull()) //old mode or zoom mode + shurtcut
return cur_instr;
else if(graphZoomMode && !(lastRightClickPosition.inBlock && zoomLevel > zoomOverviewValue)) //out of block or too small zoom value
return 0;
else
return cur_instr;
}
void DisassemblerGraphView::setupContextMenu()
{
/* Unlike old style menu, the new one now depends on zoom level and cursor position.
* There are several options for how menu will look like. This makes interaction more clear and predictable.
* E.g clicking outside of block (especially at large zoom level) will set breakpoint menu hidden
* as well as any action that needs text to be visible will also be hidden.
* Notice: keyboard shortcuts still work - this implies that user understands what he is doing. */
mMenuBuilder = new MenuBuilder(this, [this](QMenu*)
{
return DbgIsDebugging() && this->ready;
});
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]()
{
return zoomActionHelper();
});
auto zoomActionHelperNonZero = [this](QMenu*)
{
return zoomActionHelper() != 0;
};
mMenuBuilder->addAction(makeShortcutAction(DIcon(ArchValue("processor32", "processor64")), tr("Follow in &Disassembler"), SLOT(followDisassemblySlot()), "ActionGraph"), zoomActionHelperNonZero);
mMenuBuilder->addSeparator();
mCommonActions->build(mMenuBuilder, CommonActions::ActionBreakpoint | CommonActions::ActionMemoryMap | CommonActions::ActionBookmark | CommonActions::ActionLabel |
CommonActions::ActionComment | CommonActions::ActionNewOrigin | CommonActions::ActionNewThread);
mMenuBuilder->addAction(makeShortcutAction(DIcon("xrefs"), tr("Xrefs..."), SLOT(xrefSlot()), "ActionXrefs"), zoomActionHelperNonZero);
MenuBuilder* gotoMenu = new MenuBuilder(this);
gotoMenu->addAction(makeShortcutAction(DIcon("geolocation-goto"), tr("Expression"), SLOT(gotoExpressionSlot()), "ActionGotoExpression"));
gotoMenu->addAction(makeShortcutAction(DIcon("cbp"), ArchValue("EIP", "RIP"), SLOT(gotoOriginSlot()), "ActionGotoOrigin"));
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();
});
MenuBuilder* childrenAndParentMenu = new MenuBuilder(this, [this](QMenu * menu)
{
if(!zoomActionHelper())
return false;
duint cursorpos = get_cursor_pos();
const DisassemblerBlock* currentBlock = nullptr;
const Instr* currentInstruction = nullptr;
for(const auto & i : blocks)
{
if(i.second.block.entry > cursorpos)
continue;
for(const Instr & inst : i.second.block.instrs)
{
if(inst.addr <= cursorpos && inst.addr + inst.opcode.size() > cursorpos)
{
currentBlock = &i.second;
currentInstruction = &inst;
break;
}
}
if(currentInstruction)
break;
}
if(currentInstruction)
{
DISASM_INSTR instr = { 0 };
DbgDisasmAt(currentInstruction->addr, &instr);
for(int i = 0; i < instr.argcount; i++)
{
const DISASM_ARG & arg = instr.arg[i];
if(arg.type == arg_memory)
{
QString segment = "";
#ifdef _WIN64
if(arg.segment == SEG_GS)
segment = "gs:";
#else //x32
if(arg.segment == SEG_FS)
segment = "fs:";
#endif //_WIN64
if(arg.value != arg.constant)
addReferenceAction(menu, arg.value, tr("&Address: ") + segment + QString(arg.mnemonic).toUpper().trimmed());
addReferenceAction(menu, arg.constant, tr("&Constant: ") + getSymbolicName(arg.constant));
addReferenceAction(menu, arg.memvalue, tr("&Value: ") + segment + "[" + QString(arg.mnemonic) + "]");
}
else
{
QString symbolicName = getSymbolicName(arg.value);
QString mnemonic = QString(arg.mnemonic).trimmed();
if(mnemonic != ToHexString(arg.value))
mnemonic = mnemonic + ": " + symbolicName;
else
mnemonic = symbolicName;
addReferenceAction(menu, arg.value, mnemonic);
}
}
menu->addSeparator();
for(const duint & i : currentBlock->incoming) // This list is incomplete
addReferenceAction(menu, i, tr("Block incoming: %1").arg(getSymbolicName(i)));
if(!currentBlock->block.terminal)
{
menu->addSeparator();
for(const duint & i : currentBlock->block.exits)
addReferenceAction(menu, i, tr("Block exit %1").arg(getSymbolicName(i)));
}
return true;
}
return false;
});
gotoMenu->addSeparator();
gotoMenu->addBuilder(childrenAndParentMenu);
mMenuBuilder->addMenu(makeMenu(DIcon("goto"), tr("Go to")), gotoMenu);
mMenuBuilder->addAction(makeShortcutAction(DIcon("helpmnemonic"), tr("Help on mnemonic"), SLOT(mnemonicHelpSlot()), "ActionHelpOnMnemonic"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("highlight"), tr("&Highlighting mode"), SLOT(enableHighlightingModeSlot()), "ActionHighlightingMode"));
mMenuBuilder->addSeparator();
auto ifgraphZoomMode = [this](QMenu*)
{
return graphZoomMode;
};
mMenuBuilder->addAction(mZoomToCursor = makeShortcutAction(DIcon("zoom"), tr("&Zoom 100%"), SLOT(zoomToCursorSlot()), "ActionGraphZoomToCursor"), ifgraphZoomMode);
mMenuBuilder->addAction(mFitToWindow = makeShortcutAction(DIcon("fit"), tr("&Fit to window"), SLOT(fitToWindowSlot()), "ActionGraphFitToWindow"), ifgraphZoomMode);
mMenuBuilder->addAction(mToggleOverview = makeShortcutAction(DIcon("graph"), tr("&Overview"), SLOT(toggleOverviewSlot()), "ActionGraphToggleOverview"), ifgraphZoomMode);
mToggleOverview->setCheckable(true);
mMenuBuilder->addAction(mToggleSummary = makeShortcutAction(DIcon("summary"), tr("S&ummary"), SLOT(toggleSummarySlot()), "ActionGraphToggleSummary"));
mToggleSummary->setCheckable(true);
mMenuBuilder->addAction(mToggleSyncOrigin = makeShortcutAction(DIcon("lock"), tr("&Sync with %1").arg(ArchValue("EIP", "RIP")), SLOT(toggleSyncOriginSlot()), "ActionSync"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("sync"), tr("&Refresh"), SLOT(refreshSlot()), "ActionRefresh"));
mMenuBuilder->addAction(makeShortcutAction(DIcon("image"), tr("&Save as image"), SLOT(saveImageSlot()), "ActionGraphSaveImage"));
MenuBuilder* layoutMenu = new MenuBuilder(this);
QActionGroup* layoutGroup = new QActionGroup(this);
layoutGroup->addAction(makeAction(DIcon("narrow"), tr("Narrow"), [this]() { setGraphLayout(LayoutType::Narrow); }));
QAction* mediumLayout =
layoutGroup->addAction(makeAction(DIcon("medium"), tr("Medium"), [this]() { setGraphLayout(LayoutType::Medium); }));
layoutGroup->addAction(makeAction(DIcon("wide"), tr("Wide"), [this]() { setGraphLayout(LayoutType::Wide); }));
for(QAction* layoutAction : layoutGroup->actions())
{
layoutAction->setCheckable(true);
layoutMenu->addAction(layoutAction);
}
mediumLayout->setChecked(true);
mMenuBuilder->addMenu(makeMenu(DIcon("layout"), tr("Layout")), layoutMenu);
mPluginMenu = new QMenu(this);
Bridge::getBridge()->emitMenuAddToList(this, mPluginMenu, GUI_GRAPH_MENU);
mMenuBuilder->addAction(makeAction(tr("Detach"), [this]() { emit detachGraph(); }), [this](QMenu*) { return qobject_cast<QMainWindow*>(this->parent()) == nullptr; });
mMenuBuilder->addSeparator();
mMenuBuilder->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
DbgMenuPrepare(GUI_GRAPH_MENU);
menu->addActions(mPluginMenu->actions());
return true;
}));
// Highlighting mode menu
mHighlightMenuBuilder = new MenuBuilder(this);
mHighlightMenuBuilder->addAction(makeAction(DIcon("copy"), tr("Copy token &text"), SLOT(copyHighlightedTokenTextSlot())));
mHighlightMenuBuilder->addAction(makeAction(DIcon("copy_address"), tr("Copy token &value"), SLOT(copyHighlightedTokenValueSlot())), [this](QMenu*)
{
QString text;
if(!getHighlightedTokenValueText(text))
return false;
return text != mHighlightToken.text;
});
mMenuBuilder->loadFromConfig();
}
void DisassemblerGraphView::showContextMenu(QMouseEvent* event)
{
QMenu wMenu(this);
mMenuBuilder->build(&wMenu);
wMenu.exec(event->globalPos());
lastRightClickPosition.pos = {};
}
void DisassemblerGraphView::keyPressEvent(QKeyEvent* event)
{
if(event->modifiers() != 0)
return;
int key = event->key();
if(key == Qt::Key_Up)
DbgCmdExec(QString("graph dis.prev(%1), silent").arg(ToPtrString(cur_instr)));
else if(key == Qt::Key_Down)
DbgCmdExec(QString("graph dis.next(%1), silent").arg(ToPtrString(cur_instr)));
else if(key == Qt::Key_Left)
DbgCmdExec(QString("graph dis.brtrue(%1), silent").arg(ToPtrString(cur_instr)));
else if(key == Qt::Key_Right)
DbgCmdExec(QString("graph dis.brfalse(%1), silent").arg(ToPtrString(cur_instr)));
else if(key == Qt::Key_Return || key == Qt::Key_Enter)
{
//Add address to history
if(!mHistoryLock)
mHistory.addVaToHistory(cur_instr);
DbgCmdExec(QString("graph dis.branchdest(%1), silent").arg(ToPtrString(cur_instr)));
}
}
void DisassemblerGraphView::colorsUpdatedSlot()
{
disassemblyBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
graphNodeColor = ConfigColor("GraphNodeColor");
graphNodeBackgroundColor = ConfigColor("GraphNodeBackgroundColor");
if(!graphNodeBackgroundColor.alpha())
graphNodeBackgroundColor = disassemblyBackgroundColor;
graphCurrentShadowColor = ConfigColor("GraphCurrentShadowColor");
disassemblySelectionColor = ConfigColor("DisassemblySelectionColor");
disassemblyTracedColor = ConfigColor("DisassemblyTracedBackgroundColor");
auto a = disassemblySelectionColor, b = disassemblyTracedColor;
disassemblyTracedSelectionColor = QColor((a.red() + b.red()) / 2, (a.green() + b.green()) / 2, (a.blue() + b.blue()) / 2);
mAutoCommentColor = ConfigColor("DisassemblyAutoCommentColor");
mAutoCommentBackgroundColor = ConfigColor("DisassemblyAutoCommentBackgroundColor");
mCommentColor = ConfigColor("DisassemblyCommentColor");
mCommentBackgroundColor = ConfigColor("DisassemblyCommentBackgroundColor");
mLabelColor = ConfigColor("DisassemblyLabelColor");
mLabelBackgroundColor = ConfigColor("DisassemblyLabelBackgroundColor");
mAddressColor = ConfigColor("DisassemblyAddressColor");
mAddressBackgroundColor = ConfigColor("DisassemblyAddressBackgroundColor");
jmpColor = ConfigColor("GraphJmpColor");
brtrueColor = ConfigColor("GraphBrtrueColor");
brfalseColor = ConfigColor("GraphBrfalseColor");
retShadowColor = ConfigColor("GraphRetShadowColor");
indirectcallShadowColor = ConfigColor("GraphIndirectcallShadowColor");
backgroundColor = ConfigColor("GraphBackgroundColor");
if(!backgroundColor.alpha())
backgroundColor = disassemblySelectionColor;
mCipColor = ConfigColor("GraphCipColor");
mBreakpointColor = ConfigColor("GraphBreakpointColor");
mDisabledBreakpointColor = ConfigColor("GraphDisabledBreakpointColor");
mBookmarkBackgroundColor = ConfigColor("DisassemblyBookmarkBackgroundColor");
mInstructionHighlightColor = ConfigColor("InstructionHighlightColor");
mInstructionHighlightBackgroundColor = ConfigColor("InstructionHighlightBackgroundColor");
fontChanged();
loadCurrentGraph();
}
void DisassemblerGraphView::fontsUpdatedSlot()
{
fontChanged();
}
void DisassemblerGraphView::shortcutsUpdatedSlot()
{
updateShortcuts();
}
void DisassemblerGraphView::toggleOverviewSlot()
{
if(graphZoomMode)
return;
drawOverview = !drawOverview;
if(onlySummary)
{
onlySummary = false;
mToggleSummary->setChecked(false);
loadCurrentGraph();
}
else
this->viewport()->update();
}
void DisassemblerGraphView::toggleSummarySlot()
{
drawOverview = false;
onlySummary = !onlySummary;
loadCurrentGraph();
}
void DisassemblerGraphView::selectionGetSlot(SELECTIONDATA* selection)
{
selection->start = selection->end = cur_instr;
Bridge::getBridge()->setResult(BridgeResult::SelectionGet, 1);
}
void DisassemblerGraphView::disassembleAtSlot(dsint va, dsint cip)
{
Q_UNUSED(va);
auto cipChanged = mCip != cip;
mCip = cip;
if(syncOrigin && cipChanged)
gotoOriginSlot();
else
this->viewport()->update();
}
void DisassemblerGraphView::gotoExpressionSlot()
{
if(!DbgIsDebugging())
return;
if(!mGoto)
mGoto = new GotoDialog(this);
mGoto->setInitialExpression(ToPtrString(this->cur_instr));
if(mGoto->exec() == QDialog::Accepted)
{
duint value = DbgValFromString(mGoto->expressionText.toUtf8().constData());
DbgCmdExec(QString().sprintf("graph %p, silent", value));
}
}
void DisassemblerGraphView::gotoOriginSlot()
{
DbgCmdExec("graph cip, silent");
}
void DisassemblerGraphView::gotoPreviousSlot()
{
if(mHistory.historyHasPrev())
{
mHistoryLock = true;
DbgCmdExecDirect(QString("graph %1, silent").arg(ToPtrString(mHistory.historyPrev())));
mHistoryLock = false;
}
}
void DisassemblerGraphView::gotoNextSlot()
{
if(mHistory.historyHasNext())
{
mHistoryLock = true;
DbgCmdExecDirect(QString("graph %1, silent").arg(ToPtrString(mHistory.historyNext())));
mHistoryLock = false;
}
}
void DisassemblerGraphView::toggleSyncOriginSlot()
{
syncOrigin = !syncOrigin;
mToggleSyncOrigin->setCheckable(true);
mToggleSyncOrigin->setChecked(syncOrigin);
if(syncOrigin)
gotoOriginSlot();
}
void DisassemblerGraphView::refreshSlot()
{
DbgCmdExec(QString("graph %1, force").arg(ToPtrString(this->cur_instr)));
}
void DisassemblerGraphView::saveImageSlot()
{
saveGraph = true;
this->viewport()->update();
}
void DisassemblerGraphView::xrefSlot()
{
if(!DbgIsDebugging())
return;
duint wVA = this->get_cursor_pos();
if(!DbgMemIsValidReadPtr(wVA))
return;
XREF_INFO mXrefInfo;
DbgXrefGet(wVA, &mXrefInfo);
if(!mXrefInfo.refcount)
return;
BridgeFree(mXrefInfo.references);
if(!mXrefDlg)
mXrefDlg = new XrefBrowseDialog(this);
mXrefDlg->setup(wVA, [](duint addr)
{
DbgCmdExec(QString("graph %1").arg(ToPtrString(addr)));
});
mXrefDlg->showNormal();
}
void DisassemblerGraphView::followDisassemblySlot()
{
mCommonActions->followDisassemblySlot();
}
void DisassemblerGraphView::followActionSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action)
{
QString data = action->data().toString();
DbgCmdExecDirect(QString("graph %1, silent").arg(data));
}
}
void DisassemblerGraphView::mnemonicHelpSlot()
{
unsigned char data[16] = { 0xCC };
auto addr = this->get_cursor_pos();
DbgMemRead(addr, data, sizeof(data));
Zydis zydis;
zydis.Disassemble(addr, data);
DbgCmdExecDirect(QString("mnemonichelp %1").arg(zydis.Mnemonic().c_str()));
emit displayLogWidget();
}
void DisassemblerGraphView::fitToWindowSlot()
{
auto areaSize = viewport()->size();
qreal sx = qreal(areaSize.width()) / qreal(this->width);
qreal sy = qreal(areaSize.height()) / qreal(this->height);
zoomLevelOld = zoomLevel;
zoomLevel = qMin(qMin(sx, sy), qreal(1));
zoomDirection = -1;
this->adjustSize(areaSize.width(), areaSize.height(), QPoint(), true);
this->viewport()->update();
}
void DisassemblerGraphView::zoomToCursorSlot()
{
QPoint pos;
if(!lastRightClickPosition.pos.isNull())
{
pos = lastRightClickPosition.pos;
}
else
{
pos = this->mapFromGlobal(QCursor::pos());
}
zoomLevelOld = zoomLevel;
zoomLevel = 1;
zoomDirection = 1;
auto areaSize = viewport()->size();
this->adjustSize(areaSize.width(), areaSize.height(), pos);
this->viewport()->update();
}
void DisassemblerGraphView::getCurrentGraphSlot(BridgeCFGraphList* graphList)
{
*graphList = currentGraph.ToGraphList();
Bridge::getBridge()->setResult(BridgeResult::GraphCurrent);
}
void DisassemblerGraphView::dbgStateChangedSlot(DBGSTATE state)
{
if(state == stopped)
{
resetGraph();
this->viewport()->update();
}
}
void DisassemblerGraphView::copyHighlightedTokenTextSlot()
{
Bridge::CopyToClipboard(mHighlightToken.text);
}
void DisassemblerGraphView::copyHighlightedTokenValueSlot()
{
QString text;
if(getHighlightedTokenValueText(text))
Bridge::CopyToClipboard(text);
}
bool DisassemblerGraphView::getHighlightedTokenValueText(QString & text)
{
if(mHighlightToken.type <= ZydisTokenizer::TokenType::MnemonicUnusual)
return false;
duint value = mHighlightToken.value.value;
if(!mHighlightToken.value.size && !DbgFunctions()->ValFromString(mHighlightToken.text.toUtf8().constData(), &value))
return false;
text = ToHexString(value);
return true;
}
void DisassemblerGraphView::enableHighlightingModeSlot()
{
mHighlightingModeEnabled = !mHighlightingModeEnabled;
this->viewport()->update();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/DisassemblerGraphView.h | #pragma once
#include <QObject>
#include <QWidget>
#include <QAbstractScrollArea>
#include <QPaintEvent>
#include <QTimer>
#include <QSize>
#include <QResizeEvent>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <QMutex>
#include "Bridge.h"
#include "RichTextPainter.h"
#include "QBeaEngine.h"
#include "ActionHelpers.h"
#include "VaHistory.h"
class MenuBuilder;
class CachedFontMetrics;
class GotoDialog;
class XrefBrowseDialog;
class CommonActions;
class DisassemblerGraphView : public QAbstractScrollArea, public ActionHelper<DisassemblerGraphView>
{
Q_OBJECT
public:
struct DisassemblerBlock;
struct Point
{
int row; //point[0]
int col; //point[1]
int index; //point[2]
};
struct DisassemblerEdge
{
QColor color;
DisassemblerBlock* dest;
std::vector<Point> points;
int start_index = 0;
QPolygonF polyline;
QPolygonF arrow;
void addPoint(int row, int col, int index = 0)
{
Point point = {row, col, 0};
this->points.push_back(point);
if(int(this->points.size()) > 1)
this->points[this->points.size() - 2].index = index;
}
};
struct Text
{
// text to render; some words here may be colored (with highlighting mode)
std::vector<RichTextPainter::List> lines;
// tokens for selection in "Highlighting mode"; one "InstructionToken" per line
std::vector<ZydisTokenizer::InstructionToken> lineTokens;
Text() {}
void addLine(const RichTextPainter::List & richText, const ZydisTokenizer::InstructionToken & tokens)
{
lines.push_back(richText);
lineTokens.push_back(tokens);
}
// Highlight the given token and restore the original colors to the rest of the text
void updateHighlighting(const ZydisTokenizer::SingleToken & highlightToken, QColor color, QColor background)
{
// assumption: the rich text 'lines' includes a 1:1 copy of the original tokens 'lineTokens'
for(size_t nLine = 0; nLine < lines.size(); nLine++)
{
// based on the tokens X offset, find the first token in the rich text (skip RVA prefix)
int i = 0, nRtOffset = 0;
while(i < lineTokens[nLine].x && nRtOffset < (int)lines[nLine].size())
{
i += lines[nLine][nRtOffset].text.length();
nRtOffset++;
}
// check if the rich text covers all the Zydis tokens
if(lines[nLine].size() - nRtOffset < lineTokens[nLine].tokens.size())
continue; // normally should not happen
for(size_t nToken = 0; nToken < lineTokens[nLine].tokens.size(); nToken++)
{
auto & rt = lines[nLine][nToken + nRtOffset];
auto & token = lineTokens[nLine].tokens[nToken];
bool isEqual = ZydisTokenizer::TokenEquals(&token, &highlightToken);
auto tokenOrigColor = ZydisTokenizer::getTokenColor(token.type);
rt.textColor = isEqual ? color : tokenOrigColor.color;
rt.textBackground = isEqual ? background : tokenOrigColor.backgroundColor;
}
}
}
static RichTextPainter::CustomRichText_t makeRich(const QString & text, QColor color, QColor background)
{
RichTextPainter::CustomRichText_t rt;
rt.underline = false;
rt.text = text;
rt.textColor = color;
rt.textBackground = background;
rt.flags = rt.textBackground.alpha() ? RichTextPainter::FlagAll : RichTextPainter::FlagColor;
return rt;
}
QString ToQString() const
{
QString result;
for(auto & line : lines)
{
for(auto & t : line)
{
result += t.text;
}
}
return std::move(result);
}
};
struct Instr
{
duint addr = 0;
Text text;
std::vector<unsigned char> opcode; //instruction bytes
};
struct Block
{
Text header_text;
std::vector<Instr> instrs;
std::vector<duint> exits;
duint entry = 0;
duint true_path = 0;
duint false_path = 0;
bool terminal = false;
bool indirectcall = false;
};
struct DisassemblerBlock
{
DisassemblerBlock() {}
explicit DisassemblerBlock(Block & block)
: block(block) {}
Block block;
std::vector<DisassemblerEdge> edges;
std::vector<duint> incoming;
std::vector<duint> new_exits;
qreal x = 0.0;
qreal y = 0.0;
int width = 0;
int height = 0;
int col = 0;
int col_count = 0;
int row = 0;
int row_count = 0;
};
struct Function
{
bool ready;
duint entry;
std::vector<Block> blocks;
};
struct Analysis
{
duint entry = 0;
std::unordered_map<duint, Function> functions;
bool ready = false;
QString status = "Analyzing...";
bool find_instr(duint addr, duint & func, duint & instr)
{
//TODO implement
Q_UNUSED(addr);
Q_UNUSED(func);
Q_UNUSED(instr);
return false;
}
//dummy class
};
enum class LayoutType
{
Wide,
Medium,
Narrow,
};
struct ClickPosition
{
QPoint pos = QPoint(0, 0);
bool inBlock = false;
};
DisassemblerGraphView(QWidget* parent = nullptr);
~DisassemblerGraphView();
void resetGraph();
void initFont();
void adjustSize(int viewportWidth, int viewportHeight, QPoint mousePosition = QPoint(0, 0), bool fitToWindow = false);
void resizeEvent(QResizeEvent* event);
duint get_cursor_pos();
void set_cursor_pos(duint addr);
std::tuple<duint, duint> get_selection_range();
void set_selection_range(std::tuple<duint, duint> range);
void copy_address();
void paintNormal(QPainter & p, QRect & viewportRect, int xofs, int yofs);
void paintOverview(QPainter & p, QRect & viewportRect, int xofs, int yofs);
void paintEvent(QPaintEvent* event);
bool isMouseEventInBlock(QMouseEvent* event);
duint getInstrForMouseEvent(QMouseEvent* event);
bool getTokenForMouseEvent(QMouseEvent* event, ZydisTokenizer::SingleToken & token);
bool find_instr(duint addr, Instr & instr);
void mousePressEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event);
void prepareGraphNode(DisassemblerBlock & block);
void adjustGraphLayout(DisassemblerBlock & block, int col, int row);
void computeGraphLayout(DisassemblerBlock & block);
void setupContextMenu();
void keyPressEvent(QKeyEvent* event);
template<typename T>
using Matrix = std::vector<std::vector<T>>;
using EdgesVector = Matrix<std::vector<bool>>;
bool isEdgeMarked(EdgesVector & edges, int row, int col, int index);
void markEdge(EdgesVector & edges, int row, int col, int index, bool used = true);
int findHorizEdgeIndex(EdgesVector & edges, int row, int min_col, int max_col);
int findVertEdgeIndex(EdgesVector & edges, int col, int min_row, int max_row);
DisassemblerEdge routeEdge(EdgesVector & horiz_edges, EdgesVector & vert_edges, Matrix<bool> & edge_valid, DisassemblerBlock & start, DisassemblerBlock & end, QColor color);
void renderFunction(Function & func);
void show_cur_instr(bool force = false);
bool navigate(duint addr);
void fontChanged();
void setGraphLayout(LayoutType layout);
void paintZoom(QPainter & p, QRect & viewportRect, int xofs, int yofs);
void wheelEvent(QWheelEvent* event);
void showEvent(QShowEvent* event);
void zoomIn(QPoint mousePosition);
void zoomOut(QPoint mousePosition);
void showContextMenu(QMouseEvent* event);
duint zoomActionHelper();
VaHistory mHistory;
signals:
void selectionChanged(dsint parVA);
void displayLogWidget();
void detachGraph();
public slots:
void loadGraphSlot(BridgeCFGraphList* graph, duint addr);
void graphAtSlot(duint addr);
void updateGraphSlot();
void colorsUpdatedSlot();
void fontsUpdatedSlot();
void shortcutsUpdatedSlot();
void toggleOverviewSlot();
void toggleSummarySlot();
void selectionGetSlot(SELECTIONDATA* selection);
void tokenizerConfigUpdatedSlot();
void loadCurrentGraph();
void disassembleAtSlot(dsint va, dsint cip);
void gotoExpressionSlot();
void gotoOriginSlot();
void gotoPreviousSlot();
void gotoNextSlot();
void toggleSyncOriginSlot();
void followActionSlot();
void followDisassemblySlot();
void refreshSlot();
void saveImageSlot();
void xrefSlot();
void mnemonicHelpSlot();
void fitToWindowSlot();
void zoomToCursorSlot();
void getCurrentGraphSlot(BridgeCFGraphList* graphList);
void dbgStateChangedSlot(DBGSTATE state);
void copyHighlightedTokenTextSlot();
void copyHighlightedTokenValueSlot();
void enableHighlightingModeSlot();
private:
bool graphZoomMode;
qreal zoomLevel;
qreal zoomLevelOld;
qreal zoomMinimum;
qreal zoomMaximum;
qreal zoomOverviewValue;
qreal zoomStep;
//qreal zoomScrollThreshold;
int zoomDirection;
int zoomBoost;
ClickPosition lastRightClickPosition;
QString status;
Analysis analysis;
duint function;
QTimer* updateTimer;
int baseline;
qreal charWidth;
int charHeight;
int charOffset;
int width;
int height;
int renderWidth;
int renderHeight;
int renderXOfs;
int renderYOfs;
duint cur_instr;
int scroll_base_x;
int scroll_base_y;
bool scroll_mode;
bool ready;
bool viewportReady;
int* desired_pos;
std::unordered_map<duint, DisassemblerBlock> blocks;
std::vector<int> col_edge_x;
std::vector<int> row_edge_y;
CachedFontMetrics* mFontMetrics;
MenuBuilder* mMenuBuilder;
CommonActions* mCommonActions;
QMenu* mPluginMenu;
bool drawOverview;
bool onlySummary;
bool syncOrigin;
int overviewXOfs;
int overviewYOfs;
qreal overviewScale;
duint mCip;
bool forceCenter;
bool saveGraph;
bool mHistoryLock; //Don't add a history while going to previous/next
LayoutType layoutType;
MenuBuilder* mHighlightMenuBuilder;
ZydisTokenizer::SingleToken mHighlightToken;
bool mHighlightingModeEnabled;
bool mPermanentHighlightingMode;
QAction* mToggleOverview;
QAction* mToggleSummary;
QAction* mToggleSyncOrigin;
QAction* mFitToWindow;
QAction* mZoomToCursor;
QColor disassemblyBackgroundColor;
QColor disassemblySelectionColor;
QColor disassemblyTracedColor;
QColor disassemblyTracedSelectionColor;
QColor jmpColor;
QColor brtrueColor;
QColor brfalseColor;
QColor retShadowColor;
QColor indirectcallShadowColor;
QColor backgroundColor;
QColor mAutoCommentColor;
QColor mAutoCommentBackgroundColor;
QColor mCommentColor;
QColor mCommentBackgroundColor;
QColor mLabelColor;
QColor mLabelBackgroundColor;
QColor mAddressColor;
QColor mAddressBackgroundColor;
QColor mCipColor;
QColor mBreakpointColor;
QColor mDisabledBreakpointColor;
QColor mBookmarkBackgroundColor;
QColor graphNodeColor;
QColor graphNodeBackgroundColor;
QColor graphCurrentShadowColor;
QColor mInstructionHighlightColor;
QColor mInstructionHighlightBackgroundColor;
BridgeCFGraph currentGraph;
std::unordered_map<duint, duint> currentBlockMap;
QBeaEngine disasm;
GotoDialog* mGoto;
XrefBrowseDialog* mXrefDlg;
void addReferenceAction(QMenu* menu, duint addr, const QString & description);
bool getHighlightedTokenValueText(QString & text);
}; |
C++ | x64dbg-development/src/gui/Src/Gui/DisassemblyPopup.cpp | #include "DisassemblyPopup.h"
#include "CachedFontMetrics.h"
#include "Configuration.h"
#include "StringUtil.h"
#include "MiscUtil.h"
#include <QPainter>
DisassemblyPopup::DisassemblyPopup(QWidget* parent) :
QFrame(parent, Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowDoesNotAcceptFocus),
mFontMetrics(nullptr),
mDisasm(ConfigUint("Disassembler", "MaxModuleSize"))
{
addr = 0;
addrText = nullptr;
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(updateFont()));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateColors()));
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(tokenizerConfigUpdated()));
updateFont();
updateColors();
setFrameStyle(QFrame::Panel);
setLineWidth(2);
mMaxInstructions = 20;
}
void DisassemblyPopup::updateColors()
{
disassemblyBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
disassemblyTracedColor = ConfigColor("DisassemblyTracedBackgroundColor");
labelColor = ConfigColor("DisassemblyLabelColor");
labelBackgroundColor = ConfigColor("DisassemblyLabelBackgroundColor");
commentColor = ConfigColor("DisassemblyCommentColor");
commentBackgroundColor = ConfigColor("DisassemblyCommentBackgroundColor");
commentAutoColor = ConfigColor("DisassemblyAutoCommentColor");
commentAutoBackgroundColor = ConfigColor("DisassemblyAutoCommentBackgroundColor");
QPalette palette;
palette.setColor(QPalette::Foreground, ConfigColor("AbstractTableViewSeparatorColor"));
setPalette(palette);
}
void DisassemblyPopup::tokenizerConfigUpdated()
{
mDisasm.UpdateConfig();
}
void DisassemblyPopup::updateFont()
{
delete mFontMetrics;
setFont(ConfigFont("Disassembly"));
QFontMetricsF metrics(font());
mFontMetrics = new CachedFontMetrics(this, font());
// Update font size, used in layout calculations.
charWidth = mFontMetrics->width('W');
charHeight = metrics.height();
}
void DisassemblyPopup::paintEvent(QPaintEvent* event)
{
QRect viewportRect(0, 0, width(), height());
QPainter p(this);
p.setFont(font());
// Render background
p.fillRect(viewportRect, disassemblyBackgroundColor);
// Draw Address
p.setPen(QPen(labelColor));
int addrWidth = mFontMetrics->width(addrText);
p.fillRect(3, 2 + lineWidth(), addrWidth, charHeight, QBrush(labelBackgroundColor));
p.drawText(3, 2, addrWidth, charHeight, 0, addrText);
// Draw Comments
if(!addrComment.isEmpty())
{
int commentWidth = mFontMetrics->width(addrComment);
QBrush background = QBrush(addrCommentAuto ? commentAutoBackgroundColor : commentBackgroundColor);
p.setPen(addrCommentAuto ? commentAutoColor : commentColor);
p.fillRect(3 + addrWidth, 2, commentWidth, charHeight, background);
p.drawText(3 + addrWidth, 2, commentWidth, charHeight, 0, addrComment);
}
// Draw Instructions
int y = charHeight + 1;
for(auto & instruction : mDisassemblyToken)
{
if(instruction.second)
p.fillRect(QRect(3, y, mWidth - 3, charHeight), disassemblyTracedColor);
RichTextPainter::paintRichText(&p, 3, y, mWidth - 3, charHeight, 0, instruction.first, mFontMetrics);
y += charHeight;
}
QFrame::paintEvent(event);
}
void DisassemblyPopup::setAddress(duint Address)
{
addr = Address;
QList<Instruction_t> instBuffer;
mDisassemblyToken.clear();
if(addr != 0)
{
mWidth = 1;
// Get RVA
auto addr = Address;
duint size;
duint base = DbgMemFindBaseAddr(addr, &size);
// Prepare RVA of every instruction
unsigned int i = 0;
instBuffer.clear();
auto nextAddr = addr;
bool hadBranch = false;
duint bestBranch = 0;
byte data[64];
do
{
if(nextAddr >= base + size)
break;
if(!DbgMemRead(nextAddr, data, sizeof(data)))
break;
auto instruction = mDisasm.DisassembleAt(data, sizeof(data), 0, nextAddr);
if(!instruction.length)
break;
instBuffer.append(instruction);
if(!hadBranch || bestBranch <= nextAddr)
{
if(instruction.instStr.contains("ret"))
break;
if(instruction.instStr.contains("jmp") && instruction.instStr.contains("["))
break;
}
if(instruction.branchDestination && !instruction.instStr.contains("call") && !instruction.instStr.contains("ret"))
{
hadBranch = true;
if(instruction.branchDestination > bestBranch)
bestBranch = instruction.branchDestination;
}
auto nextAddr2 = nextAddr + instruction.length;
if(nextAddr2 == nextAddr)
break;
else
nextAddr = nextAddr2;
if(DbgGetFunctionTypeAt(nextAddr - 1) == FUNC_END)
break;
i++;
}
while(i < mMaxInstructions);
// Disassemble
for(auto & instruction : instBuffer)
{
RichTextPainter::List richText;
ZydisTokenizer::TokenToRichText(instruction.tokens, richText, nullptr);
// Calculate width
int currentInstructionWidth = 0;
for(auto & token : richText)
currentInstructionWidth += mFontMetrics->width(token.text);
mWidth = std::max(mWidth, currentInstructionWidth);
mDisassemblyToken.push_back(std::make_pair(std::move(richText), DbgFunctions()->GetTraceRecordHitCount(instruction.rva) != 0));
}
// Address
addrText = getSymbolicName(addr);
// Comments
GetCommentFormat(addr, addrComment, &addrCommentAuto);
if(addrComment.length())
addrText.append(' ');
// Calculate width of address
mWidth = std::max(mWidth, mFontMetrics->width(addrText) + mFontMetrics->width(addrComment));
mWidth += charWidth * 6;
// Resize popup
resize(mWidth + 2, charHeight * int(mDisassemblyToken.size() + 1) + 2);
}
update();
}
duint DisassemblyPopup::getAddress()
{
return addr;
}
void DisassemblyPopup::hide()
{
addr = 0;
QFrame::hide();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/DisassemblyPopup.h | #pragma once
#include <QFrame>
#include "Imports.h"
#include "QBeaEngine.h"
class CachedFontMetrics;
class DisassemblyPopup : public QFrame
{
Q_OBJECT
public:
explicit DisassemblyPopup(QWidget* parent);
void paintEvent(QPaintEvent* event);
void setAddress(duint Address);
duint getAddress();
public slots:
void hide();
void updateFont();
void updateColors();
void tokenizerConfigUpdated();
protected:
CachedFontMetrics* mFontMetrics;
duint addr;
QString addrText;
QString addrComment;
bool addrCommentAuto;
int charWidth;
int charHeight;
int mWidth;
unsigned int mMaxInstructions;
QColor disassemblyBackgroundColor;
QColor disassemblyTracedColor;
QColor labelColor;
QColor labelBackgroundColor;
QColor commentColor;
QColor commentBackgroundColor;
QColor commentAutoColor;
QColor commentAutoBackgroundColor;
QBeaEngine mDisasm;
std::vector<std::pair<RichTextPainter::List, bool>> mDisassemblyToken;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/EditBreakpointDialog.cpp | #include "EditBreakpointDialog.h"
#include "ui_EditBreakpointDialog.h"
#include "StringUtil.h"
#include "MiscUtil.h"
#include "Configuration.h"
EditBreakpointDialog::EditBreakpointDialog(QWidget* parent, const BRIDGEBP & bp)
: QDialog(parent),
ui(new Ui::EditBreakpointDialog),
mBp(bp)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
switch(bp.type)
{
case bp_dll:
setWindowTitle(tr("Edit DLL Breakpoint %1").arg(QString(bp.mod)));
break;
case bp_normal:
setWindowTitle(tr("Edit Breakpoint %1").arg(getSymbolicName(bp.addr)));
break;
case bp_hardware:
setWindowTitle(tr("Edit Hardware Breakpoint %1").arg(getSymbolicName(bp.addr)));
break;
case bp_memory:
setWindowTitle(tr("Edit Memory Breakpoint %1").arg(getSymbolicName(bp.addr)));
break;
case bp_exception:
setWindowTitle(tr("Edit Exception Breakpoint %1").arg(getSymbolicName(bp.addr)));
break;
default:
setWindowTitle(tr("Edit Breakpoint %1").arg(getSymbolicName(bp.addr)));
break;
}
setWindowIcon(DIcon("breakpoint"));
loadFromBp();
Config()->loadWindowGeometry(this);
}
EditBreakpointDialog::~EditBreakpointDialog()
{
Config()->saveWindowGeometry(this);
delete ui;
}
void EditBreakpointDialog::loadFromBp()
{
ui->editName->setText(mBp.name);
ui->spinHitCount->setValue(mBp.hitCount);
ui->editBreakCondition->setText(mBp.breakCondition);
ui->checkBoxFastResume->setChecked(mBp.fastResume);
ui->checkBoxSilent->setChecked(mBp.silent);
ui->checkBoxSingleshoot->setChecked(mBp.singleshoot);
ui->editLogText->setText(mBp.logText);
ui->editLogCondition->setText(mBp.logCondition);
ui->editCommandText->setText(mBp.commandText);
ui->editCommandCondition->setText(mBp.commandCondition);
}
template<typename T>
void copyTruncate(T & dest, QString src)
{
src.replace(QChar('\\'), QString("\\\\"));
src.replace(QChar('"'), QString("\\\""));
strncpy_s(dest, src.toUtf8().constData(), _TRUNCATE);
}
void EditBreakpointDialog::on_editName_textEdited(const QString & arg1)
{
copyTruncate(mBp.name, arg1);
}
void EditBreakpointDialog::on_editBreakCondition_textEdited(const QString & arg1)
{
copyTruncate(mBp.breakCondition, arg1);
}
void EditBreakpointDialog::on_editLogText_textEdited(const QString & arg1)
{
ui->checkBoxSilent->setChecked(true);
copyTruncate(mBp.logText, arg1);
}
void EditBreakpointDialog::on_editLogCondition_textEdited(const QString & arg1)
{
copyTruncate(mBp.logCondition, arg1);
}
void EditBreakpointDialog::on_editCommandText_textEdited(const QString & arg1)
{
copyTruncate(mBp.commandText, arg1);
}
void EditBreakpointDialog::on_editCommandCondition_textEdited(const QString & arg1)
{
copyTruncate(mBp.commandCondition, arg1);
}
void EditBreakpointDialog::on_checkBoxFastResume_toggled(bool checked)
{
mBp.fastResume = checked;
}
void EditBreakpointDialog::on_spinHitCount_valueChanged(int arg1)
{
mBp.hitCount = arg1;
}
void EditBreakpointDialog::on_checkBoxSilent_toggled(bool checked)
{
mBp.silent = checked;
}
void EditBreakpointDialog::on_checkBoxSingleshoot_toggled(bool checked)
{
mBp.singleshoot = checked;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/EditBreakpointDialog.h | #pragma once
#include <QDialog>
#include "Bridge.h"
namespace Ui
{
class EditBreakpointDialog;
}
class EditBreakpointDialog : public QDialog
{
Q_OBJECT
public:
explicit EditBreakpointDialog(QWidget* parent, const BRIDGEBP & bp);
~EditBreakpointDialog();
const BRIDGEBP & getBp()
{
return mBp;
}
private slots:
void on_editName_textEdited(const QString & arg1);
void on_editBreakCondition_textEdited(const QString & arg1);
void on_editLogText_textEdited(const QString & arg1);
void on_editLogCondition_textEdited(const QString & arg1);
void on_editCommandText_textEdited(const QString & arg1);
void on_editCommandCondition_textEdited(const QString & arg1);
void on_checkBoxFastResume_toggled(bool checked);
void on_spinHitCount_valueChanged(int arg1);
void on_checkBoxSilent_toggled(bool checked);
void on_checkBoxSingleshoot_toggled(bool checked);
private:
Ui::EditBreakpointDialog* ui;
BRIDGEBP mBp;
void loadFromBp();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/EditBreakpointDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>EditBreakpointDialog</class>
<widget class="QDialog" name="EditBreakpointDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>506</width>
<height>221</height>
</rect>
</property>
<property name="windowTitle">
<string>Edit breakpoint</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>6</number>
</property>
<property name="leftMargin">
<number>6</number>
</property>
<property name="topMargin">
<number>6</number>
</property>
<property name="rightMargin">
<number>6</number>
</property>
<property name="bottomMargin">
<number>6</number>
</property>
<item>
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="horizontalSpacing">
<number>6</number>
</property>
<item row="1" column="0">
<widget class="QLabel" name="labelLogText">
<property name="toolTip">
<string><html><head/><body><p>This text will be logged whenever the log condition is true.</p><p>String formatting can be used to print variables.</p></body></html></string>
</property>
<property name="text">
<string>&Log Text:</string>
</property>
<property name="buddy">
<cstring>editLogText</cstring>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="labelBreakCondition">
<property name="toolTip">
<string><html><head/><body><p>If this expression is evaluated to 1 the breakpoint will break.</p><p>Set to <span style=" text-decoration: underline;">0</span> for a breakpoint that never breaks, but can still do logging and execute command.</p></body></html></string>
</property>
<property name="text">
<string>&Break Condition:</string>
</property>
<property name="buddy">
<cstring>editBreakCondition</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="editBreakCondition">
<property name="maxLength">
<number>255</number>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="editLogText">
<property name="maxLength">
<number>255</number>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLineEdit" name="editName">
<property name="maxLength">
<number>255</number>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="editLogCondition">
<property name="maxLength">
<number>255</number>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelLogCondition">
<property name="toolTip">
<string><html><head/><body><p>String logging is enabled whenever this expression is evaluated to 1.</p></body></html></string>
</property>
<property name="text">
<string>Lo&g Condition:</string>
</property>
<property name="buddy">
<cstring>editLogCondition</cstring>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="labelName">
<property name="text">
<string>&Name:</string>
</property>
<property name="buddy">
<cstring>editName</cstring>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="labelCommandText">
<property name="toolTip">
<string><html><head/><body><p>This command will be executed whenever command condition is true.</p><p>Currently certain commands, for example, stepping from breakpoint command are not supported.</p></body></html></string>
</property>
<property name="text">
<string>&Command Text:</string>
</property>
<property name="buddy">
<cstring>editCommandText</cstring>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLineEdit" name="editCommandText">
<property name="maxLength">
<number>255</number>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QSpinBox" name="spinHitCount">
<property name="minimum">
<number>0</number>
</property>
<property name="maximum">
<number>2000000000</number>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="labelHitCount">
<property name="toolTip">
<string><html><head/><body><p>The number of times the breakpoint is hit.</p></body></html></string>
</property>
<property name="text">
<string>&Hit Count:</string>
</property>
<property name="buddy">
<cstring>spinHitCount</cstring>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="labelCommandCondition">
<property name="toolTip">
<string><html><head/><body><p>If this expression is evaluated to 1 the command specified above is executed when the breakpoint is hit.</p><p>Set the expression to <span style=" text-decoration: underline;">1</span> to always execute the command.</p></body></html></string>
</property>
<property name="text">
<string>C&ommand Condition:</string>
</property>
<property name="buddy">
<cstring>editCommandCondition</cstring>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLineEdit" name="editCommandCondition">
<property name="maxLength">
<number>255</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layoutSaveCancel">
<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="checkBoxSingleshoot">
<property name="toolTip">
<string><html><head/><body><p>Remove the breakpoint once it pauses the debuggee.</p></body></html></string>
</property>
<property name="text">
<string>Singlesho&ot</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxSilent">
<property name="toolTip">
<string><html><head/><body><p>Don't print the default breakpoint log.</p></body></html></string>
</property>
<property name="text">
<string>&Silent</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxFastResume">
<property name="toolTip">
<string><html><head/><body><p>Don't enable extended conditional breakpoint features and plugins.</p></body></html></string>
</property>
<property name="text">
<string>&Fast Resume</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonSave">
<property name="text">
<string>&Save</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonCancel">
<property name="text">
<string>C&ancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>editBreakCondition</tabstop>
<tabstop>editLogText</tabstop>
<tabstop>editLogCondition</tabstop>
<tabstop>editCommandText</tabstop>
<tabstop>editCommandCondition</tabstop>
<tabstop>editName</tabstop>
<tabstop>spinHitCount</tabstop>
<tabstop>checkBoxSingleshoot</tabstop>
<tabstop>checkBoxSilent</tabstop>
<tabstop>checkBoxFastResume</tabstop>
<tabstop>buttonSave</tabstop>
<tabstop>buttonCancel</tabstop>
</tabstops>
<resources/>
<connections>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>EditBreakpointDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>397</x>
<y>442</y>
</hint>
<hint type="destinationlabel">
<x>462</x>
<y>441</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonSave</sender>
<signal>clicked()</signal>
<receiver>EditBreakpointDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>279</x>
<y>435</y>
</hint>
<hint type="destinationlabel">
<x>321</x>
<y>442</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/EditFloatRegister.cpp | #include "EditFloatRegister.h"
#include "ui_EditFloatRegister.h"
#include "Bridge.h"
#include "StringUtil.h"
#include "MiscUtil.h"
#include "Configuration.h"
/**
* @brief Initialize EditFloatRegister dialog
*
* @param[in] RegisterSize The register size. 128 stands for XMM register, 256 stands for YMM register,
* 512 stands for ZMM register.
*
* @param[in] parent The parent of this dialog.
*
* @return Nothing.
*/
EditFloatRegister::EditFloatRegister(int RegisterSize, QWidget* parent) :
QDialog(parent), hexValidate(this), RegSize(RegisterSize),
signedShortValidator(LongLongValidator::DataType::SignedShort, this),
unsignedShortValidator(LongLongValidator::DataType::UnsignedShort, this),
signedLongValidator(LongLongValidator::DataType::SignedLong, this),
unsignedLongValidator(LongLongValidator::DataType::UnsignedLong, this),
signedLongLongValidator(LongLongValidator::DataType::SignedLongLong, this),
unsignedLongLongValidator(LongLongValidator::DataType::UnsignedLongLong, this),
doubleValidator(this),
ui(new Ui::EditFloatRegister)
{
memset(Data, 0, sizeof(Data));
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
switch(RegisterSize)
{
case 128:
hideUpperPart();
ui->labelLowRegister->setText(QString("XMM:"));
break;
case 64:
hideUpperPart();
hideNonMMXPart();
ui->hexEdit_2->setMaxLength(16);
ui->labelLowRegister->setText(QString("MM:"));
break;
case 256:
break;
case 512:
default:
GuiAddLogMessage(tr("Error, register size %1 is not supported.\n").arg(RegisterSize).toUtf8().constData());
break;
}
setFixedWidth(width());
adjustSize();
connect(ui->hexEdit, SIGNAL(textEdited(QString)), this, SLOT(editingHex1FinishedSlot(QString)));
ui->hexEdit->setValidator(&hexValidate);
connect(ui->hexEdit_2, SIGNAL(textEdited(QString)), this, SLOT(editingHex2FinishedSlot(QString)));
ui->hexEdit_2->setValidator(&hexValidate);
QRadioButton* checkedRadio;
switch(ConfigUint("Gui", "EditFloatRegisterDefaultMode"))
{
case 0:
default:
checkedRadio = ui->radioHex;
break;
case 1:
checkedRadio = ui->radioSigned;
break;
case 2:
checkedRadio = ui->radioUnsigned;
break;
}
checkedRadio->setChecked(true);
editingModeChangedSlot(false);
connect(ui->radioHex, SIGNAL(toggled(bool)), this, SLOT(editingModeChangedSlot(bool)));
connect(ui->radioSigned, SIGNAL(toggled(bool)), this, SLOT(editingModeChangedSlot(bool)));
connect(ui->radioUnsigned, SIGNAL(toggled(bool)), this, SLOT(editingModeChangedSlot(bool)));
connect(ui->shortEdit0_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort0FinishedSlot(QString)));
connect(ui->shortEdit1_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort1FinishedSlot(QString)));
connect(ui->shortEdit2_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort2FinishedSlot(QString)));
connect(ui->shortEdit3_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort3FinishedSlot(QString)));
if(RegisterSize > 64)
{
connect(ui->shortEdit4_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort4FinishedSlot(QString)));
connect(ui->shortEdit5_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort5FinishedSlot(QString)));
connect(ui->shortEdit6_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort6FinishedSlot(QString)));
connect(ui->shortEdit7_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerShort7FinishedSlot(QString)));
if(RegisterSize > 128)
{
connect(ui->shortEdit0, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort0FinishedSlot(QString)));
connect(ui->shortEdit1, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort1FinishedSlot(QString)));
connect(ui->shortEdit2, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort2FinishedSlot(QString)));
connect(ui->shortEdit3, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort3FinishedSlot(QString)));
connect(ui->shortEdit4, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort4FinishedSlot(QString)));
connect(ui->shortEdit5, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort5FinishedSlot(QString)));
connect(ui->shortEdit6, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort6FinishedSlot(QString)));
connect(ui->shortEdit7, SIGNAL(textEdited(QString)), this, SLOT(editingUpperShort7FinishedSlot(QString)));
}
}
connect(ui->longEdit0_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerLong0FinishedSlot(QString)));
connect(ui->longEdit1_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerLong1FinishedSlot(QString)));
if(RegisterSize > 64)
{
connect(ui->longEdit2_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerLong2FinishedSlot(QString)));
connect(ui->longEdit3_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerLong3FinishedSlot(QString)));
if(RegisterSize > 128)
{
connect(ui->longEdit0, SIGNAL(textEdited(QString)), this, SLOT(editingUpperLong0FinishedSlot(QString)));
connect(ui->longEdit1, SIGNAL(textEdited(QString)), this, SLOT(editingUpperLong1FinishedSlot(QString)));
connect(ui->longEdit2, SIGNAL(textEdited(QString)), this, SLOT(editingUpperLong2FinishedSlot(QString)));
connect(ui->longEdit3, SIGNAL(textEdited(QString)), this, SLOT(editingUpperLong3FinishedSlot(QString)));
}
}
connect(ui->floatEdit0_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerFloat0FinishedSlot(QString)));
connect(ui->floatEdit1_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerFloat1FinishedSlot(QString)));
if(RegisterSize > 64)
{
connect(ui->floatEdit2_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerFloat2FinishedSlot(QString)));
connect(ui->floatEdit3_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerFloat3FinishedSlot(QString)));
if(RegisterSize > 128)
{
connect(ui->floatEdit0, SIGNAL(textEdited(QString)), this, SLOT(editingUpperFloat0FinishedSlot(QString)));
connect(ui->floatEdit1, SIGNAL(textEdited(QString)), this, SLOT(editingUpperFloat1FinishedSlot(QString)));
connect(ui->floatEdit2, SIGNAL(textEdited(QString)), this, SLOT(editingUpperFloat2FinishedSlot(QString)));
connect(ui->floatEdit3, SIGNAL(textEdited(QString)), this, SLOT(editingUpperFloat3FinishedSlot(QString)));
}
}
if(RegisterSize > 64)
{
connect(ui->doubleEdit0_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerDouble0FinishedSlot(QString)));
connect(ui->doubleEdit1_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerDouble1FinishedSlot(QString)));
if(RegisterSize > 128)
{
connect(ui->doubleEdit0, SIGNAL(textEdited(QString)), this, SLOT(editingUpperDouble0FinishedSlot(QString)));
connect(ui->doubleEdit1, SIGNAL(textEdited(QString)), this, SLOT(editingUpperDouble1FinishedSlot(QString)));
}
connect(ui->longLongEdit0_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerLongLong0FinishedSlot(QString)));
connect(ui->longLongEdit1_2, SIGNAL(textEdited(QString)), this, SLOT(editingLowerLongLong1FinishedSlot(QString)));
if(RegisterSize > 128)
{
connect(ui->longLongEdit0, SIGNAL(textEdited(QString)), this, SLOT(editingUpperLongLong0FinishedSlot(QString)));
connect(ui->longLongEdit1, SIGNAL(textEdited(QString)), this, SLOT(editingUpperLongLong1FinishedSlot(QString)));
}
}
ui->floatEdit0_2->setValidator(&doubleValidator);
ui->floatEdit1_2->setValidator(&doubleValidator);
if(RegisterSize > 64)
{
ui->floatEdit2_2->setValidator(&doubleValidator);
ui->floatEdit3_2->setValidator(&doubleValidator);
if(RegisterSize > 128)
{
ui->floatEdit0->setValidator(&doubleValidator);
ui->floatEdit1->setValidator(&doubleValidator);
ui->floatEdit2->setValidator(&doubleValidator);
ui->floatEdit3->setValidator(&doubleValidator);
}
}
if(RegisterSize > 64)
{
ui->doubleEdit0_2->setValidator(&doubleValidator);
ui->doubleEdit1_2->setValidator(&doubleValidator);
if(RegisterSize > 128)
{
ui->doubleEdit0->setValidator(&doubleValidator);
ui->doubleEdit1->setValidator(&doubleValidator);
}
}
}
void EditFloatRegister::hideUpperPart()
{
QWidget* useless_controls[] = {ui->line,
ui->labelH0,
ui->labelH1,
ui->labelH2,
ui->labelH3,
ui->labelH4,
ui->labelH5,
ui->labelH6,
ui->labelH7,
ui->labelH8,
ui->labelH9,
ui->labelHA,
ui->labelHB,
ui->labelHC,
ui->labelHD,
ui->labelHE,
ui->hexEdit,
ui->shortEdit0,
ui->shortEdit1,
ui->shortEdit2,
ui->shortEdit3,
ui->shortEdit4,
ui->shortEdit5,
ui->shortEdit6,
ui->shortEdit7,
ui->longEdit0,
ui->longEdit1,
ui->longEdit2,
ui->longEdit3,
ui->floatEdit0,
ui->floatEdit1,
ui->floatEdit2,
ui->floatEdit3,
ui->doubleEdit0,
ui->doubleEdit1,
ui->longLongEdit0,
ui->longLongEdit1
};
for(auto all : useless_controls)
all->hide();
}
void EditFloatRegister::hideNonMMXPart()
{
QWidget* useless_controls[] = {ui->labelL4,
ui->labelL5,
ui->labelL6,
ui->labelL7,
ui->labelLC,
ui->labelLD,
ui->doubleEdit0_2,
ui->doubleEdit1_2,
ui->longLongEdit0_2,
ui->longLongEdit1_2,
ui->shortEdit4_2,
ui->shortEdit5_2,
ui->shortEdit6_2,
ui->shortEdit7_2,
ui->longEdit2_2,
ui->longEdit3_2,
ui->floatEdit2_2,
ui->floatEdit3_2
};
for(auto all : useless_controls)
all->hide();
}
/**
* @brief Load register data into the dialog
* @param[in] RegisterData the data to be loaded. It must be at lease the same size as the size specified in RegisterSize
* @return Nothing.
*/
void EditFloatRegister::loadData(const char* RegisterData)
{
memcpy(Data, RegisterData, RegSize / 8);
reloadDataLow();
reloadDataHigh();
}
/**
* @brief Get the register data from the dialog
* @return The output buffer.
*/
const char* EditFloatRegister::getData() const
{
return Data;
}
void EditFloatRegister::selectAllText()
{
ui->hexEdit_2->setFocus();
ui->hexEdit_2->selectAll();
}
/**
* @brief reloads the lower 128-bit of data of the dialog
*/
void EditFloatRegister::reloadDataLow()
{
if(mutex == nullptr)
mutex = this;
int maxBytes;
if(RegSize >= 128)
maxBytes = 16;
else
maxBytes = RegSize / 8;
if(mutex != ui->hexEdit_2)
{
if(ConfigBool("Gui", "FpuRegistersLittleEndian"))
ui->hexEdit_2->setText(QString(QByteArray(Data, maxBytes).toHex()).toUpper());
else
ui->hexEdit_2->setText(QString(ByteReverse(QByteArray(Data, maxBytes)).toHex()).toUpper());
}
reloadLongData(*ui->longEdit0_2, Data);
reloadLongData(*ui->longEdit1_2, Data + 4);
if(RegSize > 64)
{
reloadLongData(*ui->longEdit2_2, Data + 8);
reloadLongData(*ui->longEdit3_2, Data + 12);
}
reloadShortData(*ui->shortEdit0_2, Data);
reloadShortData(*ui->shortEdit1_2, Data + 2);
reloadShortData(*ui->shortEdit2_2, Data + 4);
reloadShortData(*ui->shortEdit3_2, Data + 6);
if(RegSize > 64)
{
reloadShortData(*ui->shortEdit4_2, Data + 8);
reloadShortData(*ui->shortEdit5_2, Data + 10);
reloadShortData(*ui->shortEdit6_2, Data + 12);
reloadShortData(*ui->shortEdit7_2, Data + 14);
}
reloadFloatData(*ui->floatEdit0_2, Data);
reloadFloatData(*ui->floatEdit1_2, Data + 4);
if(RegSize > 64)
{
reloadFloatData(*ui->floatEdit2_2, Data + 8);
reloadFloatData(*ui->floatEdit3_2, Data + 12);
reloadDoubleData(*ui->doubleEdit0_2, Data);
reloadDoubleData(*ui->doubleEdit1_2, Data + 8);
reloadLongLongData(*ui->longLongEdit0_2, Data);
reloadLongLongData(*ui->longLongEdit1_2, Data + 8);
}
mutex = nullptr;
}
/**
* @brief reloads the upper 128-bit of data of the dialog
*/
void EditFloatRegister::reloadDataHigh()
{
if(mutex == nullptr)
mutex = this;
if(mutex != ui->hexEdit)
{
if(ConfigBool("Gui", "FpuRegistersLittleEndian"))
ui->hexEdit->setText(QString(QByteArray(Data + 16, 16).toHex()).toUpper());
else
ui->hexEdit->setText(QString(ByteReverse(QByteArray(Data + 16, 16)).toHex()).toUpper());
}
reloadLongData(*ui->longEdit0, Data + 16);
reloadLongData(*ui->longEdit1, Data + 20);
reloadLongData(*ui->longEdit2, Data + 24);
reloadLongData(*ui->longEdit3, Data + 28);
reloadShortData(*ui->shortEdit0, Data + 16);
reloadShortData(*ui->shortEdit1, Data + 18);
reloadShortData(*ui->shortEdit2, Data + 20);
reloadShortData(*ui->shortEdit3, Data + 22);
reloadShortData(*ui->shortEdit4, Data + 24);
reloadShortData(*ui->shortEdit5, Data + 26);
reloadShortData(*ui->shortEdit6, Data + 28);
reloadShortData(*ui->shortEdit7, Data + 30);
reloadFloatData(*ui->floatEdit0, Data + 16);
reloadFloatData(*ui->floatEdit1, Data + 20);
reloadFloatData(*ui->floatEdit2, Data + 24);
reloadFloatData(*ui->floatEdit3, Data + 28);
reloadDoubleData(*ui->doubleEdit0, Data + 16);
reloadDoubleData(*ui->doubleEdit1, Data + 24);
reloadLongLongData(*ui->longLongEdit0, Data + 16);
reloadLongLongData(*ui->longLongEdit1, Data + 24);
mutex = nullptr;
}
void EditFloatRegister::reloadShortData(QLineEdit & txtbox, char* Data)
{
if(mutex != &txtbox)
{
if(ui->radioHex->isChecked())
txtbox.setText(QString().number((int) * (unsigned short*)Data, 16).toUpper());
else if(ui->radioSigned->isChecked())
txtbox.setText(QString().number((int) * (short*)Data));
else
txtbox.setText(QString().number((unsigned int) * (unsigned short*)Data));
}
}
void EditFloatRegister::reloadLongData(QLineEdit & txtbox, char* Data)
{
if(mutex != &txtbox)
{
if(ui->radioHex->isChecked())
txtbox.setText(QString().number(*(unsigned int*)Data, 16).toUpper());
else if(ui->radioSigned->isChecked())
txtbox.setText(QString().number(*(int*)Data));
else
txtbox.setText(QString().number(*(unsigned int*)Data));
}
}
void EditFloatRegister::reloadFloatData(QLineEdit & txtbox, char* Data)
{
if(mutex != &txtbox)
{
txtbox.setText(ToFloatString(Data));
}
}
void EditFloatRegister::reloadDoubleData(QLineEdit & txtbox, char* Data)
{
if(mutex != &txtbox)
{
txtbox.setText(ToDoubleString(Data));
}
}
void EditFloatRegister::reloadLongLongData(QLineEdit & txtbox, char* Data)
{
if(mutex != &txtbox)
{
if(ui->radioHex->isChecked())
txtbox.setText(QString().number(*(unsigned long long*)Data, 16).toUpper());
else if(ui->radioSigned->isChecked())
txtbox.setText(QString().number(*(long long*)Data));
else
txtbox.setText(QString().number(*(unsigned long long*)Data));
}
}
void EditFloatRegister::editingModeChangedSlot(bool arg)
{
Q_UNUSED(arg);
if(ui->radioHex->isChecked())
{
ui->shortEdit0_2->setMaxLength(4);
ui->shortEdit1_2->setMaxLength(4);
ui->shortEdit2_2->setMaxLength(4);
ui->shortEdit3_2->setMaxLength(4);
if(RegSize > 64)
{
ui->shortEdit4_2->setMaxLength(4);
ui->shortEdit5_2->setMaxLength(4);
ui->shortEdit6_2->setMaxLength(4);
ui->shortEdit7_2->setMaxLength(4);
if(RegSize > 128)
{
ui->shortEdit0->setMaxLength(4);
ui->shortEdit1->setMaxLength(4);
ui->shortEdit2->setMaxLength(4);
ui->shortEdit3->setMaxLength(4);
ui->shortEdit4->setMaxLength(4);
ui->shortEdit5->setMaxLength(4);
ui->shortEdit6->setMaxLength(4);
ui->shortEdit7->setMaxLength(4);
}
}
ui->longEdit0_2->setMaxLength(8);
ui->longEdit1_2->setMaxLength(8);
if(RegSize > 64)
{
ui->longEdit2_2->setMaxLength(8);
ui->longEdit3_2->setMaxLength(8);
if(RegSize > 128)
{
ui->longEdit0->setMaxLength(8);
ui->longEdit1->setMaxLength(8);
ui->longEdit2->setMaxLength(8);
ui->longEdit3->setMaxLength(8);
ui->longLongEdit0->setMaxLength(16);
ui->longLongEdit1->setMaxLength(16);
}
ui->longLongEdit0_2->setMaxLength(16);
ui->longLongEdit1_2->setMaxLength(16);
}
ui->shortEdit0_2->setValidator(&hexValidate);
ui->shortEdit1_2->setValidator(&hexValidate);
ui->shortEdit2_2->setValidator(&hexValidate);
ui->shortEdit3_2->setValidator(&hexValidate);
if(RegSize > 64)
{
ui->shortEdit4_2->setValidator(&hexValidate);
ui->shortEdit5_2->setValidator(&hexValidate);
ui->shortEdit6_2->setValidator(&hexValidate);
ui->shortEdit7_2->setValidator(&hexValidate);
if(RegSize > 128)
{
ui->shortEdit0->setValidator(&hexValidate);
ui->shortEdit1->setValidator(&hexValidate);
ui->shortEdit2->setValidator(&hexValidate);
ui->shortEdit3->setValidator(&hexValidate);
ui->shortEdit4->setValidator(&hexValidate);
ui->shortEdit5->setValidator(&hexValidate);
ui->shortEdit6->setValidator(&hexValidate);
ui->shortEdit7->setValidator(&hexValidate);
}
}
ui->longEdit0_2->setValidator(&hexValidate);
ui->longEdit1_2->setValidator(&hexValidate);
if(RegSize > 64)
{
ui->longEdit2_2->setValidator(&hexValidate);
ui->longEdit3_2->setValidator(&hexValidate);
if(RegSize > 128)
{
ui->longEdit0->setValidator(&hexValidate);
ui->longEdit1->setValidator(&hexValidate);
ui->longEdit2->setValidator(&hexValidate);
ui->longEdit3->setValidator(&hexValidate);
ui->longLongEdit0->setValidator(&hexValidate);
ui->longLongEdit1->setValidator(&hexValidate);
}
ui->longLongEdit0_2->setValidator(&hexValidate);
ui->longLongEdit1_2->setValidator(&hexValidate);
}
Config()->setUint("Gui", "EditFloatRegisterDefaultMode", 0);
}
else if(ui->radioSigned->isChecked())
{
ui->shortEdit0_2->setMaxLength(6);
ui->shortEdit1_2->setMaxLength(6);
ui->shortEdit2_2->setMaxLength(6);
ui->shortEdit3_2->setMaxLength(6);
ui->shortEdit4_2->setMaxLength(6);
ui->shortEdit5_2->setMaxLength(6);
ui->shortEdit6_2->setMaxLength(6);
ui->shortEdit7_2->setMaxLength(6);
ui->shortEdit0->setMaxLength(6);
ui->shortEdit1->setMaxLength(6);
ui->shortEdit2->setMaxLength(6);
ui->shortEdit3->setMaxLength(6);
ui->shortEdit4->setMaxLength(6);
ui->shortEdit5->setMaxLength(6);
ui->shortEdit6->setMaxLength(6);
ui->shortEdit7->setMaxLength(6);
ui->longEdit0_2->setMaxLength(12);
ui->longEdit1_2->setMaxLength(12);
ui->longEdit2_2->setMaxLength(12);
ui->longEdit3_2->setMaxLength(12);
ui->longEdit0->setMaxLength(12);
ui->longEdit1->setMaxLength(12);
ui->longEdit2->setMaxLength(12);
ui->longEdit3->setMaxLength(12);
ui->longLongEdit0->setMaxLength(64);
ui->longLongEdit1->setMaxLength(64);
ui->longLongEdit0_2->setMaxLength(64);
ui->longLongEdit1_2->setMaxLength(64);
ui->shortEdit0_2->setValidator(&signedShortValidator);
ui->shortEdit1_2->setValidator(&signedShortValidator);
ui->shortEdit2_2->setValidator(&signedShortValidator);
ui->shortEdit3_2->setValidator(&signedShortValidator);
ui->shortEdit4_2->setValidator(&signedShortValidator);
ui->shortEdit5_2->setValidator(&signedShortValidator);
ui->shortEdit6_2->setValidator(&signedShortValidator);
ui->shortEdit7_2->setValidator(&signedShortValidator);
ui->shortEdit0->setValidator(&signedShortValidator);
ui->shortEdit1->setValidator(&signedShortValidator);
ui->shortEdit2->setValidator(&signedShortValidator);
ui->shortEdit3->setValidator(&signedShortValidator);
ui->shortEdit4->setValidator(&signedShortValidator);
ui->shortEdit5->setValidator(&signedShortValidator);
ui->shortEdit6->setValidator(&signedShortValidator);
ui->shortEdit7->setValidator(&signedShortValidator);
ui->longEdit0_2->setValidator(&signedLongValidator);
ui->longEdit1_2->setValidator(&signedLongValidator);
ui->longEdit2_2->setValidator(&signedLongValidator);
ui->longEdit3_2->setValidator(&signedLongValidator);
ui->longEdit0->setValidator(&signedLongValidator);
ui->longEdit1->setValidator(&signedLongValidator);
ui->longEdit2->setValidator(&signedLongValidator);
ui->longEdit3->setValidator(&signedLongValidator);
ui->longLongEdit0->setValidator(&signedLongLongValidator);
ui->longLongEdit1->setValidator(&signedLongLongValidator);
ui->longLongEdit0_2->setValidator(&signedLongLongValidator);
ui->longLongEdit1_2->setValidator(&signedLongLongValidator);
Config()->setUint("Gui", "EditFloatRegisterDefaultMode", 1);
}
else
{
ui->shortEdit0_2->setMaxLength(6);
ui->shortEdit1_2->setMaxLength(6);
ui->shortEdit2_2->setMaxLength(6);
ui->shortEdit3_2->setMaxLength(6);
ui->shortEdit4_2->setMaxLength(6);
ui->shortEdit5_2->setMaxLength(6);
ui->shortEdit6_2->setMaxLength(6);
ui->shortEdit7_2->setMaxLength(6);
ui->shortEdit0->setMaxLength(6);
ui->shortEdit1->setMaxLength(6);
ui->shortEdit2->setMaxLength(6);
ui->shortEdit3->setMaxLength(6);
ui->shortEdit4->setMaxLength(6);
ui->shortEdit5->setMaxLength(6);
ui->shortEdit6->setMaxLength(6);
ui->shortEdit7->setMaxLength(6);
ui->longEdit0_2->setMaxLength(12);
ui->longEdit1_2->setMaxLength(12);
ui->longEdit2_2->setMaxLength(12);
ui->longEdit3_2->setMaxLength(12);
ui->longEdit0->setMaxLength(12);
ui->longEdit1->setMaxLength(12);
ui->longEdit2->setMaxLength(12);
ui->longEdit3->setMaxLength(12);
ui->shortEdit0_2->setValidator(&unsignedShortValidator);
ui->shortEdit1_2->setValidator(&unsignedShortValidator);
ui->shortEdit2_2->setValidator(&unsignedShortValidator);
ui->shortEdit3_2->setValidator(&unsignedShortValidator);
ui->shortEdit4_2->setValidator(&unsignedShortValidator);
ui->shortEdit5_2->setValidator(&unsignedShortValidator);
ui->shortEdit6_2->setValidator(&unsignedShortValidator);
ui->shortEdit7_2->setValidator(&unsignedShortValidator);
ui->shortEdit0->setValidator(&unsignedShortValidator);
ui->shortEdit1->setValidator(&unsignedShortValidator);
ui->shortEdit2->setValidator(&unsignedShortValidator);
ui->shortEdit3->setValidator(&unsignedShortValidator);
ui->shortEdit4->setValidator(&unsignedShortValidator);
ui->shortEdit5->setValidator(&unsignedShortValidator);
ui->shortEdit6->setValidator(&unsignedShortValidator);
ui->shortEdit7->setValidator(&unsignedShortValidator);
ui->longEdit0_2->setValidator(&unsignedLongValidator);
ui->longEdit1_2->setValidator(&unsignedLongValidator);
ui->longEdit2_2->setValidator(&unsignedLongValidator);
ui->longEdit3_2->setValidator(&unsignedLongValidator);
ui->longEdit0->setValidator(&unsignedLongValidator);
ui->longEdit1->setValidator(&unsignedLongValidator);
ui->longEdit2->setValidator(&unsignedLongValidator);
ui->longEdit3->setValidator(&unsignedLongValidator);
ui->longLongEdit0->setValidator(&unsignedLongLongValidator);
ui->longLongEdit1->setValidator(&unsignedLongLongValidator);
ui->longLongEdit0_2->setValidator(&unsignedLongLongValidator);
ui->longLongEdit1_2->setValidator(&unsignedLongLongValidator);
Config()->setUint("Gui", "EditFloatRegisterDefaultMode", 2);
}
reloadDataLow();
if(RegSize > 128)
reloadDataHigh();
}
/**
* @brief Desturctor of EditFloatRegister
* @return nothing
*/
EditFloatRegister::~EditFloatRegister()
{
delete ui;
}
/**
* @brief The higher part of the YMM register (or XMM register) is modified
* @param arg the new text
*/
void EditFloatRegister::editingHex1FinishedSlot(QString arg)
{
mutex = sender();
QString filled(arg.toUpper());
if(ConfigBool("Gui", "FpuRegistersLittleEndian"))
{
filled.append(QString(32 - filled.length(), QChar('0')));
for(int i = 0; i < 16; i++)
Data[i + 16] = filled.mid(i * 2, 2).toInt(0, 16);
}
else
{
filled.prepend(QString(32 - filled.length(), QChar('0')));
for(int i = 0; i < 16; i++)
Data[i + 16] = filled.mid(30 - i * 2, 2).toInt(0, 16);
}
reloadDataHigh();
}
/**
* @brief The lower part of the YMM register (or XMM register) is modified
* @param arg the new text
*/
void EditFloatRegister::editingHex2FinishedSlot(QString arg)
{
mutex = sender();
QString filled(arg.toUpper());
int maxBytes;
if(RegSize >= 128)
maxBytes = 16;
else
maxBytes = RegSize / 8;
if(ConfigBool("Gui", "FpuRegistersLittleEndian"))
{
filled.append(QString(maxBytes * 2 - filled.length(), QChar('0')));
for(int i = 0; i < maxBytes; i++)
Data[i] = filled.mid(i * 2, 2).toInt(0, 16);
}
else
{
filled.prepend(QString(maxBytes * 2 - filled.length(), QChar('0')));
for(int i = 0; i < maxBytes; i++)
Data[i] = filled.mid((maxBytes - i - 1) * 2, 2).toInt(0, 16);
}
reloadDataLow();
}
void EditFloatRegister::editingShortFinishedSlot(size_t offset, QString arg)
{
mutex = sender();
if(ui->radioHex->isChecked())
*(unsigned short*)(Data + offset) = arg.toUShort(0, 16);
else if(ui->radioSigned->isChecked())
*(short*)(Data + offset) = arg.toShort();
else
*(unsigned short*)(Data + offset) = arg.toUShort();
offset < 16 ? reloadDataLow() : reloadDataHigh();
}
void EditFloatRegister::editingLongFinishedSlot(size_t offset, QString arg)
{
mutex = sender();
if(ui->radioHex->isChecked())
*(unsigned int*)(Data + offset) = arg.toUInt(0, 16);
else if(ui->radioSigned->isChecked())
*(int*)(Data + offset) = arg.toInt();
else
*(unsigned int*)(Data + offset) = arg.toUInt();
offset < 16 ? reloadDataLow() : reloadDataHigh();
}
void EditFloatRegister::editingFloatFinishedSlot(size_t offset, QString arg)
{
mutex = sender();
bool ok;
float data = arg.toFloat(&ok);
if(ok)
*(float*)(Data + offset) = data;
offset < 16 ? reloadDataLow() : reloadDataHigh();
}
void EditFloatRegister::editingDoubleFinishedSlot(size_t offset, QString arg)
{
mutex = sender();
bool ok;
double data = arg.toDouble(&ok);
if(ok)
*(double*)(Data + offset) = data;
offset < 16 ? reloadDataLow() : reloadDataHigh();
}
void EditFloatRegister::editingLongLongFinishedSlot(size_t offset, QString arg)
{
mutex = sender();
if(ui->radioHex->isChecked())
*(unsigned long long*)(Data + offset) = arg.toULongLong(0, 16);
else if(ui->radioSigned->isChecked())
*(long long*)(Data + offset) = arg.toLongLong();
else
*(unsigned long long*)(Data + offset) = arg.toULongLong();
offset < 16 ? reloadDataLow() : reloadDataHigh();
}
void EditFloatRegister::editingLowerShort0FinishedSlot(QString arg)
{
editingShortFinishedSlot(0 * 2, arg);
}
void EditFloatRegister::editingLowerShort1FinishedSlot(QString arg)
{
editingShortFinishedSlot(1 * 2, arg);
}
void EditFloatRegister::editingLowerShort2FinishedSlot(QString arg)
{
editingShortFinishedSlot(2 * 2, arg);
}
void EditFloatRegister::editingLowerShort3FinishedSlot(QString arg)
{
editingShortFinishedSlot(3 * 2, arg);
}
void EditFloatRegister::editingLowerShort4FinishedSlot(QString arg)
{
editingShortFinishedSlot(4 * 2, arg);
}
void EditFloatRegister::editingLowerShort5FinishedSlot(QString arg)
{
editingShortFinishedSlot(5 * 2, arg);
}
void EditFloatRegister::editingLowerShort6FinishedSlot(QString arg)
{
editingShortFinishedSlot(6 * 2, arg);
}
void EditFloatRegister::editingLowerShort7FinishedSlot(QString arg)
{
editingShortFinishedSlot(7 * 2, arg);
}
void EditFloatRegister::editingUpperShort0FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 0 * 2, arg);
}
void EditFloatRegister::editingUpperShort1FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 1 * 2, arg);
}
void EditFloatRegister::editingUpperShort2FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 2 * 2, arg);
}
void EditFloatRegister::editingUpperShort3FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 3 * 2, arg);
}
void EditFloatRegister::editingUpperShort4FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 4 * 2, arg);
}
void EditFloatRegister::editingUpperShort5FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 5 * 2, arg);
}
void EditFloatRegister::editingUpperShort6FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 6 * 2, arg);
}
void EditFloatRegister::editingUpperShort7FinishedSlot(QString arg)
{
editingShortFinishedSlot(16 + 7 * 2, arg);
}
void EditFloatRegister::editingLowerLong0FinishedSlot(QString arg)
{
editingLongFinishedSlot(0 * 4, arg);
}
void EditFloatRegister::editingLowerLong1FinishedSlot(QString arg)
{
editingLongFinishedSlot(1 * 4, arg);
}
void EditFloatRegister::editingLowerLong2FinishedSlot(QString arg)
{
editingLongFinishedSlot(2 * 4, arg);
}
void EditFloatRegister::editingLowerLong3FinishedSlot(QString arg)
{
editingLongFinishedSlot(3 * 4, arg);
}
void EditFloatRegister::editingUpperLong0FinishedSlot(QString arg)
{
editingLongFinishedSlot(16 + 0 * 4, arg);
}
void EditFloatRegister::editingUpperLong1FinishedSlot(QString arg)
{
editingLongFinishedSlot(16 + 1 * 4, arg);
}
void EditFloatRegister::editingUpperLong2FinishedSlot(QString arg)
{
editingLongFinishedSlot(16 + 2 * 4, arg);
}
void EditFloatRegister::editingUpperLong3FinishedSlot(QString arg)
{
editingLongFinishedSlot(16 + 3 * 4, arg);
}
void EditFloatRegister::editingLowerFloat0FinishedSlot(QString arg)
{
editingFloatFinishedSlot(0 * 4, arg);
}
void EditFloatRegister::editingLowerFloat1FinishedSlot(QString arg)
{
editingFloatFinishedSlot(1 * 4, arg);
}
void EditFloatRegister::editingLowerFloat2FinishedSlot(QString arg)
{
editingFloatFinishedSlot(2 * 4, arg);
}
void EditFloatRegister::editingLowerFloat3FinishedSlot(QString arg)
{
editingFloatFinishedSlot(3 * 4, arg);
}
void EditFloatRegister::editingUpperFloat0FinishedSlot(QString arg)
{
editingFloatFinishedSlot(16 + 0 * 4, arg);
}
void EditFloatRegister::editingUpperFloat1FinishedSlot(QString arg)
{
editingFloatFinishedSlot(16 + 1 * 4, arg);
}
void EditFloatRegister::editingUpperFloat2FinishedSlot(QString arg)
{
editingFloatFinishedSlot(16 + 2 * 4, arg);
}
void EditFloatRegister::editingUpperFloat3FinishedSlot(QString arg)
{
editingFloatFinishedSlot(16 + 3 * 4, arg);
}
void EditFloatRegister::editingLowerDouble0FinishedSlot(QString arg)
{
editingDoubleFinishedSlot(0 * 8, arg);
}
void EditFloatRegister::editingLowerDouble1FinishedSlot(QString arg)
{
editingDoubleFinishedSlot(1 * 8, arg);
}
void EditFloatRegister::editingUpperDouble0FinishedSlot(QString arg)
{
editingDoubleFinishedSlot(16 + 0 * 8, arg);
}
void EditFloatRegister::editingUpperDouble1FinishedSlot(QString arg)
{
editingDoubleFinishedSlot(16 + 1 * 8, arg);
}
void EditFloatRegister::editingLowerLongLong0FinishedSlot(QString arg)
{
editingLongLongFinishedSlot(0 * 8, arg);
}
void EditFloatRegister::editingLowerLongLong1FinishedSlot(QString arg)
{
editingLongLongFinishedSlot(1 * 8, arg);
}
void EditFloatRegister::editingUpperLongLong0FinishedSlot(QString arg)
{
editingLongLongFinishedSlot(16 + 0 * 8, arg);
}
void EditFloatRegister::editingUpperLongLong1FinishedSlot(QString arg)
{
editingLongLongFinishedSlot(16 + 1 * 8, arg);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/EditFloatRegister.h | #pragma once
#include <QDialog>
#include <QLineEdit>
#include "HexValidator.h"
#include "LongLongValidator.h"
#include <QDoubleValidator>
namespace Ui
{
class EditFloatRegister;
}
class EditFloatRegister : public QDialog
{
Q_OBJECT
public:
explicit EditFloatRegister(int RegisterSize, QWidget* parent = 0);
void loadData(const char* RegisterData);
const char* getData() const;
void selectAllText();
~EditFloatRegister();
private slots:
void editingModeChangedSlot(bool arg);
void editingHex1FinishedSlot(QString arg);
void editingHex2FinishedSlot(QString arg);
// the compiler does not allow us to use template as slot. So we are going to waste the screen space...
void editingLowerShort0FinishedSlot(QString arg);
void editingLowerShort1FinishedSlot(QString arg);
void editingLowerShort2FinishedSlot(QString arg);
void editingLowerShort3FinishedSlot(QString arg);
void editingLowerShort4FinishedSlot(QString arg);
void editingLowerShort5FinishedSlot(QString arg);
void editingLowerShort6FinishedSlot(QString arg);
void editingLowerShort7FinishedSlot(QString arg);
void editingUpperShort0FinishedSlot(QString arg);
void editingUpperShort1FinishedSlot(QString arg);
void editingUpperShort2FinishedSlot(QString arg);
void editingUpperShort3FinishedSlot(QString arg);
void editingUpperShort4FinishedSlot(QString arg);
void editingUpperShort5FinishedSlot(QString arg);
void editingUpperShort6FinishedSlot(QString arg);
void editingUpperShort7FinishedSlot(QString arg);
void editingLowerLong0FinishedSlot(QString arg);
void editingLowerLong1FinishedSlot(QString arg);
void editingLowerLong2FinishedSlot(QString arg);
void editingLowerLong3FinishedSlot(QString arg);
void editingUpperLong0FinishedSlot(QString arg);
void editingUpperLong1FinishedSlot(QString arg);
void editingUpperLong2FinishedSlot(QString arg);
void editingUpperLong3FinishedSlot(QString arg);
void editingLowerFloat0FinishedSlot(QString arg);
void editingLowerFloat1FinishedSlot(QString arg);
void editingLowerFloat2FinishedSlot(QString arg);
void editingLowerFloat3FinishedSlot(QString arg);
void editingUpperFloat0FinishedSlot(QString arg);
void editingUpperFloat1FinishedSlot(QString arg);
void editingUpperFloat2FinishedSlot(QString arg);
void editingUpperFloat3FinishedSlot(QString arg);
void editingLowerDouble0FinishedSlot(QString arg);
void editingLowerDouble1FinishedSlot(QString arg);
void editingUpperDouble0FinishedSlot(QString arg);
void editingUpperDouble1FinishedSlot(QString arg);
void editingLowerLongLong0FinishedSlot(QString arg);
void editingLowerLongLong1FinishedSlot(QString arg);
void editingUpperLongLong0FinishedSlot(QString arg);
void editingUpperLongLong1FinishedSlot(QString arg);
private:
HexValidator hexValidate;
LongLongValidator signedShortValidator;
LongLongValidator unsignedShortValidator;
LongLongValidator signedLongValidator;
LongLongValidator unsignedLongValidator;
LongLongValidator signedLongLongValidator;
LongLongValidator unsignedLongLongValidator;
QDoubleValidator doubleValidator;
void hideUpperPart();
void hideNonMMXPart();
void reloadDataLow();
void reloadDataHigh();
void reloadShortData(QLineEdit & txtbox, char* Data);
void reloadLongData(QLineEdit & txtbox, char* Data);
void reloadFloatData(QLineEdit & txtbox, char* Data);
void reloadDoubleData(QLineEdit & txtbox, char* Data);
void reloadLongLongData(QLineEdit & txtbox, char* Data);
void editingShortFinishedSlot(size_t offset, QString arg);
void editingLongFinishedSlot(size_t offset, QString arg);
void editingFloatFinishedSlot(size_t offset, QString arg);
void editingDoubleFinishedSlot(size_t offset, QString arg);
void editingLongLongFinishedSlot(size_t offset, QString arg);
Ui::EditFloatRegister* ui;
QObject* mutex = nullptr;
char Data[64];
int RegSize;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/EditFloatRegister.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>EditFloatRegister</class>
<widget class="QDialog" name="EditFloatRegister">
<property name="windowModality">
<enum>Qt::WindowModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>696</width>
<height>428</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<property name="windowIcon">
<iconset theme="modify" resource="../../resource.qrc">
<normaloff>:/Default/icons/modify.png</normaloff>:/Default/icons/modify.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>6</number>
</property>
<property name="topMargin">
<number>6</number>
</property>
<property name="rightMargin">
<number>6</number>
</property>
<property name="bottomMargin">
<number>6</number>
</property>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="5" column="0">
<widget class="QLabel" name="labelHD">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Double:</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelHA">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Word:</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="labelHC">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Float:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelH9">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Byte:</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="labelHE">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Qword:</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="labelHB">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Dword:</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="labelH8">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>High:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_9">
<item>
<widget class="QLineEdit" name="longLongEdit0"/>
</item>
<item>
<widget class="QLineEdit" name="longLongEdit1"/>
</item>
</layout>
</item>
<item row="5" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QLineEdit" name="doubleEdit0"/>
</item>
<item>
<widget class="QLineEdit" name="doubleEdit1"/>
</item>
</layout>
</item>
<item row="4" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QLineEdit" name="floatEdit0"/>
</item>
<item>
<widget class="QLineEdit" name="floatEdit1"/>
</item>
<item>
<widget class="QLineEdit" name="floatEdit2"/>
</item>
<item>
<widget class="QLineEdit" name="floatEdit3"/>
</item>
</layout>
</item>
<item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLineEdit" name="longEdit0"/>
</item>
<item>
<widget class="QLineEdit" name="longEdit1"/>
</item>
<item>
<widget class="QLineEdit" name="longEdit2"/>
</item>
<item>
<widget class="QLineEdit" name="longEdit3"/>
</item>
</layout>
</item>
<item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLineEdit" name="shortEdit0"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit1"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit3"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit4"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit5"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit6"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit7">
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="labelH0">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>10-11</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH1">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>12-13</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH2">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>14-15</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH4">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>16-17</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH6">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>18-19</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH5">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>1A-1B</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH7">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>1C-1D</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelH3">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>1E-1F</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="hexEdit">
<property name="inputMethodHints">
<set>Qt::ImhUppercaseOnly</set>
</property>
<property name="maxLength">
<number>32</number>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout_2">
<item row="4" column="0">
<widget class="QLabel" name="labelLB">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Float:</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="labelLowRegister">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Low:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelL8">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Byte:</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="labelLA">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Dword:</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="labelLC">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Double:</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelL9">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Word:</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="labelLD">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Qword:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_17">
<item>
<widget class="QLineEdit" name="longLongEdit0_2"/>
</item>
<item>
<widget class="QLineEdit" name="longLongEdit1_2"/>
</item>
</layout>
</item>
<item row="5" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_16">
<item>
<widget class="QLineEdit" name="doubleEdit0_2"/>
</item>
<item>
<widget class="QLineEdit" name="doubleEdit1_2"/>
</item>
</layout>
</item>
<item row="4" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_15">
<item>
<widget class="QLineEdit" name="floatEdit0_2"/>
</item>
<item>
<widget class="QLineEdit" name="floatEdit1_2"/>
</item>
<item>
<widget class="QLineEdit" name="floatEdit2_2"/>
</item>
<item>
<widget class="QLineEdit" name="floatEdit3_2"/>
</item>
</layout>
</item>
<item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_14">
<item>
<widget class="QLineEdit" name="longEdit0_2"/>
</item>
<item>
<widget class="QLineEdit" name="longEdit1_2"/>
</item>
<item>
<widget class="QLineEdit" name="longEdit2_2"/>
</item>
<item>
<widget class="QLineEdit" name="longEdit3_2"/>
</item>
</layout>
</item>
<item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_13">
<item>
<widget class="QLineEdit" name="shortEdit0_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit1_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit2_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit3_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit4_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit5_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit6_2"/>
</item>
<item>
<widget class="QLineEdit" name="shortEdit7_2">
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_12">
<property name="sizeConstraint">
<enum>QLayout::SetMinimumSize</enum>
</property>
<item>
<widget class="QLabel" name="labelL0">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>0-1</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL1">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>2-3</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL2">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>4-5</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL3">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>6-7</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL4">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>8-9</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL5">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>A-B</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL6">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>C-D</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelL7">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>E-F</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_11">
<item>
<widget class="QLineEdit" name="hexEdit_2">
<property name="inputMethodHints">
<set>Qt::ImhUppercaseOnly</set>
</property>
<property name="maxLength">
<number>32</number>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_18">
<item>
<widget class="QRadioButton" name="radioHex">
<property name="text">
<string>&Hexadecimal</string>
</property>
</widget>
</item>
<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>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<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>
<tabstops>
<tabstop>hexEdit</tabstop>
<tabstop>shortEdit0</tabstop>
<tabstop>shortEdit1</tabstop>
<tabstop>shortEdit2</tabstop>
<tabstop>shortEdit3</tabstop>
<tabstop>shortEdit4</tabstop>
<tabstop>shortEdit5</tabstop>
<tabstop>shortEdit6</tabstop>
<tabstop>shortEdit7</tabstop>
<tabstop>longEdit0</tabstop>
<tabstop>longEdit1</tabstop>
<tabstop>longEdit2</tabstop>
<tabstop>longEdit3</tabstop>
<tabstop>floatEdit0</tabstop>
<tabstop>floatEdit1</tabstop>
<tabstop>floatEdit2</tabstop>
<tabstop>floatEdit3</tabstop>
<tabstop>doubleEdit0</tabstop>
<tabstop>doubleEdit1</tabstop>
<tabstop>longLongEdit0</tabstop>
<tabstop>longLongEdit1</tabstop>
<tabstop>hexEdit_2</tabstop>
<tabstop>shortEdit0_2</tabstop>
<tabstop>shortEdit1_2</tabstop>
<tabstop>shortEdit2_2</tabstop>
<tabstop>shortEdit3_2</tabstop>
<tabstop>shortEdit4_2</tabstop>
<tabstop>shortEdit5_2</tabstop>
<tabstop>shortEdit6_2</tabstop>
<tabstop>shortEdit7_2</tabstop>
<tabstop>longEdit0_2</tabstop>
<tabstop>longEdit1_2</tabstop>
<tabstop>longEdit2_2</tabstop>
<tabstop>longEdit3_2</tabstop>
<tabstop>floatEdit0_2</tabstop>
<tabstop>floatEdit1_2</tabstop>
<tabstop>floatEdit2_2</tabstop>
<tabstop>floatEdit3_2</tabstop>
<tabstop>doubleEdit0_2</tabstop>
<tabstop>doubleEdit1_2</tabstop>
<tabstop>longLongEdit0_2</tabstop>
<tabstop>longLongEdit1_2</tabstop>
<tabstop>radioHex</tabstop>
<tabstop>radioSigned</tabstop>
<tabstop>radioUnsigned</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonOk</sender>
<signal>clicked()</signal>
<receiver>EditFloatRegister</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>389</x>
<y>408</y>
</hint>
<hint type="destinationlabel">
<x>448</x>
<y>388</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>EditFloatRegister</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>440</x>
<y>428</y>
</hint>
<hint type="destinationlabel">
<x>471</x>
<y>417</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/ExceptionRangeDialog.cpp | #include "ExceptionRangeDialog.h"
#include "ui_ExceptionRangeDialog.h"
ExceptionRangeDialog::ExceptionRangeDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::ExceptionRangeDialog)
{
ui->setupUi(this);
//set window flags
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
ui->editStart->setCursorPosition(0);
ui->editEnd->setCursorPosition(0);
ui->btnOk->setEnabled(false);
rangeStart = 0;
rangeEnd = 0;
}
ExceptionRangeDialog::~ExceptionRangeDialog()
{
delete ui;
}
void ExceptionRangeDialog::on_editStart_textChanged(const QString & arg1)
{
Q_UNUSED(arg1)
if(!ui->editStart->text().size()) //nothing entered
{
ui->btnOk->setEnabled(false);
return;
}
if(ui->editStart->text() == "-1")
ui->editStart->setText("FFFFFFFF");
bool converted = false;
unsigned long start = ui->editStart->text().toUInt(&converted, 16);
if(!converted)
{
ui->btnOk->setEnabled(false);
return;
}
unsigned long end = ui->editEnd->text().toUInt(&converted, 16);
if(converted && end < start)
ui->btnOk->setEnabled(false);
else
ui->btnOk->setEnabled(true);
}
void ExceptionRangeDialog::on_editEnd_textChanged(const QString & arg1)
{
Q_UNUSED(arg1)
if(!ui->editEnd->text().size() || !ui->editStart->text().size())
{
ui->btnOk->setEnabled(false);
return;
}
if(ui->editEnd->text() == "-1")
ui->editEnd->setText("FFFFFFFF");
bool converted = false;
unsigned long start = ui->editStart->text().toUInt(&converted, 16);
if(!converted)
{
ui->btnOk->setEnabled(false);
return;
}
unsigned long end = ui->editEnd->text().toUInt(&converted, 16);
if(!converted)
{
ui->btnOk->setEnabled(false);
return;
}
if(end < start)
ui->btnOk->setEnabled(false);
else
ui->btnOk->setEnabled(true);
}
void ExceptionRangeDialog::on_btnOk_clicked()
{
rangeStart = ui->editStart->text().toUInt(0, 16);
bool converted = false;
rangeEnd = ui->editEnd->text().toUInt(&converted, 16);
if(!converted)
rangeEnd = rangeStart;
accept();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ExceptionRangeDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class ExceptionRangeDialog;
}
class ExceptionRangeDialog : public QDialog
{
Q_OBJECT
public:
explicit ExceptionRangeDialog(QWidget* parent = 0);
~ExceptionRangeDialog();
unsigned long rangeStart;
unsigned long rangeEnd;
private slots:
void on_editStart_textChanged(const QString & arg1);
void on_editEnd_textChanged(const QString & arg1);
void on_btnOk_clicked();
private:
Ui::ExceptionRangeDialog* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/ExceptionRangeDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExceptionRangeDialog</class>
<widget class="QDialog" name="ExceptionRangeDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>176</width>
<height>106</height>
</rect>
</property>
<property name="windowTitle">
<string>Range</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="lblStart">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Start:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>editStart</cstring>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="lblEnd">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>End:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>editEnd</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="editEnd">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="inputMask">
<string/>
</property>
<property name="text">
<string/>
</property>
<property name="maxLength">
<number>8</number>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="editStart">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="inputMask">
<string/>
</property>
<property name="text">
<string/>
</property>
<property name="maxLength">
<number>8</number>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layoutButtons">
<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>
<property name="default">
<bool>true</bool>
</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>
<resources/>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>ExceptionRangeDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>95</x>
<y>86</y>
</hint>
<hint type="destinationlabel">
<x>96</x>
<y>64</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/FavouriteTools.cpp | #include "FavouriteTools.h"
#include "ui_FavouriteTools.h"
#include "Bridge.h"
#include "BrowseDialog.h"
#include "MainWindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include "MiscUtil.h"
#include "Configuration.h"
#include <QTableWidget>
FavouriteTools::FavouriteTools(QWidget* parent) :
QDialog(parent),
ui(new Ui::FavouriteTools)
{
ui->setupUi(this);
//set window flags
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setModal(true);
setupTools("Tool", ui->listTools);
setupTools("Script", ui->listScript);
QStringList tblHeaderCommand;
tblHeaderCommand << tr("Command") << tr("Shortcut");
QTableWidget* list = ui->listCommand;
list->setColumnCount(2);
list->verticalHeader()->setVisible(false);
list->setHorizontalHeaderLabels(tblHeaderCommand);
list->setEditTriggers(QAbstractItemView::NoEditTriggers);
list->setSelectionBehavior(QAbstractItemView::SelectRows);
list->setSelectionMode(QAbstractItemView::SingleSelection);
list->setShowGrid(false);
list->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
list->verticalHeader()->setDefaultSectionSize(15);
char buffer[MAX_SETTING_SIZE];
int i;
std::vector<QString> allCommand;
std::vector<QString> allToolShortcut;
for(i = 1; BridgeSettingGet("Favourite", QString("Command%1").arg(i).toUtf8().constData(), buffer); i++)
{
QString command = QString(buffer);
QString commandShortcut("");
if(BridgeSettingGet("Favourite", QString("CommandShortcut%1").arg(i).toUtf8().constData(), buffer))
commandShortcut = QString(buffer);
allCommand.push_back(command);
allToolShortcut.push_back(commandShortcut);
}
i--;
if(!allCommand.empty())
{
list->setRowCount(i);
for(int j = 0; j < i; j++)
{
list->setItem(j, 0, new QTableWidgetItem(allCommand.at(j)));
list->setItem(j, 1, new QTableWidgetItem(allToolShortcut.at(j)));
}
}
originalToolsCount = ui->listTools->rowCount();
originalScriptCount = ui->listScript->rowCount();
originalCommandCount = ui->listCommand->rowCount();
ui->listTools->selectRow(0);
ui->listScript->selectRow(0);
ui->listCommand->selectRow(0);
connect(ui->listTools, SIGNAL(itemSelectionChanged()), this, SLOT(onListSelectionChanged()));
connect(ui->listScript, SIGNAL(itemSelectionChanged()), this, SLOT(onListSelectionChanged()));
connect(ui->listCommand, SIGNAL(itemSelectionChanged()), this, SLOT(onListSelectionChanged()));
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));
emit ui->listTools->itemSelectionChanged();
updateToolsBtnEnabled();
Config()->loadWindowGeometry(this);
}
void FavouriteTools::setupTools(QString name, QTableWidget* list)
{
QStringList tblHeaderTools;
tblHeaderTools << tr("Path") << tr("Shortcut") << tr("Description");
list->setColumnCount(3);
list->verticalHeader()->setVisible(false);
list->setHorizontalHeaderLabels(tblHeaderTools);
list->setEditTriggers(QAbstractItemView::NoEditTriggers);
list->setSelectionBehavior(QAbstractItemView::SelectRows);
list->setSelectionMode(QAbstractItemView::SingleSelection);
list->setShowGrid(false);
list->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
list->verticalHeader()->setDefaultSectionSize(15);
char buffer[MAX_SETTING_SIZE];
int i;
std::vector<QString> allToolPath;
std::vector<QString> allToolShortcut;
std::vector<QString> allToolDescription;
for(i = 1; BridgeSettingGet("Favourite", (name + QString::number(i)).toUtf8().constData(), buffer); i++)
{
QString toolPath = QString(buffer);
QString toolShortcut("");
QString toolDescription("");
if(BridgeSettingGet("Favourite", (name + "Shortcut" + QString::number(i)).toUtf8().constData(), buffer))
toolShortcut = QString(buffer);
if(BridgeSettingGet("Favourite", (name + "Description" + QString::number(i)).toUtf8().constData(), buffer))
toolDescription = QString(buffer);
allToolPath.push_back(toolPath);
allToolShortcut.push_back(toolShortcut);
allToolDescription.push_back(toolDescription);
}
i--;
if(!allToolPath.empty())
{
list->setRowCount(i);
for(int j = 0; j < i; j++)
{
list->setItem(j, 0, new QTableWidgetItem(allToolPath.at(j)));
list->setItem(j, 1, new QTableWidgetItem(allToolShortcut.at(j)));
list->setItem(j, 2, new QTableWidgetItem(allToolDescription.at(j)));
}
}
}
// Events
void FavouriteTools::on_btnAddFavouriteTool_clicked()
{
QString filename;
char buffer[MAX_SETTING_SIZE];
memset(buffer, 0, sizeof(buffer));
BridgeSettingGet("Favourite", "LastToolPath", buffer);
BrowseDialog browse(this, tr("Browse tool"), tr("Enter the path of the tool."), tr("Executable Files (*.exe);;All Files (*.*)"), QString(buffer), false);
if(browse.exec() != QDialog::Accepted || browse.path.length() == 0)
return;
filename = browse.path;
BridgeSettingSet("Favourite", "LastToolPath", filename.toUtf8().constData());
int rows = ui->listTools->rowCount();
ui->listTools->setRowCount(rows + 1);
ui->listTools->setItem(rows, 0, new QTableWidgetItem(filename));
ui->listTools->setItem(rows, 1, new QTableWidgetItem(QString()));
ui->listTools->setItem(rows, 2, new QTableWidgetItem(QString()));
if(rows == 0)
ui->listTools->selectRow(0);
updateToolsBtnEnabled();
}
void FavouriteTools::on_btnEditFavouriteTool_clicked()
{
QTableWidget* table = ui->listTools;
if(!table->rowCount())
return;
QString filename = table->item(table->currentRow(), 0)->text();
BrowseDialog browse(this, tr("Browse tool"), tr("Enter the path of the tool."), tr("Executable Files (*.exe);;All Files (*.*)"), filename, false);
if(browse.exec() != QDialog::Accepted)
return;
filename = browse.path;
BridgeSettingSet("Favourite", "LastToolPath", filename.toUtf8().constData());
table->item(table->currentRow(), 0)->setText(filename);
}
void FavouriteTools::upbutton(QTableWidget* table)
{
if(!table->rowCount())
return;
int currentRow = table->currentRow();
if(currentRow == 0)
return;
for(int i = 0; i < table->columnCount(); i++)
{
QString prevContent(table->item(currentRow, i)->text());
table->item(currentRow, i)->setText(table->item(currentRow - 1, i)->text());
table->item(currentRow - 1, i)->setText(prevContent);
}
table->selectRow(currentRow - 1);
}
void FavouriteTools::downbutton(QTableWidget* table)
{
if(!table->rowCount())
return;
int currentRow = table->currentRow();
if(currentRow == table->rowCount() - 1)
return;
for(int i = 0; i < table->columnCount(); i++)
{
QString prevContent(table->item(currentRow, i)->text());
table->item(currentRow, i)->setText(table->item(currentRow + 1, i)->text());
table->item(currentRow + 1, i)->setText(prevContent);
}
table->selectRow(currentRow + 1);
}
void FavouriteTools::on_btnRemoveFavouriteTool_clicked()
{
QTableWidget* table = ui->listTools;
if(!table->rowCount())
return;
table->removeRow(table->currentRow());
updateToolsBtnEnabled();
}
void FavouriteTools::on_btnDescriptionFavouriteTool_clicked()
{
QTableWidget* table = ui->listTools;
if(!table->rowCount())
return;
QString description = table->item(table->currentRow(), 2)->text();
if(SimpleInputBox(this, tr("Enter the description"), description, description, tr("This string will appear in the menu.")))
table->item(table->currentRow(), 2)->setText(description);
}
void FavouriteTools::on_btnUpFavouriteTool_clicked()
{
upbutton(ui->listTools);
}
void FavouriteTools::on_btnDownFavouriteTool_clicked()
{
downbutton(ui->listTools);
}
void FavouriteTools::on_btnAddFavouriteScript_clicked()
{
QString filename;
char buffer[MAX_SETTING_SIZE];
memset(buffer, 0, sizeof(buffer));
BridgeSettingGet("Favourite", "LastScriptPath", buffer);
filename = QFileDialog::getOpenFileName(this, tr("Select script"), QString(buffer), tr("Script files (*.txt *.scr);;All files (*.*)"));
if(filename.size() == 0)
return;
filename = QDir::toNativeSeparators(filename);
BridgeSettingSet("Favourite", "LastScriptPath", filename.toUtf8().constData());
int rows = ui->listScript->rowCount();
ui->listScript->setRowCount(rows + 1);
ui->listScript->setItem(rows, 0, new QTableWidgetItem(filename));
ui->listScript->setItem(rows, 1, new QTableWidgetItem(QString()));
ui->listScript->setItem(rows, 2, new QTableWidgetItem(QString()));
if(rows == 0)
ui->listScript->selectRow(0);
updateScriptsBtnEnabled();
}
void FavouriteTools::on_btnEditFavouriteScript_clicked()
{
QTableWidget* table = ui->listScript;
if(!table->rowCount())
return;
QString filename = table->item(table->currentRow(), 0)->text();
filename = QFileDialog::getOpenFileName(this, tr("Select script"), filename, tr("Script files (*.txt *.scr);;All files (*.*)"));
if(filename.size() == 0)
return;
filename = QDir::toNativeSeparators(filename);
BridgeSettingSet("Favourite", "LastScriptPath", filename.toUtf8().constData());
table->item(table->currentRow(), 0)->setText(filename);
}
void FavouriteTools::on_btnRemoveFavouriteScript_clicked()
{
QTableWidget* table = ui->listScript;
if(!table->rowCount())
return;
table->removeRow(table->currentRow());
updateScriptsBtnEnabled();
}
void FavouriteTools::on_btnDescriptionFavouriteScript_clicked()
{
QTableWidget* table = ui->listScript;
if(!table->rowCount())
return;
QString description = table->item(table->currentRow(), 2)->text();
if(SimpleInputBox(this, tr("Enter the description"), description, description, tr("This string will appear in the menu.")))
table->item(table->currentRow(), 2)->setText(description);
}
void FavouriteTools::on_btnUpFavouriteScript_clicked()
{
upbutton(ui->listScript);
}
void FavouriteTools::on_btnDownFavouriteScript_clicked()
{
downbutton(ui->listScript);
}
void FavouriteTools::on_btnAddFavouriteCommand_clicked()
{
QString cmd;
if(SimpleInputBox(this, tr("Enter the command you want to favourite"), "", cmd, tr("Example: bphws csp")))
{
int rows = ui->listCommand->rowCount();
ui->listCommand->setRowCount(rows + 1);
ui->listCommand->setItem(rows, 0, new QTableWidgetItem(cmd));
ui->listCommand->setItem(rows, 1, new QTableWidgetItem(QString()));
if(rows == 0)
ui->listCommand->selectRow(0);
updateCommandsBtnEnabled();
}
}
void FavouriteTools::on_btnEditFavouriteCommand_clicked()
{
QTableWidget* table = ui->listCommand;
if(!table->rowCount())
return;
QString cmd;
if(SimpleInputBox(this, tr("Enter a new command"), table->item(table->currentRow(), 0)->text(), cmd, tr("Example: bphws ESP")) && cmd.length())
table->item(table->currentRow(), 0)->setText(cmd);
}
void FavouriteTools::on_btnRemoveFavouriteCommand_clicked()
{
QTableWidget* table = ui->listCommand;
if(!table->rowCount())
return;
table->removeRow(table->currentRow());
updateCommandsBtnEnabled();
}
void FavouriteTools::on_btnUpFavouriteCommand_clicked()
{
upbutton(ui->listCommand);
}
void FavouriteTools::on_btnDownFavouriteCommand_clicked()
{
downbutton(ui->listCommand);
}
void FavouriteTools::onListSelectionChanged()
{
QTableWidget* table = qobject_cast<QTableWidget*>(sender());
if(table == nullptr)
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(indexes.count() < 1)
return;
ui->shortcutEdit->setErrorState(false);
ui->shortcutEdit->setText(table->item(table->currentRow(), 1)->text());
}
void FavouriteTools::on_shortcutEdit_askForSave()
{
QTableWidget* table;
switch(ui->tabWidget->currentIndex())
{
case 0:
table = ui->listTools;
break;
case 1:
table = ui->listScript;
break;
case 2:
table = ui->listCommand;
break;
default:
return;
}
if(!table->rowCount())
return;
const QKeySequence newKey = ui->shortcutEdit->getKeysequence();
if(newKey != currentShortcut)
{
bool good = true;
if(!newKey.isEmpty())
{
for(auto i = Config()->Shortcuts.cbegin(); i != Config()->Shortcuts.cend(); ++i)
{
if(i.value().Hotkey == newKey) //newkey is trying to override a global shortcut
{
good = false;
break;
}
}
}
if(good)
{
QString keyText = "";
if(!newKey.isEmpty())
keyText = newKey.toString(QKeySequence::NativeText);
table->item(table->currentRow(), 1)->setText(keyText);
ui->shortcutEdit->setErrorState(false);
}
else
{
ui->shortcutEdit->setErrorState(true);
}
}
}
void FavouriteTools::on_btnClearShortcut_clicked()
{
QTableWidget* table;
switch(ui->tabWidget->currentIndex())
{
case 0:
table = ui->listTools;
break;
case 1:
table = ui->listScript;
break;
case 2:
table = ui->listCommand;
break;
default:
return;
}
if(!table->rowCount())
return;
QString emptyString;
ui->shortcutEdit->setText(emptyString);
table->item(table->currentRow(), 1)->setText(emptyString);
}
void FavouriteTools::on_btnOK_clicked()
{
int i;
for(i = 1; i <= ui->listTools->rowCount(); i++)
{
BridgeSettingSet("Favourite", QString("Tool%1").arg(i).toUtf8().constData(), ui->listTools->item(i - 1, 0)->text().toUtf8().constData());
BridgeSettingSet("Favourite", QString("ToolShortcut%1").arg(i).toUtf8().constData(), ui->listTools->item(i - 1, 1)->text().toUtf8().constData());
BridgeSettingSet("Favourite", QString("ToolDescription%1").arg(i).toUtf8().constData(), ui->listTools->item(i - 1, 2)->text().toUtf8().constData());
}
if(ui->listTools->rowCount() == 0)
{
BridgeSettingSet("Favourite", "Tool1", "");
BridgeSettingSet("Favourite", "ToolShortcut1", "");
BridgeSettingSet("Favourite", "ToolDescription1", "");
}
else
{
i = ui->listTools->rowCount() + 1;
do // Run this at least once to ensure no old tools can be brought to live
{
BridgeSettingSet("Favourite", QString("Tool%1").arg(i).toUtf8().constData(), "");
BridgeSettingSet("Favourite", QString("ToolShortcut%1").arg(i).toUtf8().constData(), "");
BridgeSettingSet("Favourite", QString("ToolDescription%1").arg(i).toUtf8().constData(), "");
i++;
}
while(i <= originalToolsCount);
}
for(int i = 1; i <= ui->listScript->rowCount(); i++)
{
BridgeSettingSet("Favourite", QString("Script%1").arg(i).toUtf8().constData(), ui->listScript->item(i - 1, 0)->text().toUtf8().constData());
BridgeSettingSet("Favourite", QString("ScriptShortcut%1").arg(i).toUtf8().constData(), ui->listScript->item(i - 1, 1)->text().toUtf8().constData());
BridgeSettingSet("Favourite", QString("ScriptDescription%1").arg(i).toUtf8().constData(), ui->listScript->item(i - 1, 2)->text().toUtf8().constData());
}
if(ui->listScript->rowCount() == 0)
{
BridgeSettingSet("Favourite", "Script1", "");
BridgeSettingSet("Favourite", "ScriptShortcut1", "");
BridgeSettingSet("Favourite", "ScriptDescription1", "");
}
else
{
i = ui->listScript->rowCount() + 1;
do
{
BridgeSettingSet("Favourite", QString("Script%1").arg(i).toUtf8().constData(), "");
BridgeSettingSet("Favourite", QString("ScriptShortcut%1").arg(i).toUtf8().constData(), "");
BridgeSettingSet("Favourite", QString("ScriptDescription%1").arg(i).toUtf8().constData(), "");
i++;
}
while(i <= originalScriptCount);
}
for(int i = 1; i <= ui->listCommand->rowCount(); i++)
{
BridgeSettingSet("Favourite", QString("Command%1").arg(i).toUtf8().constData(), ui->listCommand->item(i - 1, 0)->text().toUtf8().constData());
BridgeSettingSet("Favourite", QString("CommandShortcut%1").arg(i).toUtf8().constData(), ui->listCommand->item(i - 1, 1)->text().toUtf8().constData());
}
if(ui->listCommand->rowCount() == 0)
{
BridgeSettingSet("Favourite", "Command1", "");
BridgeSettingSet("Favourite", "CommandShortcut1", "");
}
else
{
i = ui->listCommand->rowCount() + 1;
do
{
BridgeSettingSet("Favourite", QString("Command%1").arg(i).toUtf8().constData(), "");
BridgeSettingSet("Favourite", QString("CommandShortcut%1").arg(i).toUtf8().constData(), "");
i++;
}
while(i <= originalCommandCount);
}
this->done(QDialog::Accepted);
}
void FavouriteTools::tabChanged(int i)
{
switch(i)
{
case 0:
emit ui->listTools->itemSelectionChanged();
updateToolsBtnEnabled();
break;
case 1:
emit ui->listScript->itemSelectionChanged();
updateScriptsBtnEnabled();
break;
case 2:
emit ui->listCommand->itemSelectionChanged();
updateCommandsBtnEnabled();
break;
}
}
FavouriteTools::~FavouriteTools()
{
Config()->saveWindowGeometry(this);
delete ui;
}
void FavouriteTools::updateToolsBtnEnabled()
{
int rows = ui->listTools->rowCount();
bool enabled = rows != 0;
bool updownEnabled = enabled && rows != 1;
ui->btnRemoveFavouriteTool->setEnabled(enabled);
ui->btnEditFavouriteTool->setEnabled(enabled);
ui->btnUpFavouriteTool->setEnabled(updownEnabled);
ui->btnDownFavouriteTool->setEnabled(updownEnabled);
ui->btnDescriptionFavouriteTool->setEnabled(enabled);
}
void FavouriteTools::updateScriptsBtnEnabled()
{
int rows = ui->listScript->rowCount();
bool enabled = rows != 0;
bool updownEnabled = enabled && rows != 1;
ui->btnRemoveFavouriteScript->setEnabled(enabled);
ui->btnEditFavouriteScript->setEnabled(enabled);
ui->btnUpFavouriteScript->setEnabled(updownEnabled);
ui->btnDownFavouriteScript->setEnabled(updownEnabled);
ui->btnDescriptionFavouriteScript->setEnabled(enabled);
}
void FavouriteTools::updateCommandsBtnEnabled()
{
int rows = ui->listCommand->rowCount();
bool enabled = rows != 0;
bool updownEnabled = enabled && rows != 1;
ui->btnRemoveFavouriteCommand->setEnabled(enabled);
ui->btnEditFavouriteCommand->setEnabled(enabled);
ui->btnUpFavouriteCommand->setEnabled(updownEnabled);
ui->btnDownFavouriteCommand->setEnabled(updownEnabled);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/FavouriteTools.h | #pragma once
#include <QDialog>
class QTableWidget;
namespace Ui
{
class FavouriteTools;
}
class FavouriteTools : public QDialog
{
Q_OBJECT
public:
explicit FavouriteTools(QWidget* parent = 0);
~FavouriteTools();
public slots:
void on_btnAddFavouriteTool_clicked();
void on_btnEditFavouriteTool_clicked();
void on_btnRemoveFavouriteTool_clicked();
void on_btnDescriptionFavouriteTool_clicked();
void on_btnUpFavouriteTool_clicked();
void on_btnDownFavouriteTool_clicked();
void on_btnAddFavouriteScript_clicked();
void on_btnEditFavouriteScript_clicked();
void on_btnRemoveFavouriteScript_clicked();
void on_btnDescriptionFavouriteScript_clicked();
void on_btnUpFavouriteScript_clicked();
void on_btnDownFavouriteScript_clicked();
void on_btnAddFavouriteCommand_clicked();
void on_btnEditFavouriteCommand_clicked();
void on_btnRemoveFavouriteCommand_clicked();
void on_btnUpFavouriteCommand_clicked();
void on_btnDownFavouriteCommand_clicked();
void on_btnClearShortcut_clicked();
void onListSelectionChanged();
void tabChanged(int i);
void on_shortcutEdit_askForSave();
void on_btnOK_clicked();
private:
Ui::FavouriteTools* ui;
QKeySequence currentShortcut;
int originalToolsCount;
int originalScriptCount;
int originalCommandCount;
void upbutton(QTableWidget* table);
void downbutton(QTableWidget* table);
void setupTools(QString name, QTableWidget* list);
void updateToolsBtnEnabled();
void updateScriptsBtnEnabled();
void updateCommandsBtnEnabled();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/FavouriteTools.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FavouriteTools</class>
<widget class="QDialog" name="FavouriteTools">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>600</width>
<height>400</height>
</rect>
</property>
<property name="windowTitle">
<string>Favourites</string>
</property>
<property name="windowIcon">
<iconset theme="star" resource="../../resource.qrc">
<normaloff>:/Default/icons/star.png</normaloff>:/Default/icons/star.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabFavouriteTool">
<attribute name="title">
<string>Tools</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QTableWidget" name="listTools"/>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QPushButton" name="btnAddFavouriteTool">
<property name="text">
<string>&Add...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnEditFavouriteTool">
<property name="text">
<string>&Edit</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRemoveFavouriteTool">
<property name="text">
<string>&Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDescriptionFavouriteTool">
<property name="text">
<string>De&scription...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnUpFavouriteTool">
<property name="text">
<string>&Up</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDownFavouriteTool">
<property name="text">
<string>&Down</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFavouriteScript">
<attribute name="title">
<string>Script</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QTableWidget" name="listScript"/>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QPushButton" name="btnAddFavouriteScript">
<property name="text">
<string>&Add...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnEditFavouriteScript">
<property name="text">
<string>&Edit</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRemoveFavouriteScript">
<property name="text">
<string>&Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDescriptionFavouriteScript">
<property name="text">
<string>De&scription...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnUpFavouriteScript">
<property name="text">
<string>&Up</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDownFavouriteScript">
<property name="text">
<string>&Down</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFavouriteCommand">
<attribute name="title">
<string>Command</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QTableWidget" name="listCommand"/>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QPushButton" name="btnAddFavouriteCommand">
<property name="text">
<string>&Add...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnEditFavouriteCommand">
<property name="text">
<string>&Edit</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRemoveFavouriteCommand">
<property name="text">
<string>&Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnUpFavouriteCommand">
<property name="text">
<string>&Up</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDownFavouriteCommand">
<property name="text">
<string>&Down</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Shortcut</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<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>
<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="btnOK">
<property name="text">
<string>&OK</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>FavouriteTools</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>352</x>
<y>378</y>
</hint>
<hint type="destinationlabel">
<x>199</x>
<y>199</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C/C++ | x64dbg-development/src/gui/Src/Gui/FileLines.h | #pragma once
/*
MIT License
Copyright (c) 2018 Duncan Ogilvie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
struct IBufferedFileReader
{
enum Direction
{
Right,
Left
};
virtual ~IBufferedFileReader() {}
virtual bool isopen() const = 0;
virtual bool read(void* dest, uint64_t index, size_t size) = 0;
virtual uint64_t size() = 0;
virtual void setbuffersize(size_t size) = 0;
virtual void setbufferdirection(Direction direction) = 0;
bool readchar(uint64_t index, char & ch)
{
return read(&ch, index, 1);
}
bool readstring(uint64_t index, size_t size, std::string & str)
{
str.resize(size);
return read((char*)str.c_str(), index, size);
}
bool readvector(uint64_t index, size_t size, std::vector<char> & vec)
{
vec.resize(size);
return read(vec.data(), index, size);
}
};
class HandleFileReader : public IBufferedFileReader
{
HANDLE mHandle = INVALID_HANDLE_VALUE;
uint64_t mFileSize = -1;
std::vector<char> mBuffer;
size_t mBufferIndex = 0;
size_t mBufferSize = 0;
Direction mBufferDirection = Right;
bool readnobuffer(void* dest, uint64_t index, size_t size)
{
if(!isopen())
return false;
LARGE_INTEGER distance;
distance.QuadPart = index;
if(!SetFilePointerEx(mHandle, distance, nullptr, FILE_BEGIN))
return false;
DWORD read = 0;
return !!ReadFile(mHandle, dest, (DWORD)size, &read, nullptr);
}
public:
HandleFileReader(const wchar_t* szFileName)
{
mHandle = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
if(mHandle != INVALID_HANDLE_VALUE)
{
LARGE_INTEGER size;
if(GetFileSizeEx(mHandle, &size))
{
mFileSize = size.QuadPart;
}
else
{
CloseHandle(mHandle);
mHandle = INVALID_HANDLE_VALUE;
}
}
}
~HandleFileReader() override
{
if(isopen())
{
CloseHandle(mHandle);
mHandle = INVALID_HANDLE_VALUE;
}
}
HandleFileReader(const HandleFileReader &) = delete;
bool isopen() const override
{
return mHandle != INVALID_HANDLE_VALUE;
}
bool read(void* dest, uint64_t index, size_t size) override
{
if(index + size > mFileSize)
return false;
if(size > mBufferSize)
return readnobuffer(dest, index, size);
if(index < mBufferIndex || index + size > mBufferIndex + mBuffer.size())
{
auto bufferSize = std::min(uint64_t(mBufferSize), mFileSize - index);
mBuffer.resize(size_t(bufferSize));
mBufferIndex = size_t(index);
/*if (mBufferDirection == Left)
{
if (mBufferIndex >= mBufferSize + size)
mBufferIndex -= mBufferSize + size;
}*/
if(!readnobuffer(mBuffer.data(), mBufferIndex, mBuffer.size()))
return false;
}
if(size == 1)
{
*(unsigned char*)dest = mBuffer[index - mBufferIndex];
}
else
{
#ifdef _DEBUG
auto dst = (unsigned char*)dest;
for(size_t i = 0; i < size; i++)
dst[i] = mBuffer.at(index - mBufferIndex + i);
#else
memcpy(dest, mBuffer.data() + (index - mBufferIndex), size);
#endif //_DEBUG
}
return true;
}
uint64_t size() override
{
return mFileSize;
}
void setbuffersize(size_t size) override
{
mBufferSize = size_t(std::min(uint64_t(size), mFileSize));
}
void setbufferdirection(Direction direction) override
{
mBufferDirection = direction;
}
};
class FileLines
{
std::vector<uint64_t> mLines;
std::unique_ptr<IBufferedFileReader> mReader;
public:
bool isopen()
{
return mReader && mReader->isopen();
}
bool open(const wchar_t* szFileName)
{
if(isopen())
return false;
mReader = std::make_unique<HandleFileReader>(szFileName);
return mReader->isopen();
}
bool parse()
{
if(!isopen())
return false;
auto filesize = mReader->size();
mReader->setbufferdirection(IBufferedFileReader::Right);
mReader->setbuffersize(10 * 1024 * 1024);
size_t curIndex = 0, curSize = 0;
for(uint64_t i = 0; i < filesize; i++)
{
/*if (mLines.size() % 100000 == 0)
printf("%zu\n", i);*/
char ch;
if(!mReader->readchar(i, ch))
return false;
if(ch == '\r')
continue;
if(ch == '\n')
{
mLines.push_back(curIndex);
curIndex = i + 1;
curSize = 0;
continue;
}
curSize++;
}
if(curSize > 0)
mLines.push_back(curIndex);
mLines.push_back(filesize + 1);
return true;
}
size_t size() const
{
return mLines.size() - 1;
}
std::string operator[](size_t index)
{
auto lineStart = mLines[index];
auto nextLineStart = mLines[index + 1];
std::string result;
mReader->readstring(lineStart, nextLineStart - lineStart - 1, result);
while(!result.empty() && result.back() == '\r')
result.pop_back();
return result;
}
}; |
C++ | x64dbg-development/src/gui/Src/Gui/GotoDialog.cpp | #include "GotoDialog.h"
#include "ValidateExpressionThread.h"
#include "ui_GotoDialog.h"
#include "StringUtil.h"
#include "Configuration.h"
#include "QCompleter"
#include "SymbolAutoCompleteModel.h"
GotoDialog::GotoDialog(QWidget* parent, bool allowInvalidExpression, bool allowInvalidAddress, bool allowNotDebugging)
: QDialog(parent),
ui(new Ui::GotoDialog),
allowInvalidExpression(allowInvalidExpression),
allowInvalidAddress(allowInvalidAddress || allowInvalidExpression),
allowNotDebugging(allowNotDebugging)
{
//setup UI first
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
//initialize stuff
if(!allowNotDebugging && !DbgIsDebugging()) //not debugging
ui->labelError->setText(tr("<font color='red'><b>Not debugging...</b></font>"));
else
ui->labelError->setText(tr("<font color='red'><b>Invalid expression...</b></font>"));
setOkEnabled(false);
ui->editExpression->setFocus();
completer = new QCompleter(this);
completer->setModel(new SymbolAutoCompleteModel([this]
{
return mCompletionText;
}, completer));
completer->setCaseSensitivity(Config()->getBool("Gui", "CaseSensitiveAutoComplete") ? Qt::CaseSensitive : Qt::CaseInsensitive);
if(!Config()->getBool("Gui", "DisableAutoComplete"))
ui->editExpression->setCompleter(completer);
validRangeStart = 0;
validRangeEnd = ~0;
fileOffset = false;
mValidateThread = new ValidateExpressionThread(this);
mValidateThread->setOnExpressionChangedCallback(std::bind(&GotoDialog::validateExpression, this, std::placeholders::_1));
connect(mValidateThread, SIGNAL(expressionChanged(bool, bool, dsint)), this, SLOT(expressionChanged(bool, bool, dsint)));
connect(ui->editExpression, SIGNAL(textChanged(QString)), mValidateThread, SLOT(textChanged(QString)));
connect(ui->editExpression, SIGNAL(textEdited(QString)), this, SLOT(textEditedSlot(QString)));
connect(ui->labelError, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
connect(this, SIGNAL(finished(int)), this, SLOT(finishedSlot(int)));
connect(Config(), SIGNAL(disableAutoCompleteUpdated()), this, SLOT(disableAutoCompleteUpdated()));
Config()->loadWindowGeometry(this);
}
GotoDialog::~GotoDialog()
{
mValidateThread->stop();
mValidateThread->wait();
Config()->saveWindowGeometry(this);
delete ui;
}
void GotoDialog::showEvent(QShowEvent* event)
{
Q_UNUSED(event);
mValidateThread->start();
}
void GotoDialog::hideEvent(QHideEvent* event)
{
Q_UNUSED(event);
mValidateThread->stop();
mValidateThread->wait();
}
void GotoDialog::validateExpression(QString expression)
{
duint value;
bool validExpression = DbgFunctions()->ValFromString(expression.toUtf8().constData(), &value);
unsigned char ch;
bool validPointer = validExpression && DbgMemIsValidReadPtr(value) && DbgMemRead(value, &ch, sizeof(ch));
this->mValidateThread->emitExpressionChanged(validExpression, validPointer, value);
}
void GotoDialog::setInitialExpression(const QString & expression)
{
ui->editExpression->setText(expression);
emit ui->editExpression->textEdited(expression);
}
void GotoDialog::expressionChanged(bool validExpression, bool validPointer, dsint value)
{
QString expression = ui->editExpression->text();
if(!expression.length())
{
QString tips[] = {"RVA", tr("File offset"), "PEB", "TEB"};
const char* expressions[] = {":$%", ":#%", "peb()", "teb()"};
QString labelText(tr("Shortcuts: "));
for(size_t i = 0; i < 4; i++)
{
labelText += "<a href=\"";
labelText += QString(expressions[i]).replace('%', "%" + tips[i] + "%") + "\">" + QString(expressions[i]).replace('%', tips[i]) + "</a>";
if(i < 3)
labelText += '\t';
}
ui->labelError->setText(labelText);
setOkEnabled(false);
expressionText.clear();
}
if(expressionText == expression)
return;
if(!allowNotDebugging && !DbgIsDebugging()) //not debugging
{
ui->labelError->setText(tr("<font color='red'><b>Not debugging...</b></font>"));
setOkEnabled(false);
expressionText.clear();
}
else if(!validExpression) //invalid expression
{
ui->labelError->setText(tr("<font color='red'><b>Invalid expression...</b></font>"));
setOkEnabled(false);
expressionText.clear();
}
else if(fileOffset)
{
duint offset = value;
duint va = DbgFunctions()->FileOffsetToVa(modName.toUtf8().constData(), offset);
QString addrText = QString(" %1").arg(ToPtrString(va));
if(va || allowInvalidAddress)
{
ui->labelError->setText(tr("<font color='#00DD00'><b>Correct expression! -> </b></font>") + addrText);
setOkEnabled(true);
expressionText = expression;
}
else
{
ui->labelError->setText(tr("<font color='red'><b>Invalid file offset...</b></font>") + addrText);
setOkEnabled(false);
expressionText.clear();
}
}
else
{
duint addr = value;
QString addrText = QString(" %1").arg(ToPtrString(addr));
if(!validPointer && !allowInvalidAddress)
{
ui->labelError->setText(tr("<font color='red'><b>Invalid memory address...</b></font>") + addrText);
setOkEnabled(false);
expressionText.clear();
}
else if(!IsValidMemoryRange(addr) && !allowInvalidAddress)
{
ui->labelError->setText(tr("<font color='red'><b>Memory out of range...</b></font>") + addrText);
setOkEnabled(false);
expressionText.clear();
}
else
{
char module[MAX_MODULE_SIZE] = "";
char label[MAX_LABEL_SIZE] = "";
if(DbgGetLabelAt(addr, SEG_DEFAULT, label)) //has label
{
if(DbgGetModuleAt(addr, module) && !QString(label).startsWith("JMP.&"))
addrText = QString(module) + "." + QString(label);
else
addrText = QString(label);
}
else if(DbgGetModuleAt(addr, module) && !QString(label).startsWith("JMP.&"))
addrText = QString(module) + "." + ToPtrString(addr);
else
addrText = ToPtrString(addr);
ui->labelError->setText(tr("<font color='#00DD00'><b>Correct expression! -> </b></font>") + addrText);
setOkEnabled(true);
expressionText = expression;
}
}
}
bool GotoDialog::IsValidMemoryRange(duint addr)
{
return addr >= validRangeStart && addr < validRangeEnd;
}
void GotoDialog::setOkEnabled(bool enabled)
{
ui->buttonOk->setEnabled(enabled || allowInvalidExpression);
}
void GotoDialog::on_buttonOk_clicked()
{
QString expression = ui->editExpression->text();
ui->editExpression->addLineToHistory(expression);
ui->editExpression->setText("");
expressionChanged(false, false, 0);
expressionText = expression;
}
void GotoDialog::finishedSlot(int result)
{
if(result == QDialog::Rejected)
ui->editExpression->setText("");
ui->editExpression->setFocus();
}
void GotoDialog::textEditedSlot(QString text)
{
mCompletionText = text;
}
void GotoDialog::linkActivated(const QString & link)
{
if(link.contains('%'))
{
int x = link.indexOf('%');
int y = link.lastIndexOf('%');
ui->editExpression->setText(QString(link).replace('%', ""));
ui->editExpression->setSelection(x, y - 1);
}
else
ui->editExpression->setText(link);
}
void GotoDialog::disableAutoCompleteUpdated()
{
if(Config()->getBool("Gui", "DisableAutoComplete"))
ui->editExpression->setCompleter(nullptr);
else
ui->editExpression->setCompleter(completer);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/GotoDialog.h | #pragma once
#include <QDialog>
#include "Imports.h"
class ValidateExpressionThread;
class QCompleter;
namespace Ui
{
class GotoDialog;
}
class GotoDialog : public QDialog
{
Q_OBJECT
public:
explicit GotoDialog(QWidget* parent = 0, bool allowInvalidExpression = false, bool allowInvalidAddress = false, bool allowNotDebugging = false);
~GotoDialog();
QString expressionText;
duint validRangeStart;
duint validRangeEnd;
bool fileOffset;
QString modName;
bool allowInvalidExpression;
bool allowInvalidAddress;
bool allowNotDebugging;
void showEvent(QShowEvent* event);
void hideEvent(QHideEvent* event);
void validateExpression(QString expression);
void setInitialExpression(const QString & expression);
private slots:
void expressionChanged(bool validExpression, bool validPointer, dsint value);
void disableAutoCompleteUpdated();
void on_buttonOk_clicked();
void finishedSlot(int result);
void textEditedSlot(QString text);
void linkActivated(const QString & link);
private:
Ui::GotoDialog* ui;
ValidateExpressionThread* mValidateThread;
QCompleter* completer;
bool IsValidMemoryRange(duint addr);
void setOkEnabled(bool enabled);
QString mCompletionText;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/GotoDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>GotoDialog</class>
<widget class="QDialog" name="GotoDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>539</width>
<height>92</height>
</rect>
</property>
<property name="contextMenuPolicy">
<enum>Qt::NoContextMenu</enum>
</property>
<property name="windowTitle">
<string>Enter expression to follow...</string>
</property>
<property name="windowIcon">
<iconset theme="geolocation-goto" resource="../../resource.qrc">
<normaloff>:/Default/icons/geolocation-goto.png</normaloff>:/Default/icons/geolocation-goto.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="HistoryLineEdit" name="editExpression"/>
</item>
<item>
<widget class="QLabel" name="labelError">
<property name="text">
<string/>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonOk">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonCancel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>HistoryLineEdit</class>
<extends>QLineEdit</extends>
<header>HistoryLineEdit.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>editExpression</tabstop>
<tabstop>buttonOk</tabstop>
<tabstop>buttonCancel</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>GotoDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>305</x>
<y>56</y>
</hint>
<hint type="destinationlabel">
<x>156</x>
<y>60</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonOk</sender>
<signal>clicked()</signal>
<receiver>GotoDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>229</x>
<y>49</y>
</hint>
<hint type="destinationlabel">
<x>164</x>
<y>42</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/HandlesView.cpp | #include <Windows.h>
#include <QtWin>
#include "HandlesView.h"
#include "Bridge.h"
#include "VersionHelpers.h"
#include "StdTable.h"
#include "LabeledSplitter.h"
#include "StringUtil.h"
#include "ReferenceView.h"
#include "StdIconSearchListView.h"
#include "MainWindow.h"
#include "MessagesBreakpoints.h"
#include <QVBoxLayout>
HandlesView::HandlesView(QWidget* parent) : QWidget(parent)
{
// Setup handles list
mHandlesTable = new StdSearchListView(this, true, true);
mHandlesTable->setInternalTitle("Handles");
mHandlesTable->mSearchStartCol = 0;
mHandlesTable->setDrawDebugOnly(true);
mHandlesTable->setDisassemblyPopupEnabled(false);
int wCharWidth = mHandlesTable->getCharWidth();
mHandlesTable->addColumnAt(8 + 16 * wCharWidth, tr("Type"), true);
mHandlesTable->addColumnAt(8 + 8 * wCharWidth, tr("Type number"), true, "", StdTable::SortBy::AsHex);
mHandlesTable->addColumnAt(8 + sizeof(duint) * 2 * wCharWidth, tr("Handle"), true, "", StdTable::SortBy::AsHex);
mHandlesTable->addColumnAt(8 + 16 * wCharWidth, tr("Access"), true, "", StdTable::SortBy::AsHex);
mHandlesTable->addColumnAt(8 + wCharWidth * 20, tr("Name"), true);
mHandlesTable->loadColumnFromConfig("Handle");
// Setup windows list
mWindowsTable = new StdIconSearchListView(this, true, true);
mWindowsTable->setInternalTitle("Windows");
mWindowsTable->setSearchStartCol(0);
mWindowsTable->setDrawDebugOnly(true);
wCharWidth = mWindowsTable->getCharWidth();
mWindowsTable->addColumnAt(8 + sizeof(duint) * 2 * wCharWidth, tr("Proc"), true, "", StdTable::SortBy::AsHex);
mWindowsTable->addColumnAt(8 + 8 * wCharWidth, tr("Handle"), true, "", StdTable::SortBy::AsHex);
mWindowsTable->addColumnAt(8 + 120 * wCharWidth, tr("Title"), true);
mWindowsTable->addColumnAt(8 + 40 * wCharWidth, tr("Class"), true);
mWindowsTable->addColumnAt(8 + 8 * wCharWidth, tr("Thread"), true, "", StdTable::SortBy::AsHex);
mWindowsTable->addColumnAt(8 + 16 * wCharWidth, tr("Style"), true, "", StdTable::SortBy::AsHex);
mWindowsTable->addColumnAt(8 + 16 * wCharWidth, tr("StyleEx"), true, "", StdTable::SortBy::AsHex);
mWindowsTable->addColumnAt(8 + 8 * wCharWidth, tr("Parent"), true);
mWindowsTable->addColumnAt(8 + 20 * wCharWidth, tr("Size"), true);
mWindowsTable->addColumnAt(8 + 6 * wCharWidth, tr("Enable"), true);
mWindowsTable->loadColumnFromConfig("Window");
mWindowsTable->setIconColumn(2);
// Setup tcp list
mTcpConnectionsTable = new StdSearchListView(this, true, true);
mTcpConnectionsTable->setInternalTitle("TcpConnections");
mTcpConnectionsTable->setSearchStartCol(0);
mTcpConnectionsTable->setDrawDebugOnly(true);
mTcpConnectionsTable->setDisassemblyPopupEnabled(false);
wCharWidth = mTcpConnectionsTable->getCharWidth();
mTcpConnectionsTable->addColumnAt(8 + 64 * wCharWidth, tr("Remote address"), true);
mTcpConnectionsTable->addColumnAt(8 + 64 * wCharWidth, tr("Local address"), true);
mTcpConnectionsTable->addColumnAt(8 + 8 * wCharWidth, tr("State"), true);
mTcpConnectionsTable->loadColumnFromConfig("TcpConnection");
/*
mHeapsTable = new ReferenceView(this);
mHeapsTable->setWindowTitle("Heaps");
//mHeapsTable->setContextMenuPolicy(Qt::CustomContextMenu);
mHeapsTable->addColumnAt(sizeof(duint) * 2, tr("Address"));
mHeapsTable->addColumnAt(sizeof(duint) * 2, tr("Size"));
mHeapsTable->addColumnAt(20, tr("Flags"));
mHeapsTable->addColumnAt(50, tr("Comments"));
*/
mPrivilegesTable = new StdTable(this);
mPrivilegesTable->setWindowTitle("Privileges");
mPrivilegesTable->setDrawDebugOnly(true);
mPrivilegesTable->setDisassemblyPopupEnabled(false);
mPrivilegesTable->setContextMenuPolicy(Qt::CustomContextMenu);
mPrivilegesTable->addColumnAt(8 + 32 * wCharWidth, tr("Privilege"), true);
mPrivilegesTable->addColumnAt(8 + 16 * wCharWidth, tr("State"), true);
mPrivilegesTable->loadColumnFromConfig("Privilege");
// Splitter
mSplitter = new LabeledSplitter(this);
mSplitter->addWidget(mWindowsTable, tr("Windows"));
mSplitter->addWidget(mHandlesTable, tr("Handles"));
//mSplitter->addWidget(mHeapsTable, tr("Heaps"));
mSplitter->addWidget(mTcpConnectionsTable, tr("TCP Connections"));
mSplitter->addWidget(mPrivilegesTable, tr("Privileges"));
mSplitter->collapseLowerTabs();
// Layout
mVertLayout = new QVBoxLayout;
mVertLayout->setSpacing(0);
mVertLayout->setContentsMargins(0, 0, 0, 0);
mVertLayout->addWidget(mSplitter);
this->setLayout(mVertLayout);
mSplitter->loadFromConfig("HandlesViewSplitter");
// Create the action list for the right click context menu
mActionRefresh = new QAction(DIcon("arrow-restart"), tr("&Refresh"), this);
connect(mActionRefresh, SIGNAL(triggered()), this, SLOT(reloadData()));
addAction(mActionRefresh);
mActionCloseHandle = new QAction(DIcon("disable"), tr("Close handle"), this);
connect(mActionCloseHandle, SIGNAL(triggered()), this, SLOT(closeHandleSlot()));
mActionDisablePrivilege = new QAction(DIcon("disable"), tr("Disable Privilege: "), this);
connect(mActionDisablePrivilege, SIGNAL(triggered()), this, SLOT(disablePrivilegeSlot()));
mActionEnablePrivilege = new QAction(DIcon("enable"), tr("Enable Privilege: "), this);
connect(mActionEnablePrivilege, SIGNAL(triggered()), this, SLOT(enablePrivilegeSlot()));
mActionDisableAllPrivileges = new QAction(DIcon("disable"), tr("Disable all privileges"), this);
connect(mActionDisableAllPrivileges, SIGNAL(triggered()), this, SLOT(disableAllPrivilegesSlot()));
mActionEnableAllPrivileges = new QAction(DIcon("enable"), tr("Enable all privileges"), this);
connect(mActionEnableAllPrivileges, SIGNAL(triggered()), this, SLOT(enableAllPrivilegesSlot()));
mActionEnableWindow = new QAction(DIcon("enable"), tr("Enable window"), this);
connect(mActionEnableWindow, SIGNAL(triggered()), this, SLOT(enableWindowSlot()));
mActionDisableWindow = new QAction(DIcon("disable"), tr("Disable window"), this);
connect(mActionDisableWindow, SIGNAL(triggered()), this, SLOT(disableWindowSlot()));
mActionFollowProc = new QAction(DIcon(ArchValue("processor32", "processor64")), tr("Follow Proc in Disassembler"), this);
connect(mActionFollowProc, SIGNAL(triggered()), this, SLOT(followInDisasmSlot()));
mActionFollowProc->setShortcut(Qt::Key_Return);
mWindowsTable->addAction(mActionFollowProc);
mActionToggleProcBP = new QAction(DIcon("breakpoint_toggle"), tr("Toggle Breakpoint in Proc"), this);
connect(mActionToggleProcBP, SIGNAL(triggered()), this, SLOT(toggleBPSlot()));
mWindowsTable->addAction(mActionToggleProcBP);
mActionMessageProcBP = new QAction(DIcon("breakpoint_execute"), tr("Message Breakpoint"), this);
connect(mActionMessageProcBP, SIGNAL(triggered()), this, SLOT(messagesBPSlot()));
connect(mHandlesTable, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(handlesTableContextMenuSlot(QMenu*)));
connect(mWindowsTable, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(windowsTableContextMenuSlot(QMenu*)));
connect(mTcpConnectionsTable, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(tcpConnectionsTableContextMenuSlot(QMenu*)));
connect(mPrivilegesTable, SIGNAL(contextMenuSignal(const QPoint &)), this, SLOT(privilegesTableContextMenuSlot(const QPoint &)));
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcuts()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChanged(DBGSTATE)));
if(!IsWindowsVistaOrGreater())
{
mTcpConnectionsTable->setRowCount(1);
mTcpConnectionsTable->setCellContent(0, 0, tr("TCP Connection enumeration is only available on Windows Vista or greater."));
mTcpConnectionsTable->reloadData();
}
mWindowsTable->setAccessibleName(tr("Windows"));
mHandlesTable->setAccessibleName(tr("Handles"));
mTcpConnectionsTable->setAccessibleName(tr("TCP Connections"));
mPrivilegesTable->setAccessibleName(tr("Privileges"));
reloadData();
refreshShortcuts();
}
void HandlesView::reloadData()
{
if(DbgIsDebugging())
{
enumHandles();
enumWindows();
enumTcpConnections();
//enumHeaps();
enumPrivileges();
}
else
{
mHandlesTable->setRowCount(0);
mHandlesTable->reloadData();
mWindowsTable->setRowCount(0);
mWindowsTable->reloadData();
mTcpConnectionsTable->setRowCount(0);
mTcpConnectionsTable->reloadData();
//mHeapsTable->setRowCount(0);
//mHeapsTable->reloadData();
mPrivilegesTable->setRowCount(0);
mPrivilegesTable->reloadData();
}
}
void HandlesView::refreshShortcuts()
{
mActionRefresh->setShortcut(ConfigShortcut("ActionRefresh"));
mActionToggleProcBP->setShortcut(ConfigShortcut("ActionToggleBreakpoint"));
}
void HandlesView::dbgStateChanged(DBGSTATE state)
{
if(state == stopped)
reloadData();
}
void HandlesView::handlesTableContextMenuSlot(QMenu* wMenu)
{
if(!DbgIsDebugging())
return;
auto & table = *mHandlesTable->mCurList;
wMenu->addAction(mActionRefresh);
if(table.getRowCount())
wMenu->addAction(mActionCloseHandle);
}
void HandlesView::windowsTableContextMenuSlot(QMenu* wMenu)
{
if(!DbgIsDebugging())
return;
auto & table = *mWindowsTable->mCurList;
wMenu->addAction(mActionRefresh);
if(table.getRowCount())
{
if(table.getCellContent(table.getInitialSelection(), 9) == tr("Enabled"))
{
mActionDisableWindow->setText(tr("Disable window"));
wMenu->addAction(mActionDisableWindow);
}
else
{
mActionEnableWindow->setText(tr("Enable window"));
wMenu->addAction(mActionEnableWindow);
}
wMenu->addAction(mActionFollowProc);
wMenu->addAction(mActionToggleProcBP);
wMenu->addAction(mActionMessageProcBP);
}
}
void HandlesView::tcpConnectionsTableContextMenuSlot(QMenu* wMenu)
{
if(!DbgIsDebugging())
return;
wMenu->addAction(mActionRefresh);
}
void HandlesView::privilegesTableContextMenuSlot(const QPoint & pos)
{
if(!DbgIsDebugging())
return;
StdTable & table = *mPrivilegesTable;
QMenu wMenu;
bool isValid = (table.getRowCount() != 0 && table.getCellContent(table.getInitialSelection(), 1) != tr("Unknown"));
wMenu.addAction(mActionRefresh);
if(isValid)
{
if(table.getCellContent(table.getInitialSelection(), 1) == tr("Enabled"))
{
mActionDisablePrivilege->setText(tr("Disable Privilege: ") + table.getCellContent(table.getInitialSelection(), 0));
wMenu.addAction(mActionDisablePrivilege);
}
else
{
mActionEnablePrivilege->setText(tr("Enable Privilege: ") + table.getCellContent(table.getInitialSelection(), 0));
wMenu.addAction(mActionEnablePrivilege);
}
}
wMenu.addAction(mActionDisableAllPrivileges);
wMenu.addAction(mActionEnableAllPrivileges);
QMenu wCopyMenu(tr("&Copy"), this);
wCopyMenu.setIcon(DIcon("copy"));
table.setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
{
wMenu.addSeparator();
wMenu.addMenu(&wCopyMenu);
}
wMenu.exec(table.mapToGlobal(pos));
}
void HandlesView::closeHandleSlot()
{
DbgCmdExecDirect(QString("handleclose %1").arg(mHandlesTable->mCurList->getCellContent(mHandlesTable->mCurList->getInitialSelection(), 2)));
enumHandles();
}
void HandlesView::enablePrivilegeSlot()
{
DbgCmdExecDirect(QString("EnablePrivilege \"%1\"").arg(mPrivilegesTable->getCellContent(mPrivilegesTable->getInitialSelection(), 0)));
enumPrivileges();
}
void HandlesView::disablePrivilegeSlot()
{
if(!DbgIsDebugging())
return;
DbgCmdExecDirect(QString("DisablePrivilege \"%1\"").arg(mPrivilegesTable->getCellContent(mPrivilegesTable->getInitialSelection(), 0)));
enumPrivileges();
}
void HandlesView::enableAllPrivilegesSlot()
{
if(!DbgIsDebugging())
return;
for(int i = 0; i < mPrivilegesTable->getRowCount(); i++)
if(mPrivilegesTable->getCellContent(i, 1) != tr("Unknown"))
DbgCmdExecDirect(QString("EnablePrivilege \"%1\"").arg(mPrivilegesTable->getCellContent(i, 0)));
enumPrivileges();
}
void HandlesView::disableAllPrivilegesSlot()
{
if(!DbgIsDebugging())
return;
for(int i = 0; i < mPrivilegesTable->getRowCount(); i++)
if(mPrivilegesTable->getCellContent(i, 1) != tr("Unknown"))
DbgCmdExecDirect(QString("DisablePrivilege \"%1\"").arg(mPrivilegesTable->getCellContent(i, 0)));
enumPrivileges();
}
void HandlesView::enableWindowSlot()
{
DbgCmdExecDirect(QString("EnableWindow %1").arg(mWindowsTable->mCurList->getCellContent(mWindowsTable->mCurList->getInitialSelection(), 1)));
enumWindows();
}
void HandlesView::disableWindowSlot()
{
DbgCmdExecDirect(QString("DisableWindow %1").arg(mWindowsTable->mCurList->getCellContent(mWindowsTable->mCurList->getInitialSelection(), 1)));
enumWindows();
}
void HandlesView::followInDisasmSlot()
{
DbgCmdExec(QString("disasm %1").arg(mWindowsTable->mCurList->getCellContent(mWindowsTable->mCurList->getInitialSelection(), 0)));
}
void HandlesView::toggleBPSlot()
{
auto & mCurList = *mWindowsTable->mCurList;
if(!DbgIsDebugging())
return;
if(!mCurList.getRowCount())
return;
QString addrText = mCurList.getCellContent(mCurList.getInitialSelection(), 0).toUtf8().constData();
duint wVA;
if(!DbgFunctions()->ValFromString(addrText.toUtf8().constData(), &wVA))
return;
if(!DbgMemIsValidReadPtr(wVA))
return;
BPXTYPE wBpType = DbgGetBpxTypeAt(wVA);
QString wCmd;
if((wBpType & bp_normal) == bp_normal)
wCmd = "bc " + ToPtrString(wVA);
else if(wBpType == bp_none)
wCmd = "bp " + ToPtrString(wVA);
DbgCmdExecDirect(wCmd);
}
void HandlesView::messagesBPSlot()
{
auto & mCurList = *mWindowsTable->mCurList;
MessagesBreakpoints::MsgBreakpointData mbpData;
if(!mCurList.getRowCount())
return;
mbpData.wndHandle = mCurList.getCellContent(mCurList.getInitialSelection(), 1).toUtf8().constData();
mbpData.procVA = mCurList.getCellContent(mCurList.getInitialSelection(), 0).toUtf8().constData();
MessagesBreakpoints messagesBPDialog(mbpData, this);
messagesBPDialog.exec();
}
//Enum functions
//Enumerate handles and update handles table
void HandlesView::enumHandles()
{
BridgeList<HANDLEINFO> handles;
if(DbgFunctions()->EnumHandles(&handles))
{
auto count = handles.Count();
mHandlesTable->setRowCount(count);
for(auto i = 0; i < count; i++)
{
const HANDLEINFO & handle = handles[i];
char name[MAX_STRING_SIZE] = "";
char typeName[MAX_STRING_SIZE] = "";
DbgFunctions()->GetHandleName(handle.Handle, name, sizeof(name), typeName, sizeof(typeName));
mHandlesTable->setCellContent(i, 0, typeName);
mHandlesTable->setCellContent(i, 1, ToHexString(handle.TypeNumber));
mHandlesTable->setCellContent(i, 2, ToHexString(handle.Handle));
mHandlesTable->setCellContent(i, 3, ToHexString(handle.GrantedAccess));
mHandlesTable->setCellContent(i, 4, name);
}
}
else
mHandlesTable->setRowCount(0);
mHandlesTable->reloadData();
// refresh values also when in mSearchList
mHandlesTable->refreshSearchList();
}
static QIcon getWindowIcon(HWND hWnd)
{
HICON winIcon;
if(IsWindowUnicode(hWnd))
{
//Some windows only return an icon via WM_GETICON, but SendMessage is generally unsafe
//if(SendMessageTimeoutW(hWnd, WM_GETICON, 0, 0, SMTO_ABORTIFHUNG | SMTO_BLOCK | SMTO_ERRORONEXIT, 500, (PDWORD)&winIcon) == 0)
winIcon = (HICON)GetClassLongPtrW(hWnd, -14); //GCL_HICON
}
else
{
//if(SendMessageTimeoutA(hWnd, WM_GETICON, 0, 0, SMTO_ABORTIFHUNG | SMTO_BLOCK | SMTO_ERRORONEXIT, 500, (PDWORD)&winIcon) == 0)
winIcon = (HICON)GetClassLongPtrA(hWnd, -14); //GCL_HICON
}
QIcon result;
if(winIcon != 0)
{
result = QIcon(QtWin::fromHICON(winIcon));
DestroyIcon(winIcon);
}
return result;
}
//Enumerate windows and update windows table
void HandlesView::enumWindows()
{
BridgeList<WINDOW_INFO> windows;
if(DbgFunctions()->EnumWindows(&windows))
{
auto count = windows.Count();
mWindowsTable->setRowCount(count);
for(auto i = 0; i < count; i++)
{
mWindowsTable->setCellContent(i, 0, ToPtrString(windows[i].wndProc));
mWindowsTable->setCellContent(i, 1, ToHexString(windows[i].handle));
mWindowsTable->setCellContent(i, 2, QString(windows[i].windowTitle));
mWindowsTable->setCellContent(i, 3, QString(windows[i].windowClass));
char threadname[MAX_THREAD_NAME_SIZE];
if(DbgFunctions()->ThreadGetName(windows[i].threadId, threadname) && *threadname != '\0')
mWindowsTable->setCellContent(i, 4, QString::fromUtf8(threadname));
else if(Config()->getBool("Gui", "PidTidInHex"))
mWindowsTable->setCellContent(i, 4, ToHexString(windows[i].threadId));
else
mWindowsTable->setCellContent(i, 4, QString::number(windows[i].threadId));
//Style
mWindowsTable->setCellContent(i, 5, ToHexString(windows[i].style));
//StyleEx
mWindowsTable->setCellContent(i, 6, ToHexString(windows[i].styleEx));
mWindowsTable->setCellContent(i, 7, ToHexString(windows[i].parent) + (windows[i].parent == ((duint)GetDesktopWindow()) ? tr(" (Desktop window)") : ""));
//Size
QString sizeText = QString("(%1,%2);%3x%4").arg(windows[i].position.left).arg(windows[i].position.top)
.arg(windows[i].position.right - windows[i].position.left).arg(windows[i].position.bottom - windows[i].position.top);
mWindowsTable->setCellContent(i, 8, sizeText);
mWindowsTable->setCellContent(i, 9, windows[i].enabled != FALSE ? tr("Enabled") : tr("Disabled"));
mWindowsTable->setRowIcon(i, getWindowIcon((HWND)windows[i].handle));
}
}
else
mWindowsTable->setRowCount(0);
mWindowsTable->reloadData();
// refresh values also when in mSearchList
mWindowsTable->refreshSearchList();
}
//Enumerate privileges and update privileges table
void HandlesView::enumPrivileges()
{
const char* PrivilegeString[] = {"SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
"SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
"SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege",
"SeIncreaseBasePriorityPrivilege", "SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege",
"SeLoadDriverPrivilege", "SeLockMemoryPrivilege", "SeMachineAccountPrivilege",
"SeManageVolumePrivilege", "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege",
"SeRemoteShutdownPrivilege", "SeRestorePrivilege", "SeSecurityPrivilege",
"SeShutdownPrivilege", "SeSyncAgentPrivilege", "SeSystemEnvironmentPrivilege",
"SeSystemProfilePrivilege", "SeSystemtimePrivilege", "SeTakeOwnershipPrivilege",
"SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege"
};
mPrivilegesTable->setRowCount(_countof(PrivilegeString));
for(int row = 0; row < _countof(PrivilegeString); row++)
{
QString temp(PrivilegeString[row]);
DbgCmdExecDirect(QString("GetPrivilegeState \"%1\"").arg(temp).toUtf8().constData());
mPrivilegesTable->setCellContent(row, 0, temp);
switch(DbgValFromString("$result"))
{
default:
temp = tr("Unknown");
break;
case 1:
temp = tr("Disabled");
break;
case 2:
case 3:
temp = tr("Enabled");
break;
}
mPrivilegesTable->setCellContent(row, 1, temp);
}
mPrivilegesTable->reloadData();
}
//Enumerate TCP connections and update TCP connections table
void HandlesView::enumTcpConnections()
{
BridgeList<TCPCONNECTIONINFO> connections;
if(DbgFunctions()->EnumTcpConnections(&connections))
{
auto count = connections.Count();
mTcpConnectionsTable->setRowCount(count);
for(auto i = 0; i < count; i++)
{
const TCPCONNECTIONINFO & connection = connections[i];
auto remoteText = QString("%1:%2").arg(connection.RemoteAddress).arg(connection.RemotePort);
mTcpConnectionsTable->setCellContent(i, 0, remoteText);
auto localText = QString("%1:%2").arg(connection.LocalAddress).arg(connection.LocalPort);
mTcpConnectionsTable->setCellContent(i, 1, localText);
mTcpConnectionsTable->setCellContent(i, 2, connection.StateText);
}
}
else
mTcpConnectionsTable->setRowCount(0);
mTcpConnectionsTable->reloadData();
// refresh values also when in mSearchList
mTcpConnectionsTable->refreshSearchList();
}
/*
//Enumerate Heaps and update Heaps table
void HandlesView::enumHeaps()
{
BridgeList<HEAPINFO> heaps;
if(DbgFunctions()->EnumHeaps(&heaps))
{
auto count = heaps.Count();
mHeapsTable->setRowCount(count);
for(auto i = 0; i < count; i++)
{
const HEAPINFO & heap = heaps[i];
mHeapsTable->setCellContent(i, 0, ToPtrString(heap.addr));
mHeapsTable->setCellContent(i, 1, ToHexString(heap.size));
QString flagsText;
if(heap.flags == 0)
flagsText = " |"; //Always leave 2 characters to be removed
if(heap.flags & 1)
flagsText = "LF32_FIXED |";
if(heap.flags & 2)
flagsText += "LF32_FREE |";
if(heap.flags & 4)
flagsText += "LF32_MOVABLE |";
if(heap.flags & (~7))
flagsText += ToHexString(heap.flags & (~7)) + " |";
flagsText.chop(2); //Remove last 2 characters: " |"
mHeapsTable->setCellContent(i, 2, flagsText);
QString comment;
char commentUtf8[MAX_COMMENT_SIZE];
if(DbgGetCommentAt(heap.addr, commentUtf8))
comment = QString::fromUtf8(commentUtf8);
else
{
if(DbgGetStringAt(heap.addr, commentUtf8))
comment = QString::fromUtf8(commentUtf8);
}
mHeapsTable->setCellContent(i, 3, comment);
}
}
else
mHeapsTable->setRowCount(0);
mHeapsTable->reloadData();
}
*/ |
C/C++ | x64dbg-development/src/gui/Src/Gui/HandlesView.h | #pragma once
#include <QWidget>
#include "Imports.h"
class StdTable;
class ReferenceView;
class QVBoxLayout;
class LabeledSplitter;
class StdSearchListView;
class StdIconSearchListView;
class QMenu;
class HandlesView : public QWidget
{
Q_OBJECT
public:
explicit HandlesView(QWidget* parent = nullptr);
public slots:
void reloadData();
void refreshShortcuts();
void dbgStateChanged(DBGSTATE state);
void handlesTableContextMenuSlot(QMenu* wMenu);
void tcpConnectionsTableContextMenuSlot(QMenu* wMenu);
void windowsTableContextMenuSlot(QMenu*);
void privilegesTableContextMenuSlot(const QPoint & pos);
void closeHandleSlot();
void disablePrivilegeSlot();
void enablePrivilegeSlot();
void disableAllPrivilegesSlot();
void enableAllPrivilegesSlot();
void enableWindowSlot();
void disableWindowSlot();
void followInDisasmSlot();
void toggleBPSlot();
void messagesBPSlot();
private:
QVBoxLayout* mVertLayout;
LabeledSplitter* mSplitter;
StdSearchListView* mHandlesTable;
StdSearchListView* mTcpConnectionsTable;
StdIconSearchListView* mWindowsTable;
//ReferenceView* mHeapsTable;
StdTable* mPrivilegesTable;
QAction* mActionRefresh;
QAction* mActionCloseHandle;
QAction* mActionDisablePrivilege;
QAction* mActionEnablePrivilege;
QAction* mActionDisableAllPrivileges;
QAction* mActionEnableAllPrivileges;
QAction* mActionEnableWindow;
QAction* mActionDisableWindow;
QAction* mActionFollowProc;
QAction* mActionToggleProcBP;
QAction* mActionMessageProcBP;
void enumHandles();
void enumWindows();
void enumTcpConnections();
//void enumHeaps();
void enumPrivileges();
}; |
C++ | x64dbg-development/src/gui/Src/Gui/HexEditDialog.cpp | #include <QTextCodec>
#include <QCryptographicHash>
#include "Configuration.h"
#include "HexEditDialog.h"
#include "QHexEdit/QHexEdit.h"
#include "ui_HexEditDialog.h"
#include "Configuration.h"
#include "Bridge.h"
#include "CodepageSelectionDialog.h"
#include "LineEditDialog.h"
#ifndef AF_INET6
#define AF_INET6 23 // Internetwork Version 6
#endif //AF_INET6
typedef PCTSTR(__stdcall* INETNTOPW)(INT Family, PVOID pAddr, wchar_t* pStringBuf, size_t StringBufSize);
HexEditDialog::HexEditDialog(QWidget* parent) : QDialog(parent), ui(new Ui::HexEditDialog)
{
ui->setupUi(this);
ui->editCode->setFont(ConfigFont("HexEdit"));
setWindowFlags((windowFlags() & ~Qt::WindowContextHelpButtonHint) | Qt::WindowMaximizeButtonHint);
setModal(true); //modal window
//setup text fields
ui->lineEditAscii->setEncoding(QTextCodec::codecForName("System"));
ui->lineEditUnicode->setEncoding(QTextCodec::codecForName("UTF-16"));
ui->chkKeepSize->setChecked(ConfigBool("HexDump", "KeepSize"));
ui->chkEntireBlock->hide();
mDataInitialized = false;
stringEditorLock = false;
fallbackCodec = QTextCodec::codecForLocale();
//setup hex editor
mHexEdit = new QHexEdit(this);
mHexEdit->setEditFont(ConfigFont("HexEdit"));
mHexEdit->setHorizontalSpacing(6);
mHexEdit->setOverwriteMode(true);
ui->scrollArea->setWidget(mHexEdit);
mHexEdit->widget()->setFocus();
connect(mHexEdit, SIGNAL(dataChanged()), this, SLOT(dataChangedSlot()));
connect(mHexEdit, SIGNAL(dataEdited()), this, SLOT(dataEditedSlot()));
connect(ui->btnCodePage2, SIGNAL(clicked()), this, SLOT(on_btnCodepage_clicked()));
connect(ui->chkCRLF, SIGNAL(clicked()), this, SLOT(on_stringEditor_textChanged()));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateStyle()));
updateStyle();
updateCodepage();
//The following initialization code is from Data Copy Dialog.
mTypes[DataCByte] = FormatType { tr("C-Style BYTE (Hex)"), 16 };
mTypes[DataCWord] = FormatType { tr("C-Style WORD (Hex)"), 12 };
mTypes[DataCDword] = FormatType { tr("C-Style DWORD (Hex)"), 8 };
mTypes[DataCQword] = FormatType { tr("C-Style QWORD (Hex)"), 4 };
mTypes[DataCString] = FormatType { tr("C-Style String"), 1 };
mTypes[DataCUnicodeString] = FormatType { tr("C-Style Unicode String"), 1 };
mTypes[DataCShellcodeString] = FormatType { tr("C-Style Shellcode String"), 1 };
mTypes[DataASMByte] = FormatType { tr("ASM-Style BYTE (Hex)"), 16, "DB"};
mTypes[DataASMWord] = FormatType { tr("ASM-Style WORD (Hex)"), 12, "DW"};
mTypes[DataASMDWord] = FormatType { tr("ASM-Style DWORD (Hex)"), 8, "DD"};
mTypes[DataASMQWord] = FormatType { tr("ASM-Style QWORD (Hex)"), 4, "DQ"};
mTypes[DataASMString] = FormatType { tr("ASM-Style String"), 4 };
mTypes[DataPascalByte] = FormatType { tr("Pascal BYTE (Hex)"), 42 };
mTypes[DataPascalWord] = FormatType { tr("Pascal WORD (Hex)"), 21 };
mTypes[DataPascalDword] = FormatType { tr("Pascal DWORD (Hex)"), 10 };
mTypes[DataPascalQword] = FormatType { tr("Pascal QWORD (Hex)"), 5 };
mTypes[DataPython3Byte] = FormatType { tr("Python 3 BYTE (Hex)"), 1 };
mTypes[DataString] = FormatType { tr("String"), 1 };
mTypes[DataUnicodeString] = FormatType { tr("Unicode String"), 1 };
mTypes[DataUTF8String] = FormatType { tr("UTF8 String"), 1 };
mTypes[DataUCS4String] = FormatType { tr("UCS4 String"), 1 };
mTypes[DataHexStream] = FormatType { tr("Hex Stream"), 1 };
mTypes[DataGUID] = FormatType { tr("GUID"), 1 };
mTypes[DataIPv4] = FormatType { tr("IP Address (IPv4)"), 5 };
mTypes[DataIPv6] = FormatType { tr("IP Address (IPv6)"), 1 };
mTypes[DataBase64] = FormatType { tr("Base64"), 1 };
mTypes[DataMD5] = FormatType { "MD5", 1};
mTypes[DataSHA1] = FormatType { "SHA1", 1};
mTypes[DataSHA256] = FormatType { "SHA256 (SHA-2)", 1};
mTypes[DataSHA512] = FormatType { "SHA512 (SHA-2)", 1};
mTypes[DataSHA256_3] = FormatType { "SHA256 (SHA-3)", 1};
mTypes[DataSHA512_3] = FormatType { "SHA512 (SHA-3)", 1};
for(int i = 0; i < DataLast; i++)
ui->listType->addItem(mTypes[i].name);
duint lastDataType = ConfigUint("HexDump", "CopyDataType");
lastDataType = std::min(lastDataType, static_cast<duint>(ui->listType->count() - 1));
QModelIndex index = ui->listType->model()->index(lastDataType, 0);
ui->listType->setCurrentIndex(index);
Config()->loadWindowGeometry(this);
}
HexEditDialog::~HexEditDialog()
{
Config()->saveWindowGeometry(this);
delete ui;
}
void HexEditDialog::showEntireBlock(bool show, bool checked)
{
ui->chkEntireBlock->setVisible(show);
ui->chkEntireBlock->setChecked(checked);
}
void HexEditDialog::showKeepSize(bool show)
{
ui->chkKeepSize->setVisible(show);
}
void HexEditDialog::isDataCopiable(bool copyDataEnabled)
{
if(copyDataEnabled == false)
ui->tabModeSelect->removeTab(2); //This can't be undone!
}
void HexEditDialog::updateCodepage()
{
duint lastCodepage;
auto allCodecs = QTextCodec::availableCodecs();
if(!BridgeSettingGetUint("Misc", "LastCodepage", &lastCodepage) || lastCodepage >= duint(allCodecs.size()))
lastCodec = fallbackCodec;
else
lastCodec = QTextCodec::codecForName(allCodecs.at(lastCodepage));
ui->lineEditCodepage->setEncoding(lastCodec);
ui->lineEditCodepage->setData(mHexEdit->data());
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(mHexEdit->data()));
ui->labelLastCodepage->setText(lastCodec->name().constData());
ui->labelLastCodepage2->setText(ui->labelLastCodepage->text());
}
void HexEditDialog::updateCodepage(const QByteArray & name)
{
lastCodec = QTextCodec::codecForName(name);
if(!lastCodec)
lastCodec = fallbackCodec;
ui->lineEditCodepage->setEncoding(lastCodec);
ui->lineEditCodepage->setData(mHexEdit->data());
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(mHexEdit->data()));
ui->labelLastCodepage->setText(QString(name));
ui->labelLastCodepage2->setText(ui->labelLastCodepage->text());
}
bool HexEditDialog::entireBlock()
{
return ui->chkEntireBlock->isChecked();
}
void HexEditDialog::updateStyle()
{
QString style = QString("QLineEdit { border-style: outset; border-width: 1px; border-color: %1; color: %1; background-color: %2 }").arg(ConfigColor("HexEditTextColor").name(), ConfigColor("HexEditBackgroundColor").name());
ui->lineEditAscii->setStyleSheet(style);
ui->lineEditUnicode->setStyleSheet(style);
ui->lineEditCodepage->setStyleSheet(style);
mHexEdit->setTextColor(ConfigColor("HexEditTextColor"));
mHexEdit->setWildcardColor(ConfigColor("HexEditWildcardColor"));
mHexEdit->setBackgroundColor(ConfigColor("HexEditBackgroundColor"));
mHexEdit->setSelectionColor(ConfigColor("HexEditSelectionColor"));
}
void HexEditDialog::on_chkKeepSize_toggled(bool checked)
{
if(!this->isVisible())
return;
mHexEdit->setKeepSize(checked);
ui->lineEditAscii->setKeepSize(checked);
ui->lineEditUnicode->setKeepSize(checked);
ui->lineEditCodepage->setKeepSize(checked);
Config()->setBool("HexDump", "KeepSize", checked);
}
void HexEditDialog::dataChangedSlot()
{
// Allows initialization of the data by calling setData() on mHexEdit.
if(!mDataInitialized)
{
QByteArray data = mHexEdit->data();
ui->lineEditAscii->setData(data);
ui->lineEditUnicode->setData(data);
ui->lineEditCodepage->setData(data);
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(data));
checkDataRepresentable(0);
printData((DataType)ui->listType->currentIndex().row());
mDataInitialized = true;
}
}
void HexEditDialog::dataEditedSlot()
{
QByteArray data = mHexEdit->data();
ui->lineEditAscii->setData(data);
ui->lineEditUnicode->setData(data);
ui->lineEditCodepage->setData(data);
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(data));
printData((DataType)ui->listType->currentIndex().row());
checkDataRepresentable(0);
}
void HexEditDialog::on_lineEditAscii_dataEdited()
{
QByteArray data = ui->lineEditAscii->data();
data = resizeData(data);
ui->lineEditUnicode->setData(data);
ui->lineEditCodepage->setData(data);
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(data));
printData((DataType)ui->listType->currentIndex().row());
mHexEdit->setData(data);
}
void HexEditDialog::on_lineEditUnicode_dataEdited()
{
QByteArray data = ui->lineEditUnicode->data();
data = resizeData(data);
ui->lineEditAscii->setData(data);
ui->lineEditCodepage->setData(data);
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(data));
printData((DataType)ui->listType->currentIndex().row());
mHexEdit->setData(data);
}
void HexEditDialog::on_stringEditor_textChanged() //stack overflow?
{
if(stringEditorLock || ui->tabModeSelect->currentIndex() != 1) return;
stringEditorLock = true;
QTextCodec::ConverterState converter(QTextCodec::IgnoreHeader); //Don't add BOM for UTF-16
QString text = ui->stringEditor->document()->toPlainText();
if(ui->chkCRLF->checkState() == Qt::Checked)
{
text = text.replace(QChar('\n'), "\r\n");
text = text.replace("\r\r\n", "\r\n");
}
QByteArray data = lastCodec->fromUnicode(text.constData(), text.size(), &converter);
data = resizeData(data);
ui->lineEditAscii->setData(data);
ui->lineEditUnicode->setData(data);
ui->lineEditCodepage->setData(data);
printData((DataType)ui->listType->currentIndex().row());
mHexEdit->setData(data);
stringEditorLock = false;
}
void HexEditDialog::on_lineEditCodepage_dataEdited()
{
QByteArray data = ui->lineEditCodepage->data();
data = resizeData(data);
ui->lineEditAscii->setData(data);
ui->lineEditUnicode->setData(data);
ui->stringEditor->document()->setPlainText(lastCodec->toUnicode(data));
mHexEdit->setData(data);
}
QByteArray HexEditDialog::resizeData(QByteArray & data)
{
// truncate or pad the data
if(mHexEdit->keepSize())
{
int dataSize = mHexEdit->data().size();
int data_size = data.size();
if(dataSize < data_size)
data.resize(dataSize);
else if(dataSize > data_size)
data.append(QByteArray(dataSize - data_size, 0));
}
return data;
}
void HexEditDialog::on_btnCodepage_clicked()
{
CodepageSelectionDialog codepageDialog(this);
if(codepageDialog.exec() != QDialog::Accepted)
return;
stringEditorLock = true;
updateCodepage(codepageDialog.getSelectedCodepage());
checkDataRepresentable(3);
checkDataRepresentable(4);
stringEditorLock = false;
}
bool HexEditDialog::checkDataRepresentable(int mode)
{
QTextCodec* codec;
QLabel* label;
if(mode == 1)
{
codec = QTextCodec::codecForName("System");
label = ui->labelWarningCodepageASCII;
}
else if(mode == 2)
{
codec = QTextCodec::codecForName("UTF-16");
label = ui->labelWarningCodepageUTF;
}
else if(mode == 3)
{
codec = lastCodec;
label = ui->labelWarningCodepage;
}
else if(mode == 4)
{
codec = lastCodec;
label = ui->labelWarningCodepageString;
}
else
{
bool isRepresentable;
isRepresentable = checkDataRepresentable(1);
isRepresentable = checkDataRepresentable(2) && isRepresentable;
isRepresentable = checkDataRepresentable(3) && isRepresentable;
isRepresentable = checkDataRepresentable(4) && isRepresentable;
return isRepresentable;
}
if(codec == nullptr)
{
label->show();
return false;
}
QString test;
QByteArray original = mHexEdit->data();
QTextCodec::ConverterState converter(QTextCodec::IgnoreHeader);
test = codec->toUnicode(original);
QByteArray test2;
test2 = codec->fromUnicode(test.constData(), test.size(), &converter);
if(test2.size() < original.size() || memcmp(test2.constData(), original.constData(), original.size()) != 0)
{
label->show();
return false;
}
else
{
label->hide();
return true;
}
}
//The following code is from Data Copy Dialog.
static QString printEscapedString(bool & bPrevWasHex, int ch, const char* hexFormat)
{
QString data = "";
switch(ch) //escaping
{
case '\t':
data = "\\t";
bPrevWasHex = false;
break;
case '\f':
data = "\\f";
bPrevWasHex = false;
break;
case '\v':
data = "\\v";
bPrevWasHex = false;
break;
case '\n':
data = "\\n";
bPrevWasHex = false;
break;
case '\r':
data = "\\r";
bPrevWasHex = false;
break;
case '\\':
data = "\\\\";
bPrevWasHex = false;
break;
case '\"':
data = "\\\"";
bPrevWasHex = false;
break;
case '\a':
data = "\\a";
bPrevWasHex = false;
break;
case '\b':
data = "\\b";
bPrevWasHex = false;
break;
default:
if(ch >= ' ' && ch <= '~')
{
if(bPrevWasHex && isxdigit(ch))
data = QString().sprintf("\"\"%c", ch);
else
data = QString().sprintf("%c", ch);
bPrevWasHex = false;
}
else
{
bPrevWasHex = true;
data = QString().sprintf(hexFormat, ch);
}
break;
}
return data;
}
template<typename T>
static QString formatLoop(const QByteArray & bytes, const HexEditDialog::FormatType & type, QString(*format)(T))
{
QString data;
int count = bytes.size() / sizeof(T);
for(int i = 0; i < count; i++)
{
if(i)
{
data += ',';
if(type.itemsPerLine > 0 && i % type.itemsPerLine == 0)
{
data += '\n';
data += type.linePrefix;
data += ' ';
}
else
{
data += ' ';
}
}
data += format(((const T*)bytes.constData())[i]);
}
return data;
}
static QString printHash(const QByteArray & bytes, QCryptographicHash::Algorithm algorithm)
{
QCryptographicHash temp(algorithm);
temp.addData((const char*)bytes.constData(), bytes.size());
return temp.result().toHex().toUpper();
}
void HexEditDialog::printData(DataType type)
{
ui->editCode->clear();
QString data;
QByteArray mData = mHexEdit->data();
switch(type)
{
case DataCByte:
{
data = "{\n" + formatLoop<unsigned char>(mData, mTypes[mIndex], [](unsigned char n)
{
return QString().sprintf("0x%02X", n);
}) + "\n};";
}
break;
case DataCWord:
{
data = "{\n" + formatLoop<unsigned short>(mData, mTypes[mIndex], [](unsigned short n)
{
return QString().sprintf("0x%04X", n);
}) + "\n};";
}
break;
case DataCDword:
{
data = "{\n" + formatLoop<unsigned int>(mData, mTypes[mIndex], [](unsigned int n)
{
return QString().sprintf("0x%08X", n);
}) + "\n};";
}
break;
case DataCQword:
{
data = "{\n" + formatLoop<unsigned long long>(mData, mTypes[mIndex], [](unsigned long long n)
{
return QString().sprintf("0x%016llX", n);
}) + "\n};";
}
break;
case DataCString:
{
data += "\"";
bool bPrevWasHex = false;
for(int i = 0; i < mData.size(); i++)
{
byte_t ch = mData.at(i);
data += printEscapedString(bPrevWasHex, ch, "\\x%02X");
}
data += "\"";
}
break;
case DataCUnicodeString: //extended ASCII + hex escaped only
{
data += "L\"";
int numwchars = mData.size() / sizeof(unsigned short);
bool bPrevWasHex = false;
for(int i = 0; i < numwchars; i++)
{
unsigned short ch = ((unsigned short*)mData.constData())[i];
if((ch & 0xFF00) == 0) //extended ASCII
{
data += printEscapedString(bPrevWasHex, ch, "\\x%04X");
}
else //full unicode character
{
bPrevWasHex = true;
data += QString().sprintf("\\x%04X", ch);
}
}
data += "\"";
}
break;
case DataCShellcodeString:
{
data += "\"";
for(int i = 0; i < mData.size(); i++)
{
byte_t ch = mData.at(i);
data += QString().sprintf("\\x%02X", ch);
}
data += "\"";
}
break;
case DataString:
{
data = QTextCodec::codecForName("System")->makeDecoder()->toUnicode((const char*)(mData.constData()), mData.size());
}
break;
case DataUnicodeString:
{
data = QString::fromUtf16((const ushort*)(mData.constData()), mData.size() / 2);
}
break;
case DataUTF8String:
{
data = QString::fromUtf8((const char*)mData.constData(), mData.size());
}
break;
case DataUCS4String:
{
data = QString::fromUcs4((const uint*)(mData.constData()), mData.size() / 4);
}
break;
case DataASMByte:
{
data = "array DB " + formatLoop<unsigned char>(mData, mTypes[mIndex], [](unsigned char n)
{
QString value = QString().sprintf("%02Xh", n);
if(value.at(0).isLetter())
value.insert(0, '0');
return value;
});
}
break;
case DataASMWord:
{
data = "array DW " + formatLoop<unsigned short>(mData, mTypes[mIndex], [](unsigned short n)
{
QString value = QString().sprintf("%04Xh", n);
if(value.at(0).isLetter())
value.insert(0, '0');
return value;
});
}
break;
case DataASMDWord:
{
data = "array DD " + formatLoop<unsigned int>(mData, mTypes[mIndex], [](unsigned int n)
{
QString value = QString().sprintf("%08Xh", n);
if(value.at(0).isLetter())
value.insert(0, '0');
return value;
});
}
break;
case DataASMQWord:
{
data = "array DQ " + formatLoop<unsigned long long>(mData, mTypes[mIndex], [](unsigned long long n)
{
QString value = QString().sprintf("%016llXh", n);
if(value.at(0).isLetter())
value.insert(0, '0');
return value;
});
}
break;
case DataASMString:
{
QString line;
int index = 0;
bool bPrevWasHex = false;
while(index < mData.size())
{
QChar chr = QChar(mData.at(index));
if(chr >= ' ' && chr <= '~')
{
if(line.length() == 0)
line += "\"";
if(bPrevWasHex)
{
line += ",\"";
bPrevWasHex = false;
}
line += chr;
}
else
{
QString asmhex = QString().sprintf("%02Xh", (unsigned char)mData.at(index));
if(asmhex.at(0).isLetter())
asmhex.insert(0, "0");
if(line.length() == 0)
line += asmhex;
else if(!bPrevWasHex)
line += "\"," + asmhex;
else
line += "," + asmhex;
bPrevWasHex = true;
}
index++;
}
if(!bPrevWasHex)
line += "\"";
data = line;
}
break;
case DataPascalByte:
{
data += QString().sprintf("Array [1..%u] of Byte = (\n", mData.size());
data += formatLoop<unsigned char>(mData, mTypes[mIndex], [](unsigned char n)
{
return QString().sprintf("$%02X", n);
});
data += "\n);";
}
break;
case DataPascalWord:
{
data += QString().sprintf("Array [1..%u] of Word = (\n", mData.size() / 2);
data += formatLoop<unsigned short>(mData, mTypes[mIndex], [](unsigned short n)
{
return QString().sprintf("$%04X", n);
});
data += "\n);";
}
break;
case DataPascalDword:
{
data += QString().sprintf("Array [1..%u] of Dword = (\n", mData.size() / 4);
data += formatLoop<unsigned int>(mData, mTypes[mIndex], [](unsigned int n)
{
return QString().sprintf("$%08X", n);
});
data += "\n);";
}
break;
case DataPascalQword:
{
data += QString().sprintf("Array [1..%u] of Int64 = (\n", mData.size() / 8);
data += formatLoop<unsigned long long>(mData, mTypes[mIndex], [](unsigned long long n)
{
return QString().sprintf("$%016llX", n);
});
data += "\n);";
}
break;
case DataPython3Byte:
{
data += "b\"";
for(int i = 0; i < mData.size(); i++)
{
byte_t ch = mData.at(i);
data += QString().sprintf("\\x%02X", ch);
}
data += "\"";
}
break;
case DataHexStream:
{
for(int i = 0; i < mData.size(); i++)
{
byte_t ch = mData.at(i);
data += QString().sprintf("%02X", ch);
}
}
break;
case DataGUID:
{
data = formatLoop<GUID>(mData, mTypes[mIndex], [](GUID guid)
{
return QString().sprintf("{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
});
}
break;
case DataIPv4:
{
int numIPs = mData.size() / 4;
for(int i = 0; i < numIPs; i++)
{
if(i)
{
if((i % mTypes[mIndex].itemsPerLine) == 0)
data += "\n";
else
data += ", ";
}
data += QString("%1.%2.%3.%4").arg((unsigned char)(mData.constData()[i * 4])).arg((unsigned char)(mData.constData()[i * 4 + 1]))
.arg((unsigned char)(mData.constData()[i * 4 + 2])).arg((unsigned char)(mData.constData()[i * 4 + 3]));
}
}
break;
case DataIPv6:
{
INETNTOPW InetNtopW;
int numIPs = mData.size() / 16;
HMODULE hWinsock = LoadLibrary(L"ws2_32.dll");
InetNtopW = INETNTOPW(GetProcAddress(hWinsock, "InetNtopW"));
if(InetNtopW)
{
for(int i = 0; i < numIPs; i++)
{
if(i)
{
if((i % mTypes[mIndex].itemsPerLine) == 0)
data += "\n";
else
data += ", ";
}
wchar_t buffer[56];
memset(buffer, 0, sizeof(buffer));
InetNtopW(AF_INET6, const_cast<char*>(mData.constData() + i * 16), buffer, 56);
data += QString::fromWCharArray(buffer);
}
}
else //fallback for Windows XP
{
for(int i = 0; i < numIPs; i++)
{
if(i)
{
if((i % mTypes[mIndex].itemsPerLine) == 0)
data += "\n";
else
data += ", ";
}
QString temp(QByteArray(reinterpret_cast<const char*>(mData.constData() + i * 16), 16).toHex());
temp.insert(28, ':');
temp.insert(24, ':');
temp.insert(20, ':');
temp.insert(16, ':');
temp.insert(12, ':');
temp.insert(8, ':');
temp.insert(4, ':');
data += temp;
}
}
FreeLibrary(hWinsock);
}
break;
case DataBase64:
{
data = QByteArray(reinterpret_cast<const char*>(mData.constData()), mData.size()).toBase64().constData();
}
break;
case DataMD5:
data = printHash(mData, QCryptographicHash::Md5);
break;
case DataSHA1:
data = printHash(mData, QCryptographicHash::Sha1);
break;
case DataSHA256:
data = printHash(mData, QCryptographicHash::Sha256);
break;
case DataSHA512:
data = printHash(mData, QCryptographicHash::Sha512);
break;
case DataSHA256_3:
data = printHash(mData, QCryptographicHash::Sha3_256);
break;
case DataSHA512_3:
data = printHash(mData, QCryptographicHash::Sha3_512);
break;
}
ui->editCode->setPlainText(data);
}
void HexEditDialog::on_listType_currentRowChanged(int currentRow)
{
mIndex = currentRow;
ui->spinBox->setValue(mTypes[mIndex].itemsPerLine);
printData(DataType(mIndex));
Config()->setUint("HexDump", "CopyDataType", currentRow);
}
void HexEditDialog::on_buttonCopy_clicked()
{
Bridge::CopyToClipboard(ui->editCode->toPlainText());
}
void HexEditDialog::on_spinBox_valueChanged(int value)
{
mTypes[mIndex].itemsPerLine = value;
printData(DataType(mIndex));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/HexEditDialog.h | #pragma once
#include <QDialog>
#include "QHexEdit/QHexEdit.h"
namespace Ui
{
class HexEditDialog;
}
class HexEditDialog : public QDialog
{
Q_OBJECT
public:
explicit HexEditDialog(QWidget* parent = 0);
~HexEditDialog();
void showEntireBlock(bool show, bool checked = false);
void showKeepSize(bool show);
void isDataCopiable(bool copyDataEnabled);
void updateCodepage();
bool entireBlock();
QHexEdit* mHexEdit;
struct FormatType
{
QString name;
int itemsPerLine;
QString linePrefix;
};
private slots:
void updateStyle();
void on_chkKeepSize_toggled(bool checked);
void dataChangedSlot();
void dataEditedSlot();
void on_lineEditAscii_dataEdited();
void on_lineEditUnicode_dataEdited();
void on_lineEditCodepage_dataEdited();
void on_btnCodepage_clicked();
void on_stringEditor_textChanged();
private:
Ui::HexEditDialog* ui;
void updateCodepage(const QByteArray & name);
QTextCodec* lastCodec;
QTextCodec* fallbackCodec;
bool stringEditorLock;
bool mDataInitialized;
QByteArray resizeData(QByteArray & data);
bool checkDataRepresentable(int mode); //1=ASCII, 2=Unicode, 3=User-selected codepage, 4=String editor, others(0)=All modes
//The following code is from Data Copy Dialog
private slots:
void on_listType_currentRowChanged(int currentRow);
void on_buttonCopy_clicked();
void on_spinBox_valueChanged(int arg1);
private:
int mIndex;
enum DataType
{
DataCByte = 0,
DataCWord,
DataCDword,
DataCQword,
DataCString,
DataCUnicodeString,
DataCShellcodeString,
DataASMByte,
DataASMWord,
DataASMDWord,
DataASMQWord,
DataASMString,
DataPascalByte,
DataPascalWord,
DataPascalDword,
DataPascalQword,
DataPython3Byte,
DataString,
DataUnicodeString,
DataUTF8String,
DataUCS4String,
DataHexStream,
DataGUID,
DataIPv4,
DataIPv6,
DataBase64,
DataMD5,
DataSHA1,
DataSHA256,
DataSHA512,
DataSHA256_3,
DataSHA512_3,
DataLast
};
FormatType mTypes[DataLast];
void printData(DataType type);
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/HexEditDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>HexEditDialog</class>
<widget class="QDialog" name="HexEditDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>772</width>
<height>599</height>
</rect>
</property>
<property name="windowTitle">
<string>HexEdit</string>
</property>
<property name="windowIcon">
<iconset theme="document-binary" resource="../../resource.qrc">
<normaloff>:/Default/icons/document-binary.png</normaloff>:/Default/icons/document-binary.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QTabWidget" name="tabModeSelect">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabHexEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<attribute name="title">
<string>Hex</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QLabel" name="labelWarningCodepageASCII">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Warning: Data cannot be represented in selected codepage.</string>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="../../resource.qrc">:/Default/icons/fatal-error.png</pixmap>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelAscii">
<property name="text">
<string>ASCII</string>
</property>
<property name="buddy">
<cstring>lineEditAscii</cstring>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="HexLineEdit" name="lineEditAscii">
<property name="styleSheet">
<string notr="true">QLineEdit {border-style: outset; border-width: 1px; border-color: black}</string>
</property>
<property name="inputMask">
<string/>
</property>
<property name="maxLength">
<number>32767</number>
</property>
<property name="frame">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_7">
<item>
<widget class="QLabel" name="labelWarningCodepageUTF">
<property name="toolTip">
<string>Warning: Data cannot be represented in selected codepage.</string>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="../../resource.qrc">:/Default/icons/fatal-error.png</pixmap>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelUnicode">
<property name="text">
<string>&UNICODE:</string>
</property>
<property name="buddy">
<cstring>lineEditUnicode</cstring>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="HexLineEdit" name="lineEditUnicode">
<property name="styleSheet">
<string notr="true">QLineEdit {border-style: outset; border-width: 1px; border-color: black}</string>
</property>
<property name="inputMask">
<string/>
</property>
<property name="maxLength">
<number>32767</number>
</property>
<property name="frame">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="labelWarningCodepage">
<property name="toolTip">
<string>Warning: Data cannot be represented in selected codepage.</string>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="../../resource.qrc">:/Default/icons/fatal-error.png</pixmap>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelLastCodepage">
<property name="text">
<string>Last &Codepage:</string>
</property>
<property name="buddy">
<cstring>lineEditCodepage</cstring>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btnCodepage">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Code&page...</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="HexLineEdit" name="lineEditCodepage">
<property name="styleSheet">
<string notr="true">QLineEdit {border-style: outset; border-width: 1px; border-color: black}</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelHex">
<property name="text">
<string>&Hex:</string>
</property>
<property name="margin">
<number>0</number>
</property>
<property name="indent">
<number>20</number>
</property>
<property name="buddy">
<cstring>scrollArea</cstring>
</property>
</widget>
</item>
<item>
<widget class="QScrollArea" name="scrollArea">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>726</width>
<height>324</height>
</rect>
</property>
</widget>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabStringEditor">
<attribute name="title">
<string>String</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_6">
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="labelWarningCodepageString">
<property name="toolTip">
<string>Warning: Data cannot be represented in selected codepage.</string>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="../../resource.qrc">:/Default/icons/fatal-error.png</pixmap>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelLastCodepage2">
<property name="text">
<string>Last &Codepage:</string>
</property>
<property name="buddy">
<cstring>stringEditor</cstring>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btnCodePage2">
<property name="text">
<string>Code&page...</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkCRLF">
<property name="toolTip">
<string>Convert to Windows style line ending.</string>
</property>
<property name="text">
<string>CR LF</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPlainTextEdit" name="stringEditor"/>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabCopyData">
<attribute name="title">
<string>Copy data</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_7">
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QSplitter" name="splitter">
<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>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QListWidget" name="listType">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>20</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
<widget class="QPlainTextEdit" name="editCode">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>80</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QPushButton" name="buttonCopy">
<property name="text">
<string>Copy</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Items per line:</string>
</property>
<property name="buddy">
<cstring>spinBox</cstring>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinBox">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>256</number>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QCheckBox" name="chkKeepSize">
<property name="text">
<string>&Keep Size</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkEntireBlock">
<property name="text">
<string>&Entire Block</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btnOk">
<property name="text">
<string>&OK</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>HexLineEdit</class>
<extends>QLineEdit</extends>
<header>HexLineEdit.h</header>
</customwidget>
</customwidgets>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>HexEditDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>335</x>
<y>253</y>
</hint>
<hint type="destinationlabel">
<x>331</x>
<y>251</y>
</hint>
</hints>
</connection>
<connection>
<sender>btnOk</sender>
<signal>clicked()</signal>
<receiver>HexEditDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>252</x>
<y>251</y>
</hint>
<hint type="destinationlabel">
<x>238</x>
<y>251</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/HexLineEdit.cpp | #include <QTextCodec>
#include "Configuration.h"
#include "HexLineEdit.h"
#include "ui_HexLineEdit.h"
#include "Bridge.h"
#include <QKeyEvent>
HexLineEdit::HexLineEdit(QWidget* parent) :
QLineEdit(parent),
ui(new Ui::HexLineEdit)
{
ui->setupUi(this);
// setup data
mData = QByteArray();
mKeepSize = false;
mOverwriteMode = false;
mEncoding = QTextCodec::codecForName("System");
//setup text fields
QFont font("Monospace", 8, QFont::Normal, false);
font.setFixedPitch(true);
font.setStyleHint(QFont::Monospace);
setFont(font);
connect(this, SIGNAL(textEdited(const QString &)), this, SLOT(updateData(const QString &)));
}
HexLineEdit::~HexLineEdit()
{
delete ui;
}
void HexLineEdit::keyPressEvent(QKeyEvent* event)
{
// Switch between insert/overwrite mode
if(event->key() == Qt::Key_Insert && (event->modifiers() == Qt::NoModifier))
{
mOverwriteMode = !mOverwriteMode;
event->ignore();
return;
}
if(mOverwriteMode)
{
QString newText = event->text();
if(!newText.isEmpty() && newText.at(0).isPrint())
{
for(int i = 0; i < newText.size(); i++)
del();
QTextCodec::ConverterState converter(QTextCodec::IgnoreHeader);
insert(mEncoding->fromUnicode(newText.constData(), newText.size(), &converter));
event->ignore();
return;
}
}
QLineEdit::keyPressEvent(event);
}
void HexLineEdit::setData(const QByteArray & data)
{
QString text;
text = mEncoding->toUnicode(data);
mData = data;
setText(text);
}
QByteArray HexLineEdit::data()
{
return mData;
}
/**
* @brief HexLineEdit::setEncoding Set the encoding of the line edit.
* @param encoding The codec for the line edit.
* @remarks the parameter passed in will be managed by the widget. You must use a new codec.
*/
void HexLineEdit::setEncoding(QTextCodec* encoding)
{
mEncoding = encoding;
}
/**
* @brief HexLineEdit::encoding Get the encoding of the line edit.
* @return the codec instance of the line edit.
*/
QTextCodec* HexLineEdit::encoding()
{
return mEncoding;
}
void HexLineEdit::setKeepSize(const bool enabled)
{
mKeepSize = enabled;
if(enabled)
{
int dataSize = mData.size();
int charSize;
QTextCodec::ConverterState converter(QTextCodec::IgnoreHeader);
charSize = mEncoding->fromUnicode(QString("A").constData(), 1, &converter).size(); // "A\0"
setMaxLength((dataSize / charSize) + (dataSize % charSize));
}
else
{
setMaxLength(32767);
}
}
bool HexLineEdit::keepSize()
{
return mKeepSize;
}
void HexLineEdit::setOverwriteMode(bool overwriteMode)
{
mOverwriteMode = overwriteMode;
}
bool HexLineEdit::overwriteMode()
{
return mOverwriteMode;
}
void HexLineEdit::updateData(const QString & arg1)
{
Q_UNUSED(arg1);
mData = toEncodedData(text());
emit dataEdited();
}
QByteArray HexLineEdit::toEncodedData(const QString & text)
{
QTextCodec::ConverterState converter(QTextCodec::IgnoreHeader);
return mEncoding->fromUnicode(text.constData(), text.size(), &converter);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/HexLineEdit.h | #pragma once
#include <QLineEdit>
namespace Ui
{
class HexLineEdit;
}
class HexLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit HexLineEdit(QWidget* parent = 0);
~HexLineEdit();
void keyPressEvent(QKeyEvent* event);
void setData(const QByteArray & data);
QByteArray data();
void setEncoding(QTextCodec* encoding);
QTextCodec* encoding();
void setKeepSize(const bool enabled);
bool keepSize();
void setOverwriteMode(bool overwriteMode);
bool overwriteMode();
signals:
void dataEdited();
private slots:
void updateData(const QString & arg1);
private:
Ui::HexLineEdit* ui;
QByteArray mData;
QTextCodec* mEncoding;
bool mKeepSize;
bool mOverwriteMode;
QByteArray toEncodedData(const QString & text);
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/HexLineEdit.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>HexLineEdit</class>
<widget class="QLineEdit" name="HexLineEdit">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>361</width>
<height>20</height>
</rect>
</property>
<property name="widgetResizable" stdset="0">
<bool>true</bool>
</property>
</widget>
<resources/>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/LineEditDialog.cpp | #include "LineEditDialog.h"
#include "ui_LineEditDialog.h"
LineEditDialog::LineEditDialog(QWidget* parent) : QDialog(parent), ui(new Ui::LineEditDialog)
{
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true); //modal window
ui->checkBox->hide();
bChecked = false;
this->fixed_size = 0;
fpuMode = false;
ui->label->setVisible(false);
}
LineEditDialog::~LineEditDialog()
{
delete ui;
}
void LineEditDialog::selectAllText()
{
ui->textEdit->selectAll();
}
void LineEditDialog::setCursorPosition(int position)
{
ui->textEdit->setCursorPosition(position);
}
void LineEditDialog::ForceSize(unsigned int size)
{
this->fixed_size = size;
if(this->fixed_size)
ui->label->setVisible(true);
}
void LineEditDialog::setFpuMode()
{
fpuMode = true;
}
void LineEditDialog::setText(const QString & text)
{
editText = text;
ui->textEdit->setText(text);
ui->textEdit->selectAll();
}
void LineEditDialog::setPlaceholderText(const QString & text)
{
ui->textEdit->setPlaceholderText(text);
}
void LineEditDialog::enableCheckBox(bool bEnable)
{
if(bEnable)
ui->checkBox->show();
else
ui->checkBox->hide();
}
void LineEditDialog::setCheckBox(bool bSet)
{
ui->checkBox->setChecked(bSet);
bChecked = bSet;
}
void LineEditDialog::setCheckBoxText(const QString & text)
{
ui->checkBox->setText(text);
}
void LineEditDialog::on_textEdit_textEdited(const QString & arg1)
{
editText = arg1;
if(this->fixed_size != 0)
{
QString arg1Lower = arg1.toLower();
if(arg1.size() != this->fixed_size && (!fpuMode || !(arg1.contains(QChar('.')) || arg1Lower == "inf" || arg1Lower == "nan" || arg1Lower == "+inf" || arg1Lower == "-inf")))
//TODO: QNaN & SNaN
{
ui->buttonOk->setEnabled(false);
QString symbolct = "";
int ct = arg1.size() - (int) this->fixed_size;
if(ct > 0)
symbolct = "+";
ui->label->setText(tr("<font color='red'>CT: %1%2</font>").arg(symbolct).arg(ct));
}
else
{
ui->buttonOk->setEnabled(true);
ui->label->setText(QString(""));
}
}
}
void LineEditDialog::on_checkBox_toggled(bool checked)
{
bChecked = checked;
}
void LineEditDialog::setTextMaxLength(int length)
{
ui->textEdit->setMaxLength(length);
}
void LineEditDialog::on_buttonOk_clicked()
{
ui->textEdit->addLineToHistory(editText);
ui->textEdit->setText("");
accept();
}
void LineEditDialog::on_buttonCancel_clicked()
{
ui->textEdit->setText("");
close();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/LineEditDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class LineEditDialog;
}
class LineEditDialog : public QDialog
{
Q_OBJECT
public:
explicit LineEditDialog(QWidget* parent = 0);
~LineEditDialog();
QString editText;
bool bChecked;
void setText(const QString & text);
void setPlaceholderText(const QString & text);
void setTextMaxLength(int length);
void enableCheckBox(bool bEnable);
void setCheckBox(bool bSet);
void setCheckBoxText(const QString & text);
void setCursorPosition(int position);
void ForceSize(unsigned int size);
void setFpuMode();
void selectAllText();
private slots:
void on_textEdit_textEdited(const QString & arg1);
void on_checkBox_toggled(bool checked);
void on_buttonOk_clicked();
void on_buttonCancel_clicked();
private:
Ui::LineEditDialog* ui;
unsigned int fixed_size;
bool fpuMode;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/LineEditDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LineEditDialog</class>
<widget class="QDialog" name="LineEditDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>414</width>
<height>72</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</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="QHBoxLayout" name="horizontalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="HistoryLineEdit" name="textEdit"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="minimumSize">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox">
<property name="text">
<string>CheckBox</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="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>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>HistoryLineEdit</class>
<extends>QLineEdit</extends>
<header>HistoryLineEdit.h</header>
</customwidget>
</customwidgets>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/LocalVarsView.cpp | #include "LocalVarsView.h"
#include "zydis_wrapper.h"
#include "CPUMultiDump.h"
#include "MiscUtil.h"
#include "WordEditDialog.h"
#include "EncodeMap.h"
// Gets the address from an expression like "[EBP-7c]"
static bool getAddress(QString addrText, duint & output)
{
if(!(addrText.startsWith("[") && addrText.endsWith("]")))
return false; //Unable to get address of the expression
addrText.truncate(addrText.size() - 1);
addrText = addrText.right(addrText.size() - 1);
QByteArray utf8 = addrText.toUtf8();
if(!DbgIsValidExpression(utf8.constData()))
return false;
output = DbgValFromString(utf8.constData());
return true;
}
LocalVarsView::LocalVarsView(CPUMultiDump* parent) : StdTable(parent)
{
configUpdatedSlot();
int charWidth = getCharWidth();
addColumnAt(8 + 20 * charWidth, tr("Name"), true);
addColumnAt(8 + 10 * charWidth, tr("Expression"), true); //[EBP + 10]
addColumnAt(8 + 10 * charWidth, tr("Value"), true);
loadColumnFromConfig("LocalVarsView");
setupContextMenu();
connect(Bridge::getBridge(), SIGNAL(updateWatch()), this, SLOT(updateSlot()));
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(configUpdatedSlot()));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(editSlot()));
}
void LocalVarsView::setupContextMenu()
{
mMenu = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
mMenu->addAction(makeAction(DIcon("dump"), tr("&Follow in Dump"), SLOT(followDumpSlot())), [this](QMenu*)
{
return getCellContent(getInitialSelection(), 2) != "???";
});
mMenu->addAction(makeAction(DIcon("dump"), ArchValue(tr("Follow DWORD in Dump"), tr("Follow QWORD in Dump")), SLOT(followWordInDumpSlot())), [this](QMenu*)
{
duint start;
if(getAddress(getCellContent(getInitialSelection(), 1), start))
{
DbgMemRead(start, &start, sizeof(start));
return DbgMemIsValidReadPtr(start);
}
else
return false;
});
mMenu->addAction(makeShortcutAction(DIcon("stack"), tr("Follow in Stack"), SLOT(followStackSlot()), "ActionFollowStack"), [this](QMenu*)
{
duint start;
if(getAddress(getCellContent(getInitialSelection(), 1), start))
return (DbgMemIsValidReadPtr(start) && DbgMemFindBaseAddr(start, 0) == DbgMemFindBaseAddr(DbgValFromString("csp"), 0));
else
return false;
});
mMenu->addAction(makeAction(DIcon("stack"), ArchValue(tr("Follow DWORD in Stack"), tr("Follow QWORD in Stack")), SLOT(followWordInStackSlot())), [this](QMenu*)
{
duint start;
if(getAddress(getCellContent(getInitialSelection(), 1), start))
{
DbgMemRead(start, &start, sizeof(start));
return (DbgMemIsValidReadPtr(start) && DbgMemFindBaseAddr(start, 0) == DbgMemFindBaseAddr(DbgValFromString("csp"), 0));
}
else
return false;
});
mMenu->addAction(makeShortcutAction(DIcon("memmap_find_address_page"), tr("Follow in Memory Map"), SLOT(followMemMapSlot()), "ActionFollowMemMap"), [this](QMenu*)
{
return getCellContent(getInitialSelection(), 2) != "???";
});
mMenu->addAction(makeShortcutAction(DIcon("modify"), tr("&Modify Value"), SLOT(editSlot()), "ActionModifyValue"), [this](QMenu*)
{
return getCellContent(getInitialSelection(), 2) != "???";
});
mMenu->addSeparator();
mMenu->addAction(makeAction(tr("&Rename"), SLOT(renameSlot())));
MenuBuilder* copyMenu = new MenuBuilder(this);
setupCopyMenu(copyMenu);
mMenu->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
mMenu->addSeparator();
MenuBuilder* mBaseRegisters = new MenuBuilder(this);
#ifdef _WIN64
const char* baseRegisterNames[] = {"RAX", "BBX", "RCX", "RDX", "RBP", "RSP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"};
#else //x86
const char* baseRegisterNames[] = {"EAX", "EBX", "ECX", "EDX", "EBP", "ESP", "ESI", "EDI"};
#endif //_WIN64
for(unsigned int i = 0; i < _countof(baseRegisters); i++)
{
baseRegisters[i] = new QAction(baseRegisterNames[i], this);
connect(baseRegisters[i], SIGNAL(triggered()), this, SLOT(baseChangedSlot()));
baseRegisters[i]->setCheckable(true);
mBaseRegisters->addAction(baseRegisters[i]);
}
baseRegisters[4]->setChecked(true); //CBP
mMenu->addMenu(makeMenu(tr("Base Register")), mBaseRegisters);
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
}
void LocalVarsView::mousePressEvent(QMouseEvent* event)
{
if(event->buttons() == Qt::MiddleButton && getRowCount() > 0)
{
duint addr;
if(getAddress(getCellContent(getInitialSelection(), 1), addr))
Bridge::CopyToClipboard(ToPtrString(addr));
}
else
StdTable::mousePressEvent(event);
}
void LocalVarsView::contextMenuSlot(const QPoint & pos)
{
QMenu wMenu(this);
mMenu->build(&wMenu);
wMenu.exec(mapToGlobal(pos));
}
void LocalVarsView::baseChangedSlot()
{
currentFunc = 0;
updateSlot();
}
void LocalVarsView::configUpdatedSlot()
{
currentFunc = 0;
HexPrefixValues = Config()->getBool("Disassembler", "0xPrefixValues");
MemorySpaces = Config()->getBool("Disassembler", "MemorySpaces");
}
void LocalVarsView::updateSlot()
{
if(!DbgIsDebugging())
{
currentFunc = 0;
setRowCount(0);
reloadData();
return;
}
REGDUMP z;
DbgGetRegDumpEx(&z, sizeof(REGDUMP));
duint start, end;
if(DbgFunctionGet(z.regcontext.cip, &start, &end))
{
if(start != this->currentFunc) //needs analyzing
{
Zydis dis;
unsigned char* buffer = new unsigned char[end - start + 16];
if(!DbgMemRead(start, buffer, end - start + 16)) //failed to read memory for analyzing
{
delete[] buffer;
setRowCount(0);
return;
}
QSet<dsint> usedOffsets[ArchValue(8, 16)];
duint address = start;
while(address < end)
{
ENCODETYPE codeType = DbgGetEncodeTypeAt(address, 1);
if(!EncodeMap::isCode(codeType)) //Skip data bytes
{
address += DbgGetEncodeSizeAt(address, 1);
continue;
}
dis.Disassemble(address, buffer + address - start, end + 16 - address);
if(dis.IsNop()) //Skip junk instructions
{
address += dis.Size();
continue;
}
for(int i = 0; i < dis.OpCount(); i++)
{
if(dis[i].type != ZYDIS_OPERAND_TYPE_MEMORY)
continue;
if(dis[i].mem.base == ZYDIS_REGISTER_NONE) //mov eax, [10000000], global variable
continue;
if(dis[i].mem.index != ZYDIS_REGISTER_NONE) //mov eax, dword ptr ds:[ebp+ecx*4-10], indexed array
continue;
const ZydisRegister registers[] =
{
#ifdef _WIN64
ZYDIS_REGISTER_RAX, ZYDIS_REGISTER_RBX, ZYDIS_REGISTER_RCX, ZYDIS_REGISTER_RDX,
ZYDIS_REGISTER_RBP, ZYDIS_REGISTER_RSP, ZYDIS_REGISTER_RSI, ZYDIS_REGISTER_RDI,
ZYDIS_REGISTER_R8, ZYDIS_REGISTER_R9, ZYDIS_REGISTER_R10, ZYDIS_REGISTER_R11,
ZYDIS_REGISTER_R12, ZYDIS_REGISTER_R13, ZYDIS_REGISTER_R14, ZYDIS_REGISTER_R15
#else //x86
ZYDIS_REGISTER_EAX, ZYDIS_REGISTER_EBX, ZYDIS_REGISTER_ECX, ZYDIS_REGISTER_EDX,
ZYDIS_REGISTER_EBP, ZYDIS_REGISTER_ESP, ZYDIS_REGISTER_ESI, ZYDIS_REGISTER_EDI
#endif //_WIN64
};
for(unsigned int j = 0; j < _countof(registers); j++)
{
if(!baseRegisters[j]->isChecked())
continue;
if(dis[i].mem.base == registers[j])
usedOffsets[j].insert(dis[i].mem.disp.value);
}
}
address += dis.Size();
}
delete[] buffer;
int rows = 0;
for(int i = 0; i < ArchValue(8, 16); i++)
rows += usedOffsets[i].size();
setRowCount(rows);
rows = 0;
for(int i = 0; i < ArchValue(8, 16); i++)
{
std::vector<dsint> sorted;
sorted.reserve(usedOffsets[i].size());
for(const auto & j : usedOffsets[i])
sorted.push_back(j);
std::sort(sorted.begin(), sorted.end(), std::greater<dsint>());
for(const auto & j : sorted)
{
QString expr;
QString name;
if(j < 0)
{
expr = QString("%1").arg(-j, 0, 16);
if(HexPrefixValues)
expr = "0x" + expr;
if(!MemorySpaces)
expr = "-" + expr;
else
expr = " - " + expr;
}
else
{
expr = QString("%1").arg(j, 0, 16);
if(HexPrefixValues)
expr = "0x" + expr;
if(!MemorySpaces)
expr = "+" + expr;
else
expr = " + " + expr;
}
expr = QString("[%1%2]").arg(baseRegisters[i]->text()).arg(expr);
if(i == 4) //CBP
{
if(j < 0)
name = tr("Local%1").arg(-j / sizeof(dsint)); //EBP-C:Local3
else
name = tr("Arg%1").arg(j / sizeof(dsint) - 1); //EBP+C:Arg2
}
else
{
if(j < 0)
name = QString("_%2_%1").arg(-j, 0, 16); //ECX-C: _ECX_C
else
name = QString("%2_%1").arg(j, 0, 16); //ECX+C: ECX_C
name = name.arg(baseRegisters[i]->text());
}
setCellContent(rows, 0, name);
setCellContent(rows, 1, expr);
rows++;
}
} // Analyze finish
this->currentFunc = start;
}
for(dsint i = 0; i < getRowCount(); i++)
{
duint val = 0;
QByteArray buf = getCellContent(i, 1).toUtf8();
if(DbgIsValidExpression(buf.constData()))
{
val = DbgValFromString(buf.constData());
setCellContent(i, 2, getSymbolicNameStr(val));
}
else
setCellContent(i, 2, "???");
}
reloadData();
}
else
{
currentFunc = 0;
setRowCount(0);
reloadData();
}
}
void LocalVarsView::renameSlot()
{
QString newName;
if(getRowCount() > 0)
{
QString oldName = getCellContent(getInitialSelection(), 0);
if(SimpleInputBox(this, tr("Rename local variable \"%1\"").arg(oldName), oldName, newName, oldName))
{
setCellContent(getInitialSelection(), 0, newName);
reloadData();
}
}
}
void LocalVarsView::editSlot()
{
if(getRowCount() <= 0)
return;
QString expr = getCellContent(getInitialSelection(), 1);
duint addr;
if(!getAddress(expr, addr))
return;
WordEditDialog editor(this);
duint current = 0;
if(!DbgMemRead(addr, ¤t, sizeof(duint)))
return; //Memory is not accessible
editor.setup(tr("Edit %1 at %2").arg(getCellContent(getInitialSelection(), 0)).arg(ToPtrString(addr)), current, sizeof(dsint));
if(editor.exec() == QDialog::Accepted)
{
current = editor.getVal();
DbgMemWrite(addr, ¤t, sizeof(duint));
emit updateSlot();
}
}
void LocalVarsView::followDumpSlot()
{
duint addr;
if(getAddress(getCellContent(getInitialSelection(), 1), addr))
DbgCmdExec(QString("dump %1").arg(ToPtrString(addr)));
}
void LocalVarsView::followStackSlot()
{
duint addr;
if(getAddress(getCellContent(getInitialSelection(), 1), addr))
DbgCmdExec(QString("sdump %1").arg(ToPtrString(addr)));
}
void LocalVarsView::followMemMapSlot()
{
duint addr;
if(getAddress(getCellContent(getInitialSelection(), 1), addr))
DbgCmdExec(QString("memmapdump %1").arg(ToPtrString(addr)));
}
void LocalVarsView::followWordInDumpSlot()
{
duint addr;
if(getAddress(getCellContent(getInitialSelection(), 1), addr))
DbgCmdExec(QString("dump [%1]").arg(ToPtrString(addr)));
}
void LocalVarsView::followWordInStackSlot()
{
duint addr;
if(getAddress(getCellContent(getInitialSelection(), 1), addr))
DbgCmdExec(QString("sdump [%1]").arg(ToPtrString(addr)));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/LocalVarsView.h | #pragma once
#include "StdTable.h"
class CPUMultiDump;
class LocalVarsView : public StdTable
{
Q_OBJECT
public:
LocalVarsView(CPUMultiDump* parent);
public slots:
void contextMenuSlot(const QPoint & pos);
void mousePressEvent(QMouseEvent* event);
void followDumpSlot();
void followStackSlot();
void followMemMapSlot();
void followWordInDumpSlot();
void followWordInStackSlot();
void baseChangedSlot();
void renameSlot();
void updateSlot();
void configUpdatedSlot();
void editSlot();
private:
duint currentFunc;
void setupContextMenu();
MenuBuilder* mMenu;
bool HexPrefixValues;
bool MemorySpaces;
#ifdef _WIN64
QAction* baseRegisters[16];
#else //x86
QAction* baseRegisters[8];
#endif //_WIN64
}; |
C++ | x64dbg-development/src/gui/Src/Gui/LogStatusLabel.cpp | #include "LogStatusLabel.h"
#include "LogView.h"
#include <QTextDocument>
#include <QApplication>
#include <QStatusBar>
LogStatusLabel::LogStatusLabel(QStatusBar* parent) : QLabel(parent)
{
this->setTextFormat(Qt::RichText);
this->setOpenExternalLinks(false);
this->setTextInteractionFlags(Qt::LinksAccessibleByMouse);
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
connect(Bridge::getBridge(), SIGNAL(addMsgToLog(QByteArray)), this, SLOT(logUpdateUtf8(QByteArray)));
connect(Bridge::getBridge(), SIGNAL(addMsgToLogHtml(QByteArray)), this, SLOT(logUpdateUtf8Html(QByteArray)));
connect(Bridge::getBridge(), SIGNAL(addMsgToStatusBar(QString)), this, SLOT(logUpdate(QString)));
connect(Bridge::getBridge(), SIGNAL(getActiveView(ACTIVEVIEW*)), this, SLOT(getActiveView(ACTIVEVIEW*)));
connect(QApplication::instance(), SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(focusChanged(QWidget*, QWidget*)));
connect(this, SIGNAL(linkActivated(QString)), this, SLOT(linkActivatedSlot(QString)));
}
void LogStatusLabel::logUpdate(QString message, bool encodeHTML)
{
//TODO: This subroutine can be optimized
if(!message.length())
return;
// See LogView::addMsgToLogSlotRaw for details on the logic
if(encodeHTML)
{
message = message.toHtmlEscaped();
message.replace(QChar(' '), QString(" "));
LogView::linkify(message);
}
labelText += message.replace("\r\n", "\n");
QStringList lineList = labelText.split('\n');
labelText = lineList.last(); //if the last character is a newline this will be an empty string
for(int i = 0; i < lineList.length(); i++)
{
const QString & line = lineList[lineList.size() - i - 1];
if(line.length()) //set the last non-empty string from the split
{
finalLabel = line;
break;
}
}
setText(finalLabel);
}
void LogStatusLabel::logUpdateUtf8(QByteArray message)
{
logUpdate(QString::fromUtf8(message));
}
void LogStatusLabel::logUpdateUtf8Html(QByteArray message)
{
logUpdate(QString::fromUtf8(message), false);
}
void LogStatusLabel::focusChanged(QWidget* old, QWidget* now)
{
if(old && now && QString(now->metaObject()->className()) == QString("CPUWidget"))
{
old->setFocus();
return;
}
}
void LogStatusLabel::getActiveView(ACTIVEVIEW* active)
{
auto findTitle = [](QWidget * w, void* & hwnd) -> QString
{
if(!w)
return "(null)";
if(!w->windowTitle().length())
{
auto p = w->parentWidget();
if(p && p->windowTitle().length())
{
hwnd = (void*)p->winId();
return p->windowTitle();
}
}
hwnd = (void*)w->winId();
return w->windowTitle();
};
auto className = [](QWidget * w, void* & hwnd) -> QString
{
if(!w)
return "(null)";
hwnd = (void*)w->winId();
return w->metaObject()->className();
};
memset(active, 0, sizeof(ACTIVEVIEW));
QWidget* now = QApplication::focusWidget();
strncpy_s(active->title, findTitle(now, active->titleHwnd).toUtf8().constData(), _TRUNCATE);
strncpy_s(active->className, className(now, active->classHwnd).toUtf8().constData(), _TRUNCATE);
Bridge::getBridge()->setResult(BridgeResult::GetActiveView);
}
void LogStatusLabel::showMessage(const QString & message)
{
statusTip = message;
if(statusTip.isEmpty())
setText(finalLabel);
else
{
setText(statusTip);
}
}
void LogStatusLabel::linkActivatedSlot(const QString & link)
{
LogView::handleLink(this, QUrl(link));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/LogStatusLabel.h | #pragma once
#include <QLabel>
#include "Bridge.h"
class QStatusBar;
class LogStatusLabel : public QLabel
{
Q_OBJECT
public:
explicit LogStatusLabel(QStatusBar* parent = 0);
public slots:
void logUpdate(QString message, bool encodeHTML = true);
void logUpdateUtf8(QByteArray message);
void logUpdateUtf8Html(QByteArray message);
void focusChanged(QWidget* old, QWidget* now);
void getActiveView(ACTIVEVIEW* active);
// show status tip
void showMessage(const QString & message);
void linkActivatedSlot(const QString & link);
private:
QString finalLabel;
QString labelText;
QString statusTip;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/LogView.cpp | #include "LogView.h"
#include "Configuration.h"
#include "Bridge.h"
#include <QRegularExpression>
#include <QDesktopServices>
#include <QClipboard>
#include <QMimeData>
#include <QTimer>
#include <QApplication>
#include <QContextMenuEvent>
#include "BrowseDialog.h"
#include "MiscUtil.h"
#include "StringUtil.h"
/**
* @brief LogView::LogView The constructor constructs a rich text browser
* @param parent The parent
*/
LogView::LogView(QWidget* parent) : QTextBrowser(parent), logRedirection(NULL)
{
updateStyle();
this->setUndoRedoEnabled(false);
this->setReadOnly(true);
this->setOpenExternalLinks(false);
this->setOpenLinks(false);
this->setLoggingEnabled(true);
autoScroll = true;
flushTimer = new QTimer(this);
flushTimer->setInterval(500);
connect(flushTimer, SIGNAL(timeout()), this, SLOT(flushTimerSlot()));
connect(Bridge::getBridge(), SIGNAL(closeApplication()), flushTimer, SLOT(stop()));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateStyle()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(updateStyle()));
connect(Bridge::getBridge(), SIGNAL(addMsgToLog(QByteArray)), this, SLOT(addMsgToLogSlot(QByteArray)));
connect(Bridge::getBridge(), SIGNAL(addMsgToLogHtml(QByteArray)), this, SLOT(addMsgToLogHtmlSlot(QByteArray)));
connect(Bridge::getBridge(), SIGNAL(clearLog()), this, SLOT(clearLogSlot()));
connect(Bridge::getBridge(), SIGNAL(saveLog()), this, SLOT(saveSlot()));
connect(Bridge::getBridge(), SIGNAL(saveLogToFile(QString)), this, SLOT(saveToFileSlot(QString)));
connect(Bridge::getBridge(), SIGNAL(redirectLogToFile(QString)), this, SLOT(redirectLogToFileSlot(QString)));
connect(Bridge::getBridge(), SIGNAL(redirectLogStop()), this, SLOT(stopRedirectLogSlot()));
connect(Bridge::getBridge(), SIGNAL(setLogEnabled(bool)), this, SLOT(setLoggingEnabled(bool)));
connect(Bridge::getBridge(), SIGNAL(flushLog()), this, SLOT(flushLogSlot()));
connect(this, SIGNAL(anchorClicked(QUrl)), this, SLOT(onAnchorClicked(QUrl)));
dialogFindInLog = new LineEditDialog(this);
dialogFindInLog->setWindowTitle(tr("Find For"));
duint setting;
if(BridgeSettingGetUint("Misc", "Utf16LogRedirect", &setting))
utf16Redirect = !!setting;
setupContextMenu();
}
/**
* @brief LogView::~LogView The destructor
*/
LogView::~LogView()
{
if(logRedirection != nullptr)
fclose(logRedirection);
logRedirection = nullptr;
}
void LogView::updateStyle()
{
setFont(ConfigFont("Log"));
setStyleSheet(QString("QTextEdit { color: %1; background-color: %2 }").arg(ConfigColor("LogColor").name(), ConfigColor("LogBackgroundColor").name()));
QColor LogLinkBackgroundColor = ConfigColor("LogLinkBackgroundColor");
this->document()->setDefaultStyleSheet(QString("a {color: %1; background-color: %2 }").arg(ConfigColor("LogLinkColor").name(), LogLinkBackgroundColor == Qt::transparent ? "transparent" : LogLinkBackgroundColor.name()));
}
template<class T> static QAction* setupAction(const QIcon & icon, const QString & text, LogView* this_object, T slot)
{
QAction* action = new QAction(icon, text, this_object);
action->setShortcutContext(Qt::WidgetShortcut);
this_object->addAction(action);
this_object->connect(action, SIGNAL(triggered()), this_object, slot);
return action;
}
template<class T> static QAction* setupAction(const QString & text, LogView* this_object, T slot)
{
QAction* action = new QAction(text, this_object);
action->setShortcutContext(Qt::WidgetShortcut);
this_object->addAction(action);
this_object->connect(action, SIGNAL(triggered()), this_object, slot);
return action;
}
void LogView::setupContextMenu()
{
actionClear = setupAction(DIcon("eraser"), tr("Clea&r"), this, SLOT(clearLogSlot()));
actionCopy = setupAction(DIcon("copy"), tr("&Copy"), this, SLOT(copy()));
actionPaste = setupAction(DIcon("binary_paste"), tr("&Paste"), this, SLOT(pasteSlot()));
actionSelectAll = setupAction(DIcon("copy_full_table"), tr("Select &All"), this, SLOT(selectAll()));
actionSave = setupAction(DIcon("binary_save"), tr("&Save"), this, SLOT(saveSlot()));
actionToggleLogging = setupAction(DIcon("lock"), tr("Disable &Logging"), this, SLOT(toggleLoggingSlot()));
actionRedirectLog = setupAction(DIcon("database-export"), tr("&Redirect Log..."), this, SLOT(redirectLogSlot()));
actionAutoScroll = setupAction(tr("Auto Scrolling"), this, SLOT(autoScrollSlot()));
menuCopyToNotes = new QMenu(tr("Copy To Notes"), this);
menuCopyToNotes->setIcon(DIcon("notes"));
actionCopyToGlobalNotes = new QAction(tr("&Global"), menuCopyToNotes);
actionCopyToDebuggeeNotes = new QAction(tr("&Debuggee"), menuCopyToNotes);
connect(actionCopyToGlobalNotes, SIGNAL(triggered()), this, SLOT(copyToGlobalNotes()));
connect(actionCopyToDebuggeeNotes, SIGNAL(triggered()), this, SLOT(copyToDebuggeeNotes()));
menuCopyToNotes->addAction(actionCopyToGlobalNotes);
menuCopyToNotes->addAction(actionCopyToDebuggeeNotes);
actionAutoScroll->setCheckable(true);
actionAutoScroll->setChecked(autoScroll);
actionFindInLog = setupAction(tr("Find"), this, SLOT(findInLogSlot()));
actionFindNext = setupAction(tr("Find Next Occurance"), this, SLOT(findNextInLogSlot()));;
actionFindPrevious = setupAction(tr("Find Previous Occurance"), this, SLOT(findPreviousInLogSlot()));
refreshShortcutsSlot();
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcutsSlot()));
}
void LogView::refreshShortcutsSlot()
{
actionClear->setShortcut(ConfigShortcut("ActionClear"));
actionCopy->setShortcut(ConfigShortcut("ActionCopy"));
actionToggleLogging->setShortcut(ConfigShortcut("ActionToggleLogging"));
actionRedirectLog->setShortcut(ConfigShortcut("ActionRedirectLog"));
actionFindInLog->setShortcut(ConfigShortcut("ActionFind"));
actionFindNext->setShortcut(ConfigShortcut("ActionGotoNext"));
actionFindPrevious->setShortcut(ConfigShortcut("ActionGotoPrevious"));
}
void LogView::contextMenuEvent(QContextMenuEvent* event)
{
QMenu wMenu(this);
wMenu.addAction(actionClear);
wMenu.addAction(actionSelectAll);
wMenu.addAction(actionCopy);
if(QApplication::clipboard()->mimeData()->hasText())
wMenu.addAction(actionPaste);
wMenu.addAction(actionSave);
if(getLoggingEnabled())
actionToggleLogging->setText(tr("Disable &Logging"));
else
actionToggleLogging->setText(tr("Enable &Logging"));
actionCopyToDebuggeeNotes->setEnabled(DbgIsDebugging());
wMenu.addMenu(menuCopyToNotes);
wMenu.addAction(actionToggleLogging);
actionAutoScroll->setChecked(autoScroll);
wMenu.addAction(actionAutoScroll);
wMenu.addAction(actionFindInLog);
wMenu.addAction(actionFindNext);
wMenu.addAction(actionFindPrevious);
if(logRedirection == nullptr)
actionRedirectLog->setText(tr("&Redirect Log..."));
else
actionRedirectLog->setText(tr("Stop &Redirection"));
wMenu.addAction(actionRedirectLog);
wMenu.exec(event->globalPos());
}
void LogView::showEvent(QShowEvent* event)
{
flushTimerSlot();
flushTimer->start();
QTextBrowser::showEvent(event);
}
void LogView::hideEvent(QHideEvent* event)
{
flushTimer->stop();
QTextBrowser::hideEvent(event);
}
void LogView::handleLink(QWidget* parent, const QUrl & link)
{
if(link.scheme() == "x64dbg")
{
// x64dbg:path#fragment
auto path = link.path();
auto fragment = link.fragment(QUrl::FullyDecoded);
if(path == "address" || path == "/address32" || path == "/address64")
{
if(DbgIsDebugging())
{
bool ok = false;
auto address = duint(fragment.toULongLong(&ok, 16));
if(ok && DbgMemIsValidReadPtr(address))
{
if(DbgFunctions()->MemIsCodePage(address, true))
DbgCmdExec(QString("disasm %1").arg(link.fragment()));
else
{
DbgCmdExecDirect(QString("dump %1").arg(link.fragment()));
emit Bridge::getBridge()->getDumpAttention();
}
}
else
SimpleErrorBox(parent, tr("Invalid address!"), tr("The address %1 is not a valid memory location...").arg(ToPtrString(address)));
}
}
else if(path == "command")
{
DbgCmdExec(fragment.toUtf8().constData());
}
else
SimpleErrorBox(parent, tr("Url is not valid!"), tr("The Url %1 is not supported").arg(link.toString()));
}
else
QDesktopServices::openUrl(link); // external Url
}
/**
* @brief linkify Add hyperlink HTML to the message where applicable.
* @param msg The message passed by reference.
* Url format:
* x64dbg:// localhost / address64 # address
* ^fixed ^host(probably will be changed to PID + Host when remote debugging and child debugging are supported) ^token ^parameter
*/
#ifdef _WIN64
static QRegularExpression addressRegExp("([0-9A-Fa-f]{16})");
#else //x86
static QRegularExpression addressRegExp("([0-9A-Fa-f]{8})");
#endif //_WIN64
void LogView::linkify(QString & msg)
{
#ifdef _WIN64
msg.replace(addressRegExp, "<a href=\"x64dbg://localhost/address64#\\1\">\\1</a>");
#else //x86
msg.replace(addressRegExp, "<a href=\"x64dbg://localhost/address32#\\1\">\\1</a>");
#endif //_WIN64
}
/**
* @brief LogView::addMsgToLogHtmlSlot Adds a HTML message to the log view. This function is a slot for Bridge::addMsgToLogHtml.
* @param msg The log message (Which is assumed to contain HTML)
*/
void LogView::addMsgToLogHtmlSlot(QByteArray msg)
{
LogView::addMsgToLogSlotRaw(msg, false);
}
/**
* @brief LogView::addMsgToLogSlot Adds a message to the log view. This function is a slot for Bridge::addMsgToLog.
* @param msg The log message
*/
void LogView::addMsgToLogSlot(QByteArray msg)
{
LogView::addMsgToLogSlotRaw(msg, true);
}
/**
* @brief LogView::addMsgToLogSlotRaw Adds a message to the log view.
* @param msg The log message
* @param encodeHTML HTML-encode the log message or not
*/
void LogView::addMsgToLogSlotRaw(QByteArray msg, bool encodeHTML)
{
/*
* This supports the 'UTF-8 Everywhere' manifesto.
* - UTF-8 (http://utf8everywhere.org);
* - No BOM (http://utf8everywhere.org/#faq.boms);
* - No carriage return (http://utf8everywhere.org/#faq.crlf).
*/
// fix Unix-style line endings.
// redirect the log
QString msgUtf16;
bool redirectError = false;
if(logRedirection != nullptr)
{
if(utf16Redirect)
{
msgUtf16 = QString::fromUtf8(msg);
msgUtf16.replace("\n", "\r\n");
if(!fwrite(msgUtf16.utf16(), msgUtf16.length(), 2, logRedirection))
{
fclose(logRedirection);
logRedirection = nullptr;
redirectError = true;
}
}
else
{
const char* data;
std::string temp;
size_t offset = 0;
size_t buffersize = 0;
if(strstr(msg.constData(), "\r\n") != nullptr) // Don't replace "\r\n" to "\n" if there is none
{
temp = msg.constData();
while(true)
{
size_t index = temp.find("\r\n", offset);
if(index == std::string::npos)
break;
temp.erase(index);
offset = index;
}
data = temp.c_str();
buffersize = temp.size();
}
else
{
data = msg.constData();
buffersize = strlen(msg);
}
if(!fwrite(data, buffersize, 1, logRedirection))
{
fclose(logRedirection);
logRedirection = nullptr;
redirectError = true;
}
if(loggingEnabled)
msgUtf16 = QString::fromUtf8(data, int(buffersize));
}
}
else msgUtf16 = QString::fromUtf8(msg);
if(!loggingEnabled)
return;
if(encodeHTML)
{
msgUtf16 = msgUtf16.toHtmlEscaped();
/* Below line will break HTML tags with spaces separating the HTML tag name and attributes.
ie <a href="aaaa"> -> <a href="aaaa">
so we don't escape spaces where we deliberately passed in HTML.
*/
msgUtf16.replace(QChar(' '), QString(" "));
}
if(logRedirection)
{
if(utf16Redirect)
msgUtf16.replace(QString("\r\n"), QString("<br/>\n"));
else
msgUtf16.replace(QChar('\n'), QString("<br/>\n"));
}
else
{
msgUtf16.replace(QChar('\n'), QString("<br/>\n"));
msgUtf16.replace(QString("\r\n"), QString("<br/>\n"));
}
if(encodeHTML)
{
/* If we passed in non-html log string, we look for address links.
* otherwise, if our HTML contains any address-looking word, ie in our CSS, it would be mangled
* linking to addresses when passing in HTML log message is an exercise left to the plugin developer */
linkify(msgUtf16);
}
if(redirectError)
msgUtf16.append(tr("fwrite() failed (GetLastError()= %1 ). Log redirection stopped.\n").arg(GetLastError()));
if(logBuffer.length() >= MAX_LOG_BUFFER_SIZE)
logBuffer.clear();
logBuffer.append(msgUtf16);
if(flushLog)
{
flushTimerSlot();
flushLog = false;
}
}
/**
* @brief LogView::onAnchorClicked Called when a hyperlink is clicked
* @param link The clicked link
*/
void LogView::onAnchorClicked(const QUrl & link)
{
handleLink(this, link);
}
void LogView::clearLogSlot()
{
this->clear();
}
void LogView::stopRedirectLogSlot()
{
if(logRedirection != nullptr)
{
fclose(logRedirection);
logRedirection = nullptr;
GuiAddLogMessage(tr("Log redirection is stopped.\n").toUtf8().constData());
}
else
{
GuiAddLogMessage(tr("Log is not redirected.\n").toUtf8().constData());
}
}
void LogView::redirectLogToFileSlot(QString filename)
{
if(logRedirection != nullptr)
{
fclose(logRedirection);
logRedirection = nullptr;
GuiAddLogMessage(tr("Log redirection is stopped.\n").toUtf8().constData());
}
logRedirection = _wfopen(filename.toStdWString().c_str(), L"ab");
if(logRedirection == nullptr)
GuiAddLogMessage(tr("_wfopen() failed. Log will not be redirected to %1.\n").arg(QString::fromWCharArray(BridgeUserDirectory())).toUtf8().constData());
else
{
if(utf16Redirect && ftell(logRedirection) == 0)
{
unsigned short BOM = 0xfeff;
fwrite(&BOM, 2, 1, logRedirection);
}
GuiAddLogMessage(tr("Log will be redirected to %1.\n").arg(filename).toUtf8().constData());
}
}
void LogView::redirectLogSlot()
{
if(logRedirection != nullptr)
{
fclose(logRedirection);
logRedirection = nullptr;
GuiAddLogMessage(tr("Log redirection is stopped.\n").toUtf8().constData());
}
else
{
BrowseDialog browse(this, tr("Redirect log to file"), tr("Enter the file to which you want to redirect log messages."), tr("Log files (*.txt);;All files (*.*)"), QString::fromWCharArray(BridgeUserDirectory()), true);
if(browse.exec() == QDialog::Accepted)
{
redirectLogToFileSlot(browse.path);
}
}
}
void LogView::setLoggingEnabled(bool enabled)
{
if(enabled)
{
loggingEnabled = true;
GuiAddStatusBarMessage(tr("Logging will be enabled.\n").toUtf8().constData());
}
else
{
GuiAddStatusBarMessage(tr("Logging will be disabled.\n").toUtf8().constData());
loggingEnabled = false;
}
}
bool LogView::getLoggingEnabled()
{
return loggingEnabled;
}
void LogView::autoScrollSlot()
{
autoScroll = !autoScroll;
}
void LogView::saveToFileSlot(QString fileName)
{
QFile savedLog(fileName);
savedLog.open(QIODevice::Append | QIODevice::Text);
if(savedLog.error() != QFile::NoError)
{
GuiAddLogMessage(tr("Error, log have not been saved.\n").toUtf8().constData());
}
else
{
savedLog.write(this->document()->toPlainText().toUtf8().constData());
savedLog.close();
GuiAddLogMessage(tr("Log have been saved as %1\n").arg(fileName).toUtf8().constData());
}
}
/**
* @brief LogView::saveSlot Called by "save" action
*/
void LogView::saveSlot()
{
QString fileName;
fileName = QString("log-%1.txt").arg(isoDateTime());
saveToFileSlot(fileName);
}
void LogView::toggleLoggingSlot()
{
setLoggingEnabled(!getLoggingEnabled());
}
void LogView::copyToGlobalNotes()
{
char* NotesBuffer;
emit Bridge::getBridge()->getGlobalNotes(&NotesBuffer);
QString Notes = QString::fromUtf8(NotesBuffer);
BridgeFree(NotesBuffer);
Notes.append(this->textCursor().selectedText());
emit Bridge::getBridge()->setGlobalNotes(Notes);
}
void LogView::copyToDebuggeeNotes()
{
char* NotesBuffer;
emit Bridge::getBridge()->getDebuggeeNotes(&NotesBuffer);
QString Notes = QString::fromUtf8(NotesBuffer);
BridgeFree(NotesBuffer);
Notes.append(this->textCursor().selectedText());
emit Bridge::getBridge()->setDebuggeeNotes(Notes);
}
void LogView::findNextInLogSlot()
{
find(QRegExp(lastFindText));
}
void LogView::findPreviousInLogSlot()
{
find(QRegExp(lastFindText), QTextDocument::FindBackward);
}
void LogView::findInLogSlot()
{
dialogFindInLog->show();
if(dialogFindInLog->exec() == QDialog::Accepted)
{
QList<QTextEdit::ExtraSelection> extraSelections;
QColor highlight = ConfigColor("SearchListViewHighlightColor");
QColor background = ConfigColor("SearchListViewHighlightBackgroundColor");
// capturing the current location, so that we can reset it once capturing all the
// extra selections
QTextCursor resetCursorLoc = textCursor();
moveCursor(QTextCursor::Start);
// finding all occurances matching the regex given from start
while(find(QRegExp(dialogFindInLog->editText)))
{
QTextEdit::ExtraSelection extra;
extra.format.setForeground(highlight);
extra.format.setBackground(background);
extra.cursor = textCursor();
extraSelections.append(extra);
}
// highlighting all those selections
setExtraSelections(extraSelections);
setTextCursor(resetCursorLoc); // resetting the cursor location
find(QRegExp(dialogFindInLog->editText));
lastFindText = dialogFindInLog->editText;
}
}
void LogView::pasteSlot()
{
QString clipboardText = QApplication::clipboard()->text();
if(clipboardText.isEmpty())
return;
if(!clipboardText.endsWith('\n'))
clipboardText.append('\n');
addMsgToLogSlot(clipboardText.toUtf8());
}
void LogView::flushTimerSlot()
{
if(logBuffer.isEmpty())
return;
setUpdatesEnabled(false);
static unsigned char counter = 100;
counter--;
if(counter == 0)
{
if(document()->characterCount() > MAX_LOG_BUFFER_SIZE)
clear();
counter = 100;
}
QTextCursor cursor(document());
cursor.movePosition(QTextCursor::End);
cursor.beginEditBlock();
cursor.insertBlock();
// hack to not insert too many newlines: https://lists.qt-project.org/pipermail/qt-interest-old/2011-July/034725.html
cursor.deletePreviousChar();
cursor.insertHtml(logBuffer);
cursor.endEditBlock();
if(autoScroll)
moveCursor(QTextCursor::End);
setUpdatesEnabled(true);
logBuffer.clear();
}
void LogView::flushLogSlot()
{
flushLog = true;
if(flushTimer->isActive())
flushTimerSlot();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/LogView.h | #pragma once
#include <QTextBrowser>
#include <cstdio>
#include "LineEditDialog.h"
class LogView : public QTextBrowser
{
Q_OBJECT
public:
explicit LogView(QWidget* parent = 0);
~LogView();
void setupContextMenu();
void contextMenuEvent(QContextMenuEvent* event) override;
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
static void handleLink(QWidget* parent, const QUrl & link);
static void linkify(QString & msg);
public slots:
void refreshShortcutsSlot();
void updateStyle();
void addMsgToLogSlot(QByteArray msg); /* Non-HTML Log Function*/
void addMsgToLogHtmlSlot(QByteArray msg); /* HTML accepting Log Function */
void stopRedirectLogSlot();
void redirectLogToFileSlot(QString filename);
void redirectLogSlot();
void setLoggingEnabled(bool enabled);
void autoScrollSlot();
void findInLogSlot();
void findNextInLogSlot();
void findPreviousInLogSlot();
void copyToGlobalNotes();
void copyToDebuggeeNotes();
void pasteSlot();
bool getLoggingEnabled();
void onAnchorClicked(const QUrl & link);
void clearLogSlot();
void saveToFileSlot(QString filename);
void saveSlot();
void toggleLoggingSlot();
void flushTimerSlot();
void flushLogSlot();
private:
static const int MAX_LOG_BUFFER_SIZE = 1024 * 1024;
void addMsgToLogSlotRaw(QByteArray msg, bool htmlEscape); /* Non-HTML Log Function*/
bool loggingEnabled;
bool autoScroll;
bool utf16Redirect = false;
QAction* actionCopy;
QAction* actionPaste;
QAction* actionSelectAll;
QAction* actionClear;
QAction* actionSave;
QAction* actionToggleLogging;
QAction* actionRedirectLog;
QAction* actionAutoScroll;
QMenu* menuCopyToNotes;
QAction* actionCopyToGlobalNotes;
QAction* actionCopyToDebuggeeNotes;
QAction* actionFindInLog;
QAction* actionFindNext;
QAction* actionFindPrevious;
LineEditDialog* dialogFindInLog;
FILE* logRedirection;
QString logBuffer;
QTimer* flushTimer;
bool flushLog;
QString lastFindText;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/MainWindow.cpp | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QMutex>
#include <QMessageBox>
#include <QIcon>
#include <QUrl>
#include <QFileDialog>
#include <QMimeData>
#include <QDesktopServices>
#include <QStatusTipEvent>
#include "Configuration.h"
#include "SettingsDialog.h"
#include "AppearanceDialog.h"
#include "ShortcutsDialog.h"
#include "AttachDialog.h"
#include "LineEditDialog.h"
#include "StringUtil.h"
#include "MiscUtil.h"
#include "FavouriteTools.h"
#include "CPUDisassembly.h"
#include "CloseDialog.h"
#include "CommandLineEdit.h"
#include "TabWidget.h"
#include "CPUWidget.h"
#include "MemoryMapView.h"
#include "CallStackView.h"
#include "SEHChainView.h"
#include "LogView.h"
#include "SymbolView.h"
#include "BreakpointsView.h"
#include "ScriptView.h"
#include "ReferenceManager.h"
#include "ThreadView.h"
#include "PatchDialog.h"
#include "CalculatorDialog.h"
#include "DebugStatusLabel.h"
#include "LogStatusLabel.h"
#include "SourceViewerManager.h"
#include "HandlesView.h"
#include "MainWindowCloseThread.h"
#include "TimeWastedCounter.h"
#include "NotesManager.h"
#include "SettingsDialog.h"
#include "DisassemblerGraphView.h"
#include "CPUMultiDump.h"
#include "CPUStack.h"
#include "GotoDialog.h"
#include "SystemBreakpointScriptDialog.h"
#include "CustomizeMenuDialog.h"
#include "main.h"
#include "SimpleTraceDialog.h"
#include "CPUArgumentWidget.h"
#include "MRUList.h"
#include "AboutDialog.h"
#include "UpdateChecker.h"
#include "Tracer/TraceBrowser.h"
#include "Tracer/TraceWidget.h"
#include "Utils/MethodInvoker.h"
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Build information
{
const char* debugEngine = []
{
switch(DbgGetDebugEngine())
{
case DebugEngineTitanEngine:
return "TitanEngine";
case DebugEngineGleeBug:
return "GleeBug";
case DebugEngineStaticEngine:
return "StaticEngine";
}
return "";
}();
QAction* buildInfo = new QAction(tr("%1 (%2)").arg(ToDateString(GetCompileDate())).arg(debugEngine), this);
buildInfo->setEnabled(false);
ui->menuBar->addAction(buildInfo);
}
// Setup bridge signals
connect(Bridge::getBridge(), SIGNAL(updateWindowTitle(QString)), this, SLOT(updateWindowTitleSlot(QString)));
connect(Bridge::getBridge(), SIGNAL(addRecentFile(QString)), this, SLOT(addRecentFile(QString)));
connect(Bridge::getBridge(), SIGNAL(setLastException(uint)), this, SLOT(setLastException(uint)));
connect(Bridge::getBridge(), SIGNAL(getStrWindow(QString, QString*)), this, SLOT(getStrWindow(QString, QString*)));
connect(Bridge::getBridge(), SIGNAL(showCpu()), this, SLOT(displayCpuWidget()));
connect(Bridge::getBridge(), SIGNAL(showReferences()), this, SLOT(displayReferencesWidget()));
connect(Bridge::getBridge(), SIGNAL(addQWidgetTab(QWidget*)), this, SLOT(addQWidgetTab(QWidget*)));
connect(Bridge::getBridge(), SIGNAL(showQWidgetTab(QWidget*)), this, SLOT(showQWidgetTab(QWidget*)));
connect(Bridge::getBridge(), SIGNAL(closeQWidgetTab(QWidget*)), this, SLOT(closeQWidgetTab(QWidget*)));
connect(Bridge::getBridge(), SIGNAL(executeOnGuiThread(void*, void*)), this, SLOT(executeOnGuiThread(void*, void*)));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChangedSlot(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(addFavouriteItem(int, QString, QString)), this, SLOT(addFavouriteItem(int, QString, QString)));
connect(Bridge::getBridge(), SIGNAL(setFavouriteItemShortcut(int, QString, QString)), this, SLOT(setFavouriteItemShortcut(int, QString, QString)));
connect(Bridge::getBridge(), SIGNAL(selectInMemoryMap(duint)), this, SLOT(displayMemMapWidget()));
connect(Bridge::getBridge(), SIGNAL(symbolSelectModule(duint)), this, SLOT(displaySymbolWidget()));
connect(Bridge::getBridge(), SIGNAL(closeApplication()), this, SLOT(close()));
connect(Bridge::getBridge(), SIGNAL(showTraceBrowser()), this, SLOT(displayTraceWidget()));
// Setup menu API
// Because of race conditions with this API we create a direct connection. This means that the slot will directly execute on the thread that emits the signal.
// Inside the slots we need to take special care to only do bookkeeping and not interact with the QWidgets without scheduling it on the main thread
auto menuType = (Qt::ConnectionType)(Qt::UniqueConnection | Qt::DirectConnection);
connect(Bridge::getBridge(), SIGNAL(menuAddMenuToList(QWidget*, QMenu*, GUIMENUTYPE, int)), this, SLOT(addMenuToList(QWidget*, QMenu*, GUIMENUTYPE, int)), menuType);
connect(Bridge::getBridge(), SIGNAL(menuAddMenu(int, QString)), this, SLOT(addMenu(int, QString)), menuType);
connect(Bridge::getBridge(), SIGNAL(menuAddMenuEntry(int, QString)), this, SLOT(addMenuEntry(int, QString)), menuType);
connect(Bridge::getBridge(), SIGNAL(menuAddSeparator(int)), this, SLOT(addSeparator(int)), menuType);
connect(Bridge::getBridge(), SIGNAL(menuClearMenu(int, bool)), this, SLOT(clearMenu(int, bool)), menuType);
connect(Bridge::getBridge(), SIGNAL(menuRemoveMenuEntry(int)), this, SLOT(removeMenuEntry(int)), menuType);
connect(Bridge::getBridge(), SIGNAL(setIconMenu(int, QIcon)), this, SLOT(setIconMenu(int, QIcon)), menuType);
connect(Bridge::getBridge(), SIGNAL(setIconMenuEntry(int, QIcon)), this, SLOT(setIconMenuEntry(int, QIcon)), menuType);
connect(Bridge::getBridge(), SIGNAL(setCheckedMenuEntry(int, bool)), this, SLOT(setCheckedMenuEntry(int, bool)), menuType);
connect(Bridge::getBridge(), SIGNAL(setHotkeyMenuEntry(int, QString, QString)), this, SLOT(setHotkeyMenuEntry(int, QString, QString)), menuType);
connect(Bridge::getBridge(), SIGNAL(setVisibleMenuEntry(int, bool)), this, SLOT(setVisibleMenuEntry(int, bool)), menuType);
connect(Bridge::getBridge(), SIGNAL(setVisibleMenu(int, bool)), this, SLOT(setVisibleMenu(int, bool)), menuType);
connect(Bridge::getBridge(), SIGNAL(setNameMenuEntry(int, QString)), this, SLOT(setNameMenuEntry(int, QString)), menuType);
connect(Bridge::getBridge(), SIGNAL(setNameMenu(int, QString)), this, SLOT(setNameMenu(int, QString)), menuType);
initMenuApi();
Bridge::getBridge()->emitMenuAddToList(this, ui->menuPlugins, GUI_PLUGIN_MENU);
// Set window title to executable name
if(BridgeIsProcessElevated())
{
mWindowMainTitle = tr("%1 [Elevated]").arg(QCoreApplication::applicationName());
ui->actionRestartAdmin->setEnabled(false);
}
else
mWindowMainTitle = QCoreApplication::applicationName();
setWindowTitle(QString(mWindowMainTitle));
// Load application icon
SetApplicationIcon(MainWindow::winId());
// Load recent files
mMRUList = new MRUList(this, "Recent Files");
connect(mMRUList, SIGNAL(openFile(QString)), this, SLOT(openRecentFileSlot(QString)));
mMRUList->load();
updateMRUMenu();
// Log view
mLogView = new LogView();
mLogView->setWindowTitle(tr("Log"));
mLogView->setWindowIcon(DIcon("log"));
mLogView->hide();
// Symbol view
mSymbolView = new SymbolView();
Bridge::getBridge()->symbolView = mSymbolView;
mSymbolView->setWindowTitle(tr("Symbols"));
mSymbolView->setWindowIcon(DIcon("pdb"));
mSymbolView->hide();
// Source view
mSourceViewManager = new SourceViewerManager();
mSourceViewManager->setWindowTitle(tr("Source"));
mSourceViewManager->setWindowIcon(DIcon("source"));
mSourceViewManager->hide();
// Breakpoints
mBreakpointsView = new BreakpointsView();
mBreakpointsView->setWindowTitle(tr("Breakpoints"));
mBreakpointsView->setWindowIcon(DIcon("breakpoint"));
mBreakpointsView->hide();
// Memory map view
mMemMapView = new MemoryMapView();
connect(mMemMapView, SIGNAL(showReferences()), this, SLOT(displayReferencesWidget()));
mMemMapView->setWindowTitle(tr("Memory Map"));
mMemMapView->setWindowIcon(DIcon("memory-map"));
mMemMapView->hide();
// Callstack view
mCallStackView = new CallStackView();
mCallStackView->setWindowTitle(tr("Call Stack"));
mCallStackView->setWindowIcon(DIcon("callstack"));
// SEH Chain view
mSEHChainView = new SEHChainView();
mSEHChainView->setWindowTitle(tr("SEH"));
mSEHChainView->setWindowIcon(DIcon("seh-chain"));
// Script view
mScriptView = new ScriptView();
mScriptView->setWindowTitle(tr("Script"));
mScriptView->setWindowIcon(DIcon("script-code"));
mScriptView->hide();
// CPU view
mCpuWidget = new CPUWidget();
mCpuWidget->setWindowTitle(tr("CPU"));
#ifdef _WIN64
mCpuWidget->setWindowIcon(DIcon("processor64"));
#else
mCpuWidget->setWindowIcon(DIcon("processor32"));
ui->actionCpu->setIcon(DIcon("processor32"));
#endif //_WIN64
// Reference manager
mReferenceManager = new ReferenceManager(this);
Bridge::getBridge()->referenceManager = mReferenceManager;
mReferenceManager->setWindowTitle(tr("References"));
mReferenceManager->setWindowIcon(DIcon("search"));
// Thread view
mThreadView = new ThreadView();
mThreadView->setWindowTitle(tr("Threads"));
mThreadView->setWindowIcon(DIcon("arrow-threads"));
// Notes manager
mNotesManager = new NotesManager(this);
mNotesManager->setWindowTitle(tr("Notes"));
mNotesManager->setWindowIcon(DIcon("notes"));
// Handles view
mHandlesView = new HandlesView(this);
mHandlesView->setWindowTitle(tr("Handles"));
mHandlesView->setWindowIcon(DIcon("handles"));
// Trace view
mTraceWidget = new TraceWidget(this);
mTraceWidget->setWindowTitle(tr("Trace"));
mTraceWidget->setWindowIcon(DIcon("trace"));
connect(mTraceWidget->getTraceBrowser(), SIGNAL(displayReferencesWidget()), this, SLOT(displayReferencesWidget()));
connect(mTraceWidget->getTraceBrowser(), SIGNAL(displayLogWidget()), this, SLOT(displayLogWidget()));
mTabWidget = new MHTabWidget(this, true, true);
// Add all widgets to the list
mWidgetList.push_back(WidgetInfo(mCpuWidget, "CPUTab"));
mWidgetList.push_back(WidgetInfo(mLogView, "LogTab"));
mWidgetList.push_back(WidgetInfo(mNotesManager, "NotesTab"));
mWidgetList.push_back(WidgetInfo(mBreakpointsView, "BreakpointsTab"));
mWidgetList.push_back(WidgetInfo(mMemMapView, "MemoryMapTab"));
mWidgetList.push_back(WidgetInfo(mCallStackView, "CallStackTab"));
mWidgetList.push_back(WidgetInfo(mSEHChainView, "SEHTab"));
mWidgetList.push_back(WidgetInfo(mScriptView, "ScriptTab"));
mWidgetList.push_back(WidgetInfo(mSymbolView, "SymbolsTab"));
mWidgetList.push_back(WidgetInfo(mSourceViewManager, "SourceTab"));
mWidgetList.push_back(WidgetInfo(mReferenceManager, "ReferencesTab"));
mWidgetList.push_back(WidgetInfo(mThreadView, "ThreadsTab"));
mWidgetList.push_back(WidgetInfo(mHandlesView, "HandlesTab"));
mWidgetList.push_back(WidgetInfo(mTraceWidget, "TraceTab"));
// If LoadSaveTabOrder disabled, load tabs in default order
if(!ConfigBool("Gui", "LoadSaveTabOrder"))
loadTabDefaultOrder();
else
loadTabSavedOrder();
setCentralWidget(mTabWidget);
displayCpuWidget();
// Accept drops
setAcceptDrops(true);
// Setup the command and status bars
setupCommandBar();
setupStatusBar();
// Patch dialog
mPatchDialog = new PatchDialog(this);
mCalculatorDialog = new CalculatorDialog(this);
// Setup signals/slots
connect(mCmdLineEdit, SIGNAL(returnPressed()), this, SLOT(executeCommand()));
makeCommandAction(ui->actionRestartAdmin, "restartadmin");
makeCommandAction(ui->actionStepOver, "StepOver");
makeCommandAction(ui->actionStepInto, "StepInto");
connect(ui->actionCommand, SIGNAL(triggered()), this, SLOT(setFocusToCommandBar()));
makeCommandAction(ui->actionClose, "stop");
connect(ui->actionMemoryMap, SIGNAL(triggered()), this, SLOT(displayMemMapWidget()));
connect(ui->actionRun, SIGNAL(triggered()), this, SLOT(runSlot()));
makeCommandAction(ui->actionRtr, "rtr");
connect(ui->actionLog, SIGNAL(triggered()), this, SLOT(displayLogWidget()));
connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(displayAboutWidget()));
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFileSlot()));
makeCommandAction(ui->actionPause, "pause");
makeCommandAction(ui->actionScylla, "StartScylla");
connect(ui->actionRestart, SIGNAL(triggered()), this, SLOT(restartDebugging()));
connect(ui->actionBreakpoints, SIGNAL(triggered()), this, SLOT(displayBreakpointWidget()));
makeCommandAction(ui->actioneStepOver, "eStepOver");
makeCommandAction(ui->actioneStepInto, "eStepInto");
makeCommandAction(ui->actioneRun, "eRun");
makeCommandAction(ui->actioneRtr, "eRtr");
makeCommandAction(ui->actionRtu, "TraceOverConditional mod.user(cip)");
connect(ui->actionTicnd, SIGNAL(triggered()), this, SLOT(execTicnd()));
connect(ui->actionTocnd, SIGNAL(triggered()), this, SLOT(execTocnd()));
connect(ui->actionTRBit, SIGNAL(triggered()), this, SLOT(execTRBit()));
connect(ui->actionTRByte, SIGNAL(triggered()), this, SLOT(execTRByte()));
connect(ui->actionTRWord, SIGNAL(triggered()), this, SLOT(execTRWord()));
connect(ui->actionTRNone, SIGNAL(triggered()), this, SLOT(execTRNone()));
makeCommandAction(ui->actionTRTIBT, "tibt");
makeCommandAction(ui->actionTRTOBT, "tobt");
makeCommandAction(ui->actionTRTIIT, "tiit");
makeCommandAction(ui->actionTRTOIT, "toit");
makeCommandAction(ui->actionInstrUndo, "InstrUndo");
makeCommandAction(ui->actionSkipNextInstruction, "skip");
connect(ui->actionScript, SIGNAL(triggered()), this, SLOT(displayScriptWidget()));
connect(ui->actionRunSelection, SIGNAL(triggered()), this, SLOT(runSelection()));
connect(ui->actionRunExpression, SIGNAL(triggered(bool)), this, SLOT(runExpression()));
makeCommandAction(ui->actionHideDebugger, "hide");
connect(ui->actionCpu, SIGNAL(triggered()), this, SLOT(displayCpuWidgetShowCpu()));
connect(ui->actionSymbolInfo, SIGNAL(triggered()), this, SLOT(displaySymbolWidget()));
connect(ui->actionModules, SIGNAL(triggered()), this, SLOT(displaySymbolWidget()));
connect(ui->actionSource, SIGNAL(triggered()), this, SLOT(displaySourceViewWidget()));
connect(mSymbolView, SIGNAL(showReferences()), this, SLOT(displayReferencesWidget()));
connect(ui->actionReferences, SIGNAL(triggered()), this, SLOT(displayReferencesWidget()));
connect(ui->actionThreads, SIGNAL(triggered()), this, SLOT(displayThreadsWidget()));
connect(ui->actionSettings, SIGNAL(triggered()), this, SLOT(openSettings()));
connect(ui->actionStrings, SIGNAL(triggered()), this, SLOT(findStrings()));
connect(ui->actionCalls, SIGNAL(triggered()), this, SLOT(findModularCalls()));
connect(ui->actionAppearance, SIGNAL(triggered()), this, SLOT(openAppearance()));
connect(ui->actionShortcuts, SIGNAL(triggered()), this, SLOT(openShortcuts()));
connect(ui->actionTopmost, SIGNAL(toggled(bool)), this, SLOT(changeTopmost(bool)));
connect(ui->actionCalculator, SIGNAL(triggered()), this, SLOT(openCalculator()));
connect(ui->actionPatches, SIGNAL(triggered()), this, SLOT(patchWindow()));
connect(ui->actionComments, SIGNAL(triggered()), this, SLOT(displayComments()));
connect(ui->actionLabels, SIGNAL(triggered()), this, SLOT(displayLabels()));
connect(ui->actionBookmarks, SIGNAL(triggered()), this, SLOT(displayBookmarks()));
connect(ui->actionFunctions, SIGNAL(triggered()), this, SLOT(displayFunctions()));
connect(ui->actionCallStack, SIGNAL(triggered()), this, SLOT(displayCallstack()));
connect(ui->actionSEHChain, SIGNAL(triggered()), this, SLOT(displaySEHChain()));
connect(ui->actionTrace, SIGNAL(triggered()), this, SLOT(displayTraceWidget()));
connect(ui->actionDonate, SIGNAL(triggered()), this, SLOT(donate()));
connect(ui->actionReportBug, SIGNAL(triggered()), this, SLOT(reportBug()));
connect(ui->actionBlog, SIGNAL(triggered()), this, SLOT(blog()));
connect(ui->actionCrashDump, SIGNAL(triggered()), this, SLOT(crashDump()));
connect(ui->actionAttach, SIGNAL(triggered()), this, SLOT(displayAttach()));
makeCommandAction(ui->actionDetach, "detach");
connect(ui->actionChangeCommandLine, SIGNAL(triggered()), this, SLOT(changeCommandLine()));
connect(ui->actionManual, SIGNAL(triggered()), this, SLOT(displayManual()));
connect(ui->actionNotes, SIGNAL(triggered()), this, SLOT(displayNotesWidget()));
connect(ui->actionHandles, SIGNAL(triggered()), this, SLOT(displayHandlesWidget()));
connect(ui->actionGraph, SIGNAL(triggered()), this, SLOT(displayGraphWidget()));
connect(ui->actionPreviousTab, SIGNAL(triggered()), mTabWidget, SLOT(showPreviousTab()));
connect(ui->actionNextTab, SIGNAL(triggered()), mTabWidget, SLOT(showNextTab()));
connect(ui->actionPreviousView, SIGNAL(triggered()), mTabWidget, SLOT(showPreviousView()));
connect(ui->actionNextView, SIGNAL(triggered()), mTabWidget, SLOT(showNextView()));
connect(ui->actionHideTab, SIGNAL(triggered()), mTabWidget, SLOT(deleteCurrentTab()));
makeCommandAction(ui->actionStepIntoSource, "TraceIntoConditional src.line(cip) && !src.disp(cip)");
makeCommandAction(ui->actionStepOverSource, "TraceOverConditional src.line(cip) && !src.disp(cip)");
makeCommandAction(ui->actionseStepInto, "seStepInto");
makeCommandAction(ui->actionseStepOver, "seStepOver");
makeCommandAction(ui->actionseRun, "seRun");
connect(ui->actionAnimateInto, SIGNAL(triggered()), this, SLOT(animateIntoSlot()));
connect(ui->actionAnimateOver, SIGNAL(triggered()), this, SLOT(animateOverSlot()));
connect(ui->actionAnimateCommand, SIGNAL(triggered()), this, SLOT(animateCommandSlot()));
connect(ui->actionSetInitializationScript, SIGNAL(triggered()), this, SLOT(setInitializationScript()));
connect(ui->actionCustomizeMenus, SIGNAL(triggered()), this, SLOT(customizeMenu()));
connect(ui->actionVariables, SIGNAL(triggered()), this, SLOT(displayVariables()));
makeCommandAction(ui->actionDbsave, "dbsave");
makeCommandAction(ui->actionDbload, "dbload");
makeCommandAction(ui->actionDbrecovery, "dbload bak");
makeCommandAction(ui->actionDbclear, "dbclear");
connect(mCpuWidget->getDisasmWidget(), SIGNAL(updateWindowTitle(QString)), this, SLOT(updateWindowTitleSlot(QString)));
connect(mCpuWidget->getDisasmWidget(), SIGNAL(displayReferencesWidget()), this, SLOT(displayReferencesWidget()));
connect(mCpuWidget->getDisasmWidget(), SIGNAL(displaySourceManagerWidget()), this, SLOT(displaySourceViewWidget()));
connect(mCpuWidget->getDisasmWidget(), SIGNAL(displayLogWidget()), this, SLOT(displayLogWidget()));
connect(mCpuWidget->getDisasmWidget(), SIGNAL(displaySymbolsWidget()), this, SLOT(displaySymbolWidget()));
connect(mCpuWidget->getDisasmWidget(), SIGNAL(showPatches()), this, SLOT(patchWindow()));
connect(mCpuWidget->getGraphWidget(), SIGNAL(displayLogWidget()), this, SLOT(displayLogWidget()));
connect(mCpuWidget->getDumpWidget(), SIGNAL(displayReferencesWidget()), this, SLOT(displayReferencesWidget()));
connect(mCpuWidget->getStackWidget(), SIGNAL(displayReferencesWidget()), this, SLOT(displayReferencesWidget()));
connect(mTabWidget, SIGNAL(tabMovedTabWidget(int, int)), this, SLOT(tabMovedSlot(int, int)));
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcuts()));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateStyle()));
// Menu stuff
actionManageFavourites = nullptr;
mFavouriteToolbar = new QToolBar(tr("Favourite Toolbox"), this);
updateFavouriteTools();
setupLanguagesMenu();
setupThemesMenu();
setupMenuCustomization();
ui->actionAbout_Qt->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarMenuButton));
// Set default setttings (when not set)
SettingsDialog defaultSettings;
lastException = 0;
defaultSettings.SaveSettings();
// Don't need to set shortcuts because the code above will signal refreshShortcuts()
mSimpleTraceDialog = new SimpleTraceDialog(this);
// Update checker
mUpdateChecker = new UpdateChecker(this);
// Setup close thread and dialog
bCanClose = false;
bExitWhenDetached = false;
mCloseThread = new MainWindowCloseThread(this);
connect(mCloseThread, SIGNAL(canClose()), this, SLOT(canClose()));
mCloseDialog = new CloseDialog(this);
mCpuWidget->setDisasmFocus();
char setting[MAX_SETTING_SIZE] = "";
// To avoid the window from flashing briefly at the initial position before being moved to saved position and size, initialize the main window position and size here
if(BridgeSettingGet("Main Window Settings", "Geometry", setting))
restoreGeometry(QByteArray::fromBase64(QByteArray(setting)));
QTimer::singleShot(0, this, SLOT(loadWindowSettings()));
updateDarkTitleBar(this);
// Hide the menu icons if the setting is enabled
duint noIcons = 0;
BridgeSettingGetUint("Gui", "NoIcons", &noIcons);
if(noIcons)
{
QList<QList<QAction*>> stack;
stack.push_back(ui->menuBar->actions());
while(!stack.isEmpty())
{
auto actions = stack.back();
stack.pop_back();
for(auto action : actions)
{
action->setIconVisibleInMenu(false);
if(action->menu())
{
stack.push_back(action->menu()->actions());
}
}
}
}
}
MainWindow::~MainWindow()
{
delete ui;
mMenuMutex->lock();
mMenuMutex->unlock();
delete mMenuMutex;
}
void MainWindow::setupCommandBar()
{
mCmdLineEdit = new CommandLineEdit(ui->cmdBar);
ui->cmdBar->addWidget(new QLabel(tr("Command: ")));
ui->cmdBar->addWidget(mCmdLineEdit);
ui->cmdBar->addWidget(mCmdLineEdit->selectorWidget());
}
void MainWindow::setupStatusBar()
{
// Status label (Ready, Paused, ...)
mStatusLabel = new DebugStatusLabel(ui->statusBar);
mStatusLabel->setText(tr("Ready"));
ui->statusBar->addWidget(mStatusLabel);
// Log line
mLastLogLabel = new LogStatusLabel(ui->statusBar);
ui->statusBar->addPermanentWidget(mLastLogLabel, 1);
// Time wasted counter
QLabel* timeWastedLabel = new QLabel(this);
ui->statusBar->addPermanentWidget(timeWastedLabel);
mTimeWastedCounter = new TimeWastedCounter(this, timeWastedLabel);
}
void MainWindow::setupLanguagesMenu()
{
QMenu* languageMenu;
if(tr("Languages") == QString("Languages"))
languageMenu = new QMenu(QString("Languages"));
else
languageMenu = new QMenu(tr("Languages") + QString(" Languages"), this);
languageMenu->setIcon(DIcon("codepage"));
QLocale enUS(QLocale::English, QLocale::UnitedStates);
QAction* action_enUS = new QAction(QString("[%1] %2 - %3").arg(enUS.name()).arg(enUS.nativeLanguageName()).arg(enUS.nativeCountryName()), languageMenu);
connect(action_enUS, SIGNAL(triggered()), this, SLOT(chooseLanguage()));
action_enUS->setCheckable(true);
action_enUS->setChecked(false);
languageMenu->addAction(action_enUS);
connect(languageMenu, SIGNAL(aboutToShow()), this, SLOT(setupLanguagesMenu2())); //Load this menu later, since it requires directory scanning.
ui->menuOptions->addMenu(languageMenu);
}
#include "../src/bridge/Utf8Ini.h"
static void importSettings(const QString & filename, const QSet<QString> & sectionWhitelist = {})
{
QFile f(QDir::toNativeSeparators(filename));
if(f.open(QFile::ReadOnly | QFile::Text))
{
QTextStream in(&f);
auto style = in.readAll();
f.close();
Utf8Ini ini;
int errorLine;
if(ini.Deserialize(style.toStdString(), errorLine))
{
auto sections = ini.Sections();
for(const auto & section : sections)
{
if(!sectionWhitelist.isEmpty() && !sectionWhitelist.contains(QString::fromStdString(section)))
continue;
auto keys = ini.Keys(section);
for(const auto & key : keys)
BridgeSettingSet(section.c_str(), key.c_str(), ini.GetValue(section, key).c_str());
}
Config()->load();
DbgSettingsUpdated();
emit Config()->colorsUpdated();
emit Config()->fontsUpdated();
emit Config()->guiOptionsUpdated();
emit Config()->shortcutsUpdated();
emit Config()->tokenizerConfigUpdated();
// Before startup we don't need to update all views
if(Bridge::getBridge())
GuiUpdateAllViews();
}
}
}
void MainWindow::loadSelectedTheme(bool reloadOnlyStyleCss)
{
if(BridgeGetNtBuildNumber() >= 14393 /* darkmode registry release */)
{
duint lastAppsUseLightTheme = -1;
BridgeSettingGetUint("Theme", "AppsUseLightTheme", &lastAppsUseLightTheme);
auto readRegistryDword = [](HKEY hRootKey, const wchar_t* lpSubKey, const wchar_t* lpValueName, DWORD & result)
{
auto success = false;
HKEY hKey = 0;
if(RegOpenKeyExW(hRootKey, lpSubKey, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
DWORD dwBufferSize = sizeof(DWORD);
DWORD dwData = 0;
if(RegQueryValueExW(hKey, lpValueName, 0, NULL, reinterpret_cast<LPBYTE>(&dwData), &dwBufferSize) == ERROR_SUCCESS)
{
result = dwData;
success = true;
}
RegCloseKey(hKey);
}
return success;
};
DWORD appsUseLightTheme = 1;
auto subKey = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
auto valueName = L"AppsUseLightTheme";
if(!readRegistryDword(HKEY_CURRENT_USER, subKey, valueName, appsUseLightTheme))
readRegistryDword(HKEY_LOCAL_MACHINE, subKey, valueName, appsUseLightTheme);
// If the user changed the setting since last startup, adjust the default theme
if(appsUseLightTheme != lastAppsUseLightTheme)
{
BridgeSettingSet("Theme", "Selected", appsUseLightTheme ? "Default" : "Dark");
BridgeSettingSetUint("Theme", "AppsUseLightTheme", appsUseLightTheme);
reloadOnlyStyleCss = false;
}
}
char selectedTheme[MAX_SETTING_SIZE] = "Default";
if(!BridgeSettingGet("Theme", "Selected", selectedTheme))
BridgeSettingSet("Theme", "Selected", selectedTheme);
QString stylePath(":/css/default.css");
QString settingsPath;
QString applicationDirPath = QCoreApplication::applicationDirPath();
if(*selectedTheme)
{
// Handle the icon theme
QStringList searchPaths = { ":/" };
if(strcmp(selectedTheme, "Default") == 0)
{
// The Default theme needs some special handling to allow overriding
auto overrideDir = applicationDirPath + "/../themes/Default";
if(QDir(overrideDir).exists("index.theme"))
{
/*
HACK: for some reason this allows you to override icons from the themes/Default folder.
You need themes/Default/index.theme and then you can put images in themes/Default/icons:
[Icon Theme]
Name=DefaultOverride
Comment=Default icon theme override
Directories=icons
Inherits=Default
[icons]
Size=16
Type=Scalable
*/
searchPaths << overrideDir;
QIcon::setThemeName("DefaultOverride");
}
else
{
QIcon::setThemeName("Default");
}
QIcon::setThemeSearchPaths(searchPaths);
}
else
{
auto themesDir = applicationDirPath + "/../themes";
if(QDir(themesDir).exists(QString("%1/index.theme").arg(selectedTheme)))
{
searchPaths << themesDir;
QIcon::setThemeName(selectedTheme);
}
else
{
// If there is no icon theme, use the default icons
QIcon::setThemeName("Default");
}
QIcon::setThemeSearchPaths(searchPaths);
}
QString themePath = QString("%1/../themes/%2/style.css").arg(applicationDirPath).arg(selectedTheme);
if(!QFile(themePath).exists())
themePath = QString("%1/../themes/%2/theme.css").arg(applicationDirPath).arg(selectedTheme);
if(QFile(themePath).exists())
stylePath = themePath;
auto tryIni = [&applicationDirPath, &settingsPath, &selectedTheme](const char* name)
{
if(!settingsPath.isEmpty())
return;
QString iniPath = QString("%1/../themes/%2/%3").arg(applicationDirPath, selectedTheme, name);
if(QFile(iniPath).exists())
settingsPath = iniPath;
};
tryIni("style.ini");
tryIni("colors.ini");
tryIni("theme.ini");
}
else
{
// This code path should never be executed
QIcon::setThemeName("Default");
}
QFile cssFile(stylePath);
if(cssFile.open(QFile::ReadOnly | QFile::Text))
{
auto style = QTextStream(&cssFile).readAll();
cssFile.close();
style = style.replace("url(./", QString("url(approot:/themes/%1/").arg(selectedTheme));
style = style.replace("url(\"./", QString("url(\"approot:/themes/%1/").arg(selectedTheme));
style = style.replace("url('./", QString("url('approot:/themes/%1/").arg(selectedTheme));
style = style.replace("$RELPATH", QString("approot:/themes/%1").arg(selectedTheme));
qApp->setStyleSheet(style);
}
// Skip changing the settings when only reloading the CSS
// On startup we want to preserve the user's appearance
if(reloadOnlyStyleCss)
return;
if(!settingsPath.isEmpty())
{
// TODO: add an 'inherit' option to style.ini to inherit from another theme
importSettings(settingsPath, { "Colors", "Fonts" });
}
else
{
// Reset [Colors] to default
Config()->Colors = Config()->defaultColors;
Config()->writeColors();
BridgeSettingSetUint("Colors", "DarkTitleBar", 0);
// Reset [Fonts] to default (TODO: https://github.com/x64dbg/x64dbg/issues/2422)
//Config()->Fonts = Config()->defaultFonts;
//Config()->writeFonts();
// Remove custom colors
BridgeSettingSet("Colors", "CustomColorCount", nullptr);
}
}
void MainWindow::themeTriggeredSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action == nullptr)
return;
QString dir = action->data().toString();
int nameIdx = dir.lastIndexOf('/');
QString name = dir.mid(nameIdx + 1);
BridgeSettingSet("Theme", "Selected", name.toUtf8().constData());
loadSelectedTheme();
updateDarkTitleBar(this);
}
void MainWindow::setupThemesMenu()
{
auto exists = [](const QString & str)
{
return QFile(str).exists();
};
char selectedTheme[MAX_SETTING_SIZE];
BridgeSettingGet("Theme", "Selected", selectedTheme);
QDirIterator it(QString("%1/../themes").arg(QCoreApplication::applicationDirPath()), QDir::NoDotAndDotDot | QDir::Dirs);
auto actionGroup = new QActionGroup(ui->menuTheme);
actionGroup->addAction(ui->actionDefaultTheme);
while(it.hasNext())
{
auto dir = it.next();
auto nameIdx = dir.lastIndexOf('/');
auto name = dir.mid(nameIdx + 1);
// The Default theme folder is a hidden theme to override the default theme
if(name == "Default")
continue;
auto action = ui->menuTheme->addAction(name);
connect(action, SIGNAL(triggered()), this, SLOT(themeTriggeredSlot()));
action->setText(name);
action->setData(dir);
action->setCheckable(true);
actionGroup->addAction(action);
if(name == selectedTheme)
action->setChecked(true);
}
}
void MainWindow::setupLanguagesMenu2()
{
QMenu* languageMenu = dynamic_cast<QMenu*>(sender()); //The only sender is languageMenu
QAction* action_enUS = languageMenu->actions()[0]; //There is only one action "action_enUS" created by setupLanguagesMenu()
QDir translationsDir(QString("%1/../translations/").arg(QCoreApplication::applicationDirPath()));
QString wCurrentLocale(currentLocale);
if(!translationsDir.exists())
{
// translations dir do not exist
action_enUS->setChecked(true);
disconnect(languageMenu, SIGNAL(aboutToShow()), this, 0);
return;
}
if(wCurrentLocale == QString("en_US"))
action_enUS->setChecked(true);
QStringList filter;
filter << "x64dbg_*.qm";
QFileInfoList fileList = translationsDir.entryInfoList(filter, QDir::Readable | QDir::Files, QDir::Size); //Search for all translations
auto allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
for(auto i : fileList)
{
QString localeName = i.baseName().mid(7);
for(auto j : allLocales)
{
if(j.name().startsWith(localeName))
{
QAction* actionLanguage = new QAction(QString("[%1] %2 - %3").arg(localeName).arg(j.nativeLanguageName()).arg(j.nativeCountryName()), languageMenu);
connect(actionLanguage, SIGNAL(triggered()), this, SLOT(chooseLanguage()));
actionLanguage->setCheckable(true);
actionLanguage->setChecked(localeName == wCurrentLocale);
languageMenu->addAction(actionLanguage);
break;
}
}
}
disconnect(languageMenu, SIGNAL(aboutToShow()), this, 0); //Done. Let's disconnect it to prevent it from initializing twice.
}
void MainWindow::closeEvent(QCloseEvent* event)
{
if(DbgIsDebugging() && ConfigBool("Gui", "ShowExitConfirmation"))
{
auto cb = new QCheckBox(tr("Always stop the debuggee and exit"));
QMessageBox msgbox(this);
msgbox.setText(tr("The debuggee is still running and will be terminated if you exit. What do you want to do?"));
msgbox.setWindowTitle(tr("Debuggee is still running"));
msgbox.setWindowIcon(DIcon("bug"));
auto exitButton = msgbox.addButton(QMessageBox::Yes);
exitButton->setText(tr("&Exit"));
exitButton->setToolTip(tr("Stop the debuggee and exit x64dbg."));
auto detachButton = msgbox.addButton(QMessageBox::Abort);
detachButton->setText(tr("&Detach and exit"));
detachButton->setToolTip(tr("Detach from the debuggee (leaving it running) and exit x64dbg."));
auto restartButton = msgbox.addButton(QMessageBox::Retry);
restartButton->setText(tr("&Restart debugging"));
restartButton->setToolTip(tr("Restart the debuggee and keep x64dbg open."));
auto continueButton = msgbox.addButton(QMessageBox::Cancel);
continueButton->setText(tr("&Continue debugging"));
continueButton->setToolTip(tr("Close this dialog and continue where you left off."));
msgbox.setDefaultButton(QMessageBox::Cancel);
msgbox.setEscapeButton(QMessageBox::Cancel);
msgbox.setCheckBox(cb);
QObject::connect(cb, &QCheckBox::toggled, [detachButton, restartButton](bool checked)
{
auto showConfirmation = !checked;
detachButton->setEnabled(showConfirmation);
restartButton->setEnabled(showConfirmation);
Config()->setBool("Gui", "ShowExitConfirmation", showConfirmation);
});
auto code = msgbox.exec();
if(code == QMessageBox::Retry)
restartDebugging();
else if(code == QMessageBox::Abort)
{
bExitWhenDetached = true;
DbgCmdExec("detach");
}
if(code != QMessageBox::Yes)
{
event->ignore();
return;
}
}
duint noClose = 0;
if(bCanClose)
{
saveWindowSettings();
}
if(BridgeSettingGetUint("Gui", "NoCloseDialog", &noClose) && noClose)
mCloseDialog->hide();
else
{
mCloseDialog->show();
mCloseDialog->setFocus();
}
static volatile bool bExecuteThread = true;
if(bExecuteThread)
{
bExecuteThread = false;
Sleep(100);
mCloseThread->start();
emit Bridge::getBridge()->shutdown();
}
if(bCanClose)
{
mCloseDialog->allowClose();
mCloseDialog->close();
event->accept();
}
else
event->ignore();
}
void MainWindow::setTab(QWidget* widget)
{
// shown tabs
for(int i = 0; i < mTabWidget->count(); i++)
{
if(mTabWidget->widget(i) == widget)
{
mTabWidget->setCurrentIndex(i);
return;
}
}
// hidden tabs
for(int i = 0; i < mWidgetList.count(); i++)
{
if(mWidgetList[i].widget == widget)
{
addQWidgetTab(mWidgetList[i].widget, mWidgetList[i].nativeName);
mTabWidget->setCurrentIndex(mTabWidget->count() - 1);
return;
}
}
//TODO: restore configuration index
}
void MainWindow::loadTabDefaultOrder()
{
clearTabWidget();
// Setup tabs
for(int i = 0; i < mWidgetList.size(); i++)
addQWidgetTab(mWidgetList[i].widget, mWidgetList[i].nativeName);
// Add plugin tabs to the end
// TODO: this collection is always empty
for(const auto & widget : mPluginWidgetList)
addQWidgetTab(widget.widget, widget.nativeName);
}
void MainWindow::loadTabSavedOrder()
{
clearTabWidget();
QMap<duint, std::pair<QWidget*, QString>> tabIndexToWidget;
// Get tabIndex for each widget and add them to tabIndexToWidget
duint lastValidTabIndex = 0;
for(int i = 0; i < mWidgetList.size(); i++)
{
auto tabName = mWidgetList[i].nativeName;
duint tabIndex = 0;
if(BridgeSettingGetUint("TabOrder", tabName.toUtf8().constData(), &tabIndex))
{
lastValidTabIndex = tabIndex;
}
else
{
tabIndex = lastValidTabIndex;
}
if(!tabIndexToWidget.contains(tabIndex))
tabIndexToWidget.insert(tabIndex, std::make_pair(mWidgetList[i].widget, tabName));
else
{
// Conflicts. Try to find an unused tab index.
for(int j = 0; j < mWidgetList.size(); j++)
{
auto item = tabIndexToWidget.find(j);
if(item == tabIndexToWidget.end())
{
tabIndexToWidget.insert(j, std::make_pair(mWidgetList[i].widget, tabName));
break;
}
}
}
}
// Setup tabs
for(auto & widget : tabIndexToWidget)
addQWidgetTab(widget.first, widget.second);
// 'Restore' deleted tabs
for(int i = 0; i < mWidgetList.size(); i++)
{
duint isDeleted = 0;
BridgeSettingGetUint("Deleted Tabs", mWidgetList[i].nativeName.toUtf8().constData(), &isDeleted);
if(isDeleted)
mTabWidget->DeleteTab(mTabWidget->indexOf(mWidgetList[i].widget));
}
// Add plugin tabs to the end
// TODO: this collection is always empty
for(const auto & widget : mPluginWidgetList)
addQWidgetTab(widget.widget, widget.nativeName);
}
void MainWindow::clearTabWidget()
{
if(mTabWidget->count() <= 0)
return;
// Remove all tabs starting from the end
for(int i = mTabWidget->count() - 1; i >= 0; i--)
mTabWidget->removeTab(i);
}
void MainWindow::saveWindowSettings()
{
// Save favourite toolbar
BridgeSettingSetUint("Main Window Settings", "FavToolbarVisible", mFavouriteToolbar->isVisible() ? 1 : 0);
removeToolBar(mFavouriteToolbar); //Remove it before saving main window settings, otherwise it crashes
// Main Window settings
BridgeSettingSet("Main Window Settings", "Geometry", saveGeometry().toBase64().data());
BridgeSettingSet("Main Window Settings", "State", saveState().toBase64().data());
// Set of currently detached tabs
QSet<QWidget*> detachedTabWindows = mTabWidget->windows().toSet();
// For all tabs, save detached status. If detached, save geometry.
for(int i = 0; i < mWidgetList.size(); i++)
{
bool isDetached = detachedTabWindows.contains(mWidgetList[i].widget);
bool isDeleted = !isDetached && mTabWidget->indexOf(mWidgetList[i].widget) == -1;
BridgeSettingSetUint("Detached Windows", mWidgetList[i].nativeName.toUtf8().constData(), isDetached);
BridgeSettingSetUint("Deleted Tabs", mWidgetList[i].nativeName.toUtf8().constData(), isDeleted);
if(isDetached)
BridgeSettingSet("Tab Window Settings", mWidgetList[i].nativeName.toUtf8().constData(),
mWidgetList[i].widget->parentWidget()->saveGeometry().toBase64().data());
}
mCpuWidget->saveWindowSettings();
mSymbolView->saveWindowSettings();
}
void MainWindow::loadWindowSettings()
{
// Main Window settings
char setting[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("Main Window Settings", "State", setting))
restoreState(QByteArray::fromBase64(QByteArray(setting)));
// Restore detached windows size and position
// If a tab was detached last session, manually detach it now to populate MHTabWidget::windows
for(int i = 0; i < mWidgetList.size(); i++)
{
duint isDetached = 0;
BridgeSettingGetUint("Detached Windows", mWidgetList[i].nativeName.toUtf8().constData(), &isDetached);
if(isDetached)
mTabWidget->DetachTab(mTabWidget->indexOf(mWidgetList[i].widget), QPoint());
}
// Restore geometry for every tab we just detached
QSet<QWidget*> detachedTabWindows = mTabWidget->windows().toSet();
for(int i = 0; i < mWidgetList.size(); i++)
{
if(detachedTabWindows.contains(mWidgetList[i].widget))
{
if(BridgeSettingGet("Tab Window Settings", mWidgetList[i].nativeName.toUtf8().constData(), setting))
mWidgetList[i].widget->parentWidget()->restoreGeometry(QByteArray::fromBase64(QByteArray(setting)));
}
}
// 'Restore' deleted tabs
for(int i = 0; i < mWidgetList.size(); i++)
{
duint isDeleted = 0;
BridgeSettingGetUint("Deleted Tabs", mWidgetList[i].nativeName.toUtf8().constData(), &isDeleted);
if(isDeleted)
mTabWidget->DeleteTab(mTabWidget->indexOf(mWidgetList[i].widget));
}
// Load favourite toolbar
duint isVisible = 0;
BridgeSettingGetUint("Main Window Settings", "FavToolbarVisible", &isVisible);
addToolBar(mFavouriteToolbar);
mFavouriteToolbar->setVisible(isVisible == 1);
mCpuWidget->loadWindowSettings();
mSymbolView->loadWindowSettings();
// Make x64dbg topmost
if(ConfigBool("Gui", "Topmost"))
ui->actionTopmost->setChecked(true);
}
void MainWindow::setGlobalShortcut(QAction* action, const QKeySequence & key)
{
action->setShortcut(key);
action->setShortcutContext(Qt::ApplicationShortcut);
}
void MainWindow::refreshShortcuts()
{
setGlobalShortcut(ui->actionOpen, ConfigShortcut("FileOpen"));
setGlobalShortcut(ui->actionAttach, ConfigShortcut("FileAttach"));
setGlobalShortcut(ui->actionDetach, ConfigShortcut("FileDetach"));
setGlobalShortcut(ui->actionDbload, ConfigShortcut("FileDbload"));
setGlobalShortcut(ui->actionDbsave, ConfigShortcut("FileDbsave"));
setGlobalShortcut(ui->actionDbclear, ConfigShortcut("FileDbclear"));
setGlobalShortcut(ui->actionDbrecovery, ConfigShortcut("FileDbrecovery"));
setGlobalShortcut(ui->actionImportdatabase, ConfigShortcut("FileImportDatabase"));
setGlobalShortcut(ui->actionExportdatabase, ConfigShortcut("FileExportDatabase"));
setGlobalShortcut(ui->actionRestartAdmin, ConfigShortcut("FileRestartAdmin"));
setGlobalShortcut(ui->actionExit, ConfigShortcut("FileExit"));
setGlobalShortcut(ui->actionCpu, ConfigShortcut("ViewCpu"));
setGlobalShortcut(ui->actionLog, ConfigShortcut("ViewLog"));
setGlobalShortcut(ui->actionBreakpoints, ConfigShortcut("ViewBreakpoints"));
setGlobalShortcut(ui->actionMemoryMap, ConfigShortcut("ViewMemoryMap"));
setGlobalShortcut(ui->actionCallStack, ConfigShortcut("ViewCallStack"));
setGlobalShortcut(ui->actionSEHChain, ConfigShortcut("ViewSEHChain"));
setGlobalShortcut(ui->actionScript, ConfigShortcut("ViewScript"));
setGlobalShortcut(ui->actionSymbolInfo, ConfigShortcut("ViewSymbolInfo"));
setGlobalShortcut(ui->actionModules, ConfigShortcut("ViewModules"));
setGlobalShortcut(ui->actionSource, ConfigShortcut("ViewSource"));
setGlobalShortcut(ui->actionReferences, ConfigShortcut("ViewReferences"));
setGlobalShortcut(ui->actionThreads, ConfigShortcut("ViewThreads"));
setGlobalShortcut(ui->actionPatches, ConfigShortcut("ViewPatches"));
setGlobalShortcut(ui->actionComments, ConfigShortcut("ViewComments"));
setGlobalShortcut(ui->actionLabels, ConfigShortcut("ViewLabels"));
setGlobalShortcut(ui->actionBookmarks, ConfigShortcut("ViewBookmarks"));
setGlobalShortcut(ui->actionFunctions, ConfigShortcut("ViewFunctions"));
setGlobalShortcut(ui->actionVariables, ConfigShortcut("ViewVariables"));
setGlobalShortcut(ui->actionHandles, ConfigShortcut("ViewHandles"));
setGlobalShortcut(ui->actionGraph, ConfigShortcut("ViewGraph"));
setGlobalShortcut(ui->actionPreviousTab, ConfigShortcut("ViewPreviousTab"));
setGlobalShortcut(ui->actionNextTab, ConfigShortcut("ViewNextTab"));
setGlobalShortcut(ui->actionPreviousView, ConfigShortcut("ViewPreviousHistory"));
setGlobalShortcut(ui->actionNextView, ConfigShortcut("ViewNextHistory"));
setGlobalShortcut(ui->actionHideTab, ConfigShortcut("ViewHideTab"));
setGlobalShortcut(ui->actionRun, ConfigShortcut("DebugRun"));
setGlobalShortcut(ui->actioneRun, ConfigShortcut("DebugeRun"));
setGlobalShortcut(ui->actionseRun, ConfigShortcut("DebugseRun"));
setGlobalShortcut(ui->actionRunSelection, ConfigShortcut("DebugRunSelection"));
setGlobalShortcut(ui->actionRunExpression, ConfigShortcut("DebugRunExpression"));
setGlobalShortcut(ui->actionPause, ConfigShortcut("DebugPause"));
setGlobalShortcut(ui->actionRestart, ConfigShortcut("DebugRestart"));
setGlobalShortcut(ui->actionClose, ConfigShortcut("DebugClose"));
setGlobalShortcut(ui->actionStepInto, ConfigShortcut("DebugStepInto"));
setGlobalShortcut(ui->actioneStepInto, ConfigShortcut("DebugeStepInto"));
setGlobalShortcut(ui->actionseStepInto, ConfigShortcut("DebugseStepInto"));
setGlobalShortcut(ui->actionStepIntoSource, ConfigShortcut("DebugStepIntoSource"));
setGlobalShortcut(ui->actionStepOver, ConfigShortcut("DebugStepOver"));
setGlobalShortcut(ui->actioneStepOver, ConfigShortcut("DebugeStepOver"));
setGlobalShortcut(ui->actionseStepOver, ConfigShortcut("DebugseStepOver"));
setGlobalShortcut(ui->actionStepOverSource, ConfigShortcut("DebugStepOverSource"));
setGlobalShortcut(ui->actionRtr, ConfigShortcut("DebugRtr"));
setGlobalShortcut(ui->actioneRtr, ConfigShortcut("DebugeRtr"));
setGlobalShortcut(ui->actionRtu, ConfigShortcut("DebugRtu"));
setGlobalShortcut(ui->actionCommand, ConfigShortcut("DebugCommand"));
setGlobalShortcut(ui->actionSkipNextInstruction, ConfigShortcut("DebugSkipNextInstruction"));
setGlobalShortcut(ui->actionTicnd, ConfigShortcut("DebugTraceIntoConditional"));
setGlobalShortcut(ui->actionTocnd, ConfigShortcut("DebugTraceOverConditional"));
setGlobalShortcut(ui->actionTRBit, ConfigShortcut("DebugEnableTraceRecordBit"));
setGlobalShortcut(ui->actionTRNone, ConfigShortcut("DebugTraceRecordNone"));
setGlobalShortcut(ui->actionInstrUndo, ConfigShortcut("DebugInstrUndo"));
setGlobalShortcut(ui->actionAnimateInto, ConfigShortcut("DebugAnimateInto"));
setGlobalShortcut(ui->actionAnimateOver, ConfigShortcut("DebugAnimateOver"));
setGlobalShortcut(ui->actionAnimateCommand, ConfigShortcut("DebugAnimateCommand"));
setGlobalShortcut(ui->actionTRTIIT, ConfigShortcut("DebugTraceIntoIntoTracerecord"));
setGlobalShortcut(ui->actionTRTOIT, ConfigShortcut("DebugTraceOverIntoTracerecord"));
setGlobalShortcut(ui->actionTRTIBT, ConfigShortcut("DebugTraceIntoBeyondTracerecord"));
setGlobalShortcut(ui->actionTRTOBT, ConfigShortcut("DebugTraceOverBeyondTracerecord"));
setGlobalShortcut(ui->actionScylla, ConfigShortcut("PluginsScylla"));
setGlobalShortcut(actionManageFavourites, ConfigShortcut("FavouritesManage"));
setGlobalShortcut(ui->actionSettings, ConfigShortcut("OptionsPreferences"));
setGlobalShortcut(ui->actionAppearance, ConfigShortcut("OptionsAppearance"));
setGlobalShortcut(ui->actionShortcuts, ConfigShortcut("OptionsShortcuts"));
setGlobalShortcut(ui->actionTopmost, ConfigShortcut("OptionsTopmost"));
setGlobalShortcut(ui->actionReloadStylesheet, ConfigShortcut("OptionsReloadStylesheet"));
setGlobalShortcut(ui->actionAbout, ConfigShortcut("HelpAbout"));
setGlobalShortcut(ui->actionBlog, ConfigShortcut("HelpBlog"));
setGlobalShortcut(ui->actionDonate, ConfigShortcut("HelpDonate"));
setGlobalShortcut(ui->actionCalculator, ConfigShortcut("HelpCalculator"));
setGlobalShortcut(ui->actionReportBug, ConfigShortcut("HelpReportBug"));
setGlobalShortcut(ui->actionManual, ConfigShortcut("HelpManual"));
setGlobalShortcut(ui->actionCrashDump, ConfigShortcut("HelpCrashDump"));
setGlobalShortcut(ui->actionStrings, ConfigShortcut("ActionFindStrings"));
setGlobalShortcut(ui->actionCalls, ConfigShortcut("ActionFindIntermodularCalls"));
for(const MenuEntryInfo & entry : mEntryList)
if(!entry.hotkeyId.isEmpty())
entry.mAction->setShortcut(ConfigShortcut(entry.hotkeyId));
}
void MainWindow::updateMRUMenu()
{
QMenu* fileMenu = ui->menuRecentFiles;
QList<QAction*> list = fileMenu->actions();
for(int i = 1; i < list.length(); ++i)
fileMenu->removeAction(list.at(i));
mMRUList->appendMenu(fileMenu);
}
void MainWindow::executeCommand()
{
mCmdLineEdit->execute();
}
QAction* MainWindow::makeCommandAction(QAction* action, const QString & command)
{
action->setData(QVariant(command));
connect(action, SIGNAL(triggered()), this, SLOT(execCommandSlot()));
return action;
}
void MainWindow::execCommandSlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action)
DbgCmdExec(action->data().toString());
}
void MainWindow::setFocusToCommandBar()
{
mCmdLineEdit->setFocus();
}
void MainWindow::execTRBit()
{
mCpuWidget->getDisasmWidget()->traceCoverageBitSlot();
}
void MainWindow::execTRByte()
{
mCpuWidget->getDisasmWidget()->traceCoverageByteSlot();
}
void MainWindow::execTRWord()
{
mCpuWidget->getDisasmWidget()->traceCoverageWordSlot();
}
void MainWindow::execTRNone()
{
mCpuWidget->getDisasmWidget()->traceCoverageDisableSlot();
}
void MainWindow::execTicnd()
{
if(!DbgIsDebugging())
return;
if(DbgIsRunning())
{
SimpleErrorBox(this, tr("Error"), tr("Cannot start a trace when running, pause execution first."));
return;
}
mSimpleTraceDialog->setTraceCommand("TraceIntoConditional");
mSimpleTraceDialog->setWindowTitle(tr("Trace into..."));
mSimpleTraceDialog->setWindowIcon(DIcon("traceinto"));
mSimpleTraceDialog->exec();
}
void MainWindow::execTocnd()
{
if(!DbgIsDebugging())
return;
if(DbgIsRunning())
{
SimpleErrorBox(this, tr("Error"), tr("Cannot start a trace when running, pause execution first."));
return;
}
mSimpleTraceDialog->setTraceCommand("TraceOverConditional");
mSimpleTraceDialog->setWindowTitle(tr("Trace over..."));
mSimpleTraceDialog->setWindowIcon(DIcon("traceover"));
mSimpleTraceDialog->exec();
}
void MainWindow::displayMemMapWidget()
{
showQWidgetTab(mMemMapView);
}
void MainWindow::displayVariables()
{
DbgCmdExec("varlist");
showQWidgetTab(mReferenceManager);
}
void MainWindow::displayLogWidget()
{
showQWidgetTab(mLogView);
}
void MainWindow::displayScriptWidget()
{
showQWidgetTab(mScriptView);
}
void MainWindow::displayAboutWidget()
{
AboutDialog dialog(mUpdateChecker, this);
dialog.exec();
}
void MainWindow::openFileSlot()
{
auto filename = QFileDialog::getOpenFileName(this, tr("Open file"), mMRUList->getEntry(0), tr("Executables (*.exe *.dll);;All files (*.*)"));
if(!filename.length())
return;
filename = QDir::toNativeSeparators(filename); //convert to native path format (with backlashes)
openRecentFileSlot(filename);
}
void MainWindow::openRecentFileSlot(QString filename)
{
DbgCmdExec(QString().sprintf("init \"%s\"", filename.toUtf8().constData()));
}
void MainWindow::runSlot()
{
if(DbgIsDebugging())
DbgCmdExec("run");
else
restartDebugging();
}
void MainWindow::restartDebugging()
{
auto last = mMRUList->getEntry(0);
if(!last.isEmpty())
DbgCmdExec(QString("init \"%1\"").arg(last));
}
void MainWindow::displayBreakpointWidget()
{
showQWidgetTab(mBreakpointsView);
}
void MainWindow::dragEnterEvent(QDragEnterEvent* pEvent)
{
if(pEvent->mimeData()->hasUrls())
{
pEvent->acceptProposedAction();
}
}
void MainWindow::dropEvent(QDropEvent* pEvent)
{
if(pEvent->mimeData()->hasUrls())
{
QString filename = QDir::toNativeSeparators(pEvent->mimeData()->urls()[0].toLocalFile());
DbgCmdExec(QString().sprintf("init \"%s\"", filename.toUtf8().constData()));
pEvent->acceptProposedAction();
}
}
bool MainWindow::event(QEvent* event)
{
// just make sure mTabWidget take current view as the latest
if(event->type() == QEvent::WindowActivate && this->isActiveWindow())
{
mTabWidget->setCurrentIndex(mTabWidget->currentIndex());
}
else if(event->type() == QEvent::StatusTip)
{
QStatusTipEvent* tip = dynamic_cast<QStatusTipEvent*>(event);
mLastLogLabel->showMessage(tip->tip());
return true;
}
return QMainWindow::event(event);
}
void MainWindow::updateWindowTitleSlot(QString filename)
{
if(filename.length())
{
setWindowTitle(filename + QString(" - ") + mWindowMainTitle);
}
else
{
setWindowTitle(mWindowMainTitle);
}
}
void MainWindow::updateDarkTitleBar(QWidget* widget)
{
auto NtBuildNumber = BridgeGetNtBuildNumber();
if(NtBuildNumber < 17763)
return;
duint darkTitleBar = 0;
BridgeSettingGetUint("Colors", "DarkTitleBar", &darkTitleBar);
// Do not make the title bar dark/light when already done
auto darkProp = widget->property("DarkTitleBar");
if(darkProp.isValid() && darkProp.toUInt() == darkTitleBar)
{
return;
}
widget->setProperty("DarkTitleBar", QVariant(darkTitleBar != 0));
static auto hdwmapi = LoadLibraryW(L"dwmapi.dll");
if(hdwmapi)
{
typedef int(WINAPI * DWMSETWINDOWATTRIBUTE)(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute);
static auto DwmSetWindowAttribute = (DWMSETWINDOWATTRIBUTE)GetProcAddress(hdwmapi, "DwmSetWindowAttribute");
auto hwnd = (HWND)widget->winId();
DwmSetWindowAttribute(hwnd, (NtBuildNumber >= 18985) ? 20 : 19, &darkTitleBar, sizeof(uint32_t));
// HACK: Create a 1x1 pixel frameless window on top of the title bar to force Windows to redraw it
auto w = new QWidget(nullptr, Qt::FramelessWindowHint);
w->resize(1, 1);
w->move(widget->pos());
w->show();
delete w;
}
}
// Used by View->CPU
void MainWindow::displayCpuWidgetShowCpu()
{
showQWidgetTab(mCpuWidget);
mCpuWidget->setDisasmFocus();
}
// GuiShowCpu()
void MainWindow::displayCpuWidget()
{
showQWidgetTab(mCpuWidget);
}
void MainWindow::displaySymbolWidget()
{
showQWidgetTab(mSymbolView);
}
void MainWindow::displaySourceViewWidget()
{
showQWidgetTab(mSourceViewManager);
}
void MainWindow::displayReferencesWidget()
{
showQWidgetTab(mReferenceManager);
}
void MainWindow::displayThreadsWidget()
{
showQWidgetTab(mThreadView);
}
void MainWindow::displayGraphWidget()
{
showQWidgetTab(mCpuWidget);
mCpuWidget->setGraphFocus();
}
void MainWindow::openSettings()
{
SettingsDialog settings(this);
connect(&settings, SIGNAL(chkSaveLoadTabOrderStateChanged(bool)), this, SLOT(chkSaveloadTabSavedOrderStateChangedSlot(bool)));
settings.lastException = lastException;
settings.exec();
}
void MainWindow::openAppearance()
{
AppearanceDialog appearance(this);
appearance.exec();
}
void MainWindow::openCalculator()
{
mCalculatorDialog->showNormal();
mCalculatorDialog->setFocus();
mCalculatorDialog->setExpressionFocus();
}
void MainWindow::openShortcuts()
{
ShortcutsDialog shortcuts(this);
shortcuts.exec();
}
void MainWindow::changeTopmost(bool checked)
{
if(checked)
{
if(SetWindowPos((HWND)this->winId(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE))
{
Config()->setBool("Gui", "Topmost", true);
return;
}
}
else
SetWindowPos((HWND)this->winId(), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
Config()->setBool("Gui", "Topmost", false);
}
void MainWindow::addRecentFile(QString file)
{
mMRUList->addEntry(file);
updateMRUMenu();
mMRUList->save();
}
void MainWindow::setLastException(unsigned int exceptionCode)
{
lastException = exceptionCode;
}
void MainWindow::findStrings()
{
DbgCmdExec(QString("strref " + ToPtrString(mCpuWidget->getDisasmWidget()->getSelectedVa())));
displayReferencesWidget();
}
void MainWindow::findModularCalls()
{
DbgCmdExec(QString("modcallfind " + ToPtrString(mCpuWidget->getDisasmWidget()->getSelectedVa())));
displayReferencesWidget();
}
void MainWindow::initMenuApi()
{
mMenuMutex = new QMutex(QMutex::Recursive);
//256 entries are reserved
hEntryMenuPool = 256;
mEntryList.reserve(1024);
mMenuList.reserve(1024);
}
void MainWindow::menuEntrySlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action && action->objectName().startsWith("ENTRY|"))
{
int hEntry = -1;
if(sscanf_s(action->objectName().mid(6).toUtf8().constData(), "%d", &hEntry) == 1)
DbgMenuEntryClicked(hEntry);
}
}
MainWindow::MenuInfo* MainWindow::findMenu(int hMenu)
{
if(hMenu == -1)
return nullptr;
// TODO: optimize with a map
for(auto & menu : mMenuList)
if(menu.hMenu == hMenu)
return menu.deleted ? nullptr : &menu;
return nullptr;
}
MainWindow::MenuEntryInfo* MainWindow::findMenuEntry(int hEntry)
{
if(hEntry == -1)
return nullptr;
// TODO: optimize with a map
for(auto & entry : mEntryList)
if(entry.hEntry == hEntry)
return entry.deleted ? nullptr : &entry;
return nullptr;
}
void MainWindow::addMenuToList(QWidget* parent, QMenu* menu, GUIMENUTYPE hMenu, int hParentMenu)
{
QMutexLocker locker(mMenuMutex);
if(!findMenu(hMenu))
mMenuList.push_back(MenuInfo(parent, menu, hMenu, hParentMenu, hMenu == GUI_PLUGIN_MENU));
Bridge::getBridge()->setResult(BridgeResult::MenuAddToList);
}
void MainWindow::addMenu(int hMenu, QString title)
{
QMutexLocker locker(mMenuMutex);
auto parentMenu = findMenu(hMenu);
if(hMenu != -1 && parentMenu == nullptr)
{
Bridge::getBridge()->setResult(BridgeResult::MenuAdd, -1);
return;
}
int hMenuNew = hEntryMenuPool++;
MenuInfo newInfo;
newInfo.hMenu = hMenuNew;
newInfo.hParentMenu = hMenu;
newInfo.globalMenu = !parentMenu || parentMenu->globalMenu;
mMenuList.push_back(newInfo);
MethodInvoker::invokeMethod([this, hMenuNew, title]
{
QMutexLocker locker(mMenuMutex);
// Abort if another thread deleted the entry or the parent menu
auto menu = findMenu(hMenuNew);
if(!menu)
return;
auto parentMenu = findMenu(menu->hParentMenu);
if(parentMenu == nullptr && menu->hParentMenu != -1)
return;
// Actually create the menu
QWidget* parent = menu->hParentMenu == -1 ? this : parentMenu->parent;
menu->parent = parent;
QMenu* wMenu = new QMenu(title, parent);
menu->mMenu = wMenu;
wMenu->menuAction()->setVisible(false);
if(menu->hParentMenu == -1) //top-level
ui->menuBar->addMenu(wMenu);
else //deeper level
{
parentMenu->mMenu->addMenu(wMenu);
parentMenu->mMenu->menuAction()->setVisible(true);
}
});
Bridge::getBridge()->setResult(BridgeResult::MenuAdd, hMenuNew);
}
void MainWindow::addMenuEntry(int hMenu, QString title)
{
QMutexLocker locker(mMenuMutex);
if(hMenu != -1 && findMenu(hMenu) == nullptr)
{
Bridge::getBridge()->setResult(BridgeResult::MenuAddEntry, -1);
return;
}
MenuEntryInfo newInfo;
int hEntryNew = hEntryMenuPool++;
newInfo.hEntry = hEntryNew;
newInfo.hParentMenu = hMenu;
mEntryList.push_back(newInfo);
MethodInvoker::invokeMethod([this, hEntryNew, title]
{
QMutexLocker locker(mMenuMutex);
// Abort if another thread deleted the entry or the parent menu
auto entry = findMenuEntry(hEntryNew);
if(entry == nullptr)
return;
auto menu = findMenu(entry->hParentMenu);
if(menu == nullptr && entry->hParentMenu != -1)
return;
// Actually create the menu action
QWidget* parent = entry->hParentMenu == -1 ? this : menu->parent;
QAction* wAction = new QAction(title, parent);
parent->addAction(wAction);
wAction->setObjectName(QString().sprintf("ENTRY|%d", hEntryNew));
wAction->setShortcutContext((!menu || menu->globalMenu) ? Qt::ApplicationShortcut : Qt::WidgetShortcut);
parent->addAction(wAction); // TODO: something is wrong here
connect(wAction, SIGNAL(triggered()), this, SLOT(menuEntrySlot()));
entry->mAction = wAction;
if(entry->hParentMenu == -1) //top level
ui->menuBar->addAction(wAction);
else //deeper level
{
menu->mMenu->addAction(wAction);
menu->mMenu->menuAction()->setVisible(true);
}
});
Bridge::getBridge()->setResult(BridgeResult::MenuAddEntry, hEntryNew);
}
void MainWindow::addSeparator(int hMenu)
{
QMutexLocker locker(mMenuMutex);
if(findMenu(hMenu) == nullptr)
{
Bridge::getBridge()->setResult(BridgeResult::MenuAddSeparator, -1);
return;
}
MenuEntryInfo newInfo;
auto hEntryNew = hEntryMenuPool++;
newInfo.hEntry = hEntryNew;
newInfo.hParentMenu = hMenu;
mEntryList.push_back(newInfo);
MethodInvoker::invokeMethod([this, hEntryNew]
{
QMutexLocker locker(mMenuMutex);
// Abort if another thread deleted the entry or the parent menu
auto entry = findMenuEntry(hEntryNew);
if(entry == nullptr)
return;
auto menu = findMenu(entry->hParentMenu);
if(menu == nullptr)
return;
// Actually create the separator
entry->mAction = menu->mMenu->addSeparator();
});
Bridge::getBridge()->setResult(BridgeResult::MenuAddSeparator, hEntryNew);
}
void MainWindow::clearMenuHelper(int hMenu, bool markAsDeleted)
{
//delete menu entries
for(int i = mEntryList.size() - 1; i != -1; i--)
{
if(hMenu == mEntryList[i].hParentMenu) //we found an entry that has the menu as parent
{
if(markAsDeleted)
mEntryList[i].deleted = true;
else
mEntryList.erase(mEntryList.begin() + i);
}
}
//delete the menus
std::vector<int> menuClearQueue;
for(int i = mMenuList.size() - 1; i != -1; i--)
{
if(hMenu == mMenuList[i].hParentMenu) //we found a menu that has the menu as parent
{
menuClearQueue.push_back(mMenuList[i].hMenu);
if(markAsDeleted)
mMenuList[i].deleted = true;
else
mMenuList.erase(mMenuList.begin() + i);
}
}
//recursively clear the menus
for(auto & hMenu : menuClearQueue)
clearMenuHelper(hMenu, markAsDeleted);
}
void MainWindow::clearMenuImpl(int hMenu, bool erase)
{
//this recursively removes the entries from mEntryList and mMenuList
clearMenuHelper(hMenu, false);
for(auto it = mMenuList.begin(); it != mMenuList.end(); ++it)
{
auto & curMenu = *it;
if(hMenu == curMenu.hMenu)
{
if(erase)
{
auto parentMenu = findMenu(curMenu.hParentMenu);
if(parentMenu)
{
parentMenu->mMenu->removeAction(curMenu.mMenu->menuAction()); //remove the QMenu from the parent
if(parentMenu->mMenu->actions().empty()) //hide the parent if it is now empty
parentMenu->mMenu->menuAction()->setVisible(false);
}
it = mMenuList.erase(it);
}
else
{
curMenu.mMenu->clear(); //clear the QMenu
curMenu.mMenu->menuAction()->setVisible(false);
}
break;
}
}
}
void MainWindow::clearMenu(int hMenu, bool erase)
{
QMutexLocker locker(mMenuMutex);
if(findMenu(hMenu) == nullptr)
{
Bridge::getBridge()->setResult(BridgeResult::MenuClear, -1);
return;
}
// Mark all the children of the menu as deleted
clearMenuHelper(hMenu, true);
MethodInvoker::invokeMethod([this, hMenu, erase]
{
QMutexLocker locker(mMenuMutex);
// Actually clear the menu
clearMenuImpl(hMenu, erase);
});
Bridge::getBridge()->setResult(BridgeResult::MenuClear);
}
void MainWindow::removeMenuEntry(int hEntryMenu)
{
QMutexLocker locker(mMenuMutex);
auto entry = findMenuEntry(hEntryMenu);
if(entry != nullptr)
{
// Delete a single menu entry
entry->deleted = true;
MethodInvoker::invokeMethod([this, hEntryMenu]
{
QMutexLocker locker(mMenuMutex);
for(int i = 0; i < mEntryList.size(); i++)
{
if(mEntryList.at(i).hEntry == hEntryMenu)
{
auto & entry = mEntryList.at(i);
auto parentMenu = findMenu(entry.hParentMenu);
if(parentMenu)
{
parentMenu->mMenu->removeAction(entry.mAction);
if(parentMenu->mMenu->actions().empty())
parentMenu->mMenu->menuAction()->setVisible(false);
mEntryList.erase(mEntryList.begin() + i);
}
break;
}
}
});
Bridge::getBridge()->setResult(BridgeResult::MenuRemove);
return;
}
auto menu = findMenu(hEntryMenu);
if(menu != nullptr)
{
// Mark the menu and all submenus as deleted
menu->deleted = true;
clearMenuHelper(hEntryMenu, true);
MethodInvoker::invokeMethod([this, hEntryMenu]
{
// Actually delete the menu and all submenus
clearMenuImpl(hEntryMenu, true);
});
Bridge::getBridge()->setResult(BridgeResult::MenuRemove);
return;
}
Bridge::getBridge()->setResult(BridgeResult::MenuRemove, -1);
}
void MainWindow::setIconMenuEntry(int hEntry, QIcon icon)
{
MethodInvoker::invokeMethod([this, hEntry, icon]
{
QMutexLocker locker(mMenuMutex);
auto entry = findMenuEntry(hEntry);
if(entry == nullptr)
return;
entry->mAction->setIcon(icon);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetEntryIcon);
}
void MainWindow::setIconMenu(int hMenu, QIcon icon)
{
MethodInvoker::invokeMethod([this, hMenu, icon]
{
QMutexLocker locker(mMenuMutex);
auto menu = findMenu(hMenu);
if(menu == nullptr)
return;
menu->mMenu->setIcon(icon);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetIcon);
}
void MainWindow::setCheckedMenuEntry(int hEntry, bool checked)
{
MethodInvoker::invokeMethod([this, hEntry, checked]
{
QMutexLocker locker(mMenuMutex);
auto entry = findMenuEntry(hEntry);
if(entry == nullptr)
return;
entry->mAction->setCheckable(true);
entry->mAction->setChecked(checked);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetEntryChecked);
}
QString MainWindow::nestedMenuDescription(const MenuInfo* menu)
{
auto found = findMenu(menu->hParentMenu);
if(!found)
return menu->mMenu->title();
auto nest = nestedMenuDescription(found);
if(nest.isEmpty())
{
switch(menu->hParentMenu)
{
case GUI_DISASM_MENU:
nest = tr("&Plugins") + " -> " + tr("Disassembly");
break;
case GUI_DUMP_MENU:
nest = tr("&Plugins") + " -> " + tr("Dump");
break;
case GUI_STACK_MENU:
nest = tr("&Plugins") + " -> " + tr("Stack");
break;
}
}
nest += " -> ";
return nest + menu->mMenu->title();
}
QString MainWindow::nestedMenuEntryDescription(const MenuEntryInfo & entry)
{
return QString(nestedMenuDescription(findMenu(entry.hParentMenu)) + " -> " + entry.mAction->text()).replace("&", "");
}
void MainWindow::setHotkeyMenuEntry(int hEntry, QString hotkey, QString id)
{
MethodInvoker::invokeMethod([this, hEntry, hotkey, id]
{
QMutexLocker locker(mMenuMutex);
auto entry = findMenuEntry(hEntry);
if(entry == nullptr)
return;
entry->hotkeyId = QString("Plugin_") + id;
entry->hotkey = hotkey;
entry->hotkeyGlobal = entry->mAction->shortcutContext() == Qt::ApplicationShortcut;
Config()->setPluginShortcut(entry->hotkeyId, nestedMenuEntryDescription(*entry), hotkey, entry->hotkeyGlobal);
refreshShortcuts();
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetEntryHotkey);
}
void MainWindow::setVisibleMenuEntry(int hEntry, bool visible)
{
MethodInvoker::invokeMethod([this, hEntry, visible]
{
QMutexLocker locker(mMenuMutex);
auto entry = findMenuEntry(hEntry);
if(entry == nullptr)
return;
entry->mAction->setVisible(visible);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetEntryVisible);
}
void MainWindow::setVisibleMenu(int hMenu, bool visible)
{
MethodInvoker::invokeMethod([this, hMenu, visible]
{
QMutexLocker locker(mMenuMutex);
auto menu = findMenu(hMenu);
if(menu == nullptr)
return;
menu->mMenu->setVisible(visible);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetVisible);
}
void MainWindow::setNameMenuEntry(int hEntry, QString name)
{
MethodInvoker::invokeMethod([this, hEntry, name]
{
QMutexLocker locker(mMenuMutex);
auto entry = findMenuEntry(hEntry);
if(entry == nullptr)
return;
entry->mAction->setText(name);
Config()->setPluginShortcut(entry->hotkeyId, nestedMenuEntryDescription(*entry), entry->hotkey, entry->hotkeyGlobal);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetEntryName);
}
void MainWindow::setNameMenu(int hMenu, QString name)
{
MethodInvoker::invokeMethod([this, hMenu, name]
{
QMutexLocker locker(mMenuMutex);
auto menu = findMenu(hMenu);
if(menu == nullptr)
return;
menu->mMenu->setTitle(name);
});
Bridge::getBridge()->setResult(BridgeResult::MenuSetName);
}
void MainWindow::runSelection()
{
if(DbgIsDebugging())
{
duint addr = 0;
if(mTabWidget->currentWidget() == mCpuWidget || (mCpuWidget->window() != this && mCpuWidget->isActiveWindow()))
addr = mCpuWidget->getSelectionVa();
else if(mTabWidget->currentWidget() == mCallStackView || (mCallStackView->window() != this && mCallStackView->isActiveWindow()))
addr = mCallStackView->getSelectionVa();
if(addr)
DbgCmdExec("run " + ToPtrString(addr));
}
}
void MainWindow::runExpression()
{
if(!DbgIsDebugging())
return;
GotoDialog gotoDialog(this);
gotoDialog.setWindowTitle(tr("Enter expression to run to..."));
if(gotoDialog.exec() != QDialog::Accepted)
return;
if(DbgCmdExecDirect(QString("bp \"%1\", ss").arg(gotoDialog.expressionText).toUtf8().constData()))
DbgCmdExecDirect("run");
}
void MainWindow::getStrWindow(const QString title, QString* text)
{
LineEditDialog mLineEdit(this);
mLineEdit.setWindowTitle(title);
bool bResult = true;
if(mLineEdit.exec() != QDialog::Accepted)
bResult = false;
*text = mLineEdit.editText;
Bridge::getBridge()->setResult(BridgeResult::GetlineWindow, bResult);
}
void MainWindow::patchWindow()
{
if(!DbgIsDebugging())
{
SimpleErrorBox(this, tr("Error!"), tr("Patches can only be shown while debugging..."));
return;
}
GuiUpdatePatches();
mPatchDialog->showNormal();
mPatchDialog->setFocus();
}
void MainWindow::displayComments()
{
if(!DbgIsDebugging())
return;
DbgCmdExec("commentlist");
displayReferencesWidget();
}
void MainWindow::displayLabels()
{
if(!DbgIsDebugging())
return;
DbgCmdExec("labellist");
displayReferencesWidget();
}
void MainWindow::displayBookmarks()
{
if(!DbgIsDebugging())
return;
DbgCmdExec("bookmarklist");
displayReferencesWidget();
}
void MainWindow::displayFunctions()
{
if(!DbgIsDebugging())
return;
DbgCmdExec("functionlist");
displayReferencesWidget();
}
void MainWindow::displayCallstack()
{
showQWidgetTab(mCallStackView);
}
void MainWindow::displaySEHChain()
{
showQWidgetTab(mSEHChainView);
}
void MainWindow::displayTraceWidget()
{
showQWidgetTab(mTraceWidget);
}
void MainWindow::donate()
{
QMessageBox msg(QMessageBox::Information, tr("Donate"), tr("All the money will go to x64dbg development."));
msg.setWindowIcon(DIcon("donate"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setDefaultButton(QMessageBox::Ok);
if(msg.exec() != QMessageBox::Ok)
return;
QDesktopServices::openUrl(QUrl("https://donate.x64dbg.com"));
}
void MainWindow::blog()
{
QMessageBox msg(QMessageBox::Information, tr("Blog"), tr("You will visit x64dbg's official blog."));
msg.setWindowIcon(DIcon("hex"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setDefaultButton(QMessageBox::Ok);
if(msg.exec() != QMessageBox::Ok)
return;
QDesktopServices::openUrl(QUrl("http://blog.x64dbg.com"));
}
void MainWindow::reportBug()
{
QMessageBox msg(QMessageBox::Information, tr("Report Bug"), tr("You will be taken to a website where you can report a bug.\nMake sure to fill in as much information as possible."));
msg.setWindowIcon(DIcon("bug-report"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setDefaultButton(QMessageBox::Ok);
if(msg.exec() != QMessageBox::Ok)
return;
QDesktopServices::openUrl(QUrl("http://report.x64dbg.com"));
}
void MainWindow::crashDump()
{
QMessageBox msg(QMessageBox::Critical, tr("Generate crash dump"), tr("This action will crash the debugger and generate a crash dump. You will LOSE ALL YOUR UNSAVED DATA. Do you really want to continue?"));
msg.setWindowIcon(DIcon("fatal-error"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setDefaultButton(QMessageBox::Cancel);
if(msg.exec() != QMessageBox::Ok)
return;
// Fatal error
__debugbreak();
// Congratulations! We survived a fatal error!
SimpleWarningBox(this, tr("Have fun debugging the debugger!"), tr("Debugger detected!"));
}
void MainWindow::displayAttach()
{
AttachDialog attach(this);
attach.exec();
mCpuWidget->setDisasmFocus();
}
static bool getCmdLine(QString & cmdLine)
{
auto result = false;
size_t cbsize = 0;
if(DbgFunctions()->GetCmdline(0, &cbsize))
{
auto buffer = new char[cbsize];
if(DbgFunctions()->GetCmdline(buffer, 0))
{
cmdLine = buffer;
result = true;
}
delete[] buffer;
}
return result;
}
void MainWindow::changeCommandLine()
{
if(!DbgIsDebugging())
return;
LineEditDialog mLineEdit(this);
mLineEdit.setText("");
mLineEdit.setWindowTitle(tr("Change Command Line"));
mLineEdit.setWindowIcon(DIcon("changeargs"));
QString cmdLine;
if(!getCmdLine(cmdLine))
mLineEdit.setText(tr("Cannot get remote command line, use the 'getcmdline' command for more information."));
else
mLineEdit.setText(cmdLine);
mLineEdit.setCursorPosition(0);
if(mLineEdit.exec() != QDialog::Accepted)
return; //pressed cancel
if(!DbgFunctions()->SetCmdline((char*)mLineEdit.editText.toUtf8().constData()))
SimpleErrorBox(this, tr("Error!"), tr("Could not set command line!"));
else
{
DbgFunctions()->MemUpdateMap();
GuiUpdateMemoryView();
getCmdLine(cmdLine);
GuiAddLogMessage((tr("New command line: ") + cmdLine + "\n").toUtf8().constData());
}
}
static void onlineManual()
{
QDesktopServices::openUrl(QUrl("http://help.x64dbg.com"));
}
void MainWindow::displayManual()
{
duint setting = 0;
if(BridgeSettingGetUint("Misc", "UseLocalHelpFile", &setting) && setting)
{
// Open the Windows CHM in the upper directory
if(!QDesktopServices::openUrl(QUrl(QUrl::fromLocalFile(QString("%1/../x64dbg.chm").arg(QCoreApplication::applicationDirPath())))))
{
QMessageBox messagebox(QMessageBox::Critical, tr("Error"),
tr("Manual cannot be opened. Please check if x64dbg.chm exists and ensure there is no other problems with your system.") + '\n'
+ tr("Do you want to open online manual at http://help.x64dbg.com ?"),
QMessageBox::Yes | QMessageBox::No);
if(messagebox.exec() == QMessageBox::Yes)
onlineManual();
}
}
else
onlineManual();
}
void MainWindow::canClose()
{
bCanClose = true;
close();
}
void MainWindow::addQWidgetTab(QWidget* qWidget, QString nativeName)
{
mTabWidget->addTabEx(qWidget, qWidget->windowIcon(), qWidget->windowTitle(), nativeName);
}
void MainWindow::addQWidgetTab(QWidget* qWidget)
{
QString nativeName = qWidget->objectName();
if(nativeName.isEmpty())
nativeName = qWidget->metaObject()->className();
nativeName = "Plugin" + nativeName.replace(" ", "_").replace("=", "_");
WidgetInfo info(qWidget, nativeName);
addQWidgetTab(info.widget, info.nativeName);
mPluginWidgetList.append(info);
}
void MainWindow::showQWidgetTab(QWidget* qWidget)
{
qWidget->show();
qWidget->setFocus();
setTab(qWidget);
}
void MainWindow::closeQWidgetTab(QWidget* qWidget)
{
for(int i = 0; i < mTabWidget->count(); i++)
{
if(mTabWidget->widget(i) == qWidget)
{
mTabWidget->DeleteTab(i);
break;
}
}
}
void MainWindow::executeOnGuiThread(void* cbGuiThread, void* userdata)
{
((GUICALLBACKEX)cbGuiThread)(userdata);
}
void MainWindow::tabMovedSlot(int from, int to)
{
Q_UNUSED(from);
Q_UNUSED(to);
for(int i = 0; i < mTabWidget->count(); i++)
{
auto tabName = mTabWidget->getNativeName(i);
BridgeSettingSetUint("TabOrder", tabName.toUtf8().constData(), i);
}
}
void MainWindow::chkSaveloadTabSavedOrderStateChangedSlot(bool state)
{
if(state)
loadTabSavedOrder();
else
loadTabDefaultOrder();
}
void MainWindow::dbgStateChangedSlot(DBGSTATE state)
{
if(state == initialized) //fixes a crash when restarting with certain settings in another tab
displayCpuWidget();
if(bExitWhenDetached && state == stopped) //detach and exit: the debugger has detached, no exit confirmation dialog this time
close();
}
void MainWindow::on_actionFaq_triggered()
{
QDesktopServices::openUrl(QUrl("http://faq.x64dbg.com"));
}
void MainWindow::on_actionReloadStylesheet_triggered()
{
loadSelectedTheme(true);
ensurePolished();
update();
}
void MainWindow::displayNotesWidget()
{
showQWidgetTab(mNotesManager);
}
void MainWindow::displayHandlesWidget()
{
showQWidgetTab(mHandlesView);
}
void MainWindow::manageFavourites()
{
FavouriteTools favToolsDialog(this);
favToolsDialog.exec();
updateFavouriteTools();
}
static void splitToolPath(const QString & toolPath, QString & file, QString & cmd)
{
if(toolPath.startsWith('\"'))
{
auto endQuote = toolPath.indexOf('\"', 1);
if(endQuote == -1) //"failure with spaces
file = toolPath.mid(1);
else //"path with spaces" arguments
{
file = toolPath.mid(1, endQuote - 1);
cmd = toolPath.mid(endQuote + 1);
}
}
else
{
auto firstSpace = toolPath.indexOf(' ');
if(firstSpace == -1) //pathwithoutspaces
file = toolPath;
else //pathwithoutspaces argument
{
file = toolPath.left(firstSpace);
cmd = toolPath.mid(firstSpace + 1);
}
}
file = file.trimmed();
cmd = cmd.trimmed();
}
void MainWindow::updateFavouriteTools()
{
char buffer[MAX_SETTING_SIZE];
bool isanythingexists = false;
ui->menuFavourites->clear();
delete actionManageFavourites;
mFavouriteToolbar->clear();
actionManageFavourites = new QAction(DIcon("star"), tr("&Manage Favourite Tools..."), this);
actionManageFavourites->setStatusTip(tr("Open the Favourites dialog to manage the favourites menu"));
for(unsigned int i = 1; BridgeSettingGet("Favourite", QString("Tool%1").arg(i).toUtf8().constData(), buffer); i++)
{
QString toolPath = QString(buffer);
QAction* newAction = new QAction(actionManageFavourites); // Auto delete these actions on updateFavouriteTools()
// Set up user data to be used in clickFavouriteTool()
newAction->setData(QVariant(QString("Tool,%1").arg(toolPath)));
if(BridgeSettingGet("Favourite", QString("ToolShortcut%1").arg(i).toUtf8().constData(), buffer))
if(*buffer && strcmp(buffer, "NOT_SET") != 0)
setGlobalShortcut(newAction, QKeySequence(QString(buffer)));
QString description;
if(BridgeSettingGet("Favourite", QString("ToolDescription%1").arg(i).toUtf8().constData(), buffer))
description = QString(buffer);
else
description = toolPath;
newAction->setText(description);
newAction->setStatusTip(description);
// Get the icon of the executable
QString file, cmd;
QIcon icon;
splitToolPath(toolPath, file, cmd);
icon = getFileIcon(file);
if(icon.isNull())
icon = DIcon("plugin");
newAction->setIcon(icon);
connect(newAction, SIGNAL(triggered()), this, SLOT(clickFavouriteTool()));
ui->menuFavourites->addAction(newAction);
mFavouriteToolbar->addAction(newAction);
isanythingexists = true;
}
if(isanythingexists)
{
isanythingexists = false;
ui->menuFavourites->addSeparator();
mFavouriteToolbar->addSeparator();
}
for(unsigned int i = 1; BridgeSettingGet("Favourite", QString("Script%1").arg(i).toUtf8().constData(), buffer); i++)
{
QString scriptPath = QString(buffer);
QAction* newAction = new QAction(actionManageFavourites);
// Set up user data to be used in clickFavouriteTool()
newAction->setData(QVariant(QString("Script,%1").arg(scriptPath)));
if(BridgeSettingGet("Favourite", QString("ScriptShortcut%1").arg(i).toUtf8().constData(), buffer))
if(*buffer && strcmp(buffer, "NOT_SET") != 0)
setGlobalShortcut(newAction, QKeySequence(QString(buffer)));
QString description;
if(BridgeSettingGet("Favourite", QString("ScriptDescription%1").arg(i).toUtf8().constData(), buffer))
description = QString(buffer);
else
description = scriptPath;
newAction->setText(description);
newAction->setStatusTip(description);
connect(newAction, SIGNAL(triggered()), this, SLOT(clickFavouriteTool()));
newAction->setIcon(DIcon("script-code"));
ui->menuFavourites->addAction(newAction);
mFavouriteToolbar->addAction(newAction);
isanythingexists = true;
}
if(isanythingexists)
{
isanythingexists = false;
ui->menuFavourites->addSeparator();
mFavouriteToolbar->addSeparator();
}
for(unsigned int i = 1; BridgeSettingGet("Favourite", QString("Command%1").arg(i).toUtf8().constData(), buffer); i++)
{
QAction* newAction = new QAction(QString(buffer), actionManageFavourites);
newAction->setStatusTip(QString(buffer));
// Set up user data to be used in clickFavouriteTool()
newAction->setData(QVariant(QString("Command")));
if(BridgeSettingGet("Favourite", QString("CommandShortcut%1").arg(i).toUtf8().constData(), buffer))
if(*buffer && strcmp(buffer, "NOT_SET") != 0)
setGlobalShortcut(newAction, QKeySequence(QString(buffer)));
connect(newAction, SIGNAL(triggered()), this, SLOT(clickFavouriteTool()));
newAction->setIcon(DIcon("star"));
ui->menuFavourites->addAction(newAction);
mFavouriteToolbar->addAction(newAction);
isanythingexists = true;
}
if(isanythingexists)
{
ui->menuFavourites->addSeparator();
mFavouriteToolbar->addSeparator();
}
ui->menuFavourites->addAction(actionManageFavourites);
setGlobalShortcut(actionManageFavourites, ConfigShortcut("FavouritesManage"));
connect(ui->menuFavourites->actions().last(), SIGNAL(triggered()), this, SLOT(manageFavourites()));
mFavouriteToolbar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->menuFavourites->addAction(mFavouriteToolbar->toggleViewAction());
}
static QString stringFormatInline(const QString & format)
{
if(!DbgFunctions()->StringFormatInline)
return QString();
char result[MAX_SETTING_SIZE] = "";
if(DbgFunctions()->StringFormatInline(format.toUtf8().constData(), MAX_SETTING_SIZE, result))
return result;
return CPUArgumentWidget::tr("[Formatting Error]");
}
void MainWindow::clickFavouriteTool()
{
QAction* action = qobject_cast<QAction*>(sender());
if(action == nullptr)
return;
QString data = action->data().toString();
if(data.startsWith("Tool,"))
{
QString toolPath = data.mid(5);
duint PID = DbgValFromString("$pid");
toolPath.replace(QString("%PID%"), QString::number(PID), Qt::CaseInsensitive);
toolPath.replace(QString("%DEBUGGEE%"), mMRUList->getEntry(0), Qt::CaseInsensitive);
char modpath[MAX_MODULE_SIZE] = "";
DbgFunctions()->ModPathFromAddr(DbgValFromString("dis.sel()"), modpath, MAX_MODULE_SIZE);
toolPath.replace(QString("%MODULE%"), modpath, Qt::CaseInsensitive);
while(true)
{
auto sfStart = toolPath.indexOf("%-");
auto sfEnd = toolPath.indexOf("-%");
if(sfStart < 0 || sfEnd < 0 || sfEnd < sfStart)
break;
auto format = toolPath.mid(sfStart + 2, sfEnd - sfStart - 2);
toolPath.replace(sfStart, sfEnd - sfStart + 2, stringFormatInline(format));
}
GuiAddLogMessage(tr("Starting tool %1\n").arg(toolPath).toUtf8().constData());
PROCESS_INFORMATION procinfo;
STARTUPINFO startupinfo;
memset(&procinfo, 0, sizeof(PROCESS_INFORMATION));
memset(&startupinfo, 0, sizeof(startupinfo));
startupinfo.cb = sizeof(startupinfo);
if(CreateProcessW(nullptr, (LPWSTR)toolPath.toStdWString().c_str(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startupinfo, &procinfo))
{
CloseHandle(procinfo.hThread);
CloseHandle(procinfo.hProcess);
}
else if(GetLastError() == ERROR_ELEVATION_REQUIRED)
{
QString file, cmd;
splitToolPath(toolPath, file, cmd);
ShellExecuteW(nullptr, L"runas", file.toStdWString().c_str(), cmd.toStdWString().c_str(), nullptr, SW_SHOWNORMAL);
}
}
else if(data.startsWith("Script,"))
{
QString scriptPath = data.mid(7);
mScriptView->openRecentFile(scriptPath);
displayScriptWidget();
}
else if(data.compare("Command") == 0)
{
DbgCmdExec(action->text());
}
}
void MainWindow::chooseLanguage()
{
QAction* action = qobject_cast<QAction*>(sender());
QString localeName = action->text();
localeName = localeName.mid(1, localeName.indexOf(QChar(']')) - 1);
action->setChecked(localeName == QString(currentLocale));
if(localeName != "en_US")
{
QDir translationsDir(QString("%1/../translations/").arg(QCoreApplication::applicationDirPath()));
QFile file(translationsDir.absoluteFilePath(QString("x64dbg_%1.qm").arg(localeName)));
// A translation file less than 0.5KB is probably not useful
if(file.size() < 512)
{
QMessageBox msg(this);
msg.setWindowIcon(DIcon("codepage"));
msg.setIcon(QMessageBox::Information);
if(tr("Languages") == QString("Languages"))
{
msg.setWindowTitle(QString("Languages"));
msg.setText(QString("The translation is nearly empty. Do you still want to use this language?"));
}
else
{
msg.setWindowTitle(tr("Languages") + QString(" Languages"));
msg.setText(tr("The translation is nearly empty. Do you still want to use this language?") + QString("\r\nThe translation is nearly empty. Do you still want to use this language?"));
}
msg.addButton(QMessageBox::Yes);
msg.addButton(QMessageBox::No);
if(msg.exec() == QMessageBox::No)
return;
}
}
BridgeSettingSet("Engine", "Language", localeName.toUtf8().constData());
QMessageBox msg(this);
msg.setIcon(QMessageBox::Information);
msg.setWindowIcon(DIcon("codepage"));
if(tr("Languages") == QString("Languages"))
{
msg.setWindowTitle(QString("Languages"));
msg.setText(QString("New language setting will take effect upon restart."));
}
else
{
msg.setWindowTitle(tr("Languages") + QString(" Languages"));
msg.setText(tr("New language setting will take effect upon restart.") + QString("\r\nNew language setting will take effect upon restart."));
}
msg.exec();
}
void MainWindow::addFavouriteItem(int type, const QString & name, const QString & description)
{
if(type == 0) // Tools
{
char buffer[MAX_SETTING_SIZE];
unsigned int i;
for(i = 1; BridgeSettingGet("Favourite", (QString("Tool") + QString::number(i)).toUtf8().constData(), buffer); i++)
{
}
BridgeSettingSet("Favourite", (QString("Tool") + QString::number(i)).toUtf8().constData(), name.toUtf8().constData());
BridgeSettingSet("Favourite", (QString("ToolDescription") + QString::number(i)).toUtf8().constData(), description.toUtf8().constData());
if(BridgeSettingGet("Favourite", (QString("Tool") + QString::number(i + 1)).toUtf8().constData(), buffer))
{
buffer[0] = 0;
BridgeSettingSet("Favourite", (QString("Tool") + QString::number(i + 1)).toUtf8().constData(), buffer);
}
updateFavouriteTools();
}
else if(type == 2) // Commands
{
char buffer[MAX_SETTING_SIZE];
unsigned int i;
for(i = 1; BridgeSettingGet("Favourite", (QString("Command") + QString::number(i)).toUtf8().constData(), buffer); i++)
{
}
BridgeSettingSet("Favourite", (QString("Command") + QString::number(i)).toUtf8().constData(), name.toUtf8().constData());
BridgeSettingSet("Favourite", (QString("CommandShortcut") + QString::number(i)).toUtf8().constData(), description.toUtf8().constData());
if(BridgeSettingGet("Favourite", (QString("Command") + QString::number(i + 1)).toUtf8().constData(), buffer))
{
buffer[0] = 0;
BridgeSettingSet("Favourite", (QString("Command") + QString::number(i + 1)).toUtf8().constData(), buffer);
}
updateFavouriteTools();
}
}
void MainWindow::setFavouriteItemShortcut(int type, const QString & name, const QString & shortcut)
{
if(type == 0)
{
char buffer[MAX_SETTING_SIZE];
for(unsigned int i = 1; BridgeSettingGet("Favourite", QString("Tool%1").arg(i).toUtf8().constData(), buffer); i++)
{
if(QString(buffer) == name)
{
BridgeSettingSet("Favourite", (QString("ToolShortcut") + QString::number(i)).toUtf8().constData(), shortcut.toUtf8().constData());
updateFavouriteTools();
break;
}
}
}
}
void MainWindow::animateIntoSlot()
{
if(DbgIsDebugging())
DbgFunctions()->AnimateCommand("StepInto;AnimateWait");
}
void MainWindow::animateOverSlot()
{
if(DbgIsDebugging())
DbgFunctions()->AnimateCommand("StepOver;AnimateWait");
}
void MainWindow::animateCommandSlot()
{
QString command;
if(SimpleInputBox(this, tr("Animate command"), "", command, tr("Example: StepInto")))
DbgFunctions()->AnimateCommand(command.toUtf8().constData());
}
void MainWindow::setInitializationScript()
{
SystemBreakpointScriptDialog dialog(this);
dialog.exec();
}
void MainWindow::customizeMenu()
{
CustomizeMenuDialog customMenuDialog(this);
customMenuDialog.setWindowTitle(tr("Customize Menus"));
customMenuDialog.setWindowIcon(DIcon("analysis"));
customMenuDialog.exec();
onMenuCustomized();
}
void MainWindow::on_actionImportSettings_triggered()
{
auto filename = QFileDialog::getOpenFileName(this, tr("Open file"), QString::fromWCharArray(BridgeUserDirectory()), tr("Settings (*.ini);;All files (*.*)"));
if(!filename.length())
return;
importSettings(filename);
}
void MainWindow::on_actionImportdatabase_triggered()
{
if(!DbgIsDebugging())
return;
auto filename = QFileDialog::getOpenFileName(this, tr("Import database"), QString(), tr("Databases (%1);;Database backup (%1.bak);;All files (*.*)").arg(ArchValue("*.dd32", "*.dd64")));
if(!filename.length())
return;
DbgCmdExec(QString("dbload \"%1\"").arg(QDir::toNativeSeparators(filename)));
}
void MainWindow::on_actionExportdatabase_triggered()
{
if(!DbgIsDebugging())
return;
auto filename = QFileDialog::getSaveFileName(this, tr("Export database"), QString(), tr("Databases (%1);;All files (*.*)").arg(ArchValue("*.dd32", "*.dd64")));
if(!filename.length())
return;
DbgCmdExec(QString("dbsave \"%1\"").arg(QDir::toNativeSeparators(filename)));
}
static void setupMenuCustomizationHelper(QMenu* parentMenu, QList<QAction*> & stringList)
{
for(int i = 0; i < parentMenu->actions().size(); i++)
{
QAction* action = parentMenu->actions().at(i);
stringList.append(action);
}
}
void MainWindow::setupMenuCustomization()
{
mFileMenuStrings.append(new QAction("File", this));
setupMenuCustomizationHelper(ui->menuFile, mFileMenuStrings);
mDebugMenuStrings.append(new QAction("Debug", this));
setupMenuCustomizationHelper(ui->menuDebug, mDebugMenuStrings);
mOptionsMenuStrings.append(new QAction("Option", this));
setupMenuCustomizationHelper(ui->menuOptions, mOptionsMenuStrings);
mHelpMenuStrings.append(new QAction("Help", this));
setupMenuCustomizationHelper(ui->menuHelp, mHelpMenuStrings);
mViewMenuStrings.append(new QAction("View", this));
setupMenuCustomizationHelper(ui->menuView, mViewMenuStrings);
onMenuCustomized();
Config()->registerMainMenuStringList(&mFileMenuStrings);
Config()->registerMainMenuStringList(&mDebugMenuStrings);
Config()->registerMainMenuStringList(&mOptionsMenuStrings);
Config()->registerMainMenuStringList(&mHelpMenuStrings);
Config()->registerMainMenuStringList(&mViewMenuStrings);
}
void MainWindow::onMenuCustomized()
{
QList<QMenu*> menus;
QList<QString> menuNativeNames;
QList<QList<QAction*>*> menuTextStrings;
menus << ui->menuFile << ui->menuDebug << ui->menuOptions << ui->menuHelp << ui->menuView;
menuNativeNames << "File" << "Debug" << "Option" << "Help" << "View";
menuTextStrings << &mFileMenuStrings << &mDebugMenuStrings << &mOptionsMenuStrings << &mHelpMenuStrings << &mViewMenuStrings;
for(int i = 0; i < menus.size(); i++)
{
QMenu* currentMenu = menus[i];
QMenu* moreCommands = nullptr;
bool moreCommandsUsed = false;
QList<QAction*> list = currentMenu->actions();
moreCommands = list.last()->menu();
if(moreCommands && moreCommands->title().compare(tr("More Commands")) == 0)
{
for(auto & j : moreCommands->actions())
moreCommands->removeAction(j);
QAction* separatorMoreCommands = list.at(list.length() - 2);
currentMenu->removeAction(separatorMoreCommands); // Separator
delete separatorMoreCommands;
}
else
{
moreCommands = new QMenu(tr("More Commands"), currentMenu);
}
for(auto & j : list)
currentMenu->removeAction(j);
for(int j = 0; j < menuTextStrings.at(i)->size() - 1; j++)
{
QAction* a = menuTextStrings.at(i)->at(j + 1);
if(Config()->getBool("Gui", QString("Menu%1Hidden%2").arg(menuNativeNames[i]).arg(j)))
{
moreCommands->addAction(a);
moreCommandsUsed = true;
}
else
{
currentMenu->addAction(a);
}
}
if(moreCommandsUsed)
{
currentMenu->addSeparator();
currentMenu->addMenu(moreCommands);
}
else
delete moreCommands;
}
}
void MainWindow::on_actionPlugins_triggered()
{
QDesktopServices::openUrl(QUrl("http://plugins.x64dbg.com"));
}
void MainWindow::on_actionCheckUpdates_triggered()
{
mUpdateChecker->checkForUpdates();
}
void MainWindow::on_actionDefaultTheme_triggered()
{
// Revert to the Default theme
BridgeSettingSet("Theme", "Selected", "Default");
// Load style
loadSelectedTheme();
updateDarkTitleBar(this);
}
void MainWindow::on_actionAbout_Qt_triggered()
{
auto w = new QWidget(this);
w->setWindowIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarMenuButton));
QMessageBox::aboutQt(w);
delete w;
}
void MainWindow::updateStyle()
{
// Set configured link color
QPalette appPalette = QApplication::palette();
appPalette.setColor(QPalette::Link, ConfigColor("LinkColor"));
QApplication::setPalette(appPalette);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/MainWindow.h | #pragma once
#include <QMainWindow>
#include "Imports.h"
class QMutex;
class QDragEnterEvent;
class QDropEvent;
class QMutex;
class CloseDialog;
class CommandLineEdit;
class MHTabWidget;
class CPUWidget;
class MemoryMapView;
class CallStackView;
class SEHChainView;
class LogView;
class SymbolView;
class BreakpointsView;
class ScriptView;
class ReferenceManager;
class ThreadView;
class PatchDialog;
class CalculatorDialog;
class DebugStatusLabel;
class LogStatusLabel;
class SourceViewerManager;
class HandlesView;
class MainWindowCloseThread;
class TimeWastedCounter;
class NotesManager;
class SettingsDialog;
class SimpleTraceDialog;
class MRUList;
class UpdateChecker;
class TraceWidget;
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
void setupCommandBar();
void setupStatusBar();
void closeEvent(QCloseEvent* event);
void setTab(QWidget* widget);
void loadTabDefaultOrder();
void loadTabSavedOrder();
void clearTabWidget();
static void loadSelectedTheme(bool reloadOnlyStyleCss = false);
static void updateDarkTitleBar(QWidget* widget);
public slots:
void saveWindowSettings();
void loadWindowSettings();
void executeCommand();
void execCommandSlot();
void setFocusToCommandBar();
void displayMemMapWidget();
void displayLogWidget();
void displayScriptWidget();
void displayAboutWidget();
void execTocnd();
void execTicnd();
void animateIntoSlot();
void animateOverSlot();
void animateCommandSlot();
void openFileSlot();
void openRecentFileSlot(QString filename);
void restartDebugging();
void displayBreakpointWidget();
void updateWindowTitleSlot(QString filename);
void runSlot();
void execTRBit();
void execTRByte();
void execTRWord();
void execTRNone();
void displayCpuWidget();
void displayCpuWidgetShowCpu();
void displaySymbolWidget();
void displaySourceViewWidget();
void displayReferencesWidget();
void displayThreadsWidget();
void displayVariables();
void displayGraphWidget();
void displayTraceWidget();
void openSettings();
void openAppearance();
void openCalculator();
void addRecentFile(QString file);
void setLastException(unsigned int exceptionCode);
void findStrings();
void findModularCalls();
void addMenuToList(QWidget* parent, QMenu* menu, GUIMENUTYPE hMenu, int hParentMenu = -1);
void addMenu(int hMenu, QString title);
void addMenuEntry(int hMenu, QString title);
void addSeparator(int hMenu);
void clearMenu(int hMenu, bool erase);
void menuEntrySlot();
void removeMenuEntry(int hEntryMenu);
void setIconMenuEntry(int hEntry, QIcon icon);
void setIconMenu(int hMenu, QIcon icon);
void setCheckedMenuEntry(int hEntry, bool checked);
void setHotkeyMenuEntry(int hEntry, QString hotkey, QString id);
void setVisibleMenuEntry(int hEntry, bool visible);
void setVisibleMenu(int hMenu, bool visible);
void setNameMenuEntry(int hEntry, QString name);
void setNameMenu(int hMenu, QString name);
void runSelection();
void runExpression();
void getStrWindow(const QString title, QString* text);
void patchWindow();
void displayComments();
void displayLabels();
void displayBookmarks();
void displayFunctions();
void crashDump();
void displayCallstack();
void displaySEHChain();
void setGlobalShortcut(QAction* action, const QKeySequence & key);
void refreshShortcuts();
void openShortcuts();
void changeTopmost(bool checked);
void donate();
void blog();
void reportBug();
void displayAttach();
void changeCommandLine();
void displayManual();
void canClose();
void addQWidgetTab(QWidget* qWidget, QString nativeName);
void addQWidgetTab(QWidget* qWidget);
void showQWidgetTab(QWidget* qWidget);
void closeQWidgetTab(QWidget* qWidget);
void executeOnGuiThread(void* cbGuiThread, void* userdata);
void tabMovedSlot(int from, int to);
void chkSaveloadTabSavedOrderStateChangedSlot(bool state);
void dbgStateChangedSlot(DBGSTATE state);
void displayNotesWidget();
void displayHandlesWidget();
void manageFavourites();
void updateFavouriteTools();
void clickFavouriteTool();
void chooseLanguage();
void setInitializationScript();
void customizeMenu();
void addFavouriteItem(int type, const QString & name, const QString & description);
void setFavouriteItemShortcut(int type, const QString & name, const QString & shortcut);
void themeTriggeredSlot();
private:
Ui::MainWindow* ui;
CloseDialog* mCloseDialog;
CommandLineEdit* mCmdLineEdit;
MHTabWidget* mTabWidget;
CPUWidget* mCpuWidget;
MemoryMapView* mMemMapView;
CallStackView* mCallStackView;
SEHChainView* mSEHChainView;
LogView* mLogView;
SymbolView* mSymbolView;
SourceViewerManager* mSourceViewManager;
BreakpointsView* mBreakpointsView;
ScriptView* mScriptView;
ReferenceManager* mReferenceManager;
ThreadView* mThreadView;
PatchDialog* mPatchDialog;
CalculatorDialog* mCalculatorDialog;
HandlesView* mHandlesView;
NotesManager* mNotesManager;
TraceWidget* mTraceWidget;
SimpleTraceDialog* mSimpleTraceDialog;
UpdateChecker* mUpdateChecker;
DebugStatusLabel* mStatusLabel;
LogStatusLabel* mLastLogLabel;
QToolBar* mFavouriteToolbar;
TimeWastedCounter* mTimeWastedCounter;
QString mWindowMainTitle;
MRUList* mMRUList;
unsigned int lastException;
QAction* actionManageFavourites;
void updateMRUMenu();
void setupLanguagesMenu();
void setupThemesMenu();
void onMenuCustomized();
void setupMenuCustomization();
QAction* makeCommandAction(QAction* action, const QString & command);
//lists for menu customization
QList<QAction*> mFileMenuStrings;
QList<QAction*> mViewMenuStrings;
QList<QAction*> mDebugMenuStrings;
//"Plugins" menu cannot be customized for item hiding.
//"Favourites" menu cannot be customized for item hiding.
QList<QAction*> mOptionsMenuStrings;
QList<QAction*> mHelpMenuStrings;
//menu api
struct MenuEntryInfo
{
MenuEntryInfo() = default;
QAction* mAction = nullptr;
int hEntry = -1;
int hParentMenu = -1;
QString hotkey;
QString hotkeyId;
bool hotkeyGlobal = false;
bool deleted = false;
};
struct MenuInfo
{
public:
MenuInfo(QWidget* parent, QMenu* mMenu, int hMenu, int hParentMenu, bool globalMenu)
: parent(parent), mMenu(mMenu), hMenu(hMenu), hParentMenu(hParentMenu), globalMenu(globalMenu)
{
}
MenuInfo() = default;
QWidget* parent = nullptr;
QMenu* mMenu = nullptr;
int hMenu = -1;
int hParentMenu = -1;
bool globalMenu = false;
bool deleted = false;
};
QMutex* mMenuMutex = nullptr;
int hEntryMenuPool;
QList<MenuEntryInfo> mEntryList;
QList<MenuInfo> mMenuList;
void initMenuApi();
MenuInfo* findMenu(int hMenu);
MenuEntryInfo* findMenuEntry(int hEntry);
QString nestedMenuDescription(const MenuInfo* menu);
QString nestedMenuEntryDescription(const MenuEntryInfo & entry);
void clearMenuHelper(int hMenu, bool markAsDeleted);
void clearMenuImpl(int hMenu, bool erase);
bool bCanClose;
bool bExitWhenDetached;
MainWindowCloseThread* mCloseThread;
struct WidgetInfo
{
public:
WidgetInfo(QWidget* widget, QString nativeName)
{
this->widget = widget;
this->nativeName = nativeName;
}
QWidget* widget;
QString nativeName;
};
QList<WidgetInfo> mWidgetList;
QList<WidgetInfo> mPluginWidgetList;
protected:
void dragEnterEvent(QDragEnterEvent* pEvent) override;
void dropEvent(QDropEvent* pEvent) override;
bool event(QEvent* event) override;
private slots:
void setupLanguagesMenu2();
void updateStyle();
void on_actionFaq_triggered();
void on_actionReloadStylesheet_triggered();
void on_actionImportSettings_triggered();
void on_actionImportdatabase_triggered();
void on_actionExportdatabase_triggered();
void on_actionPlugins_triggered();
void on_actionCheckUpdates_triggered();
void on_actionDefaultTheme_triggered();
void on_actionAbout_Qt_triggered();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/MainWindow.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>868</width>
<height>600</height>
</rect>
</property>
<property name="contextMenuPolicy">
<enum>Qt::NoContextMenu</enum>
</property>
<property name="windowTitle">
<string>x64dbg</string>
</property>
<widget class="QWidget" name="centralWidget"/>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>868</width>
<height>21</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>&File</string>
</property>
<widget class="QMenu" name="menuRecentFiles">
<property name="title">
<string>&Recent Files</string>
</property>
<property name="icon">
<iconset theme="recentfiles" resource="../../resource.qrc">
<normaloff>:/Default/icons/recentfiles.png</normaloff>:/Default/icons/recentfiles.png</iconset>
</property>
<addaction name="separator"/>
</widget>
<widget class="QMenu" name="menuDatabase">
<property name="title">
<string>Database</string>
</property>
<property name="icon">
<iconset theme="data-copy" resource="../../resource.qrc">
<normaloff>:/Default/icons/data-copy.png</normaloff>:/Default/icons/data-copy.png</iconset>
</property>
<addaction name="actionDbsave"/>
<addaction name="actionDbload"/>
<addaction name="actionDbrecovery"/>
<addaction name="actionDbclear"/>
<addaction name="separator"/>
<addaction name="actionImportdatabase"/>
<addaction name="actionExportdatabase"/>
</widget>
<addaction name="actionOpen"/>
<addaction name="menuRecentFiles"/>
<addaction name="actionAttach"/>
<addaction name="actionDetach"/>
<addaction name="menuDatabase"/>
<addaction name="actionPatches"/>
<addaction name="actionChangeCommandLine"/>
<addaction name="actionRestartAdmin"/>
<addaction name="separator"/>
<addaction name="actionExit"/>
</widget>
<widget class="QMenu" name="menuView">
<property name="title">
<string>&View</string>
</property>
<addaction name="actionCpu"/>
<addaction name="actionLog"/>
<addaction name="actionNotes"/>
<addaction name="actionBreakpoints"/>
<addaction name="actionMemoryMap"/>
<addaction name="actionCallStack"/>
<addaction name="actionSEHChain"/>
<addaction name="actionScript"/>
<addaction name="actionSymbolInfo"/>
<addaction name="actionModules"/>
<addaction name="actionSource"/>
<addaction name="actionReferences"/>
<addaction name="actionThreads"/>
<addaction name="actionHandles"/>
<addaction name="actionGraph"/>
<addaction name="actionTrace"/>
<addaction name="actionPatches"/>
<addaction name="actionComments"/>
<addaction name="actionLabels"/>
<addaction name="actionBookmarks"/>
<addaction name="actionFunctions"/>
<addaction name="actionVariables"/>
<addaction name="actionCommand"/>
<addaction name="separator"/>
<addaction name="actionPreviousTab"/>
<addaction name="actionNextTab"/>
<addaction name="actionPreviousView"/>
<addaction name="actionNextView"/>
<addaction name="actionHideTab"/>
</widget>
<widget class="QMenu" name="menuDebug">
<property name="title">
<string>&Debug</string>
</property>
<widget class="QMenu" name="menuAdvanced">
<property name="title">
<string>Advanced</string>
</property>
<property name="icon">
<iconset theme="branchpreview" resource="../../resource.qrc">
<normaloff>:/Default/icons/branchpreview.png</normaloff>:/Default/icons/branchpreview.png</iconset>
</property>
<addaction name="actioneRun"/>
<addaction name="actionseRun"/>
<addaction name="actionRunExpression"/>
<addaction name="separator"/>
<addaction name="actioneStepInto"/>
<addaction name="actionseStepInto"/>
<addaction name="actionStepIntoSource"/>
<addaction name="actioneStepOver"/>
<addaction name="actionseStepOver"/>
<addaction name="actionStepOverSource"/>
<addaction name="separator"/>
<addaction name="actioneRtr"/>
<addaction name="actionSkipNextInstruction"/>
<addaction name="actionInstrUndo"/>
<addaction name="separator"/>
<addaction name="actionHideDebugger"/>
</widget>
<addaction name="actionRun"/>
<addaction name="actionRunSelection"/>
<addaction name="actionPause"/>
<addaction name="actionRestart"/>
<addaction name="actionClose"/>
<addaction name="separator"/>
<addaction name="actionStepInto"/>
<addaction name="actionStepOver"/>
<addaction name="separator"/>
<addaction name="actionRtr"/>
<addaction name="actionRtu"/>
<addaction name="separator"/>
<addaction name="separator"/>
<addaction name="menuAdvanced"/>
</widget>
<widget class="QMenu" name="menuHelp">
<property name="title">
<string>&Help</string>
</property>
<addaction name="actionCalculator"/>
<addaction name="actionCheckUpdates"/>
<addaction name="actionBlog"/>
<addaction name="actionDonate"/>
<addaction name="actionReportBug"/>
<addaction name="actionPlugins"/>
<addaction name="separator"/>
<addaction name="actionManual"/>
<addaction name="actionFaq"/>
<addaction name="actionAbout"/>
<addaction name="actionAbout_Qt"/>
<addaction name="separator"/>
<addaction name="actionCrashDump"/>
</widget>
<widget class="QMenu" name="menuPlugins">
<property name="title">
<string>&Plugins</string>
</property>
<addaction name="actionScylla"/>
</widget>
<widget class="QMenu" name="menuOptions">
<property name="title">
<string>&Options</string>
</property>
<widget class="QMenu" name="menuTheme">
<property name="title">
<string>&Theme</string>
</property>
<property name="icon">
<iconset theme="themes" resource="../../resource.qrc">
<normaloff>:/Default/icons/themes.png</normaloff>:/Default/icons/themes.png</iconset>
</property>
<addaction name="actionDefaultTheme"/>
</widget>
<addaction name="actionSettings"/>
<addaction name="actionAppearance"/>
<addaction name="actionShortcuts"/>
<addaction name="actionCustomizeMenus"/>
<addaction name="actionTopmost"/>
<addaction name="actionReloadStylesheet"/>
<addaction name="actionSetInitializationScript"/>
<addaction name="actionImportSettings"/>
<addaction name="menuTheme"/>
</widget>
<widget class="QMenu" name="menuFavourites">
<property name="title">
<string>Favour&ites</string>
</property>
</widget>
<widget class="QMenu" name="menu_Trace">
<property name="title">
<string>Traci&ng</string>
</property>
<widget class="QMenu" name="menuTrace_record">
<property name="title">
<string>Trace &coverage</string>
</property>
<property name="icon">
<iconset theme="trace" resource="../../resource.qrc">
<normaloff>:/Default/icons/trace.png</normaloff>:/Default/icons/trace.png</iconset>
</property>
<addaction name="actionTRBit"/>
<addaction name="actionTRByte"/>
<addaction name="actionTRWord"/>
<addaction name="actionTRNone"/>
<addaction name="separator"/>
<addaction name="actionTRTIBT"/>
<addaction name="actionTRTOBT"/>
<addaction name="actionTRTIIT"/>
<addaction name="actionTRTOIT"/>
</widget>
<addaction name="actionTicnd"/>
<addaction name="actionTocnd"/>
<addaction name="menuTrace_record"/>
<addaction name="separator"/>
<addaction name="actionAnimateInto"/>
<addaction name="actionAnimateOver"/>
<addaction name="actionAnimateCommand"/>
</widget>
<addaction name="menuFile"/>
<addaction name="menuView"/>
<addaction name="menuDebug"/>
<addaction name="menu_Trace"/>
<addaction name="menuPlugins"/>
<addaction name="menuFavourites"/>
<addaction name="menuOptions"/>
<addaction name="menuHelp"/>
</widget>
<widget class="QToolBar" name="mainToolBar">
<property name="windowTitle">
<string>Toolbar</string>
</property>
<property name="movable">
<bool>false</bool>
</property>
<property name="iconSize">
<size>
<width>16</width>
<height>16</height>
</size>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionOpen"/>
<addaction name="actionRestart"/>
<addaction name="actionClose"/>
<addaction name="separator"/>
<addaction name="actionRun"/>
<addaction name="actionPause"/>
<addaction name="separator"/>
<addaction name="actionStepInto"/>
<addaction name="actionStepOver"/>
<addaction name="separator"/>
<addaction name="actionTicnd"/>
<addaction name="actionTocnd"/>
<addaction name="separator"/>
<addaction name="actionRtr"/>
<addaction name="actionRtu"/>
<addaction name="separator"/>
<addaction name="actionScylla"/>
<addaction name="separator"/>
<addaction name="actionPatches"/>
<addaction name="actionComments"/>
<addaction name="actionLabels"/>
<addaction name="actionBookmarks"/>
<addaction name="actionFunctions"/>
<addaction name="actionVariables"/>
<addaction name="separator"/>
<addaction name="actionStrings"/>
<addaction name="actionCalls"/>
<addaction name="separator"/>
<addaction name="actionCalculator"/>
<addaction name="actionCheckUpdates"/>
</widget>
<widget class="QStatusBar" name="statusBar">
<property name="sizeGripEnabled">
<bool>false</bool>
</property>
</widget>
<widget class="QToolBar" name="cmdBar">
<property name="windowTitle">
<string>CommandBar</string>
</property>
<property name="movable">
<bool>false</bool>
</property>
<property name="allowedAreas">
<set>Qt::BottomToolBarArea</set>
</property>
<attribute name="toolBarArea">
<enum>BottomToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<action name="actionOpen">
<property name="icon">
<iconset theme="folder-horizontal-open" resource="../../resource.qrc">
<normaloff>:/Default/icons/folder-horizontal-open.png</normaloff>:/Default/icons/folder-horizontal-open.png</iconset>
</property>
<property name="text">
<string>&Open</string>
</property>
<property name="statusTip">
<string>Run the file and start debugging.</string>
</property>
</action>
<action name="actionExit">
<property name="icon">
<iconset theme="control-exit" resource="../../resource.qrc">
<normaloff>:/Default/icons/control-exit.png</normaloff>:/Default/icons/control-exit.png</iconset>
</property>
<property name="text">
<string>E&xit</string>
</property>
<property name="statusTip">
<string>Exit x64dbg.</string>
</property>
</action>
<action name="actionRun">
<property name="icon">
<iconset theme="arrow-run" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-run.png</normaloff>:/Default/icons/arrow-run.png</iconset>
</property>
<property name="text">
<string>&Run</string>
</property>
<property name="statusTip">
<string>Run the debuggee or restart debugging.</string>
</property>
</action>
<action name="actionPause">
<property name="icon">
<iconset theme="control-pause" resource="../../resource.qrc">
<normaloff>:/Default/icons/control-pause.png</normaloff>:/Default/icons/control-pause.png</iconset>
</property>
<property name="text">
<string>&Pause</string>
</property>
<property name="statusTip">
<string>Pause the execution of debuggee to debug it, or stop animate into/animate over.</string>
</property>
</action>
<action name="actionRestart">
<property name="icon">
<iconset theme="arrow-restart" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-restart.png</normaloff>:/Default/icons/arrow-restart.png</iconset>
</property>
<property name="text">
<string>Re&start</string>
</property>
<property name="statusTip">
<string>Stop the debuggee and restart it, or restart the last debugged file.</string>
</property>
</action>
<action name="actionClose">
<property name="icon">
<iconset theme="control-stop" resource="../../resource.qrc">
<normaloff>:/Default/icons/control-stop.png</normaloff>:/Default/icons/control-stop.png</iconset>
</property>
<property name="text">
<string>&Close</string>
</property>
<property name="statusTip">
<string>Terminate the debuggee and stop debugging.</string>
</property>
</action>
<action name="actionStepInto">
<property name="icon">
<iconset theme="arrow-step-into" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-into.png</normaloff>:/Default/icons/arrow-step-into.png</iconset>
</property>
<property name="text">
<string>Step &into</string>
</property>
<property name="statusTip">
<string>Execute a single instruction</string>
</property>
</action>
<action name="actionStepOver">
<property name="icon">
<iconset theme="arrow-step-over" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-over.png</normaloff>:/Default/icons/arrow-step-over.png</iconset>
</property>
<property name="text">
<string>Step &over</string>
</property>
<property name="statusTip">
<string>Execute a single instruction without entering the CALL instruction</string>
</property>
</action>
<action name="actionCommand">
<property name="icon">
<iconset theme="terminal-command" resource="../../resource.qrc">
<normaloff>:/Default/icons/terminal-command.png</normaloff>:/Default/icons/terminal-command.png</iconset>
</property>
<property name="text">
<string>Co&mmand</string>
</property>
<property name="statusTip">
<string>Focus on the command bar</string>
</property>
</action>
<action name="actionRtr">
<property name="icon">
<iconset theme="arrow-step-rtr" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-rtr.png</normaloff>:/Default/icons/arrow-step-rtr.png</iconset>
</property>
<property name="text">
<string>E&xecute till return</string>
</property>
<property name="statusTip">
<string>Trace over until the RET instruction would be executed and stack pointer is less than or equal to current value.</string>
</property>
</action>
<action name="actionMemoryMap">
<property name="icon">
<iconset theme="memory-map" resource="../../resource.qrc">
<normaloff>:/Default/icons/memory-map.png</normaloff>:/Default/icons/memory-map.png</iconset>
</property>
<property name="text">
<string>&Memory Map</string>
</property>
<property name="statusTip">
<string>Show the Memory Map tab.</string>
</property>
</action>
<action name="actionLog">
<property name="icon">
<iconset theme="log" resource="../../resource.qrc">
<normaloff>:/Default/icons/log.png</normaloff>:/Default/icons/log.png</iconset>
</property>
<property name="text">
<string>&Log Window</string>
</property>
<property name="statusTip">
<string>Show the Log tab.</string>
</property>
</action>
<action name="actionAbout">
<property name="icon">
<iconset theme="information" resource="../../resource.qrc">
<normaloff>:/Default/icons/information.png</normaloff>:/Default/icons/information.png</iconset>
</property>
<property name="text">
<string>&About</string>
</property>
<property name="statusTip">
<string>Display information about x64dbg</string>
</property>
</action>
<action name="actionScylla">
<property name="icon">
<iconset theme="scylla" resource="../../resource.qrc">
<normaloff>:/Default/icons/scylla.png</normaloff>:/Default/icons/scylla.png</iconset>
</property>
<property name="text">
<string>Scylla</string>
</property>
</action>
<action name="actionBreakpoints">
<property name="icon">
<iconset theme="breakpoint" resource="../../resource.qrc">
<normaloff>:/Default/icons/breakpoint.png</normaloff>:/Default/icons/breakpoint.png</iconset>
</property>
<property name="text">
<string>&Breakpoints</string>
</property>
<property name="statusTip">
<string>Show the Breakpoints tab.</string>
</property>
</action>
<action name="actioneStepInto">
<property name="icon">
<iconset theme="arrow-step-into" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-into.png</normaloff>:/Default/icons/arrow-step-into.png</iconset>
</property>
<property name="text">
<string>Step into (pass all exceptions)</string>
</property>
<property name="statusTip">
<string>Execute a single instruction, pass exceptions to the debuggee.</string>
</property>
</action>
<action name="actioneStepOver">
<property name="icon">
<iconset theme="arrow-step-over" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-over.png</normaloff>:/Default/icons/arrow-step-over.png</iconset>
</property>
<property name="text">
<string>Step over (pass all exceptions)</string>
</property>
</action>
<action name="actioneRun">
<property name="icon">
<iconset theme="arrow-run" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-run.png</normaloff>:/Default/icons/arrow-run.png</iconset>
</property>
<property name="text">
<string>Run (pass all exceptions)</string>
</property>
<property name="statusTip">
<string>Run the debuggee and pass all exceptions to the debuggee without pausing.</string>
</property>
</action>
<action name="actioneRtr">
<property name="icon">
<iconset theme="arrow-step-rtr" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-rtr.png</normaloff>:/Default/icons/arrow-step-rtr.png</iconset>
</property>
<property name="text">
<string>Execute till return (pass all exceptions)</string>
</property>
</action>
<action name="actionScript">
<property name="icon">
<iconset theme="script-code" resource="../../resource.qrc">
<normaloff>:/Default/icons/script-code.png</normaloff>:/Default/icons/script-code.png</iconset>
</property>
<property name="text">
<string>&Script</string>
</property>
<property name="toolTip">
<string>Script</string>
</property>
<property name="statusTip">
<string>Show the Script tab.</string>
</property>
</action>
<action name="actionRunSelection">
<property name="icon">
<iconset theme="arrow-run-cursor" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-run-cursor.png</normaloff>:/Default/icons/arrow-run-cursor.png</iconset>
</property>
<property name="text">
<string>Run &until selection</string>
</property>
<property name="toolTip">
<string>Run until selection</string>
</property>
<property name="statusTip">
<string>Put a breakpoint on selection and run the debuggee.</string>
</property>
</action>
<action name="actionCpu">
<property name="icon">
<iconset theme="processor64" resource="../../resource.qrc">
<normaloff>:/Default/icons/processor64.png</normaloff>:/Default/icons/processor64.png</iconset>
</property>
<property name="text">
<string>&CPU</string>
</property>
<property name="toolTip">
<string>CPU</string>
</property>
<property name="statusTip">
<string>Show the CPU tab to display the disassembly.</string>
</property>
</action>
<action name="actionSymbolInfo">
<property name="icon">
<iconset theme="pdb" resource="../../resource.qrc">
<normaloff>:/Default/icons/pdb.png</normaloff>:/Default/icons/pdb.png</iconset>
</property>
<property name="text">
<string>Symbol &Info</string>
</property>
<property name="toolTip">
<string>Symbol Info</string>
</property>
<property name="statusTip">
<string>Show the Symbols tab.</string>
</property>
</action>
<action name="actionReferences">
<property name="icon">
<iconset theme="search" resource="../../resource.qrc">
<normaloff>:/Default/icons/search.png</normaloff>:/Default/icons/search.png</iconset>
</property>
<property name="text">
<string>&References</string>
</property>
<property name="toolTip">
<string>References</string>
</property>
<property name="statusTip">
<string>Show the References tab.</string>
</property>
</action>
<action name="actionThreads">
<property name="icon">
<iconset theme="arrow-threads" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-threads.png</normaloff>:/Default/icons/arrow-threads.png</iconset>
</property>
<property name="text">
<string>&Threads</string>
</property>
<property name="toolTip">
<string>Threads</string>
</property>
<property name="statusTip">
<string>Show the Threads tab.</string>
</property>
</action>
<action name="actionSettings">
<property name="icon">
<iconset theme="settings" resource="../../resource.qrc">
<normaloff>:/Default/icons/settings.png</normaloff>:/Default/icons/settings.png</iconset>
</property>
<property name="text">
<string>&Preferences</string>
</property>
<property name="toolTip">
<string>Preferences</string>
</property>
<property name="statusTip">
<string>Opem the Preferences dialog.</string>
</property>
</action>
<action name="actionStrings">
<property name="icon">
<iconset theme="strings" resource="../../resource.qrc">
<normaloff>:/Default/icons/strings.png</normaloff>:/Default/icons/strings.png</iconset>
</property>
<property name="text">
<string>&Find Strings</string>
</property>
<property name="toolTip">
<string>Find Strings</string>
</property>
<property name="statusTip">
<string>Find possible strings in the current module. Equivalent command "strref"</string>
</property>
</action>
<action name="actionAppearance">
<property name="icon">
<iconset theme="color-swatches" resource="../../resource.qrc">
<normaloff>:/Default/icons/color-swatches.png</normaloff>:/Default/icons/color-swatches.png</iconset>
</property>
<property name="text">
<string>&Appearance</string>
</property>
<property name="statusTip">
<string>Open the Appearance dialog to adjust color and font settings.</string>
</property>
</action>
<action name="actionCalls">
<property name="icon">
<iconset theme="call" resource="../../resource.qrc">
<normaloff>:/Default/icons/call.png</normaloff>:/Default/icons/call.png</iconset>
</property>
<property name="text">
<string>Find Intermodular Calls</string>
</property>
<property name="toolTip">
<string>Find Intermodular Calls</string>
</property>
<property name="statusTip">
<string>Find intermodular calls in the current module. Equivalent command "modcallfind"</string>
</property>
</action>
<action name="actionPatches">
<property name="icon">
<iconset theme="patch" resource="../../resource.qrc">
<normaloff>:/Default/icons/patch.png</normaloff>:/Default/icons/patch.png</iconset>
</property>
<property name="text">
<string>Patch file...</string>
</property>
<property name="toolTip">
<string>Patches</string>
</property>
<property name="statusTip">
<string>Open the patch dialog.</string>
</property>
</action>
<action name="actionComments">
<property name="icon">
<iconset theme="comments" resource="../../resource.qrc">
<normaloff>:/Default/icons/comments.png</normaloff>:/Default/icons/comments.png</iconset>
</property>
<property name="text">
<string>Comments</string>
</property>
<property name="statusTip">
<string>Show a list of comments. Equivalent command "commentlist"</string>
</property>
</action>
<action name="actionLabels">
<property name="icon">
<iconset theme="labels" resource="../../resource.qrc">
<normaloff>:/Default/icons/labels.png</normaloff>:/Default/icons/labels.png</iconset>
</property>
<property name="text">
<string>Labels</string>
</property>
<property name="statusTip">
<string>Show a list of labels. Equivalent command "labellist"</string>
</property>
</action>
<action name="actionBookmarks">
<property name="icon">
<iconset theme="bookmarks" resource="../../resource.qrc">
<normaloff>:/Default/icons/bookmarks.png</normaloff>:/Default/icons/bookmarks.png</iconset>
</property>
<property name="text">
<string>Bookmarks</string>
</property>
<property name="statusTip">
<string>Show a list of bookmarks. Equivalent command "bookmarklist"</string>
</property>
</action>
<action name="actionFunctions">
<property name="icon">
<iconset theme="functions" resource="../../resource.qrc">
<normaloff>:/Default/icons/functions.png</normaloff>:/Default/icons/functions.png</iconset>
</property>
<property name="text">
<string>Functions</string>
</property>
<property name="statusTip">
<string>Show a list of functions. Equivalent command "functionlist"</string>
</property>
</action>
<action name="actionCheckUpdates">
<property name="icon">
<iconset theme="update" resource="../../resource.qrc">
<normaloff>:/Default/icons/update.png</normaloff>:/Default/icons/update.png</iconset>
</property>
<property name="text">
<string>Check for &Updates</string>
</property>
<property name="statusTip">
<string>Connect to Github to check for updates</string>
</property>
</action>
<action name="actionCallStack">
<property name="icon">
<iconset theme="callstack" resource="../../resource.qrc">
<normaloff>:/Default/icons/callstack.png</normaloff>:/Default/icons/callstack.png</iconset>
</property>
<property name="text">
<string>Call Stack</string>
</property>
<property name="toolTip">
<string>Call Stack</string>
</property>
<property name="statusTip">
<string>Show the Call Stack tab.</string>
</property>
</action>
<action name="actionShortcuts">
<property name="icon">
<iconset theme="shortcut" resource="../../resource.qrc">
<normaloff>:/Default/icons/shortcut.png</normaloff>:/Default/icons/shortcut.png</iconset>
</property>
<property name="text">
<string>Hotkeys</string>
</property>
<property name="statusTip">
<string>Open the Hotkeys dialog to customize keyboard hotkeys.</string>
</property>
</action>
<action name="actionDonate">
<property name="icon">
<iconset theme="donate" resource="../../resource.qrc">
<normaloff>:/Default/icons/donate.png</normaloff>:/Default/icons/donate.png</iconset>
</property>
<property name="text">
<string>&Donate</string>
</property>
<property name="toolTip">
<string>Donate</string>
</property>
<property name="statusTip">
<string>Open http://donate.x64dbg.com</string>
</property>
</action>
<action name="actionCalculator">
<property name="icon">
<iconset theme="calculator" resource="../../resource.qrc">
<normaloff>:/Default/icons/calculator.png</normaloff>:/Default/icons/calculator.png</iconset>
</property>
<property name="text">
<string>Calculator</string>
</property>
<property name="statusTip">
<string>Open the Calculator dialog.</string>
</property>
</action>
<action name="actionAttach">
<property name="icon">
<iconset theme="attach" resource="../../resource.qrc">
<normaloff>:/Default/icons/attach.png</normaloff>:/Default/icons/attach.png</iconset>
</property>
<property name="text">
<string>Attach</string>
</property>
<property name="toolTip">
<string>Attach</string>
</property>
<property name="statusTip">
<string>Attach the debugger to a process to debug it.</string>
</property>
</action>
<action name="actionDetach">
<property name="icon">
<iconset theme="detach" resource="../../resource.qrc">
<normaloff>:/Default/icons/detach.png</normaloff>:/Default/icons/detach.png</iconset>
</property>
<property name="text">
<string>Detach</string>
</property>
<property name="toolTip">
<string>Detach</string>
</property>
<property name="statusTip">
<string>Detach from the debuggee so that it continues running without being debugged.</string>
</property>
</action>
<action name="actionChangeCommandLine">
<property name="icon">
<iconset theme="changeargs" resource="../../resource.qrc">
<normaloff>:/Default/icons/changeargs.png</normaloff>:/Default/icons/changeargs.png</iconset>
</property>
<property name="text">
<string>Change Command &Line</string>
</property>
<property name="statusTip">
<string>Set the command line of the debuggee.</string>
</property>
</action>
<action name="actionSkipNextInstruction">
<property name="icon">
<iconset theme="arrow-skip" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-skip.png</normaloff>:/Default/icons/arrow-skip.png</iconset>
</property>
<property name="text">
<string>Skip next instruction</string>
</property>
<property name="toolTip">
<string>Skip next instruction</string>
</property>
</action>
<action name="actionTopmost">
<property name="checkable">
<bool>true</bool>
</property>
<property name="icon">
<iconset theme="topmost" resource="../../resource.qrc">
<normaloff>:/Default/icons/topmost.png</normaloff>:/Default/icons/topmost.png</iconset>
</property>
<property name="text">
<string>Topmost</string>
</property>
<property name="toolTip">
<string>Topmost Window</string>
</property>
<property name="statusTip">
<string>Make x64dbg topmost</string>
</property>
</action>
<action name="actionReportBug">
<property name="icon">
<iconset theme="bug-report" resource="../../resource.qrc">
<normaloff>:/Default/icons/bug-report.png</normaloff>:/Default/icons/bug-report.png</iconset>
</property>
<property name="text">
<string>&Report Bug</string>
</property>
<property name="toolTip">
<string>Report Bug</string>
</property>
<property name="statusTip">
<string>Open http://report.x64dbg.com</string>
</property>
</action>
<action name="actionSource">
<property name="icon">
<iconset theme="source" resource="../../resource.qrc">
<normaloff>:/Default/icons/source.png</normaloff>:/Default/icons/source.png</iconset>
</property>
<property name="text">
<string>&Source</string>
</property>
<property name="toolTip">
<string>Source</string>
</property>
<property name="statusTip">
<string>Show the Source tab.</string>
</property>
</action>
<action name="actionManual">
<property name="icon">
<iconset theme="win-help" resource="../../resource.qrc">
<normaloff>:/Default/icons/win-help.png</normaloff>:/Default/icons/win-help.png</iconset>
</property>
<property name="text">
<string>&Manual</string>
</property>
<property name="statusTip">
<string>Open the CHM manual or online documentation at http://help.x64dbg.com</string>
</property>
</action>
<action name="actionFaq">
<property name="icon">
<iconset theme="faq" resource="../../resource.qrc">
<normaloff>:/Default/icons/faq.png</normaloff>:/Default/icons/faq.png</iconset>
</property>
<property name="text">
<string>&FAQ</string>
</property>
<property name="toolTip">
<string>FAQ</string>
</property>
<property name="statusTip">
<string>Open http://faq.x64dbg.com</string>
</property>
</action>
<action name="actionSEHChain">
<property name="icon">
<iconset theme="seh-chain" resource="../../resource.qrc">
<normaloff>:/Default/icons/seh-chain.png</normaloff>:/Default/icons/seh-chain.png</iconset>
</property>
<property name="text">
<string>SEH Chain</string>
</property>
</action>
<action name="actionHideDebugger">
<property name="icon">
<iconset theme="hide-debugger" resource="../../resource.qrc">
<normaloff>:/Default/icons/hide-debugger.png</normaloff>:/Default/icons/hide-debugger.png</iconset>
</property>
<property name="text">
<string>Hide debugger (PEB)</string>
</property>
<property name="toolTip">
<string>Hide debugger (PEB)</string>
</property>
<property name="statusTip">
<string>Modifies the PEB to hide debugger.</string>
</property>
</action>
<action name="actionReloadStylesheet">
<property name="icon">
<iconset theme="css" resource="../../resource.qrc">
<normaloff>:/Default/icons/css.png</normaloff>:/Default/icons/css.png</iconset>
</property>
<property name="text">
<string>Reload style.css</string>
</property>
<property name="toolTip">
<string>Reload style.css</string>
</property>
<property name="statusTip">
<string>Read style.css from disk to apply theme changes.</string>
</property>
</action>
<action name="actionNotes">
<property name="icon">
<iconset theme="notes" resource="../../resource.qrc">
<normaloff>:/Default/icons/notes.png</normaloff>:/Default/icons/notes.png</iconset>
</property>
<property name="text">
<string>Notes</string>
</property>
<property name="statusTip">
<string>Show the Notes tab.</string>
</property>
</action>
<action name="actionHandles">
<property name="icon">
<iconset theme="handles" resource="../../resource.qrc">
<normaloff>:/Default/icons/handles.png</normaloff>:/Default/icons/handles.png</iconset>
</property>
<property name="text">
<string>Handles</string>
</property>
<property name="statusTip">
<string>Show the Handles tab.</string>
</property>
</action>
<action name="actionTocnd">
<property name="icon">
<iconset theme="traceover" resource="../../resource.qrc">
<normaloff>:/Default/icons/traceover.png</normaloff>:/Default/icons/traceover.png</iconset>
</property>
<property name="text">
<string>Trace over...</string>
</property>
<property name="toolTip">
<string>Trace over...</string>
</property>
<property name="statusTip">
<string>Step over until a condition becomes true, and optionally log and execute commands when tracing. Equivalent command "tocnd"</string>
</property>
</action>
<action name="actionTicnd">
<property name="icon">
<iconset theme="traceinto" resource="../../resource.qrc">
<normaloff>:/Default/icons/traceinto.png</normaloff>:/Default/icons/traceinto.png</iconset>
</property>
<property name="text">
<string>Trace into...</string>
</property>
<property name="toolTip">
<string>Trace into...</string>
</property>
<property name="statusTip">
<string>Step into until a condition becomes true, and optionally log and execute commands when tracing. Equivalent command "ticnd"</string>
</property>
</action>
<action name="actionTRBit">
<property name="icon">
<iconset theme="bit" resource="../../resource.qrc">
<normaloff>:/Default/icons/bit.png</normaloff>:/Default/icons/bit.png</iconset>
</property>
<property name="text">
<string>Bit</string>
</property>
<property name="statusTip">
<string>Enable trace coverage with 1 bit (whether an instruction was executed or not)</string>
</property>
</action>
<action name="actionTRByte">
<property name="icon">
<iconset theme="byte" resource="../../resource.qrc">
<normaloff>:/Default/icons/byte.png</normaloff>:/Default/icons/byte.png</iconset>
</property>
<property name="text">
<string>Byte</string>
</property>
<property name="statusTip">
<string>Enable trace coverage with 1 byte to record how many times an instruction has been executed.</string>
</property>
</action>
<action name="actionTRWord">
<property name="icon">
<iconset theme="word" resource="../../resource.qrc">
<normaloff>:/Default/icons/word.png</normaloff>:/Default/icons/word.png</iconset>
</property>
<property name="text">
<string>Word</string>
</property>
<property name="statusTip">
<string>Enable trace coverage with 1 word to record how many times an instruction has been executed.</string>
</property>
</action>
<action name="actionTRTIBT">
<property name="icon">
<iconset theme="traceinto" resource="../../resource.qrc">
<normaloff>:/Default/icons/traceinto.png</normaloff>:/Default/icons/traceinto.png</iconset>
</property>
<property name="text">
<string>Step into until reaching uncovered code</string>
</property>
<property name="statusTip">
<string>Step into until reaching an instruction that was not covered before. Equivalent command "tibt"</string>
</property>
</action>
<action name="actionTRTOBT">
<property name="icon">
<iconset theme="traceover" resource="../../resource.qrc">
<normaloff>:/Default/icons/traceover.png</normaloff>:/Default/icons/traceover.png</iconset>
</property>
<property name="text">
<string>Step over until reaching uncovered code</string>
</property>
<property name="statusTip">
<string>Step over until reaching an instruction that was not covered before. Equivalent command "tobt"</string>
</property>
</action>
<action name="actionTRTIIT">
<property name="icon">
<iconset theme="arrow-step-into" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-into.png</normaloff>:/Default/icons/arrow-step-into.png</iconset>
</property>
<property name="text">
<string>Step into until reaching covered code</string>
</property>
<property name="statusTip">
<string>Step into until reaching an instruction that has been covered before. Equivalent command "tiit"</string>
</property>
</action>
<action name="actionTRTOIT">
<property name="icon">
<iconset theme="arrow-step-over" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-over.png</normaloff>:/Default/icons/arrow-step-over.png</iconset>
</property>
<property name="text">
<string>Step over until reaching covered code</string>
</property>
<property name="statusTip">
<string>Step over until reaching an instruction that has been covered before. Equivalent command "toit"</string>
</property>
</action>
<action name="actionTRNone">
<property name="icon">
<iconset theme="close-all-tabs" resource="../../resource.qrc">
<normaloff>:/Default/icons/close-all-tabs.png</normaloff>:/Default/icons/close-all-tabs.png</iconset>
</property>
<property name="text">
<string>Disable</string>
</property>
<property name="statusTip">
<string>Disable trace coverage</string>
</property>
</action>
<action name="actionRtu">
<property name="icon">
<iconset theme="runtouser" resource="../../resource.qrc">
<normaloff>:/Default/icons/runtouser.png</normaloff>:/Default/icons/runtouser.png</iconset>
</property>
<property name="text">
<string>Run to &user code</string>
</property>
<property name="statusTip">
<string>Trace over until user code would be executed.</string>
</property>
</action>
<action name="actionRunExpression">
<property name="icon">
<iconset theme="arrow-run-cursor" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-run-cursor.png</normaloff>:/Default/icons/arrow-run-cursor.png</iconset>
</property>
<property name="text">
<string>Run until e&xpression</string>
</property>
</action>
<action name="actionInstrUndo">
<property name="icon">
<iconset theme="undo" resource="../../resource.qrc">
<normaloff>:/Default/icons/undo.png</normaloff>:/Default/icons/undo.png</iconset>
</property>
<property name="text">
<string>Undo last instruction</string>
</property>
</action>
<action name="actionCrashDump">
<property name="icon">
<iconset theme="crash_dump" resource="../../resource.qrc">
<normaloff>:/Default/icons/crash_dump.png</normaloff>:/Default/icons/crash_dump.png</iconset>
</property>
<property name="text">
<string>Generate crash dump</string>
</property>
</action>
<action name="actionManageFavourite">
<property name="icon">
<iconset theme="star" resource="../../resource.qrc">
<normaloff>:/Default/icons/star.png</normaloff>:/Default/icons/star.png</iconset>
</property>
<property name="text">
<string>&Manage Favourite Tools...</string>
</property>
</action>
<action name="actionStepOverSource">
<property name="icon">
<iconset theme="arrow-step-over" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-over.png</normaloff>:/Default/icons/arrow-step-over.png</iconset>
</property>
<property name="text">
<string>Step over (source)</string>
</property>
<property name="statusTip">
<string>Execute a single line of source code without entering the subroutine. Equivalent to "TraceOverConditional src.line(cip) && !src.disp(cip)"</string>
</property>
</action>
<action name="actionStepIntoSource">
<property name="icon">
<iconset theme="arrow-step-into" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-into.png</normaloff>:/Default/icons/arrow-step-into.png</iconset>
</property>
<property name="text">
<string>Step into (source)</string>
</property>
<property name="statusTip">
<string>Execute a single source code line. Equivalent to "TraceIntoConditional src.line(cip) && !src.disp(cip)"</string>
</property>
</action>
<action name="actionGraph">
<property name="icon">
<iconset theme="graph" resource="../../resource.qrc">
<normaloff>:/Default/icons/graph.png</normaloff>:/Default/icons/graph.png</iconset>
</property>
<property name="text">
<string>&Graph</string>
</property>
<property name="statusTip">
<string>Show the CPU tab and switch to Graph mode.</string>
</property>
</action>
<action name="actionseStepInto">
<property name="icon">
<iconset theme="arrow-step-into" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-into.png</normaloff>:/Default/icons/arrow-step-into.png</iconset>
</property>
<property name="text">
<string>Step into (swallow exception)</string>
</property>
<property name="statusTip">
<string/>
</property>
</action>
<action name="actionseStepOver">
<property name="icon">
<iconset theme="arrow-step-over" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-step-over.png</normaloff>:/Default/icons/arrow-step-over.png</iconset>
</property>
<property name="text">
<string>Step over (swallow exception)</string>
</property>
</action>
<action name="actionseRun">
<property name="icon">
<iconset theme="arrow-run" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-run.png</normaloff>:/Default/icons/arrow-run.png</iconset>
</property>
<property name="text">
<string>Run (swallow exception)</string>
</property>
<property name="statusTip">
<string>Run the debuggee and ignore all exceptions so the debuggee will not process the exception.</string>
</property>
</action>
<action name="actionBlog">
<property name="icon">
<iconset theme="hex" resource="../../resource.qrc">
<normaloff>:/Default/icons/hex.png</normaloff>:/Default/icons/hex.png</iconset>
</property>
<property name="text">
<string>Blog</string>
</property>
<property name="statusTip">
<string>Open http://blog.x64dbg.com</string>
</property>
</action>
<action name="actionAnimateInto">
<property name="icon">
<iconset theme="animateinto" resource="../../resource.qrc">
<normaloff>:/Default/icons/animateinto.png</normaloff>:/Default/icons/animateinto.png</iconset>
</property>
<property name="text">
<string>Animate into</string>
</property>
<property name="statusTip">
<string>Execute the step into command at a fixed pace</string>
</property>
</action>
<action name="actionAnimateOver">
<property name="icon">
<iconset theme="animateover" resource="../../resource.qrc">
<normaloff>:/Default/icons/animateover.png</normaloff>:/Default/icons/animateover.png</iconset>
</property>
<property name="text">
<string>Animate over</string>
</property>
<property name="statusTip">
<string>Execute the step over command at a fixed pace</string>
</property>
</action>
<action name="actionAnimateCommand">
<property name="icon">
<iconset theme="animatecommand" resource="../../resource.qrc">
<normaloff>:/Default/icons/animatecommand.png</normaloff>:/Default/icons/animatecommand.png</iconset>
</property>
<property name="text">
<string>Animate command...</string>
</property>
<property name="statusTip">
<string>Execute a command at a fixed pace</string>
</property>
</action>
<action name="actionSetInitializationScript">
<property name="icon">
<iconset theme="initscript" resource="../../resource.qrc">
<normaloff>:/Default/icons/initscript.png</normaloff>:/Default/icons/initscript.png</iconset>
</property>
<property name="text">
<string>System breakpoint scripts</string>
</property>
<property name="statusTip">
<string>Set the script file to run automatically when the system breakpoint is reached.</string>
</property>
</action>
<action name="actionImportSettings">
<property name="icon">
<iconset theme="importsettings" resource="../../resource.qrc">
<normaloff>:/Default/icons/importsettings.png</normaloff>:/Default/icons/importsettings.png</iconset>
</property>
<property name="text">
<string>Import settings...</string>
</property>
<property name="statusTip">
<string>Import settings from an external file</string>
</property>
</action>
<action name="actionCustomizeMenus">
<property name="icon">
<iconset theme="analysis" resource="../../resource.qrc">
<normaloff>:/Default/icons/analysis.png</normaloff>:/Default/icons/analysis.png</iconset>
</property>
<property name="text">
<string>Customize menus</string>
</property>
<property name="statusTip">
<string>Open the Customize Menus dialog to hide infrequently used menu items into the "more commands" submenu.</string>
</property>
</action>
<action name="actionImportdatabase">
<property name="icon">
<iconset theme="database-import" resource="../../resource.qrc">
<normaloff>:/Default/icons/database-import.png</normaloff>:/Default/icons/database-import.png</iconset>
</property>
<property name="text">
<string>&Import database</string>
</property>
<property name="statusTip">
<string>Open an external database file to import data.</string>
</property>
</action>
<action name="actionExportdatabase">
<property name="icon">
<iconset theme="database-export" resource="../../resource.qrc">
<normaloff>:/Default/icons/database-export.png</normaloff>:/Default/icons/database-export.png</iconset>
</property>
<property name="text">
<string>&Export database</string>
</property>
</action>
<action name="actionPreviousTab">
<property name="icon">
<iconset theme="previous" resource="../../resource.qrc">
<normaloff>:/Default/icons/previous.png</normaloff>:/Default/icons/previous.png</iconset>
</property>
<property name="text">
<string>Previous Tab</string>
</property>
<property name="statusTip">
<string>Show the tab on the left.</string>
</property>
</action>
<action name="actionNextTab">
<property name="icon">
<iconset theme="next" resource="../../resource.qrc">
<normaloff>:/Default/icons/next.png</normaloff>:/Default/icons/next.png</iconset>
</property>
<property name="text">
<string>Next Tab</string>
</property>
<property name="statusTip">
<string>Show the tab on the right.</string>
</property>
</action>
<action name="actionPreviousView">
<property name="icon">
<iconset theme="previous" resource="../../resource.qrc">
<normaloff>:/Default/icons/previous.png</normaloff>:/Default/icons/previous.png</iconset>
</property>
<property name="text">
<string>Previous View</string>
</property>
<property name="statusTip">
<string>Show the tab history popup window and select more recently used tab.</string>
</property>
</action>
<action name="actionNextView">
<property name="icon">
<iconset theme="next" resource="../../resource.qrc">
<normaloff>:/Default/icons/next.png</normaloff>:/Default/icons/next.png</iconset>
</property>
<property name="text">
<string>Next View</string>
</property>
<property name="statusTip">
<string>Show the tab history popup window and select previously viewed tab.</string>
</property>
</action>
<action name="actionHideTab">
<property name="icon">
<iconset theme="hidetab" resource="../../resource.qrc">
<normaloff>:/Default/icons/hidetab.png</normaloff>:/Default/icons/hidetab.png</iconset>
</property>
<property name="text">
<string>Hide Tab</string>
</property>
<property name="statusTip">
<string>Hide the current tab. The hidden tab can be reopened from the View menu.</string>
</property>
</action>
<action name="actionVariables">
<property name="icon">
<iconset theme="variables" resource="../../resource.qrc">
<normaloff>:/Default/icons/variables.png</normaloff>:/Default/icons/variables.png</iconset>
</property>
<property name="text">
<string>&Variables</string>
</property>
<property name="statusTip">
<string>Show a list of x64dbg variables. Equivalent command "varlist"</string>
</property>
</action>
<action name="actionRestartAdmin">
<property name="icon">
<iconset theme="uac" resource="../../resource.qrc">
<normaloff>:/Default/icons/uac.png</normaloff>:/Default/icons/uac.png</iconset>
</property>
<property name="text">
<string>Restart as Admin</string>
</property>
<property name="statusTip">
<string>Restart x64dbg under Administrator privilege.</string>
</property>
</action>
<action name="actionPlugins">
<property name="icon">
<iconset theme="plugin" resource="../../resource.qrc">
<normaloff>:/Default/icons/plugin.png</normaloff>:/Default/icons/plugin.png</iconset>
</property>
<property name="text">
<string>Plugins</string>
</property>
<property name="statusTip">
<string>Open http://plugins.x64dbg.com</string>
</property>
</action>
<action name="actionTrace">
<property name="icon">
<iconset theme="trace" resource="../../resource.qrc">
<normaloff>:/Default/icons/trace.png</normaloff>:/Default/icons/trace.png</iconset>
</property>
<property name="text">
<string>Trace</string>
</property>
<property name="statusTip">
<string>Show the Trace tab.</string>
</property>
</action>
<action name="actionModules">
<property name="icon">
<iconset theme="lib" resource="../../resource.qrc">
<normaloff>:/Default/icons/lib.png</normaloff>:/Default/icons/lib.png</iconset>
</property>
<property name="text">
<string>Modules</string>
</property>
<property name="statusTip">
<string>Show the Symbols tab. Note that the Modules list is in the symbols tab.</string>
</property>
</action>
<action name="action_Theme">
<property name="text">
<string>&Theme</string>
</property>
</action>
<action name="actionDefaultTheme">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>&Default</string>
</property>
</action>
<action name="actionDbsave">
<property name="icon">
<iconset theme="binary_save" resource="../../resource.qrc">
<normaloff>:/Default/icons/binary_save.png</normaloff>:/Default/icons/binary_save.png</iconset>
</property>
<property name="text">
<string>&Save database</string>
</property>
<property name="statusTip">
<string>Save all data. The database will be automatically saved when debugging is stopped.</string>
</property>
</action>
<action name="actionDbload">
<property name="icon">
<iconset theme="arrow-restart" resource="../../resource.qrc">
<normaloff>:/Default/icons/arrow-restart.png</normaloff>:/Default/icons/arrow-restart.png</iconset>
</property>
<property name="text">
<string>Re&load database</string>
</property>
<property name="statusTip">
<string>Discard all modifications and read all data from disk.</string>
</property>
</action>
<action name="actionDbrecovery">
<property name="icon">
<iconset theme="help" resource="../../resource.qrc">
<normaloff>:/Default/icons/help.png</normaloff>:/Default/icons/help.png</iconset>
</property>
<property name="text">
<string>&Restore backup database</string>
</property>
<property name="statusTip">
<string>Read data from the backup database to recover from database corruption.</string>
</property>
</action>
<action name="actionDbclear">
<property name="icon">
<iconset theme="crash_dump" resource="../../resource.qrc">
<normaloff>:/Default/icons/crash_dump.png</normaloff>:/Default/icons/crash_dump.png</iconset>
</property>
<property name="text">
<string>&Clear database</string>
</property>
<property name="statusTip">
<string>Clear all data.</string>
</property>
</action>
<action name="actionAbout_Qt">
<property name="text">
<string>About Qt</string>
</property>
<property name="statusTip">
<string>Display information about Qt</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>actionExit</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>399</x>
<y>299</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/MemoryMapView.cpp | #include <QFileDialog>
#include <QMessageBox>
#include "MemoryMapView.h"
#include "Configuration.h"
#include "Bridge.h"
#include "PageMemoryRights.h"
#include "HexEditDialog.h"
#include "MiscUtil.h"
#include "GotoDialog.h"
#include "WordEditDialog.h"
#include "VirtualModDialog.h"
#include "LineEditDialog.h"
#include "RichTextPainter.h"
MemoryMapView::MemoryMapView(StdTable* parent)
: StdIconTable(parent),
mCipBase(0)
{
setDrawDebugOnly(true);
enableMultiSelection(true);
setDisassemblyPopupEnabled(false);
int charwidth = getCharWidth();
addColumnAt(8 + charwidth * 2 * sizeof(duint), tr("Address"), true, tr("Address")); //addr
addColumnAt(8 + charwidth * 2 * sizeof(duint), tr("Size"), false, tr("Size")); //size
addColumnAt(charwidth * 9, tr("Party"), false); // party
addColumnAt(8 + charwidth * 32, tr("Info"), false, tr("Page Information")); //page information
addColumnAt(8 + charwidth * 28, tr("Content"), false, tr("Content of section")); //content of section
addColumnAt(8 + charwidth * 5, tr("Type"), true, tr("Allocation Type")); //allocation type
addColumnAt(8 + charwidth * 11, tr("Protection"), true, tr("Current Protection")); //current protection
addColumnAt(8 + charwidth * 8, tr("Initial"), true, tr("Allocation Protection")); //allocation protection
loadColumnFromConfig("MemoryMap");
setIconColumn(ColParty);
connect(Bridge::getBridge(), SIGNAL(updateMemory()), this, SLOT(refreshMap()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(stateChangedSlot(DBGSTATE)));
connect(Bridge::getBridge(), SIGNAL(selectInMemoryMap(duint)), this, SLOT(selectAddress(duint)));
connect(Bridge::getBridge(), SIGNAL(selectionMemmapGet(SELECTIONDATA*)), this, SLOT(selectionGetSlot(SELECTIONDATA*)));
connect(Bridge::getBridge(), SIGNAL(disassembleAt(dsint, dsint)), this, SLOT(disassembleAtSlot(dsint, dsint)));
connect(Bridge::getBridge(), SIGNAL(focusMemmap()), this, SLOT(setFocus()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
setupContextMenu();
}
void MemoryMapView::setupContextMenu()
{
//Follow in Dump
mFollowDump = new QAction(DIcon("dump"), tr("&Follow in Dump"), this);
connect(mFollowDump, SIGNAL(triggered()), this, SLOT(followDumpSlot()));
//Follow in Disassembler
mFollowDisassembly = new QAction(DIcon(ArchValue("processor32", "processor64")), tr("Follow in &Disassembler"), this);
connect(mFollowDisassembly, SIGNAL(triggered()), this, SLOT(followDisassemblerSlot()));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(doubleClickedSlot()));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(doubleClickedSlot()));
//Follow in Symbols
mFollowSymbols = new QAction(DIcon("pdb"), tr("&Follow in Symbols"), this);
connect(mFollowSymbols, SIGNAL(triggered()), this, SLOT(followSymbolsSlot()));
//Set PageMemory Rights
mPageMemoryRights = new QAction(DIcon("memmap_set_page_memory_rights"), tr("Set Page Memory Rights"), this);
connect(mPageMemoryRights, SIGNAL(triggered()), this, SLOT(pageMemoryRights()));
//Switch View
mSwitchView = new QAction(DIcon("change-view"), tr("&Switch View"), this);
connect(mSwitchView, SIGNAL(triggered()), this, SLOT(switchView()));
//Breakpoint menu
mBreakpointMenu = new QMenu(tr("Memory &Breakpoint"), this);
mBreakpointMenu->setIcon(DIcon("breakpoint"));
//Breakpoint->Memory Access
mMemoryAccessMenu = new QMenu(tr("Access"), this);
mMemoryAccessMenu->setIcon(DIcon("breakpoint_memory_access"));
mMemoryAccessSingleshoot = new QAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), this);
makeCommandAction(mMemoryAccessSingleshoot, "bpm $, 0, a");
mMemoryAccessMenu->addAction(mMemoryAccessSingleshoot);
mMemoryAccessRestore = new QAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore"), this);
makeCommandAction(mMemoryAccessRestore, "bpm $, 1, a");
mMemoryAccessMenu->addAction(mMemoryAccessRestore);
mBreakpointMenu->addMenu(mMemoryAccessMenu);
//Breakpoint->Memory Read
mMemoryReadMenu = new QMenu(tr("Read"), this);
mMemoryReadMenu->setIcon(DIcon("breakpoint_memory_read"));
mMemoryReadSingleshoot = new QAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), this);
makeCommandAction(mMemoryReadSingleshoot, "bpm $, 0, r");
mMemoryReadMenu->addAction(mMemoryReadSingleshoot);
mMemoryReadRestore = new QAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore"), this);
makeCommandAction(mMemoryReadRestore, "bpm $, 1, r");
mMemoryReadMenu->addAction(mMemoryReadRestore);
mBreakpointMenu->addMenu(mMemoryReadMenu);
//Breakpoint->Memory Write
mMemoryWriteMenu = new QMenu(tr("Write"), this);
mMemoryWriteMenu->setIcon(DIcon("breakpoint_memory_write"));
mMemoryWriteSingleshoot = new QAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), this);
makeCommandAction(mMemoryWriteSingleshoot, "bpm $, 0, w");
mMemoryWriteMenu->addAction(mMemoryWriteSingleshoot);
mMemoryWriteRestore = new QAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore"), this);
makeCommandAction(mMemoryWriteRestore, "bpm $, 1, w");
mMemoryWriteMenu->addAction(mMemoryWriteRestore);
mBreakpointMenu->addMenu(mMemoryWriteMenu);
//Breakpoint->Memory Execute
mMemoryExecuteMenu = new QMenu(tr("Execute"), this);
mMemoryExecuteMenu->setIcon(DIcon("breakpoint_memory_execute"));
mMemoryExecuteSingleshoot = new QAction(DIcon("breakpoint_memory_singleshoot"), tr("&Singleshoot"), this);
makeCommandAction(mMemoryExecuteSingleshoot, "bpm $, 0, x");
mMemoryExecuteMenu->addAction(mMemoryExecuteSingleshoot);
mMemoryExecuteRestore = new QAction(DIcon("breakpoint_memory_restore_on_hit"), tr("&Restore"), this);
makeCommandAction(mMemoryExecuteRestore, "bpm $, 1, x");
mMemoryExecuteMenu->addAction(mMemoryExecuteRestore);
mBreakpointMenu->addMenu(mMemoryExecuteMenu);
//Breakpoint->Remove
mMemoryRemove = new QAction(tr("&Remove"), this);
mMemoryRemove->setShortcutContext(Qt::WidgetShortcut);
makeCommandAction(mMemoryRemove, "bpmc $");
mBreakpointMenu->addAction(mMemoryRemove);
//Action shortcut action that does something
mMemoryExecuteSingleshootToggle = new QAction(this);
mMemoryExecuteSingleshootToggle->setShortcutContext(Qt::WidgetShortcut);
this->addAction(mMemoryExecuteSingleshootToggle);
connect(mMemoryExecuteSingleshootToggle, SIGNAL(triggered()), this, SLOT(memoryExecuteSingleshootToggleSlot()));
//Allocate memory
mMemoryAllocate = new QAction(DIcon("memmap_alloc_memory"), tr("&Allocate memory"), this);
mMemoryAllocate->setShortcutContext(Qt::WidgetShortcut);
connect(mMemoryAllocate, SIGNAL(triggered()), this, SLOT(memoryAllocateSlot()));
this->addAction(mMemoryAllocate);
//Free memory
mMemoryFree = new QAction(DIcon("memmap_free_memory"), tr("&Free memory"), this);
mMemoryFree->setShortcutContext(Qt::WidgetShortcut);
makeCommandAction(mMemoryFree, "free $");
this->addAction(mMemoryFree);
//Goto
mGotoMenu = new QMenu(tr("Go to"), this);
mGotoMenu->setIcon(DIcon("goto"));
//Goto->Origin
mGotoOrigin = new QAction(DIcon("cbp"), ArchValue("EIP", "RIP"), this);
mGotoOrigin->setShortcutContext(Qt::WidgetShortcut);
connect(mGotoOrigin, SIGNAL(triggered()), this, SLOT(gotoOriginSlot()));
this->addAction(mGotoOrigin);
mGotoMenu->addAction(mGotoOrigin);
//Goto->Expression
mGotoExpression = new QAction(DIcon("geolocation-goto"), tr("Expression"), this);
mGotoExpression->setShortcutContext(Qt::WidgetShortcut);
connect(mGotoExpression, SIGNAL(triggered()), this, SLOT(gotoExpressionSlot()));
this->addAction(mGotoExpression);
mGotoMenu->addAction(mGotoExpression);
//Find
mFindPattern = new QAction(DIcon("search-for"), tr("&Find Pattern..."), this);
this->addAction(mFindPattern);
mFindPattern->setShortcutContext(Qt::WidgetShortcut);
connect(mFindPattern, SIGNAL(triggered()), this, SLOT(findPatternSlot()));
//Dump
//TODO: These two actions should also appear in CPUDump
mDumpMemory = new QAction(DIcon("binary_save"), tr("&Dump Memory to File"), this);
connect(mDumpMemory, SIGNAL(triggered()), this, SLOT(dumpMemory()));
//Load
mLoadMemory = new QAction(DIcon(""), tr("&Overwrite with Data from File"), this);
connect(mLoadMemory, SIGNAL(triggered()), this, SLOT(loadMemory()));
//Add virtual module
mAddVirtualMod = new QAction(DIcon("virtual"), tr("Add virtual module"), this);
connect(mAddVirtualMod, SIGNAL(triggered()), this, SLOT(addVirtualModSlot()));
//References
mReferences = new QAction(DIcon("find"), tr("Find references to region"), this);
connect(mReferences, SIGNAL(triggered()), this, SLOT(findReferencesSlot()));
//Comment
mComment = new QAction(DIcon("comment"), tr("&Comment"), this);
this->addAction(mComment);
connect(mComment, SIGNAL(triggered()), this, SLOT(commentSlot()));
mComment->setShortcutContext(Qt::WidgetShortcut);
mPluginMenu = new QMenu(this);
Bridge::getBridge()->emitMenuAddToList(this, mPluginMenu, GUI_MEMMAP_MENU);
refreshShortcutsSlot();
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcutsSlot()));
}
void MemoryMapView::refreshShortcutsSlot()
{
mMemoryExecuteSingleshoot->setShortcut(ConfigShortcut("ActionToggleBreakpoint"));
mMemoryRemove->setShortcut(ConfigShortcut("ActionToggleBreakpoint"));
mMemoryExecuteSingleshootToggle->setShortcut(ConfigShortcut("ActionToggleBreakpoint"));
mFindPattern->setShortcut(ConfigShortcut("ActionFindPattern"));
mGotoOrigin->setShortcut(ConfigShortcut("ActionGotoOrigin"));
mGotoExpression->setShortcut(ConfigShortcut("ActionGotoExpression"));
mMemoryFree->setShortcut(ConfigShortcut("ActionFreeMemory"));
mMemoryAllocate->setShortcut(ConfigShortcut("ActionAllocateMemory"));
mComment->setShortcut(ConfigShortcut("ActionSetComment"));
}
void MemoryMapView::contextMenuSlot(const QPoint & pos)
{
if(!DbgIsDebugging())
return;
duint selectedAddr = getSelectionAddr();
QMenu wMenu(this); //create context menu
wMenu.addAction(mFollowDisassembly);
wMenu.addAction(mFollowDump);
if(DbgFunctions()->ModBaseFromAddr(selectedAddr))
wMenu.addAction(mFollowSymbols);
wMenu.addAction(mDumpMemory);
//wMenu.addAction(mLoadMemory); //TODO:loaddata command
wMenu.addAction(mComment);
wMenu.addAction(mFindPattern);
wMenu.addAction(mSwitchView);
wMenu.addAction(mReferences);
wMenu.addSeparator();
wMenu.addAction(mMemoryAllocate);
wMenu.addAction(mMemoryFree);
wMenu.addAction(mAddVirtualMod);
wMenu.addMenu(mGotoMenu);
wMenu.addSeparator();
wMenu.addAction(mPageMemoryRights);
wMenu.addSeparator();
wMenu.addMenu(mBreakpointMenu);
wMenu.addSeparator();
DbgMenuPrepare(GUI_MEMMAP_MENU);
wMenu.addActions(mPluginMenu->actions());
QMenu wCopyMenu(tr("&Copy"), this);
wCopyMenu.setIcon(DIcon("copy"));
setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
{
wMenu.addSeparator();
wMenu.addMenu(&wCopyMenu);
}
if((DbgGetBpxTypeAt(selectedAddr) & bp_memory) == bp_memory) //memory breakpoint set
{
mMemoryAccessMenu->menuAction()->setVisible(false);
mMemoryReadMenu->menuAction()->setVisible(false);
mMemoryWriteMenu->menuAction()->setVisible(false);
mMemoryExecuteMenu->menuAction()->setVisible(false);
mMemoryRemove->setVisible(true);
}
else //memory breakpoint not set
{
mMemoryAccessMenu->menuAction()->setVisible(true);
mMemoryReadMenu->menuAction()->setVisible(true);
mMemoryWriteMenu->menuAction()->setVisible(true);
mMemoryExecuteMenu->menuAction()->setVisible(true);
mMemoryRemove->setVisible(false);
}
mAddVirtualMod->setVisible(!DbgFunctions()->ModBaseFromAddr(selectedAddr));
wMenu.exec(mapToGlobal(pos)); //execute context menu
}
static QString getProtectionString(DWORD Protect)
{
#define RIGHTS_STRING (sizeof("ERWCG"))
char rights[RIGHTS_STRING];
if(!DbgFunctions()->PageRightsToString(Protect, rights))
return "bad";
return QString(rights);
}
QString MemoryMapView::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if(col == 0) //address
{
int row = rowBase + rowOffset;
auto addr = getCellUserdata(row, ColAddress);
QColor color = mTextColor;
QColor backgroundColor = Qt::transparent;
bool isBp = (DbgGetBpxTypeAt(addr) & bp_memory) == bp_memory;
bool isCip = addr == mCipBase;
if(isCip && isBp)
{
color = ConfigColor("MemoryMapBreakpointBackgroundColor");
backgroundColor = ConfigColor("MemoryMapCipBackgroundColor");
}
else if(isBp)
{
color = ConfigColor("MemoryMapBreakpointColor");
backgroundColor = ConfigColor("MemoryMapBreakpointBackgroundColor");
}
else if(isCip)
{
color = ConfigColor("MemoryMapCipColor");
backgroundColor = ConfigColor("MemoryMapCipBackgroundColor");
}
else if(isSelected(rowBase, rowOffset) == true)
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor));
if(backgroundColor.alpha())
painter->fillRect(QRect(x, y, w - 1, h), QBrush(backgroundColor));
painter->setPen(color);
QString wStr = getCellContent(rowBase + rowOffset, col);
painter->drawText(QRect(x + 4, y, getColumnWidth(col) - 4, getRowHeight()), Qt::AlignVCenter | Qt::AlignLeft, wStr);
return QString();
}
else if(col == ColPageInfo) //info
{
QString wStr = StdIconTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
auto addr = getCellUserdata(rowBase + rowOffset, ColAddress);
if(wStr.contains(" \""))
{
auto idx = wStr.indexOf(" \"");
auto pre = wStr.mid(0, idx);
auto post = wStr.mid(idx);
RichTextPainter::List richText;
RichTextPainter::CustomRichText_t entry;
entry.flags = RichTextPainter::FlagColor;
if(!pre.isEmpty())
{
entry.text = pre;
entry.textColor = mTextColor;
richText.push_back(entry);
}
entry.text = post;
entry.textColor = ConfigColor("MemoryMapSectionTextColor");
richText.push_back(entry);
RichTextPainter::paintRichText(painter, x, y, getColumnWidth(col), getRowHeight(), 4, richText, mFontMetrics);
return QString();
}
else if(DbgFunctions()->ModBaseFromAddr(addr) == addr) // module header page
{
auto party = DbgFunctions()->ModGetParty(addr);
painter->setPen(ConfigColor(party == mod_user ? "SymbolUserTextColor" : "SymbolSystemTextColor"));
painter->drawText(QRect(x + 4, y, getColumnWidth(col) - 4, getRowHeight()), Qt::AlignVCenter | Qt::AlignLeft, wStr);
return QString();
}
}
else if(col == ColCurProtect) //CPROT
{
QString wStr = StdIconTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);;
if(!ConfigBool("Engine", "ListAllPages"))
{
painter->setPen(ConfigColor("MemoryMapSectionTextColor"));
painter->drawText(QRect(x + 4, y, getColumnWidth(col) - 4, getRowHeight()), Qt::AlignVCenter | Qt::AlignLeft, wStr);
return QString();
}
}
return StdIconTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
}
QAction* MemoryMapView::makeCommandAction(QAction* action, const QString & command)
{
action->setData(QVariant(command));
connect(action, SIGNAL(triggered()), this, SLOT(ExecCommand()));
return action;
}
/**
* @brief MemoryMapView::ExecCommand execute command slot for menus.
*/
void MemoryMapView::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, ColAddress))); // $ -> Base address
DbgCmdExec(specializedCommand);
}
}
else
DbgCmdExec(command);
}
}
void MemoryMapView::refreshMap()
{
MEMMAP wMemMapStruct;
int wI;
memset(&wMemMapStruct, 0, sizeof(MEMMAP));
DbgMemMap(&wMemMapStruct);
setRowCount(wMemMapStruct.count);
QString wS;
MEMORY_BASIC_INFORMATION wMbi;
for(wI = 0; wI < wMemMapStruct.count; wI++)
{
wMbi = (wMemMapStruct.page)[wI].mbi;
// Base address
setCellContent(wI, ColAddress, ToPtrString((duint)wMbi.BaseAddress));
setCellUserdata(wI, ColAddress, (duint)wMbi.BaseAddress);
// Size
setCellContent(wI, ColSize, ToPtrString((duint)wMbi.RegionSize));
setCellUserdata(wI, ColSize, (duint)wMbi.RegionSize);
// Party
int party = DbgFunctions()->ModGetParty((duint)wMbi.BaseAddress);
switch(party)
{
case mod_user:
setCellContent(wI, ColParty, tr("User"));
setRowIcon(wI, DIcon("markasuser"));
break;
case mod_system:
setCellContent(wI, ColParty, tr("System"));
setRowIcon(wI, DIcon("markassystem"));
break;
default:
setCellContent(wI, ColParty, QString::number(party));
setRowIcon(wI, DIcon("markasparty"));
break;
}
// Information
wS = QString((wMemMapStruct.page)[wI].info);
setCellContent(wI, ColPageInfo, wS);
// Content, TODO: proper section content analysis in dbg/memory.cpp:MemUpdateMap
char comment_text[MAX_COMMENT_SIZE];
if(DbgFunctions()->GetUserComment((duint)wMbi.BaseAddress, comment_text)) // user comment present
wS = comment_text;
else if(wS.contains(".bss"))
wS = tr("Uninitialized data");
else if(wS.contains(".data"))
wS = tr("Initialized data");
else if(wS.contains(".edata"))
wS = tr("Export tables");
else if(wS.contains(".idata"))
wS = tr("Import tables");
else if(wS.contains(".pdata"))
wS = tr("Exception information");
else if(wS.contains(".rdata"))
wS = tr("Read-only initialized data");
else if(wS.contains(".reloc"))
wS = tr("Base relocations");
else if(wS.contains(".rsrc"))
wS = tr("Resources");
else if(wS.contains(".text"))
wS = tr("Executable code");
else if(wS.contains(".tls"))
wS = tr("Thread-local storage");
else if(wS.contains(".xdata"))
wS = tr("Exception information");
else
wS = QString("");
setCellContent(wI, ColContent, std::move(wS));
// Type
const char* type = "";
switch(wMbi.Type)
{
case MEM_IMAGE:
type = "IMG";
break;
case MEM_MAPPED:
type = "MAP";
break;
case MEM_PRIVATE:
type = "PRV";
break;
default:
type = "N/A";
break;
}
setCellContent(wI, ColAllocation, type);
// current access protection
setCellContent(wI, ColCurProtect, getProtectionString(wMbi.Protect));
// allocation protection
setCellContent(wI, ColAllocProtect, getProtectionString(wMbi.AllocationProtect));
}
if(wMemMapStruct.page != 0)
BridgeFree(wMemMapStruct.page);
reloadData(); //refresh memory map
}
void MemoryMapView::stateChangedSlot(DBGSTATE state)
{
if(state == paused)
refreshMap();
}
void MemoryMapView::followDumpSlot()
{
DbgCmdExecDirect(QString("dump %1").arg(getSelectionText()));
}
void MemoryMapView::followDisassemblerSlot()
{
DbgCmdExec(QString("disasm %1").arg(getSelectionText()));
}
void MemoryMapView::followSymbolsSlot()
{
DbgCmdExec(QString("symfollow %1").arg(getSelectionText()));
}
void MemoryMapView::doubleClickedSlot()
{
auto addr = DbgValFromString(getSelectionText().toUtf8().constData());
if(!addr)
return;
if(DbgFunctions()->MemIsCodePage(addr, false))
followDisassemblerSlot();
else
{
followDumpSlot();
emit Bridge::getBridge()->getDumpAttention();
}
}
void MemoryMapView::memoryExecuteSingleshootToggleSlot()
{
for(int i : getSelection())
{
QString addr_text = getCellContent(i, ColAddress);
duint selectedAddr = getSelectionAddr();
if((DbgGetBpxTypeAt(selectedAddr) & bp_memory) == bp_memory) //memory breakpoint set
DbgCmdExec(QString("bpmc ") + addr_text);
else
DbgCmdExec(QString("bpm %1, 0, x").arg(addr_text));
}
}
void MemoryMapView::pageMemoryRights()
{
PageMemoryRights PageMemoryRightsDialog(this);
connect(&PageMemoryRightsDialog, SIGNAL(refreshMemoryMap()), this, SLOT(refreshMap()));
duint addr = getSelectionAddr();
duint size = getCellUserdata(getInitialSelection(), ColSize);
PageMemoryRightsDialog.RunAddrSize(addr, size, getCellContent(getInitialSelection(), ColCurProtect));
}
void MemoryMapView::switchView()
{
Config()->setBool("Engine", "ListAllPages", !ConfigBool("Engine", "ListAllPages"));
Config()->writeBools();
DbgSettingsUpdated();
DbgFunctions()->MemUpdateMap();
setSingleSelection(0);
setTableOffset(0);
stateChangedSlot(paused);
}
void MemoryMapView::memoryAllocateSlot()
{
WordEditDialog mLineEdit(this);
mLineEdit.setup(tr("Size"), 0x1000, sizeof(duint));
if(mLineEdit.exec() == QDialog::Accepted)
{
duint memsize = mLineEdit.getVal();
if(memsize == 0)
{
SimpleWarningBox(this, tr("Warning"), tr("You're trying to allocate a zero-sized buffer just now."));
return;
}
if(memsize > 1024 * 1024 * 1024) // 1GB
{
SimpleErrorBox(this, tr("Error"), tr("The size of buffer you're trying to allocate exceeds 1GB. Please check your expression to ensure nothing is wrong."));
return;
}
DbgCmdExecDirect(QString("alloc %1").arg(ToPtrString(memsize)));
duint addr = DbgValFromString("$result");
if(addr != 0)
DbgCmdExec("dump $result");
else
SimpleErrorBox(this, tr("Error"), tr("Memory allocation failed!"));
}
}
void MemoryMapView::findPatternSlot()
{
HexEditDialog hexEdit(this);
duint entireBlockEnabled = 0;
BridgeSettingGetUint("Gui", "MemoryMapEntireBlock", &entireBlockEnabled);
hexEdit.showEntireBlock(true, entireBlockEnabled);
hexEdit.showKeepSize(false);
hexEdit.isDataCopiable(false);
hexEdit.mHexEdit->setOverwriteMode(false);
hexEdit.setWindowTitle(tr("Find Pattern..."));
if(hexEdit.exec() != QDialog::Accepted)
return;
duint addr = getSelectionAddr();
entireBlockEnabled = hexEdit.entireBlock();
BridgeSettingSetUint("Gui", "MemoryMapEntireBlock", entireBlockEnabled);
if(entireBlockEnabled)
addr = 0;
DbgCmdExec(QString("findallmem %1, %2, &data&").arg(ToPtrString(addr)).arg(hexEdit.mHexEdit->pattern()));
emit showReferences();
}
void MemoryMapView::dumpMemory()
{
duint start = 0;
duint end = 0;
for(auto row : getSelection())
{
auto base = getCellUserdata(row, ColAddress);
auto size = getCellUserdata(row, ColSize);
if(end == 0)
{
start = base;
}
else if(end != base)
{
QMessageBox::critical(this, tr("Error"), tr("Dumping non-consecutive memory ranges is not supported!"));
return;
}
end = base + size;
}
auto modname = mainModuleName();
if(!modname.isEmpty())
modname += '_';
QString defaultFile = QString("%1/%2%3.bin").arg(QDir::currentPath(), modname, getSelectionText());
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Memory Region"), defaultFile, tr("Binary files (*.bin);;All files (*.*)"));
if(fileName.length())
{
fileName = QDir::toNativeSeparators(fileName);
DbgCmdExec(QString("savedata \"%1\",%2,%3").arg(fileName, ToPtrString(start), ToHexString(end - start)));
}
}
void MemoryMapView::loadMemory()
{
auto modname = mainModuleName();
if(!modname.isEmpty())
modname += '_';
auto addr = getSelectionText();
QString defaultFile = QString("%1/%2%3.bin").arg(QDir::currentPath(), modname, addr);
QString fileName = QFileDialog::getOpenFileName(this, tr("Load Memory Region"), defaultFile, tr("Binary files (*.bin);;All files (*.*)"));
if(fileName.length())
{
fileName = QDir::toNativeSeparators(fileName);
//TODO: loaddata command (Does ODbgScript support that?)
DbgCmdExec(QString("savedata \"%1\",%2,%3").arg(fileName, addr, getCellContent(getInitialSelection(), ColSize)));
}
}
void MemoryMapView::selectAddress(duint va)
{
auto base = DbgMemFindBaseAddr(va, nullptr);
if(base)
{
auto rows = getRowCount();
for(dsint row = 0; row < rows; row++)
if(getCellUserdata(row, ColAddress) == base)
{
scrollSelect(row);
reloadData();
return;
}
}
SimpleErrorBox(this, tr("Error"), tr("Address %0 not found in memory map...").arg(ToPtrString(va)));
}
void MemoryMapView::gotoOriginSlot()
{
selectAddress(mCipBase);
}
void MemoryMapView::gotoExpressionSlot()
{
if(!mGoto)
mGoto = new GotoDialog(this);
mGoto->setWindowTitle(tr("Enter the address to find..."));
mGoto->setInitialExpression(ToPtrString(getSelectionAddr()));
if(mGoto->exec() == QDialog::Accepted)
{
selectAddress(DbgValFromString(mGoto->expressionText.toUtf8().constData()));
}
}
void MemoryMapView::addVirtualModSlot()
{
auto base = getSelectionAddr();
auto size = getCellUserdata(getInitialSelection(), ColSize);
VirtualModDialog mDialog(this);
mDialog.setData("", base, size);
if(mDialog.exec() != QDialog::Accepted)
return;
QString modname;
if(!mDialog.getData(modname, base, size))
return;
DbgCmdExec(QString("virtualmod \"%1\", %2, %3").arg(modname).arg(ToHexString(base)).arg(ToHexString(size)));
}
void MemoryMapView::findReferencesSlot()
{
auto base = getSelectionAddr();
auto size = getCellUserdata(getInitialSelection(), ColSize);
DbgCmdExec(QString("reffindrange %1, %2, dis.sel()").arg(ToPtrString(base)).arg(ToPtrString(base + size)));
emit showReferences();
}
void MemoryMapView::selectionGetSlot(SELECTIONDATA* selection)
{
auto sel = getSelection();
selection->start = getCellUserdata(sel.front(), ColAddress);
selection->end = getCellUserdata(sel.back(), ColAddress) + getCellUserdata(sel.back(), ColSize) - 1;
Bridge::getBridge()->setResult(BridgeResult::SelectionGet, 1);
}
void MemoryMapView::disassembleAtSlot(dsint va, dsint cip)
{
Q_UNUSED(va)
mCipBase = DbgMemFindBaseAddr(cip, nullptr);;
}
void MemoryMapView::commentSlot()
{
duint wVA = getSelectionAddr();
LineEditDialog mLineEdit(this);
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;
if(!DbgSetCommentAt(wVA, mLineEdit.editText.replace('\r', "").replace('\n', "").toUtf8().constData()))
SimpleErrorBox(this, tr("Error!"), tr("DbgSetCommentAt failed!"));
GuiUpdateMemoryView();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/MemoryMapView.h | #pragma once
#include "StdIconTable.h"
class GotoDialog;
class MemoryMapView : public StdIconTable
{
Q_OBJECT
public:
explicit MemoryMapView(StdTable* parent = 0);
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h);
void setupContextMenu();
signals:
void showReferences();
public slots:
void refreshShortcutsSlot();
void stateChangedSlot(DBGSTATE state);
void followDumpSlot();
void followDisassemblerSlot();
void followSymbolsSlot();
void doubleClickedSlot();
void memoryExecuteSingleshootToggleSlot();
void memoryAllocateSlot();
void ExecCommand();
void contextMenuSlot(const QPoint & pos);
void switchView();
void pageMemoryRights();
void refreshMap();
void findPatternSlot();
void dumpMemory();
void loadMemory();
void commentSlot();
void selectAddress(duint va);
void gotoOriginSlot();
void gotoExpressionSlot();
void addVirtualModSlot();
void findReferencesSlot();
void selectionGetSlot(SELECTIONDATA* selection);
void disassembleAtSlot(dsint va, dsint cip);
private:
enum
{
ColAddress = 0,
ColSize,
ColParty,
ColPageInfo,
ColContent,
ColAllocation,
ColCurProtect,
ColAllocProtect
};
inline duint getSelectionAddr()
{
return getCellUserdata(getInitialSelection(), ColAddress);
}
inline QString getSelectionText()
{
return getCellContent(getInitialSelection(), ColAddress);
}
QAction* makeCommandAction(QAction* action, const QString & command);
GotoDialog* mGoto = nullptr;
QAction* mFollowDump;
QAction* mFollowDisassembly;
QAction* mFollowSymbols;
QAction* mSwitchView;
QAction* mPageMemoryRights;
QAction* mDumpMemory;
QAction* mLoadMemory;
QMenu* mBreakpointMenu;
QMenu* mMemoryAccessMenu;
QAction* mMemoryAccessSingleshoot;
QAction* mMemoryAccessRestore;
QMenu* mMemoryReadMenu;
QAction* mMemoryReadSingleshoot;
QAction* mMemoryReadRestore;
QMenu* mMemoryWriteMenu;
QAction* mMemoryWriteSingleshoot;
QAction* mMemoryWriteRestore;
QMenu* mMemoryExecuteMenu;
QAction* mMemoryExecuteSingleshoot;
QAction* mMemoryExecuteRestore;
QAction* mMemoryRemove;
QAction* mMemoryExecuteSingleshootToggle;
QAction* mFindPattern;
QMenu* mGotoMenu;
QAction* mGotoOrigin;
QAction* mGotoExpression;
QAction* mMemoryAllocate;
QAction* mMemoryFree;
QAction* mAddVirtualMod;
QAction* mComment;
QAction* mReferences;
QMenu* mPluginMenu;
duint mCipBase;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/MessagesBreakpoints.cpp | #include "MessagesBreakpoints.h"
#include "ui_MessagesBreakpoints.h"
MessagesBreakpoints::MessagesBreakpoints(MsgBreakpointData pbpData, QWidget* parent) :
QDialog(parent),
ui(new Ui::MessagesBreakpoints)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(true);
bpData = pbpData;
int index = 0;
filterMessages =
{
"ACM_", "BFFM_", "BM_", "CB_", "CBEM_", "CCM_", "CDM_", "CTL3D_", "DDM_", "DL_",
"DM_", "DTM_", "EM_", "HDM_", "HKM_", "IE_", "IPM_", "LB_", "LVM_", "MCIWNDM_",
"MCM_", "MN_", "MSG_", "NIN_", "OCM_", "PBM_", "PGM_", "PSM_", "RB_", "SB_",
"SBM_", "SM_", "STM_", "TAPI_", "TB_", "TBM_", "TCM_", "TTM_", "TV_", "TVM_",
"UDM_", "UM_", "WIZ_", "WLX_", "WM_"
};
BridgeList<CONSTANTINFO> constants;
DbgFunctions()->EnumConstants(&constants);
for(int i = 0; i < constants.Count(); i++)
{
foreach(QString filter, filterMessages)
{
if(QString(constants[i].name).startsWith(filter))
{
messages.insert(constants[i].value, constants[i].name);
ui->cboxMessages->addItem(constants[i].name);
break;
}
}
}
for(int i = 0; i < ui->cboxMessages->count(); i++)
if(ui->cboxMessages->itemText(i) == "WM_COMMAND")
index = i;
ui->cboxMessages->setCurrentIndex(index);
}
MessagesBreakpoints::~MessagesBreakpoints()
{
delete ui;
}
void MessagesBreakpoints::on_btnOk_clicked()
{
duint procVA;
duint wndHandle;
QString bpCondCmd;
bool translMsg = ui->chkTranslateMessage->isChecked();
if(!DbgFunctions()->ValFromString(bpData.wndHandle.toUtf8().constData(), &wndHandle) ||
!DbgFunctions()->ValFromString(bpData.procVA.toUtf8().constData(), &procVA))
return;
if(!DbgMemIsValidReadPtr(procVA) || !IsWindow((HWND)wndHandle))
return;
if(!translMsg)
{
BPXTYPE wBpType = DbgGetBpxTypeAt(procVA);
if(wBpType == bp_none)
DbgCmdExec(QString("bp 0x%1").arg(bpData.procVA));
bpCondCmd = QString("bpcnd 0x%1, \"arg.get(1) == 0x%2").arg(bpData.procVA).arg(messages.key(ui->cboxMessages->currentText()), 1, 16);
bpCondCmd.append(ui->rbtnBreakCurrent->isChecked() ? QString(" && arg.get(0) == 0x%1\"").arg(bpData.wndHandle) : "\"");
}
else
{
BPXTYPE wBpType = DbgGetBpxTypeAt(DbgValFromString("TranslateMessage"));
if(wBpType == bp_none)
DbgCmdExec("bp TranslateMessage");
#ifdef _WIN64
bpCondCmd = QString("bpcnd TranslateMessage, \"4:[arg.get(0)+8] == 0x%1").arg(messages.key(ui->cboxMessages->currentText()), 1, 16);
bpCondCmd.append(ui->rbtnBreakCurrent->isChecked() ? QString(" && 4:[arg.get(0)] == 0x%1\"").arg(bpData.wndHandle) : "\"");
#else //x86
bpCondCmd = QString("bpcnd TranslateMessage, \"[arg.get(0)+4] == 0x%1").arg(messages.key(ui->cboxMessages->currentText()), 1, 16);
bpCondCmd.append(ui->rbtnBreakCurrent->isChecked() ? QString(" && [arg.get(0)] == 0x%1\"").arg(bpData.wndHandle) : "\"");
#endif //_WIN64
}
DbgCmdExec(bpCondCmd);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/MessagesBreakpoints.h | #pragma once
#include <QDialog>
#include <QLayout>
#include <QMap>
#include <QVector>
#include "Imports.h"
namespace Ui
{
class MessagesBreakpoints;
}
class MessagesBreakpoints : public QDialog
{
Q_OBJECT
public:
struct MsgBreakpointData
{
QString procVA;
QString wndHandle;
};
explicit MessagesBreakpoints(MsgBreakpointData pbpData, QWidget* parent = 0);
~MessagesBreakpoints();
MsgBreakpointData bpData;
private slots:
void on_btnOk_clicked();
private:
Ui::MessagesBreakpoints* ui;
QMap<duint, QString> messages;
QVector<QString> filterMessages;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/MessagesBreakpoints.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MessagesBreakpoints</class>
<widget class="QDialog" name="MessagesBreakpoints">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>289</width>
<height>214</height>
</rect>
</property>
<property name="windowTitle">
<string>Message Breakpoint</string>
</property>
<property name="windowIcon">
<iconset theme="breakpoint_execute" resource="../../resource.qrc">
<normaloff>:/Default/icons/breakpoint_execute.png</normaloff>:/Default/icons/breakpoint_execute.png</iconset>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="modal">
<bool>false</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="lblMessages">
<property name="text">
<string>Messages:</string>
</property>
<property name="buddy">
<cstring>cboxMessages</cstring>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="cboxMessages">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QGroupBox" name="gboxBreakpoints">
<property name="title">
<string/>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QRadioButton" name="rbtnBreakAny">
<property name="text">
<string>Break on any window</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="rbtnBreakCurrent">
<property name="text">
<string>Break on current window only
(Invalid for next session)</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="chkTranslateMessage">
<property name="text">
<string>Use TranslateMessage</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<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="btnOk">
<property name="text">
<string>OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnCancel">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>MessagesBreakpoints</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>237</x>
<y>181</y>
</hint>
<hint type="destinationlabel">
<x>150</x>
<y>104</y>
</hint>
</hints>
</connection>
<connection>
<sender>btnOk</sender>
<signal>clicked()</signal>
<receiver>MessagesBreakpoints</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>157</x>
<y>181</y>
</hint>
<hint type="destinationlabel">
<x>150</x>
<y>104</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/MultiItemsSelectWindow.cpp | #include "MultiItemsSelectWindow.h"
#define QTC_ASSERT(cond, action) if (cond) {} else { action; } do {} while (0)
#include <QFocusEvent>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QScrollBar>
#include <QApplication>
enum class Role
{
ItemData = Qt::UserRole
};
MultiItemsSelectWindow::MultiItemsSelectWindow(MultiItemsDataProvider* hp, QWidget* parent, bool showIcon) :
QFrame(parent, Qt::Popup),
mDataProvider(hp),
mShowIcon(showIcon),
mEditorList(new OpenViewsTreeWidget(this))
{
setMinimumSize(300, 200);
mEditorList->setColumnCount(1);
mEditorList->header()->hide();
mEditorList->setIndentation(0);
mEditorList->setSelectionMode(QAbstractItemView::SingleSelection);
mEditorList->setTextElideMode(Qt::ElideMiddle);
mEditorList->installEventFilter(this);
setFrameStyle(mEditorList->frameStyle());
mEditorList->setFrameStyle(QFrame::NoFrame);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->addWidget(mEditorList);
connect(mEditorList, &QTreeWidget::itemClicked,
this, &MultiItemsSelectWindow::editorClicked);
setVisible(false);
}
void MultiItemsSelectWindow::gotoNextItem()
{
if(isVisible())
{
selectPreviousEditor();
}
else
{
addItems();
selectPreviousEditor();
showPopupOrSelectDocument();
}
}
void MultiItemsSelectWindow::gotoPreviousItem()
{
if(isVisible())
{
selectNextEditor();
}
else
{
addItems();
selectNextEditor();
showPopupOrSelectDocument();
}
}
void MultiItemsSelectWindow::showPopupOrSelectDocument()
{
if(QApplication::keyboardModifiers() == Qt::NoModifier)
{
selectAndHide();
}
else
{
QWidget* activeWindow = QApplication::activeWindow();
if(!activeWindow)
return;
QWidget* referenceWidget = activeWindow;
const QPoint p = referenceWidget->mapToGlobal(QPoint(0, 0));
this->setMaximumSize(qMax(this->minimumWidth(), referenceWidget->width() / 2),
qMax(this->minimumHeight(), referenceWidget->height() / 2));
this->adjustSize();
this->move((referenceWidget->width() - this->width()) / 2 + p.x(),
(referenceWidget->height() - this->height()) / 2 + p.y());
this->setVisible(true);
}
}
void MultiItemsSelectWindow::selectAndHide()
{
setVisible(false);
selectEditor(mEditorList->currentItem());
}
void MultiItemsSelectWindow::setVisible(bool visible)
{
QWidget::setVisible(visible);
if(visible)
setFocus();
}
bool MultiItemsSelectWindow::eventFilter(QObject* obj, QEvent* e)
{
if(obj == mEditorList)
{
if(e->type() == QEvent::KeyPress)
{
QKeyEvent* ke = static_cast<QKeyEvent*>(e);
if(ke->key() == Qt::Key_Escape)
{
setVisible(false);
return true;
}
if(ke->key() == Qt::Key_Return
|| ke->key() == Qt::Key_Enter)
{
selectEditor(mEditorList->currentItem());
return true;
}
}
else if(e->type() == QEvent::KeyRelease)
{
QKeyEvent* ke = static_cast<QKeyEvent*>(e);
if(ke->modifiers() == 0
/*HACK this is to overcome some event inconsistencies between platforms*/
|| (ke->modifiers() == Qt::AltModifier
&& (ke->key() == Qt::Key_Alt || ke->key() == -1)))
{
selectAndHide();
}
}
}
return QWidget::eventFilter(obj, e);
}
void MultiItemsSelectWindow::focusInEvent(QFocusEvent*)
{
mEditorList->setFocus();
}
void MultiItemsSelectWindow::selectUpDown(bool up)
{
int itemCount = mEditorList->topLevelItemCount();
if(itemCount < 2)
return;
int index = mEditorList->indexOfTopLevelItem(mEditorList->currentItem());
if(index < 0)
return;
QTreeWidgetItem* editor = 0;
int count = 0;
while(!editor && count < itemCount)
{
if(up)
{
index--;
if(index < 0)
index = itemCount - 1;
}
else
{
index++;
if(index >= itemCount)
index = 0;
}
editor = mEditorList->topLevelItem(index);
count++;
}
if(editor)
{
mEditorList->setCurrentItem(editor);
ensureCurrentVisible();
}
}
void MultiItemsSelectWindow::selectPreviousEditor()
{
selectUpDown(false);
}
QSize MultiItemsSelectWindow::OpenViewsTreeWidget::sizeHint() const
{
return QSize(sizeHintForColumn(0) + verticalScrollBar()->width() + frameWidth() * 2,
viewportSizeHint().height() + frameWidth() * 2);
}
QSize MultiItemsSelectWindow::sizeHint() const
{
return mEditorList->sizeHint() + QSize(frameWidth() * 2, frameWidth() * 2);
}
void MultiItemsSelectWindow::selectNextEditor()
{
selectUpDown(true);
}
void MultiItemsSelectWindow::addItems()
{
mEditorList->clear();
auto & history = mDataProvider->MIDP_getItems();
for(auto & i : history)
{
addItem(i);
}
}
void MultiItemsSelectWindow::selectEditor(QTreeWidgetItem* item)
{
if(!item)
return;
auto index = item->data(0, int(Role::ItemData)).value<MIDPKey>();
mDataProvider->MIDP_selected(index);
}
void MultiItemsSelectWindow::editorClicked(QTreeWidgetItem* item)
{
selectEditor(item);
setFocus();
}
void MultiItemsSelectWindow::ensureCurrentVisible()
{
mEditorList->scrollTo(mEditorList->currentIndex(), QAbstractItemView::PositionAtCenter);
}
void MultiItemsSelectWindow::addItem(MIDPKey index)
{
QTreeWidgetItem* item = new QTreeWidgetItem();
if(mShowIcon)
item->setIcon(0, mDataProvider->MIDP_getIcon(index));
item->setText(0, mDataProvider->MIDP_getItemName(index));
item->setData(0, int(Role::ItemData), QVariant::fromValue(index));
item->setTextAlignment(0, Qt::AlignLeft);
mEditorList->addTopLevelItem(item);
if(mEditorList->topLevelItemCount() == 1)
mEditorList->setCurrentItem(item);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/MultiItemsSelectWindow.h | #pragma once
// stolen from http://code.qt.io/cgit/qt-creator/qt-creator.git/tree/src/plugins/coreplugin/editormanager/openeditorswindow.h
#include <QFrame>
#include <QIcon>
#include <QList>
#include <QTreeWidget>
QT_BEGIN_NAMESPACE
class QTreeWidgetItem;
class QWidget;
QT_END_NAMESPACE
typedef void* MIDPKey;
class MultiItemsDataProvider
{
public:
virtual const QList<MIDPKey> & MIDP_getItems() const = 0;
virtual QString MIDP_getItemName(MIDPKey index) = 0;
virtual QIcon MIDP_getIcon(MIDPKey index) = 0;
virtual void MIDP_selected(MIDPKey index) = 0;
};
class MultiItemsSelectWindow : public QFrame
{
Q_OBJECT
public:
MultiItemsSelectWindow(MultiItemsDataProvider* hp, QWidget* parent, bool showIcon);
void gotoNextItem();
void gotoPreviousItem();
private slots:
void selectAndHide();
private:
void addItems();
bool eventFilter(QObject* src, QEvent* e);
void focusInEvent(QFocusEvent*);
void setVisible(bool visible);
void selectNextEditor();
void selectPreviousEditor();
QSize sizeHint() const;
void showPopupOrSelectDocument();
void editorClicked(QTreeWidgetItem* item);
void selectEditor(QTreeWidgetItem* item);
void addItem(MIDPKey index);
void ensureCurrentVisible();
void selectUpDown(bool up);
class OpenViewsTreeWidget : public QTreeWidget
{
public:
explicit OpenViewsTreeWidget(QWidget* parent = 0) : QTreeWidget(parent) {}
~OpenViewsTreeWidget() {}
QSize sizeHint() const;
};
OpenViewsTreeWidget* mEditorList;
MultiItemsDataProvider* mDataProvider = nullptr;
bool mShowIcon;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/NotepadView.cpp | #include "NotepadView.h"
#include "Configuration.h"
#include "Bridge.h"
#include <QMessageBox>
NotepadView::NotepadView(QWidget* parent, BridgeResult::Type type) : QPlainTextEdit(parent), mType(type)
{
updateStyle();
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateStyle()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(updateStyle()));
}
void NotepadView::updateStyle()
{
setFont(ConfigFont("Log"));
setStyleSheet(QString("QPlainTextEdit { color: %1; background-color: %2 }").arg(ConfigColor("AbstractTableViewTextColor").name(), ConfigColor("AbstractTableViewBackgroundColor").name()));
}
void NotepadView::setNotes(const QString text)
{
setPlainText(text);
}
void NotepadView::getNotes(void* ptr)
{
QByteArray text = toPlainText().replace('\n', "\r\n").toUtf8();
char* result = 0;
if(text.length())
{
result = (char*)BridgeAlloc(text.length() + 1);
strcpy_s(result, text.length() + 1, text.constData());
}
*(char**)ptr = result;
Bridge::getBridge()->setResult(mType);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/NotepadView.h | #pragma once
#include <QPlainTextEdit>
#include "BridgeResult.h"
class NotepadView : public QPlainTextEdit
{
Q_OBJECT
public:
NotepadView(QWidget* parent, BridgeResult::Type type);
public slots:
void updateStyle();
void setNotes(const QString text);
void getNotes(void* ptr);
private:
BridgeResult::Type mType;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/NotesManager.cpp | #include "NotesManager.h"
#include "Bridge.h"
NotesManager::NotesManager(QWidget* parent) : QTabWidget(parent)
{
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChangedSlot(DBGSTATE)));
mGlobal = new NotepadView(this, BridgeResult::GetGlobalNotes);
mGlobal->setWindowTitle("GlobalNotes");
connect(Bridge::getBridge(), SIGNAL(setGlobalNotes(QString)), mGlobal, SLOT(setNotes(QString)));
connect(Bridge::getBridge(), SIGNAL(getGlobalNotes(void*)), mGlobal, SLOT(getNotes(void*)));
addTab(mGlobal, tr("Global"));
mDebuggee = new NotepadView(this, BridgeResult::GetDebuggeeNotes);
mDebuggee->setWindowTitle("DebuggeeNotes");
connect(Bridge::getBridge(), SIGNAL(setDebuggeeNotes(QString)), mDebuggee, SLOT(setNotes(QString)));
connect(Bridge::getBridge(), SIGNAL(getDebuggeeNotes(void*)), mDebuggee, SLOT(getNotes(void*)));
mDebuggee->hide();
}
void NotesManager::dbgStateChangedSlot(DBGSTATE state)
{
if(state == initialized)
{
mDebuggee->show();
addTab(mDebuggee, tr("Debuggee"));
}
else if(state == stopped)
{
mDebuggee->hide();
removeTab(1);
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/NotesManager.h | #pragma once
#include <QWidget>
#include <QTabWidget>
#include "NotepadView.h"
#include "Bridge.h"
class NotesManager : public QTabWidget
{
Q_OBJECT
public:
explicit NotesManager(QWidget* parent = 0);
public slots:
void dbgStateChangedSlot(DBGSTATE state);
private:
NotepadView* mGlobal;
NotepadView* mDebuggee;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/PageMemoryRights.cpp | #include "Imports.h"
#include "PageMemoryRights.h"
#include "ui_PageMemoryRights.h"
#include "StringUtil.h"
PageMemoryRights::PageMemoryRights(QWidget* parent) : QDialog(parent), ui(new Ui::PageMemoryRights)
{
ui->setupUi(this);
//set window flags
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setModal(true);
addr = 0;
size = 0;
}
PageMemoryRights::~PageMemoryRights()
{
delete ui;
}
void PageMemoryRights::RunAddrSize(duint addrin, duint sizein, QString pagetypein)
{
addr = addrin;
size = sizein;
pagetype = pagetypein;
QTableWidget* tableWidget = ui->pagetableWidget;
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
duint nr_pages = size / PAGE_SIZE;
tableWidget->setColumnCount(2);
tableWidget->setRowCount(nr_pages);
tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem(QString(tr("Address"))));
tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem(QString(tr("Rights"))));
duint actual_addr;
char rights[RIGHTS_STRING_SIZE];
for(duint i = 0; i < nr_pages; i++)
{
actual_addr = addr + (i * PAGE_SIZE);
tableWidget->setItem(i, 0, new QTableWidgetItem(ToPtrString(actual_addr)));
if(DbgFunctions()->GetPageRights(actual_addr, rights))
tableWidget->setItem(i, 1, new QTableWidgetItem(QString(rights)));
}
tableWidget->resizeColumnsToContents();
QModelIndex idx = (ui->pagetableWidget->model()->index(0, 0));
ui->pagetableWidget->selectionModel()->select(idx, QItemSelectionModel::Select);
idx = (ui->pagetableWidget->model()->index(0, 1));
ui->pagetableWidget->selectionModel()->select(idx, QItemSelectionModel::Select);
ui->radioFullaccess->setChecked(true);
ui->chkPageguard->setCheckable(true);
exec();
}
void PageMemoryRights::on_btnSelectall_clicked()
{
for(int i = 0; i < ui->pagetableWidget->rowCount(); i++)
{
for(int j = 0; j < ui->pagetableWidget->columnCount(); j++)
{
QModelIndex idx = (ui->pagetableWidget->model()->index(i, j));
ui->pagetableWidget->selectionModel()->select(idx, QItemSelectionModel::Select);
}
}
}
void PageMemoryRights::on_btnDeselectall_clicked()
{
QModelIndexList indexList = ui->pagetableWidget->selectionModel()->selectedIndexes();
foreach(QModelIndex index, indexList)
{
ui->pagetableWidget->selectionModel()->select(index, QItemSelectionModel::Deselect);
}
}
void PageMemoryRights::on_btnSetrights_clicked()
{
duint actual_addr;
QString rights;
char newrights[RIGHTS_STRING_SIZE];
bool one_right_changed = false;
if(ui->radioExecute->isChecked())
rights = "Execute";
else if(ui->radioExecuteread->isChecked())
rights = "ExecuteRead";
else if(ui->radioNoaccess->isChecked())
rights = "NoAccess";
else if(ui->radioFullaccess ->isChecked())
rights = "ExecuteReadWrite";
else if(ui->radioReadonly->isChecked())
rights = "ReadOnly";
else if(ui->radioReadwrite->isChecked())
rights = "ReadWrite";
else if(ui->radioWritecopy->isChecked())
rights = "WriteCopy";
else if(ui->radioExecutewritecopy->isChecked())
rights = "ExecuteWriteCopy";
else
return;
if(ui->chkPageguard->isChecked())
rights = "G" + rights;
QModelIndexList indexList = ui->pagetableWidget->selectionModel()->selectedIndexes();
foreach(QModelIndex index, indexList)
{
#ifdef _WIN64
actual_addr = ui->pagetableWidget->item(index.row(), 0)->text().toULongLong(0, 16);
#else //x86
actual_addr = ui->pagetableWidget->item(index.row(), 0)->text().toULong(0, 16);
#endif //_WIN64
if(DbgFunctions()->SetPageRights(actual_addr, (char*)rights.toUtf8().constData()))
{
one_right_changed = true;
if(DbgFunctions()->GetPageRights(actual_addr, newrights))
ui->pagetableWidget->setItem(index.row(), 1, new QTableWidgetItem(QString(newrights)));
}
}
DbgFunctions()->MemUpdateMap();
emit refreshMemoryMap();
if(one_right_changed)
ui->LnEdStatus->setText(tr("Pages Rights Changed to: ") + rights);
else
ui->LnEdStatus->setText(tr("Error setting rights, read the MSDN to learn the valid rights of: ") + pagetype);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/PageMemoryRights.h | #pragma once
#include <QDialog>
#include "dbg_types.h"
namespace Ui
{
class PageMemoryRights;
}
class PageMemoryRights : public QDialog
{
Q_OBJECT
public:
explicit PageMemoryRights(QWidget* parent = 0);
void RunAddrSize(duint, duint, QString);
~PageMemoryRights();
private slots:
void on_btnSelectall_clicked();
void on_btnDeselectall_clicked();
void on_btnSetrights_clicked();
signals:
void refreshMemoryMap();
private:
Ui::PageMemoryRights* ui;
duint addr;
duint size;
QString pagetype;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/PageMemoryRights.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PageMemoryRights</class>
<widget class="QDialog" name="PageMemoryRights">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>445</width>
<height>349</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Set Page Memory Rights</string>
</property>
<property name="windowIcon">
<iconset theme="memory-map" resource="../../resource.qrc">
<normaloff>:/Default/icons/memory-map.png</normaloff>:/Default/icons/memory-map.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTableWidget" name="pagetableWidget">
<property name="enabled">
<bool>true</bool>
</property>
<property name="autoScroll">
<bool>true</bool>
</property>
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<attribute name="verticalHeaderVisible">
<bool>false</bool>
</attribute>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttonsLayout">
<item>
<widget class="QPushButton" name="btnSelectall">
<property name="text">
<string>Select ALL</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDeselectall">
<property name="text">
<string>Deselect ALL</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayoutGroup">
<item>
<widget class="QGroupBox" name="rightsGroup">
<property name="title">
<string>Rights</string>
</property>
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<item row="0" column="0">
<widget class="QRadioButton" name="radioNoaccess">
<property name="text">
<string>NO ACCESS</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QRadioButton" name="radioReadonly">
<property name="text">
<string>READ ONLY</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QRadioButton" name="radioReadwrite">
<property name="text">
<string>READ WRITE</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QRadioButton" name="radioExecute">
<property name="text">
<string>EXECUTE</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QRadioButton" name="radioExecuteread">
<property name="text">
<string>EXECUTE READ</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QRadioButton" name="radioFullaccess">
<property name="text">
<string>FULL ACCESS</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QRadioButton" name="radioWritecopy">
<property name="text">
<string>WRITE COPY</string>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QRadioButton" name="radioExecutewritecopy">
<property name="text">
<string>EXECUTE WRITE COPY</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnSetrights">
<property name="text">
<string>Set Rights</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="chkPageguard">
<property name="text">
<string>PAGE GUARD</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Press CTRL or SHIFT key to select multiple pages</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="LnEdStatus">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>pagetableWidget</tabstop>
<tabstop>btnSelectall</tabstop>
<tabstop>btnDeselectall</tabstop>
<tabstop>radioNoaccess</tabstop>
<tabstop>radioReadonly</tabstop>
<tabstop>radioReadwrite</tabstop>
<tabstop>radioExecute</tabstop>
<tabstop>radioExecuteread</tabstop>
<tabstop>radioFullaccess</tabstop>
<tabstop>radioWritecopy</tabstop>
<tabstop>radioExecutewritecopy</tabstop>
<tabstop>btnSetrights</tabstop>
<tabstop>chkPageguard</tabstop>
<tabstop>LnEdStatus</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>pushButton</sender>
<signal>clicked()</signal>
<receiver>PageMemoryRights</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>460</x>
<y>314</y>
</hint>
<hint type="destinationlabel">
<x>496</x>
<y>316</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/PatchDialog.cpp | #include "PatchDialog.h"
#include "ui_PatchDialog.h"
#include <QMessageBox>
#include <QIcon>
#include <QFileDialog>
#include <QTextStream>
#include "MiscUtil.h"
#include "StringUtil.h"
#include "Configuration.h"
PatchDialog::PatchDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::PatchDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setModal(false); //non-modal window
connect(Bridge::getBridge(), SIGNAL(updatePatches()), this, SLOT(updatePatches()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(dbgStateChanged(DBGSTATE)));
mGroupSelector = new PatchDialogGroupSelector(parent);
mGroupSelector->setGroup(0);
connect(mGroupSelector, SIGNAL(rejected()), this, SLOT(showNormal()));
connect(mGroupSelector, SIGNAL(rejected()), this, SLOT(setFocus()));
connect(mGroupSelector, SIGNAL(groupToggle()), this, SLOT(groupToggle()));
connect(mGroupSelector, SIGNAL(groupPrevious()), this, SLOT(groupPrevious()));
connect(mGroupSelector, SIGNAL(groupNext()), this, SLOT(groupNext()));
mIsWorking = false;
}
PatchDialog::~PatchDialog()
{
delete ui;
}
bool PatchDialog::isPartOfPreviousGroup(const PatchInfoList & patchList, int index)
{
if(!index)
return true;
uint addr = patchList.at(index).patch.addr;
uint prevAddr = patchList.at(index - 1).patch.addr;
for(int i = 1; i < 10; i++) //10 bytes in between groups
if(addr - i == prevAddr)
return true;
return false;
}
bool PatchDialog::isGroupEnabled(const PatchInfoList & patchList, int group)
{
for(int i = 0; i < patchList.size(); i++)
if(patchList.at(i).status.group == group && !patchList.at(i).status.checked)
return false;
return true;
}
bool PatchDialog::hasPreviousGroup(const PatchInfoList & patchList, int group)
{
for(int i = 0; i < patchList.size(); i++)
if(patchList.at(i).status.group < group)
return true;
return false;
}
bool PatchDialog::hasNextGroup(const PatchInfoList & patchList, int group)
{
for(int i = 0; i < patchList.size(); i++)
if(patchList.at(i).status.group > group)
return true;
return false;
}
dsint PatchDialog::getGroupAddress(const PatchInfoList & patchList, int group)
{
for(int i = 0; i < patchList.size(); i++)
if(patchList.at(i).status.group == group)
return patchList.at(i).patch.addr;
return -1;
}
void PatchDialog::dbgStateChanged(DBGSTATE state)
{
if(state == stopped)
{
mGroupSelector->hide();
reject();
}
}
void PatchDialog::updatePatches()
{
if(this->isVisible())
mGroupSelector->reject();
mIsWorking = true;
//clear GUI
ui->listModules->clear();
ui->listPatches->clear();
mPatches.clear();
//get patches from DBG
size_t cbsize;
if(!DbgFunctions()->PatchEnum || !DbgFunctions()->PatchEnum(0, &cbsize))
return;
int numPatches = (int)cbsize / sizeof(DBGPATCHINFO);
if(!numPatches)
return;
DBGPATCHINFO* patches = new DBGPATCHINFO[numPatches];
memset(patches, 0, numPatches * sizeof(DBGPATCHINFO));
if(!DbgFunctions()->PatchEnum(patches, 0))
{
delete [] patches;
mIsWorking = false;
return;
}
//fill the patch list
STATUSINFO defaultStatus;
defaultStatus.group = 0;
defaultStatus.checked = true;
for(int i = 0; i < numPatches; i++)
{
if(!patches[i].addr)
continue;
if(!*patches[i].mod)
continue;
QString mod = patches[i].mod;
PatchMap::iterator found = mPatches.find(mod);
if(found != mPatches.end()) //found
mPatches[mod].append(PatchPair(patches[i], defaultStatus));
else //not found
{
PatchInfoList patchList;
patchList.append(PatchPair(patches[i], defaultStatus));
mPatches.insert(mod, patchList);
}
}
delete [] patches;
//sort the patches by address
for(PatchMap::iterator i = mPatches.begin(); i != mPatches.end(); ++i)
{
qSort(i.value().begin(), i.value().end(), PatchInfoLess);
PatchInfoList & curPatchList = i.value();
//group the patched bytes
for(int j = 0, group = 0; j < curPatchList.size(); j++)
{
if(!isPartOfPreviousGroup(curPatchList, j))
group++;
curPatchList[j].status.group = group;
unsigned char byte;
if(DbgMemRead(curPatchList[j].patch.addr, &byte, sizeof(byte)))
curPatchList[j].status.checked = byte == curPatchList[j].patch.newbyte;
}
ui->listModules->addItem(i.key());
}
if(mPatches.size())
ui->listModules->item(0)->setSelected(true); //select first module
mIsWorking = false;
}
void PatchDialog::groupToggle()
{
int group = mGroupSelector->group();
if(mIsWorking || !ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
PatchInfoList & curPatchList = found.value();
bool enabled = !isGroupEnabled(curPatchList, group);
Qt::CheckState checkState = enabled ? Qt::Checked : Qt::Unchecked;
mIsWorking = true;
for(int i = 0; i < curPatchList.size(); i++)
{
if(curPatchList.at(i).status.group != group)
continue;
ui->listPatches->item(i)->setCheckState(checkState);
curPatchList[i].status.checked = enabled;
//change the byte to reflect the change for the user (cypherpunk reported this)
unsigned char writebyte = curPatchList[i].status.checked ? curPatchList[i].patch.newbyte : curPatchList[i].patch.oldbyte;
DbgMemWrite(curPatchList[i].patch.addr, &writebyte, sizeof(writebyte));
}
mIsWorking = false;
dsint groupStart = getGroupAddress(curPatchList, group);
GuiUpdateAllViews();
if(!groupStart)
return;
QString color = enabled ? "#00DD00" : "red";
QString addrText = ToPtrString(groupStart);
QString title = "<font color='" + color + "'><b>" + QString().sprintf("%d:", group) + addrText + "</b></font>";
mGroupSelector->setGroupTitle(title);
}
void PatchDialog::groupPrevious()
{
int group = mGroupSelector->group();
if(!ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
PatchInfoList & curPatchList = found.value();
if(!hasPreviousGroup(curPatchList, group))
return;
group--;
QString color = isGroupEnabled(curPatchList, group) ? "#00DD00" : "red";
QString addrText = ToPtrString(getGroupAddress(curPatchList, group));
QString title = "<font color='" + color + "'><b>" + QString().sprintf("%d:", group) + addrText + "</b></font>";
mGroupSelector->setGroupTitle(title);
mGroupSelector->setGroup(group);
mGroupSelector->setPreviousEnabled(hasPreviousGroup(curPatchList, group));
mGroupSelector->setNextEnabled(hasNextGroup(curPatchList, group));
mGroupSelector->showNormal();
DbgCmdExecDirect(QString("disasm " + addrText));
DbgCmdExecDirect(QString("dump " + addrText));
}
void PatchDialog::groupNext()
{
int group = mGroupSelector->group();
if(!ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
PatchInfoList & curPatchList = found.value();
if(!hasNextGroup(curPatchList, group))
return;
group++;
QString color = isGroupEnabled(curPatchList, group) ? "#00DD00" : "red";
QString addrText = ToPtrString(getGroupAddress(curPatchList, group));
QString title = "<font color='" + color + "'><b>" + QString().sprintf("%d:", group) + addrText + "</b></font>";
mGroupSelector->setGroupTitle(title);
mGroupSelector->setGroup(group);
mGroupSelector->setPreviousEnabled(hasPreviousGroup(curPatchList, group));
mGroupSelector->setNextEnabled(hasNextGroup(curPatchList, group));
mGroupSelector->showNormal();
DbgCmdExecDirect(QString("disasm " + addrText));
DbgCmdExecDirect(QString("dump " + addrText));
}
void PatchDialog::on_listModules_itemSelectionChanged()
{
if(!ui->listModules->selectedItems().size())
return;
QString mod(ui->listModules->selectedItems().at(0)->text());
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
mIsWorking = true;
PatchInfoList & patchList = found.value();
ui->listPatches->clear();
for(int i = 0; i < patchList.size(); i++)
{
const DBGPATCHINFO curPatch = patchList.at(i).patch;
QString addrText = ToPtrString(curPatch.addr);
QListWidgetItem* item = new QListWidgetItem(QString().sprintf("%d", patchList.at(i).status.group).rightJustified(4, ' ', true) + "|" + addrText + QString().sprintf(":%.2X->%.2X", curPatch.oldbyte, curPatch.newbyte), ui->listPatches);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
Qt::CheckState state = patchList.at(i).status.checked ? Qt::Checked : Qt::Unchecked;
item->setCheckState(state);
if(DbgFunctions()->ModRelocationAtAddr(patchList.at(i).patch.addr, nullptr))
{
item->setTextColor(ConfigColor("PatchRelocatedByteHighlightColor"));
item->setToolTip(tr("Byte is located in relocation region"));
}
}
mIsWorking = false;
}
void PatchDialog::on_listPatches_itemChanged(QListWidgetItem* item) //checkbox changed
{
if(mIsWorking || !ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
bool checked = item->checkState() == Qt::Checked;
PatchInfoList & curPatchList = found.value();
PatchPair & patch = curPatchList[ui->listPatches->row(item)];
if(patch.status.checked == checked) //check state did not change
return;
patch.status.checked = checked;
//change the byte to reflect the change for the user (cypherpunk reported this)
unsigned char writebyte = patch.status.checked ? patch.patch.newbyte : patch.patch.oldbyte;
DbgMemWrite(patch.patch.addr, &writebyte, sizeof(writebyte));
//check state changed
if((QApplication::keyboardModifiers() & Qt::ControlModifier) != Qt::ControlModifier)
{
mIsWorking = true;
//check/uncheck the complete group
for(int i = 0; i < curPatchList.size(); i++)
if(curPatchList.at(i).status.group == patch.status.group)
{
//change the patch state
curPatchList[i].status.checked = checked;
ui->listPatches->item(i)->setCheckState(item->checkState());
//change the byte to reflect the change for the user (cypherpunk reported this)
unsigned char writebyte = curPatchList[i].status.checked ? curPatchList[i].patch.newbyte : curPatchList[i].patch.oldbyte;
DbgMemWrite(curPatchList[i].patch.addr, &writebyte, sizeof(writebyte));
}
mIsWorking = false;
}
int group = mGroupSelector->group();
QString color = isGroupEnabled(curPatchList, group) ? "#00DD00" : "red";
QString addrText = ToPtrString(getGroupAddress(curPatchList, group));
QString title = "<font color='" + color + "'><b>" + QString().sprintf("%d:", group) + addrText + "</b></font>";
mGroupSelector->setGroupTitle(title);
mGroupSelector->setPreviousEnabled(hasPreviousGroup(curPatchList, group));
mGroupSelector->setNextEnabled(hasNextGroup(curPatchList, group));
GuiUpdateAllViews();
}
void PatchDialog::on_btnSelectAll_clicked()
{
if(!ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
mIsWorking = true;
PatchInfoList & curPatchList = found.value();
for(int i = 0; i < curPatchList.size(); i++)
{
ui->listPatches->item(i)->setCheckState(Qt::Checked);
curPatchList[i].status.checked = true;
//change the byte to reflect the change for the user (cypherpunk reported this)
DbgMemWrite(curPatchList[i].patch.addr, &curPatchList[i].patch.newbyte, sizeof(unsigned char));
}
GuiUpdateAllViews();
mIsWorking = false;
}
void PatchDialog::on_btnDeselectAll_clicked()
{
if(!ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
mIsWorking = true;
PatchInfoList & curPatchList = found.value();
for(int i = 0; i < curPatchList.size(); i++)
{
ui->listPatches->item(i)->setCheckState(Qt::Unchecked);
curPatchList[i].status.checked = false;
//change the byte to reflect the change for the user (cypherpunk reported this)
DbgMemWrite(curPatchList[i].patch.addr, &curPatchList[i].patch.oldbyte, sizeof(unsigned char));
}
GuiUpdateAllViews();
mIsWorking = false;
}
void PatchDialog::on_btnRestoreSelected_clicked()
{
if(!ui->listModules->selectedItems().size())
return;
int selModIdx = ui->listModules->row(ui->listModules->selectedItems().at(0));
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
mIsWorking = true;
PatchInfoList & curPatchList = found.value();
int removed = 0;
int total = curPatchList.size();
for(int i = 0; i < total; i++)
{
if(curPatchList.at(i).status.checked)
{
DbgFunctions()->PatchRestore(curPatchList.at(i).patch.addr);
removed++;
}
}
mIsWorking = false;
updatePatches();
if(removed != total)
ui->listModules->setCurrentRow(selModIdx);
GuiUpdateAllViews();
}
void PatchDialog::on_listPatches_itemSelectionChanged()
{
if(!ui->listModules->selectedItems().size() || !ui->listPatches->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
PatchInfoList & curPatchList = found.value();
PatchPair & patch = curPatchList[ui->listPatches->row(ui->listPatches->selectedItems().at(0))]; //selected item
dsint groupStart = getGroupAddress(curPatchList, patch.status.group);
if(!groupStart)
return;
QString addrText = ToPtrString(groupStart);
DbgCmdExecDirect(QString("disasm " + addrText));
DbgCmdExecDirect(QString("dump " + addrText));
}
void PatchDialog::on_btnPickGroups_clicked()
{
if(!ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
PatchInfoList & curPatchList = found.value();
if(!curPatchList.size())
return;
this->showMinimized();
int group = mGroupSelector->group();
QString color = isGroupEnabled(curPatchList, group) ? "#00DD00" : "red";
QString addrText = ToPtrString(getGroupAddress(curPatchList, group));
QString title = "<font color='" + color + "'><b>" + QString().sprintf("%d:", group) + addrText + "</b></font>";
mGroupSelector->setGroupTitle(title);
mGroupSelector->setPreviousEnabled(hasPreviousGroup(curPatchList, group));
mGroupSelector->setNextEnabled(hasNextGroup(curPatchList, group));
mGroupSelector->show();
DbgCmdExecDirect(QString("disasm " + addrText));
DbgCmdExecDirect(QString("dump " + addrText));
}
void PatchDialog::on_btnPatchFile_clicked()
{
//get current module
if(!ui->listModules->selectedItems().size())
return;
QString mod = ui->listModules->selectedItems().at(0)->text();
PatchMap::iterator found = mPatches.find(mod);
if(found == mPatches.end()) //not found
return;
PatchInfoList & curPatchList = found.value();
//get patches to save
QList<DBGPATCHINFO> patchList;
for(int i = 0; i < curPatchList.size(); i++)
if(curPatchList.at(i).status.checked)
patchList.push_back(curPatchList.at(i).patch);
if(!curPatchList.size() || !patchList.size())
{
SimpleInfoBox(this, tr("Information"), tr("Nothing to patch!"));
return;
}
if(containsRelocatedBytes(curPatchList) && !showRelocatedBytesWarning())
return;
char szModName[MAX_PATH] = "";
if(!DbgFunctions()->ModPathFromAddr(DbgFunctions()->ModBaseFromName(mod.toUtf8().constData()), szModName, MAX_PATH))
{
SimpleErrorBox(this, tr("Error!"), tr("Failed to get module filename..."));
return;
}
//open the save file dialog
int len = (int)strlen(szModName);
while(szModName[len] != '\\')
len--;
char szDirName[MAX_PATH] = "";
strcpy_s(szDirName, szModName);
szDirName[len] = '\0';
QString filename = QFileDialog::getSaveFileName(this, tr("Save file"), szDirName, tr("All files (*.*)"));
if(!filename.length())
return;
filename = QDir::toNativeSeparators(filename); //convert to native path format (with backlashes)
//call patchSave function
DBGPATCHINFO* dbgPatchList = new DBGPATCHINFO[patchList.size()];
for(int i = 0; i < patchList.size(); i++)
dbgPatchList[i] = patchList.at(i);
char error[MAX_ERROR_SIZE] = "";
int patched = DbgFunctions()->PatchFile(dbgPatchList, patchList.size(), filename.toUtf8().constData(), error);
delete [] dbgPatchList;
if(patched == -1)
{
SimpleErrorBox(this, tr("Error!"), tr("Failed to save patched file (%1)").arg(error));
return;
}
SimpleInfoBox(this, tr("Information"), tr("%1/%2 patch(es) applied!").arg(patched).arg(patchList.size()));
}
void PatchDialog::on_btnImport_clicked()
{
QStringList filenamelist = QFileDialog::getOpenFileNames(this, tr("Open patch"), "", tr("Patch files (*.1337)"));
int patched = 0;
bool bBadOriginal = false;
bool bAlreadyDone = false;
typedef struct _IMPORTSTATUS
{
bool badoriginal;
bool alreadypatched;
} IMPORTSTATUS;
QList<QPair<DBGPATCHINFO, IMPORTSTATUS>> patchList;
DBGPATCHINFO curPatch;
if(!filenamelist.size())
return; // No files are selected, don't show the "No patches to apply in the current process." dialog.
for(const auto & filename1 : filenamelist)
{
if(!filename1.length())
continue;
QString filename = QDir::toNativeSeparators(filename1); //convert to native path format (with backlashes)
QFile file(filename);
file.open(QFile::ReadOnly | QFile::Text);
QTextStream in(&file);
QString patch = in.readAll();
file.close();
patch = patch.replace("\r\n", "\n");
QStringList lines = patch.split("\n", QString::SkipEmptyParts);
if(!lines.size())
{
SimpleErrorBox(this, tr("Error!"), tr("The patch file is empty..."));
continue;
}
dsint modbase = 0;
for(int i = 0; i < lines.size(); i++)
{
ULONGLONG rva;
unsigned int oldbyte;
unsigned int newbyte;
QString curLine = lines.at(i);
if(curLine.startsWith(">")) //module
{
strcpy_s(curPatch.mod, curLine.toUtf8().constData() + 1);
modbase = DbgFunctions()->ModBaseFromName(curPatch.mod);
continue;
}
if(!modbase)
continue;
curLine = curLine.replace(" ", "");
if(sscanf_s(curLine.toUtf8().constData(), "%llX:%X->%X", &rva, &oldbyte, &newbyte) != 3)
{
//File format is error. Don't continue processing this file
SimpleErrorBox(this, tr("Error!"), tr("Patch file format is incorrect..."));
break;
}
oldbyte &= 0xFF;
newbyte &= 0xFF;
curPatch.addr = rva + modbase;
if(!DbgMemIsValidReadPtr(curPatch.addr))
continue;
unsigned char checkbyte = 0;
DbgMemRead(curPatch.addr, &checkbyte, sizeof(checkbyte));
IMPORTSTATUS status;
status.alreadypatched = (checkbyte == newbyte);
status.badoriginal = (checkbyte != oldbyte);
if(status.alreadypatched)
bAlreadyDone = true;
else if(status.badoriginal)
bBadOriginal = true;
curPatch.oldbyte = oldbyte;
curPatch.newbyte = newbyte;
patchList.push_back(QPair<DBGPATCHINFO, IMPORTSTATUS>(curPatch, status));
}
}
//Check if any patch exists
if(!patchList.size())
{
SimpleInfoBox(this, tr("Information"), tr("No patches to apply in the current process."));
return;
}
//Warn if some are already patched
bool bUndoPatched = false;
if(bAlreadyDone)
{
QMessageBox msg(QMessageBox::Question, tr("Question"), tr("Some patches are already applied.\n\nDo you want to remove these patches?"), QMessageBox::Yes | QMessageBox::No);
msg.setWindowIcon(DIcon("question"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Yes)
bUndoPatched = true;
}
bool bPatchBadOriginals = false;
if(bBadOriginal)
{
QMessageBox msg(QMessageBox::Question, tr("Question"), tr("Some bytes do not match the original in the patch file.\n\nDo you want to apply these patches anyway?"), QMessageBox::Yes | QMessageBox::No);
msg.setWindowIcon(DIcon("question"));
msg.setParent(this, Qt::Dialog);
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
if(msg.exec() == QMessageBox::Yes)
bPatchBadOriginals = true;
}
//Apply all of the patches
for(int i = 0; i < patchList.size(); i++)
{
if(!bPatchBadOriginals && patchList.at(i).second.badoriginal)
continue;
curPatch = patchList.at(i).first;
if(bUndoPatched && patchList.at(i).second.alreadypatched)
{
if(DbgFunctions()->MemPatch(curPatch.addr, &curPatch.oldbyte, 1))
patched++;
}
else
{
if(DbgFunctions()->MemPatch(curPatch.addr, &curPatch.newbyte, 1))
patched++;
}
}
updatePatches();
GuiUpdateAllViews();
SimpleInfoBox(this, tr("Information"), tr("%1/%2 patch(es) applied!").arg(patched).arg(patchList.size()));
}
void PatchDialog::on_btnExport_clicked()
{
if(!mPatches.size())
return;
if(containsRelocatedBytes() && !showRelocatedBytesWarning())
return;
QString filename = QFileDialog::getSaveFileName(this, tr("Save patch"), "", tr("Patch files (*.1337)"));
if(!filename.length())
return;
filename = QDir::toNativeSeparators(filename); //convert to native path format (with backlashes)
if(filename.endsWith(QString(".1337")))
saveAs1337(filename);
// TODO: C program source
}
void PatchDialog::saveAs1337(const QString & filename)
{
QStringList lines;
int patches = 0;
for(PatchMap::iterator i = mPatches.begin(); i != mPatches.end(); ++i)
{
const PatchInfoList & curPatchList = i.value();
bool bModPlaced = false;
dsint modbase = DbgFunctions()->ModBaseFromName(i.key().toUtf8().constData());
if(!modbase)
continue;
for(int j = 0; j < curPatchList.size(); j++)
{
if(!curPatchList.at(j).status.checked) //skip unchecked patches
continue;
if(!bModPlaced)
{
lines.push_back(">" + i.key());
bModPlaced = true;
}
QString addrText = ToPtrString(curPatchList.at(j).patch.addr - modbase);
lines.push_back(addrText + QString().sprintf(":%.2X->%.2X", curPatchList.at(j).patch.oldbyte, curPatchList.at(j).patch.newbyte));
patches++;
}
}
if(!lines.size())
{
SimpleInfoBox(this, tr("Information"), tr("No patches to export."));
return;
}
QFile file(filename);
file.open(QFile::WriteOnly | QFile::Text);
QString text = lines.join("\n");
QByteArray textUtf8 = text.toUtf8();
file.write(textUtf8.constData(), textUtf8.length());
file.close();
SimpleInfoBox(this, tr("Information"), tr("%1 patch(es) exported!").arg(patches));
}
bool PatchDialog::containsRelocatedBytes()
{
for(PatchMap::iterator i = mPatches.begin(); i != mPatches.end(); ++i)
{
const PatchInfoList & curPatchList = i.value();
if(containsRelocatedBytes(curPatchList))
return true;
}
return false;
}
bool PatchDialog::containsRelocatedBytes(const PatchInfoList & patchList)
{
for(int i = 0; i < patchList.size(); i++)
{
if(patchList.at(i).status.checked && DbgFunctions()->ModRelocationAtAddr(patchList.at(i).patch.addr, nullptr))
return true;
}
return false;
}
bool PatchDialog::showRelocatedBytesWarning()
{
auto result = QMessageBox::question(this, tr("Patches overlap with relocation regions"), tr("Your patches overlap with relocation regions. This can cause your code to become corrupted when you load the patched executable. Do you want to continue?"));
return result == QMessageBox::Yes;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/PatchDialog.h | #pragma once
#include <QDialog>
#include <QListWidgetItem>
#include "PatchDialogGroupSelector.h"
#include "Bridge.h"
namespace Ui
{
class PatchDialog;
}
class PatchDialog : public QDialog
{
Q_OBJECT
struct STATUSINFO
{
bool checked;
int group;
};
struct PatchPair
{
DBGPATCHINFO patch;
STATUSINFO status;
PatchPair(const DBGPATCHINFO & patch, const STATUSINFO & status)
{
this->patch = patch;
this->status = status;
}
};
//typedef QPair<DBGPATCHINFO, STATUSINFO> PatchPair;
typedef QList<PatchPair> PatchInfoList;
typedef QMap<QString, PatchInfoList> PatchMap;
static bool PatchInfoLess(const PatchPair & a, const PatchPair & b)
{
return a.patch.addr < b.patch.addr;
}
public:
explicit PatchDialog(QWidget* parent = 0);
~PatchDialog();
private:
Ui::PatchDialog* ui;
PatchMap mPatches;
PatchDialogGroupSelector* mGroupSelector;
bool mIsWorking;
bool isPartOfPreviousGroup(const PatchInfoList & patchList, int index);
bool isGroupEnabled(const PatchInfoList & patchList, int group);
bool hasPreviousGroup(const PatchInfoList & patchList, int group);
bool hasNextGroup(const PatchInfoList & patchList, int group);
dsint getGroupAddress(const PatchInfoList & patchList, int group);
void saveAs1337(const QString & filename);
//void saveAsC(const QString & filename);
bool containsRelocatedBytes();
bool containsRelocatedBytes(const PatchInfoList & patchList);
bool showRelocatedBytesWarning();
private slots:
void dbgStateChanged(DBGSTATE state);
void updatePatches();
void groupToggle();
void groupPrevious();
void groupNext();
void on_listModules_itemSelectionChanged();
void on_listPatches_itemChanged(QListWidgetItem* item);
void on_btnSelectAll_clicked();
void on_btnDeselectAll_clicked();
void on_btnRestoreSelected_clicked();
void on_listPatches_itemSelectionChanged();
void on_btnPickGroups_clicked();
void on_btnPatchFile_clicked();
void on_btnImport_clicked();
void on_btnExport_clicked();
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/PatchDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PatchDialog</class>
<widget class="QDialog" name="PatchDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>511</width>
<height>451</height>
</rect>
</property>
<property name="windowTitle">
<string>Patches</string>
</property>
<property name="windowIcon">
<iconset theme="patch" resource="../../resource.qrc">
<normaloff>:/Default/icons/patch.png</normaloff>:/Default/icons/patch.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="handleWidth">
<number>1</number>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="layoutWidget">
<layout class="QVBoxLayout" name="layoutModules">
<item>
<widget class="QGroupBox" name="groupModules">
<property name="title">
<string>&Modules</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QListWidget" name="listModules">
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QPushButton" name="btnImport">
<property name="text">
<string>&Import</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnExport">
<property name="text">
<string>&Export</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="layoutWidget_1">
<layout class="QVBoxLayout" name="layoutPatches">
<item>
<widget class="QGroupBox" name="groupPatches">
<property name="title">
<string>P&atches</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QListWidget" name="listPatches">
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="btnSelectAll">
<property name="text">
<string>&Select All</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnDeselectAll">
<property name="text">
<string>&Deselect All</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRestoreSelected">
<property name="text">
<string>&Restore Selected</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="btnPickGroups">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Pick &Groups</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnPatchFile">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>&Patch File</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>listModules</tabstop>
<tabstop>btnImport</tabstop>
<tabstop>btnExport</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/PatchDialogGroupSelector.cpp | #include "PatchDialogGroupSelector.h"
#include "ui_PatchDialogGroupSelector.h"
PatchDialogGroupSelector::PatchDialogGroupSelector(QWidget* parent) :
QDialog(parent),
ui(new Ui::PatchDialogGroupSelector)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setModal(false); //non-modal window
mGroup = 0;
}
PatchDialogGroupSelector::~PatchDialogGroupSelector()
{
delete ui;
}
void PatchDialogGroupSelector::keyPressEvent(QKeyEvent* event)
{
if(event->modifiers() != Qt::NoModifier)
return;
if(event->key() == Qt::Key_Space)
on_btnToggle_clicked();
else if(event->key() == Qt::Key_BracketLeft)
on_btnPrevious_clicked();
else if(event->key() == Qt::Key_BracketRight)
on_btnNext_clicked();
}
void PatchDialogGroupSelector::setGroupTitle(const QString & title)
{
ui->lblTitle->setText(title);
}
void PatchDialogGroupSelector::setPreviousEnabled(bool enable)
{
ui->btnPrevious->setEnabled(enable);
}
void PatchDialogGroupSelector::setNextEnabled(bool enable)
{
ui->btnNext->setEnabled(enable);
}
void PatchDialogGroupSelector::setGroup(int group)
{
mGroup = group;
}
int PatchDialogGroupSelector::group()
{
return mGroup;
}
void PatchDialogGroupSelector::on_btnToggle_clicked()
{
emit groupToggle();
}
void PatchDialogGroupSelector::on_btnPrevious_clicked()
{
if(ui->btnPrevious->isEnabled())
emit groupPrevious();
}
void PatchDialogGroupSelector::on_btnNext_clicked()
{
if(ui->btnNext->isEnabled())
emit groupNext();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/PatchDialogGroupSelector.h | #pragma once
#include <QDialog>
#include <QKeyEvent>
namespace Ui
{
class PatchDialogGroupSelector;
}
class PatchDialogGroupSelector : public QDialog
{
Q_OBJECT
public:
explicit PatchDialogGroupSelector(QWidget* parent = 0);
~PatchDialogGroupSelector();
void setGroupTitle(const QString & title);
void setPreviousEnabled(bool enable);
void setNextEnabled(bool enable);
void setGroup(int group);
int group();
signals:
void groupToggle();
void groupPrevious();
void groupNext();
private slots:
void on_btnToggle_clicked();
void on_btnPrevious_clicked();
void on_btnNext_clicked();
protected:
void keyPressEvent(QKeyEvent* event);
private:
Ui::PatchDialogGroupSelector* ui;
int mGroup;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/PatchDialogGroupSelector.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PatchDialogGroupSelector</class>
<widget class="QDialog" name="PatchDialogGroupSelector">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>261</width>
<height>71</height>
</rect>
</property>
<property name="windowTitle">
<string>Group Selector</string>
</property>
<property name="windowIcon">
<iconset theme="patch" resource="../../resource.qrc">
<normaloff>:/Default/icons/patch.png</normaloff>:/Default/icons/patch.png</iconset>
</property>
<widget class="QWidget" name="layoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>241</width>
<height>51</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="lblTitle">
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="text">
<string>0000000000000000</string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="btnToggle">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>&Toggle</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnPrevious">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>&Previous</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnNext">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>&Next</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/ReferenceManager.cpp | #include "ReferenceManager.h"
#include "Bridge.h"
ReferenceManager::ReferenceManager(QWidget* parent) : QTabWidget(parent)
{
setMovable(true);
setTabsClosable(true);
mCurrentReferenceView = 0;
//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);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(Bridge::getBridge(), SIGNAL(referenceInitialize(QString)), this, SLOT(newReferenceView(QString)));
connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
}
ReferenceView* ReferenceManager::currentReferenceView()
{
//get the current index, disconnects the previous view if it's not the current one, set and connect the new current view, then return it
int currentIndex = QTabWidget::currentIndex();
if(mCurrentReferenceView && mCurrentReferenceView != widget(currentIndex))
{
mCurrentReferenceView->disconnectBridge();
mCurrentReferenceView = qobject_cast<ReferenceView*>(widget(currentIndex));
if(mCurrentReferenceView)
mCurrentReferenceView->connectBridge();
}
return mCurrentReferenceView;
}
void ReferenceManager::newReferenceView(QString name)
{
if(mCurrentReferenceView) //disconnect previous reference view
mCurrentReferenceView->disconnectBridge();
mCurrentReferenceView = new ReferenceView(false, this);
mCurrentReferenceView->connectBridge();
connect(mCurrentReferenceView, SIGNAL(showCpu()), this, SIGNAL(showCpu()));
insertTab(0, mCurrentReferenceView, name);
setCurrentIndex(0);
Bridge::getBridge()->setResult(BridgeResult::RefInitialize, 1);
}
void ReferenceManager::closeTab(int index)
{
removeTab(index);
if(count() <= 0)
emit showCpu();
}
void ReferenceManager::closeAllTabs()
{
clear();
emit showCpu();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ReferenceManager.h | #pragma once
#include <QTabWidget>
#include <QPushButton>
#include "ReferenceView.h"
class ReferenceManager : public QTabWidget
{
Q_OBJECT
public:
explicit ReferenceManager(QWidget* parent = 0);
ReferenceView* currentReferenceView();
private slots:
void newReferenceView(QString name);
void closeTab(int index);
void closeAllTabs();
signals:
void showCpu();
private:
ReferenceView* mCurrentReferenceView;
QPushButton* mCloseAllTabs;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/RegistersView.cpp | #include <QMessageBox>
#include <QListWidget>
#include <QToolTip>
#include <stdint.h>
#include "RegistersView.h"
#include "CPUDisassembly.h"
#include "CPUMultiDump.h"
#include "Configuration.h"
#include "WordEditDialog.h"
#include "LineEditDialog.h"
#include "EditFloatRegister.h"
#include "SelectFields.h"
#include "MiscUtil.h"
#include "ldconvert.h"
int RegistersView::getEstimateHeight()
{
return mRowsNeeded * mRowHeight;
}
void RegistersView::SetChangeButton(QPushButton* push_button)
{
mChangeViewButton = push_button;
fontsUpdatedSlot();
}
void RegistersView::InitMappings()
{
// create mapping from internal id to name
mRegisterMapping.clear();
mRegisterPlaces.clear();
mRegisterRelativePlaces.clear();
int offset = 0;
/* Register_Position is a struct definition the position
*
* (line , start, labelwidth, valuesize )
*/
#ifdef _WIN64
mRegisterMapping.insert(CAX, "RAX");
mRegisterPlaces.insert(CAX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CAX, Register_Relative_Position(UNKNOWN, CBX));
mRegisterMapping.insert(CBX, "RBX");
mRegisterPlaces.insert(CBX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CBX, Register_Relative_Position(CAX, CCX));
mRegisterMapping.insert(CCX, "RCX");
mRegisterPlaces.insert(CCX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CCX, Register_Relative_Position(CBX, CDX));
mRegisterMapping.insert(CDX, "RDX");
mRegisterPlaces.insert(CDX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CDX, Register_Relative_Position(CCX, CBP));
mRegisterMapping.insert(CBP, "RBP");
mRegisterPlaces.insert(CBP, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CBP, Register_Relative_Position(CDX, CSP));
mRegisterMapping.insert(CSP, "RSP");
mRegisterPlaces.insert(CSP, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CSP, Register_Relative_Position(CBP, CSI));
mRegisterMapping.insert(CSI, "RSI");
mRegisterPlaces.insert(CSI, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CSI, Register_Relative_Position(CSP, CDI));
mRegisterMapping.insert(CDI, "RDI");
mRegisterPlaces.insert(CDI, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CDI, Register_Relative_Position(CSI, R8));
offset++;
mRegisterMapping.insert(R8, "R8");
mRegisterPlaces.insert(R8, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R8, Register_Relative_Position(CDI, R9));
mRegisterMapping.insert(R9, "R9");
mRegisterPlaces.insert(R9, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R9, Register_Relative_Position(R8, R10));
mRegisterMapping.insert(R10, "R10");
mRegisterPlaces.insert(R10, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R10, Register_Relative_Position(R9, R11));
mRegisterMapping.insert(R11, "R11");
mRegisterPlaces.insert(R11, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R11, Register_Relative_Position(R10, R12));
mRegisterMapping.insert(R12, "R12");
mRegisterPlaces.insert(R12, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R12, Register_Relative_Position(R11, R13));
mRegisterMapping.insert(R13, "R13");
mRegisterPlaces.insert(R13, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R13, Register_Relative_Position(R12, R14));
mRegisterMapping.insert(R14, "R14");
mRegisterPlaces.insert(R14, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R14, Register_Relative_Position(R13, R15));
mRegisterMapping.insert(R15, "R15");
mRegisterPlaces.insert(R15, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(R15, Register_Relative_Position(R14, CIP));
offset++;
mRegisterMapping.insert(CIP, "RIP");
mRegisterPlaces.insert(CIP, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CIP, Register_Relative_Position(R15, EFLAGS));
offset++;
mRegisterMapping.insert(EFLAGS, "RFLAGS");
mRegisterPlaces.insert(EFLAGS, Register_Position(offset++, 0, 9, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(EFLAGS, Register_Relative_Position(CIP, ZF));
#else //x32
mRegisterMapping.insert(CAX, "EAX");
mRegisterPlaces.insert(CAX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CAX, Register_Relative_Position(UNKNOWN, CBX));
mRegisterMapping.insert(CBX, "EBX");
mRegisterPlaces.insert(CBX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CBX, Register_Relative_Position(CAX, CCX));
mRegisterMapping.insert(CCX, "ECX");
mRegisterPlaces.insert(CCX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CCX, Register_Relative_Position(CBX, CDX));
mRegisterMapping.insert(CDX, "EDX");
mRegisterPlaces.insert(CDX, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CDX, Register_Relative_Position(CCX, CBP));
mRegisterMapping.insert(CBP, "EBP");
mRegisterPlaces.insert(CBP, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CBP, Register_Relative_Position(CDX, CSP));
mRegisterMapping.insert(CSP, "ESP");
mRegisterPlaces.insert(CSP, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CSP, Register_Relative_Position(CBP, CSI));
mRegisterMapping.insert(CSI, "ESI");
mRegisterPlaces.insert(CSI, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CSI, Register_Relative_Position(CSP, CDI));
mRegisterMapping.insert(CDI, "EDI");
mRegisterPlaces.insert(CDI, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CDI, Register_Relative_Position(CSI, CIP));
offset++;
mRegisterMapping.insert(CIP, "EIP");
mRegisterPlaces.insert(CIP, Register_Position(offset++, 0, 6, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(CIP, Register_Relative_Position(CDI, EFLAGS));
offset++;
mRegisterMapping.insert(EFLAGS, "EFLAGS");
mRegisterPlaces.insert(EFLAGS, Register_Position(offset++, 0, 9, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(EFLAGS, Register_Relative_Position(CIP, ZF));
#endif
mRegisterMapping.insert(ZF, "ZF");
mRegisterPlaces.insert(ZF, Register_Position(offset, 0, 3, 1));
mRegisterRelativePlaces.insert(ZF, Register_Relative_Position(EFLAGS, PF, EFLAGS, OF));
mRegisterMapping.insert(PF, "PF");
mRegisterPlaces.insert(PF, Register_Position(offset, 6, 3, 1));
mRegisterRelativePlaces.insert(PF, Register_Relative_Position(ZF, AF, EFLAGS, SF));
mRegisterMapping.insert(AF, "AF");
mRegisterPlaces.insert(AF, Register_Position(offset++, 12, 3, 1));
mRegisterRelativePlaces.insert(AF, Register_Relative_Position(PF, OF, EFLAGS, DF));
mRegisterMapping.insert(OF, "OF");
mRegisterPlaces.insert(OF, Register_Position(offset, 0, 3, 1));
mRegisterRelativePlaces.insert(OF, Register_Relative_Position(AF, SF, ZF, CF));
mRegisterMapping.insert(SF, "SF");
mRegisterPlaces.insert(SF, Register_Position(offset, 6, 3, 1));
mRegisterRelativePlaces.insert(SF, Register_Relative_Position(OF, DF, PF, TF));
mRegisterMapping.insert(DF, "DF");
mRegisterPlaces.insert(DF, Register_Position(offset++, 12, 3, 1));
mRegisterRelativePlaces.insert(DF, Register_Relative_Position(SF, CF, AF, IF));
mRegisterMapping.insert(CF, "CF");
mRegisterPlaces.insert(CF, Register_Position(offset, 0, 3, 1));
mRegisterRelativePlaces.insert(CF, Register_Relative_Position(DF, TF, OF, LastError));
mRegisterMapping.insert(TF, "TF");
mRegisterPlaces.insert(TF, Register_Position(offset, 6, 3, 1));
mRegisterRelativePlaces.insert(TF, Register_Relative_Position(CF, IF, SF, LastError));
mRegisterMapping.insert(IF, "IF");
mRegisterPlaces.insert(IF, Register_Position(offset++, 12, 3, 1));
mRegisterRelativePlaces.insert(IF, Register_Relative_Position(TF, LastError, DF, LastError));
offset++;
mRegisterMapping.insert(LastError, "LastError");
mRegisterPlaces.insert(LastError, Register_Position(offset++, 0, 11, 20));
mRegisterRelativePlaces.insert(LastError, Register_Relative_Position(IF, LastStatus));
mMODIFYDISPLAY.insert(LastError);
mRegisterMapping.insert(LastStatus, "LastStatus");
mRegisterPlaces.insert(LastStatus, Register_Position(offset++, 0, 11, 20));
mRegisterRelativePlaces.insert(LastStatus, Register_Relative_Position(LastError, GS));
mMODIFYDISPLAY.insert(LastStatus);
offset++;
mRegisterMapping.insert(GS, "GS");
mRegisterPlaces.insert(GS, Register_Position(offset, 0, 3, 4));
mRegisterRelativePlaces.insert(GS, Register_Relative_Position(LastStatus, FS, LastStatus, ES));
mRegisterMapping.insert(FS, "FS");
mRegisterPlaces.insert(FS, Register_Position(offset++, 9, 3, 4));
mRegisterRelativePlaces.insert(FS, Register_Relative_Position(GS, ES, LastStatus, DS));
mRegisterMapping.insert(ES, "ES");
mRegisterPlaces.insert(ES, Register_Position(offset, 0, 3, 4));
mRegisterRelativePlaces.insert(ES, Register_Relative_Position(FS, DS, GS, CS));
mRegisterMapping.insert(DS, "DS");
mRegisterPlaces.insert(DS, Register_Position(offset++, 9, 3, 4));
mRegisterRelativePlaces.insert(DS, Register_Relative_Position(ES, CS, FS, SS));
mRegisterMapping.insert(CS, "CS");
mRegisterPlaces.insert(CS, Register_Position(offset, 0, 3, 4));
mRegisterMapping.insert(SS, "SS");
mRegisterPlaces.insert(SS, Register_Position(offset++, 9, 3, 4));
if(mShowFpu)
{
REGISTER_NAME tempRegisterName = UNKNOWN;
offset++;
if(mFpuMode == 1)
{
tempRegisterName = x87r0;
mRegisterMapping.insert(x87r0, "x87r0");
mRegisterPlaces.insert(x87r0, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r0, Register_Relative_Position(SS, x87r1));
mRegisterMapping.insert(x87r1, "x87r1");
mRegisterPlaces.insert(x87r1, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r1, Register_Relative_Position(x87r0, x87r2));
mRegisterMapping.insert(x87r2, "x87r2");
mRegisterPlaces.insert(x87r2, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r2, Register_Relative_Position(x87r1, x87r3));
mRegisterMapping.insert(x87r3, "x87r3");
mRegisterPlaces.insert(x87r3, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r3, Register_Relative_Position(x87r2, x87r4));
mRegisterMapping.insert(x87r4, "x87r4");
mRegisterPlaces.insert(x87r4, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r4, Register_Relative_Position(x87r3, x87r5));
mRegisterMapping.insert(x87r5, "x87r5");
mRegisterPlaces.insert(x87r5, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r5, Register_Relative_Position(x87r4, x87r6));
mRegisterMapping.insert(x87r6, "x87r6");
mRegisterPlaces.insert(x87r6, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r6, Register_Relative_Position(x87r5, x87r7));
mRegisterMapping.insert(x87r7, "x87r7");
mRegisterPlaces.insert(x87r7, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87r7, Register_Relative_Position(x87r6, x87TagWord));
}
else if(mFpuMode == 0)
{
tempRegisterName = x87st0;
mRegisterMapping.insert(x87st0, "ST(0)");
mRegisterPlaces.insert(x87st0, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st0, Register_Relative_Position(SS, x87st1));
mRegisterMapping.insert(x87st1, "ST(1)");
mRegisterPlaces.insert(x87st1, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st1, Register_Relative_Position(x87st0, x87st2));
mRegisterMapping.insert(x87st2, "ST(2)");
mRegisterPlaces.insert(x87st2, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st2, Register_Relative_Position(x87st1, x87st3));
mRegisterMapping.insert(x87st3, "ST(3)");
mRegisterPlaces.insert(x87st3, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st3, Register_Relative_Position(x87st2, x87st4));
mRegisterMapping.insert(x87st4, "ST(4)");
mRegisterPlaces.insert(x87st4, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st4, Register_Relative_Position(x87st3, x87st5));
mRegisterMapping.insert(x87st5, "ST(5)");
mRegisterPlaces.insert(x87st5, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st5, Register_Relative_Position(x87st4, x87st6));
mRegisterMapping.insert(x87st6, "ST(6)");
mRegisterPlaces.insert(x87st6, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st6, Register_Relative_Position(x87st5, x87st7));
mRegisterMapping.insert(x87st7, "ST(7)");
mRegisterPlaces.insert(x87st7, Register_Position(offset++, 0, 6, 10 * 2));
mRegisterRelativePlaces.insert(x87st7, Register_Relative_Position(x87st6, x87TagWord));
}
else if(mFpuMode == 2)
{
tempRegisterName = MM0;
mRegisterMapping.insert(MM0, "MM0");
mRegisterPlaces.insert(MM0, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM0, Register_Relative_Position(SS, MM1));
mRegisterMapping.insert(MM1, "MM1");
mRegisterPlaces.insert(MM1, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM1, Register_Relative_Position(MM0, MM2));
mRegisterMapping.insert(MM2, "MM2");
mRegisterPlaces.insert(MM2, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM2, Register_Relative_Position(MM1, MM3));
mRegisterMapping.insert(MM3, "MM3");
mRegisterPlaces.insert(MM3, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM3, Register_Relative_Position(MM2, MM4));
mRegisterMapping.insert(MM4, "MM4");
mRegisterPlaces.insert(MM4, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM4, Register_Relative_Position(MM3, MM5));
mRegisterMapping.insert(MM5, "MM5");
mRegisterPlaces.insert(MM5, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM5, Register_Relative_Position(MM4, MM6));
mRegisterMapping.insert(MM6, "MM6");
mRegisterPlaces.insert(MM6, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM6, Register_Relative_Position(MM5, MM7));
mRegisterMapping.insert(MM7, "MM7");
mRegisterPlaces.insert(MM7, Register_Position(offset++, 0, 4, 8 * 2));
mRegisterRelativePlaces.insert(MM7, Register_Relative_Position(MM6, x87TagWord));
}
mRegisterRelativePlaces.insert(CS, Register_Relative_Position(DS, SS, ES, tempRegisterName));
mRegisterRelativePlaces.insert(SS, Register_Relative_Position(CS, tempRegisterName, DS, tempRegisterName));
offset++;
mRegisterMapping.insert(x87TagWord, "x87TagWord");
mRegisterPlaces.insert(x87TagWord, Register_Position(offset++, 0, 11, sizeof(WORD) * 2));
switch(mFpuMode)
{
case 0:
tempRegisterName = x87st7;
break;
case 1:
tempRegisterName = x87r7;
break;
case 2:
tempRegisterName = MM7;
break;
}
mRegisterRelativePlaces.insert(x87TagWord, Register_Relative_Position(tempRegisterName, x87TW_0));
//Special treatment of long internationalized string
int NextColumnPosition = 20;
int temp;
QFontMetrics metrics(font());
//13 = 20 - strlen("Nonzero")
temp = metrics.width(QApplication::translate("RegistersView_ConstantsOfRegisters", "Nonzero")) / mCharWidth + 13;
NextColumnPosition = std::max(NextColumnPosition, temp);
temp = metrics.width(QApplication::translate("RegistersView_ConstantsOfRegisters", "Zero")) / mCharWidth + 13;
NextColumnPosition = std::max(NextColumnPosition, temp);
temp = metrics.width(QApplication::translate("RegistersView_ConstantsOfRegisters", "Special")) / mCharWidth + 13;
NextColumnPosition = std::max(NextColumnPosition, temp);
temp = metrics.width(QApplication::translate("RegistersView_ConstantsOfRegisters", "Empty")) / mCharWidth + 13;
NextColumnPosition = std::max(NextColumnPosition, temp);
mRegisterMapping.insert(x87TW_0, "x87TW_0");
mRegisterPlaces.insert(x87TW_0, Register_Position(offset, 0, 8, 10));
mRegisterRelativePlaces.insert(x87TW_0, Register_Relative_Position(x87TagWord, x87TW_1, x87TagWord, x87TW_2));
mRegisterMapping.insert(x87TW_1, "x87TW_1");
mRegisterPlaces.insert(x87TW_1, Register_Position(offset++, NextColumnPosition, 8, 10));
mRegisterRelativePlaces.insert(x87TW_1, Register_Relative_Position(x87TW_0, x87TW_2, x87TagWord, x87TW_3));
mRegisterMapping.insert(x87TW_2, "x87TW_2");
mRegisterPlaces.insert(x87TW_2, Register_Position(offset, 0, 8, 10));
mRegisterRelativePlaces.insert(x87TW_2, Register_Relative_Position(x87TW_1, x87TW_3, x87TW_0, x87TW_4));
mRegisterMapping.insert(x87TW_3, "x87TW_3");
mRegisterPlaces.insert(x87TW_3, Register_Position(offset++, NextColumnPosition, 8, 10));
mRegisterRelativePlaces.insert(x87TW_3, Register_Relative_Position(x87TW_2, x87TW_4, x87TW_1, x87TW_5));
mRegisterMapping.insert(x87TW_4, "x87TW_4");
mRegisterPlaces.insert(x87TW_4, Register_Position(offset, 0, 8, 10));
mRegisterRelativePlaces.insert(x87TW_4, Register_Relative_Position(x87TW_3, x87TW_5, x87TW_2, x87TW_6));
mRegisterMapping.insert(x87TW_5, "x87TW_5");
mRegisterPlaces.insert(x87TW_5, Register_Position(offset++, NextColumnPosition, 8, 10));
mRegisterRelativePlaces.insert(x87TW_5, Register_Relative_Position(x87TW_4, x87TW_6, x87TW_3, x87TW_7));
mRegisterMapping.insert(x87TW_6, "x87TW_6");
mRegisterPlaces.insert(x87TW_6, Register_Position(offset, 0, 8, 10));
mRegisterRelativePlaces.insert(x87TW_6, Register_Relative_Position(x87TW_5, x87TW_7, x87TW_4, x87StatusWord));
mRegisterMapping.insert(x87TW_7, "x87TW_7");
mRegisterPlaces.insert(x87TW_7, Register_Position(offset++, NextColumnPosition, 8, 10));
mRegisterRelativePlaces.insert(x87TW_7, Register_Relative_Position(x87TW_6, x87StatusWord, x87TW_5, x87StatusWord));
offset++;
mRegisterMapping.insert(x87StatusWord, "x87StatusWord");
mRegisterPlaces.insert(x87StatusWord, Register_Position(offset++, 0, 14, sizeof(WORD) * 2));
mRegisterRelativePlaces.insert(x87StatusWord, Register_Relative_Position(x87TW_7, x87SW_B));
mRegisterMapping.insert(x87SW_B, "x87SW_B");
mRegisterPlaces.insert(x87SW_B, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87SW_B, Register_Relative_Position(x87StatusWord, x87SW_C3, x87StatusWord, x87SW_C1));
mRegisterMapping.insert(x87SW_C3, "x87SW_C3");
mRegisterPlaces.insert(x87SW_C3, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87SW_C3, Register_Relative_Position(x87SW_B, x87SW_C2, x87StatusWord, x87SW_C0));
mRegisterMapping.insert(x87SW_C2, "x87SW_C2");
mRegisterPlaces.insert(x87SW_C2, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(x87SW_C2, Register_Relative_Position(x87SW_C3, x87SW_C1, x87StatusWord, x87SW_ES));
mRegisterMapping.insert(x87SW_C1, "x87SW_C1");
mRegisterPlaces.insert(x87SW_C1, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87SW_C1, Register_Relative_Position(x87SW_C2, x87SW_C0, x87SW_B, x87SW_SF));
mRegisterMapping.insert(x87SW_C0, "x87SW_C0");
mRegisterPlaces.insert(x87SW_C0, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87SW_C0, Register_Relative_Position(x87SW_C1, x87SW_ES, x87SW_C3, x87SW_P));
mRegisterMapping.insert(x87SW_ES, "x87SW_ES");
mRegisterPlaces.insert(x87SW_ES, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(x87SW_ES, Register_Relative_Position(x87SW_C0, x87SW_SF, x87SW_C2, x87SW_U));
mRegisterMapping.insert(x87SW_SF, "x87SW_SF");
mRegisterPlaces.insert(x87SW_SF, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87SW_SF, Register_Relative_Position(x87SW_ES, x87SW_P, x87SW_C1, x87SW_O));
mRegisterMapping.insert(x87SW_P, "x87SW_P");
mRegisterPlaces.insert(x87SW_P, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87SW_P, Register_Relative_Position(x87SW_SF, x87SW_U, x87SW_C0, x87SW_Z));
mRegisterMapping.insert(x87SW_U, "x87SW_U");
mRegisterPlaces.insert(x87SW_U, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(x87SW_U, Register_Relative_Position(x87SW_P, x87SW_O, x87SW_ES, x87SW_D));
mRegisterMapping.insert(x87SW_O, "x87SW_O");
mRegisterPlaces.insert(x87SW_O, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87SW_O, Register_Relative_Position(x87SW_U, x87SW_Z, x87SW_SF, x87SW_I));
mRegisterMapping.insert(x87SW_Z, "x87SW_Z");
mRegisterPlaces.insert(x87SW_Z, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87SW_Z, Register_Relative_Position(x87SW_O, x87SW_D, x87SW_P, x87SW_TOP));
mRegisterMapping.insert(x87SW_D, "x87SW_D");
mRegisterPlaces.insert(x87SW_D, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(x87SW_D, Register_Relative_Position(x87SW_Z, x87SW_I, x87SW_U, x87SW_TOP));
mRegisterMapping.insert(x87SW_I, "x87SW_I");
mRegisterPlaces.insert(x87SW_I, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87SW_I, Register_Relative_Position(x87SW_D, x87SW_TOP, x87SW_O, x87ControlWord));
mRegisterMapping.insert(x87SW_TOP, "x87SW_TOP");
mRegisterPlaces.insert(x87SW_TOP, Register_Position(offset++, 12, 10, 13));
mRegisterRelativePlaces.insert(x87SW_TOP, Register_Relative_Position(x87SW_I, x87ControlWord, x87SW_Z, x87ControlWord));
offset++;
mRegisterMapping.insert(x87ControlWord, "x87ControlWord");
mRegisterPlaces.insert(x87ControlWord, Register_Position(offset++, 0, 15, sizeof(WORD) * 2));
mRegisterRelativePlaces.insert(x87ControlWord, Register_Relative_Position(x87SW_TOP, x87CW_IC));
mRegisterMapping.insert(x87CW_IC, "x87CW_IC");
mRegisterPlaces.insert(x87CW_IC, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87CW_IC, Register_Relative_Position(x87ControlWord, x87CW_ZM, x87ControlWord, x87CW_UM));
mRegisterMapping.insert(x87CW_ZM, "x87CW_ZM");
mRegisterPlaces.insert(x87CW_ZM, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87CW_ZM, Register_Relative_Position(x87CW_IC, x87CW_PM, x87ControlWord, x87CW_OM));
mRegisterMapping.insert(x87CW_PM, "x87CW_PM");
mRegisterPlaces.insert(x87CW_PM, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(x87CW_PM, Register_Relative_Position(x87CW_ZM, x87CW_UM, x87ControlWord, x87CW_PC));
mRegisterMapping.insert(x87CW_UM, "x87CW_UM");
mRegisterPlaces.insert(x87CW_UM, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87CW_UM, Register_Relative_Position(x87CW_PM, x87CW_OM, x87CW_IC, x87CW_DM));
mRegisterMapping.insert(x87CW_OM, "x87CW_OM");
mRegisterPlaces.insert(x87CW_OM, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87CW_OM, Register_Relative_Position(x87CW_UM, x87CW_PC, x87CW_ZM, x87CW_IM));
mRegisterMapping.insert(x87CW_PC, "x87CW_PC");
mRegisterPlaces.insert(x87CW_PC, Register_Position(offset++, 25, 10, 14));
mRegisterRelativePlaces.insert(x87CW_PC, Register_Relative_Position(x87CW_OM, x87CW_DM, x87CW_PM, x87CW_RC));
mRegisterMapping.insert(x87CW_DM, "x87CW_DM");
mRegisterPlaces.insert(x87CW_DM, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(x87CW_DM, Register_Relative_Position(x87CW_PC, x87CW_IM, x87CW_UM, MxCsr));
mRegisterMapping.insert(x87CW_IM, "x87CW_IM");
mRegisterPlaces.insert(x87CW_IM, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(x87CW_IM, Register_Relative_Position(x87CW_DM, x87CW_RC, x87CW_OM, MxCsr));
mRegisterMapping.insert(x87CW_RC, "x87CW_RC");
mRegisterPlaces.insert(x87CW_RC, Register_Position(offset++, 25, 10, 14));
mRegisterRelativePlaces.insert(x87CW_RC, Register_Relative_Position(x87CW_IM, MxCsr, x87CW_PC, MxCsr));
offset++;
mRegisterMapping.insert(MxCsr, "MxCsr");
mRegisterPlaces.insert(MxCsr, Register_Position(offset++, 0, 6, sizeof(DWORD) * 2));
mRegisterRelativePlaces.insert(MxCsr, Register_Relative_Position(x87CW_RC, MxCsr_FZ));
mRegisterMapping.insert(MxCsr_FZ, "MxCsr_FZ");
mRegisterPlaces.insert(MxCsr_FZ, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(MxCsr_FZ, Register_Relative_Position(MxCsr, MxCsr_PM, MxCsr, MxCsr_OM));
mRegisterMapping.insert(MxCsr_PM, "MxCsr_PM");
mRegisterPlaces.insert(MxCsr_PM, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_PM, Register_Relative_Position(MxCsr_FZ, MxCsr_UM, MxCsr, MxCsr_ZM));
mRegisterMapping.insert(MxCsr_UM, "MxCsr_UM");
mRegisterPlaces.insert(MxCsr_UM, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_UM, Register_Relative_Position(MxCsr_PM, MxCsr_OM, MxCsr, MxCsr_IM));
mRegisterMapping.insert(MxCsr_OM, "MxCsr_OM");
mRegisterPlaces.insert(MxCsr_OM, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(MxCsr_OM, Register_Relative_Position(MxCsr_UM, MxCsr_ZM, MxCsr_FZ, MxCsr_UE));
mRegisterMapping.insert(MxCsr_ZM, "MxCsr_ZM");
mRegisterPlaces.insert(MxCsr_ZM, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_ZM, Register_Relative_Position(MxCsr_OM, MxCsr_IM, MxCsr_PM, MxCsr_PE));
mRegisterMapping.insert(MxCsr_IM, "MxCsr_IM");
mRegisterPlaces.insert(MxCsr_IM, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_IM, Register_Relative_Position(MxCsr_ZM, MxCsr_UE, MxCsr_UM, MxCsr_DAZ));
mRegisterMapping.insert(MxCsr_UE, "MxCsr_UE");
mRegisterPlaces.insert(MxCsr_UE, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(MxCsr_UE, Register_Relative_Position(MxCsr_IM, MxCsr_PE, MxCsr_OM, MxCsr_OE));
mRegisterMapping.insert(MxCsr_PE, "MxCsr_PE");
mRegisterPlaces.insert(MxCsr_PE, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_PE, Register_Relative_Position(MxCsr_UE, MxCsr_DAZ, MxCsr_ZM, MxCsr_ZE));
mRegisterMapping.insert(MxCsr_DAZ, "MxCsr_DAZ");
mRegisterPlaces.insert(MxCsr_DAZ, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_DAZ, Register_Relative_Position(MxCsr_PE, MxCsr_OE, MxCsr_IM, MxCsr_DE));
mRegisterMapping.insert(MxCsr_OE, "MxCsr_OE");
mRegisterPlaces.insert(MxCsr_OE, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(MxCsr_OE, Register_Relative_Position(MxCsr_DAZ, MxCsr_ZE, MxCsr_UE, MxCsr_IE));
mRegisterMapping.insert(MxCsr_ZE, "MxCsr_ZE");
mRegisterPlaces.insert(MxCsr_ZE, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_ZE, Register_Relative_Position(MxCsr_OE, MxCsr_DE, MxCsr_PE, MxCsr_DM));
mRegisterMapping.insert(MxCsr_DE, "MxCsr_DE");
mRegisterPlaces.insert(MxCsr_DE, Register_Position(offset++, 25, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_DE, Register_Relative_Position(MxCsr_ZE, MxCsr_IE, MxCsr_DAZ, MxCsr_RC));
mRegisterMapping.insert(MxCsr_IE, "MxCsr_IE");
mRegisterPlaces.insert(MxCsr_IE, Register_Position(offset, 0, 9, 1));
mRegisterRelativePlaces.insert(MxCsr_IE, Register_Relative_Position(MxCsr_DE, MxCsr_DM, MxCsr_OE, XMM0));
mRegisterMapping.insert(MxCsr_DM, "MxCsr_DM");
mRegisterPlaces.insert(MxCsr_DM, Register_Position(offset, 12, 10, 1));
mRegisterRelativePlaces.insert(MxCsr_DM, Register_Relative_Position(MxCsr_IE, MxCsr_RC, MxCsr_ZE, XMM0));
mRegisterMapping.insert(MxCsr_RC, "MxCsr_RC");
mRegisterPlaces.insert(MxCsr_RC, Register_Position(offset++, 25, 10, 19));
mRegisterRelativePlaces.insert(MxCsr_RC, Register_Relative_Position(MxCsr_DM, XMM0, MxCsr_DE, XMM0));
offset++;
mRegisterMapping.insert(XMM0, "XMM0");
mRegisterPlaces.insert(XMM0, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM0, Register_Relative_Position(MxCsr_RC, XMM1));
mRegisterMapping.insert(XMM1, "XMM1");
mRegisterPlaces.insert(XMM1, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM1, Register_Relative_Position(XMM0, XMM2));
mRegisterMapping.insert(XMM2, "XMM2");
mRegisterPlaces.insert(XMM2, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM2, Register_Relative_Position(XMM1, XMM3));
mRegisterMapping.insert(XMM3, "XMM3");
mRegisterPlaces.insert(XMM3, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM3, Register_Relative_Position(XMM2, XMM4));
mRegisterMapping.insert(XMM4, "XMM4");
mRegisterPlaces.insert(XMM4, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM4, Register_Relative_Position(XMM3, XMM5));
mRegisterMapping.insert(XMM5, "XMM5");
mRegisterPlaces.insert(XMM5, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM5, Register_Relative_Position(XMM4, XMM6));
mRegisterMapping.insert(XMM6, "XMM6");
mRegisterPlaces.insert(XMM6, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM6, Register_Relative_Position(XMM5, XMM7));
#ifdef _WIN64
mRegisterMapping.insert(XMM7, "XMM7");
mRegisterPlaces.insert(XMM7, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM7, Register_Relative_Position(XMM6, XMM8));
mRegisterMapping.insert(XMM8, "XMM8");
mRegisterPlaces.insert(XMM8, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM8, Register_Relative_Position(XMM7, XMM9));
mRegisterMapping.insert(XMM9, "XMM9");
mRegisterPlaces.insert(XMM9, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM9, Register_Relative_Position(XMM8, XMM10));
mRegisterMapping.insert(XMM10, "XMM10");
mRegisterPlaces.insert(XMM10, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM10, Register_Relative_Position(XMM9, XMM11));
mRegisterMapping.insert(XMM11, "XMM11");
mRegisterPlaces.insert(XMM11, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM11, Register_Relative_Position(XMM10, XMM12));
mRegisterMapping.insert(XMM12, "XMM12");
mRegisterPlaces.insert(XMM12, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM12, Register_Relative_Position(XMM11, XMM13));
mRegisterMapping.insert(XMM13, "XMM13");
mRegisterPlaces.insert(XMM13, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM13, Register_Relative_Position(XMM12, XMM14));
mRegisterMapping.insert(XMM14, "XMM14");
mRegisterPlaces.insert(XMM14, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM14, Register_Relative_Position(XMM13, XMM15));
mRegisterMapping.insert(XMM15, "XMM15");
mRegisterPlaces.insert(XMM15, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM15, Register_Relative_Position(XMM14, YMM0));
#else
mRegisterMapping.insert(XMM7, "XMM7");
mRegisterPlaces.insert(XMM7, Register_Position(offset++, 0, 6, 16 * 2));
mRegisterRelativePlaces.insert(XMM7, Register_Relative_Position(XMM6, YMM0));
#endif
offset++;
#ifdef _WIN64
mRegisterMapping.insert(YMM0, "YMM0");
mRegisterPlaces.insert(YMM0, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM0, Register_Relative_Position(XMM15, YMM1));
#else
mRegisterMapping.insert(YMM0, "YMM0");
mRegisterPlaces.insert(YMM0, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM0, Register_Relative_Position(XMM7, YMM1));
#endif
mRegisterMapping.insert(YMM1, "YMM1");
mRegisterPlaces.insert(YMM1, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM1, Register_Relative_Position(YMM0, YMM2));
mRegisterMapping.insert(YMM2, "YMM2");
mRegisterPlaces.insert(YMM2, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM2, Register_Relative_Position(YMM1, YMM3));
mRegisterMapping.insert(YMM3, "YMM3");
mRegisterPlaces.insert(YMM3, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM3, Register_Relative_Position(YMM2, YMM4));
mRegisterMapping.insert(YMM4, "YMM4");
mRegisterPlaces.insert(YMM4, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM4, Register_Relative_Position(YMM3, YMM5));
mRegisterMapping.insert(YMM5, "YMM5");
mRegisterPlaces.insert(YMM5, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM5, Register_Relative_Position(YMM4, YMM6));
mRegisterMapping.insert(YMM6, "YMM6");
mRegisterPlaces.insert(YMM6, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM6, Register_Relative_Position(YMM5, YMM7));
#ifdef _WIN64
mRegisterMapping.insert(YMM7, "YMM7");
mRegisterPlaces.insert(YMM7, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM7, Register_Relative_Position(YMM6, YMM8));
mRegisterMapping.insert(YMM8, "YMM8");
mRegisterPlaces.insert(YMM8, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM8, Register_Relative_Position(YMM7, YMM9));
mRegisterMapping.insert(YMM9, "YMM9");
mRegisterPlaces.insert(YMM9, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM9, Register_Relative_Position(YMM8, YMM10));
mRegisterMapping.insert(YMM10, "YMM10");
mRegisterPlaces.insert(YMM10, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM10, Register_Relative_Position(YMM9, YMM11));
mRegisterMapping.insert(YMM11, "YMM11");
mRegisterPlaces.insert(YMM11, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM11, Register_Relative_Position(YMM10, YMM12));
mRegisterMapping.insert(YMM12, "YMM12");
mRegisterPlaces.insert(YMM12, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM12, Register_Relative_Position(YMM11, YMM13));
mRegisterMapping.insert(YMM13, "YMM13");
mRegisterPlaces.insert(YMM13, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM13, Register_Relative_Position(YMM12, YMM14));
mRegisterMapping.insert(YMM14, "YMM14");
mRegisterPlaces.insert(YMM14, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM14, Register_Relative_Position(YMM13, YMM15));
mRegisterMapping.insert(YMM15, "YMM15");
mRegisterPlaces.insert(YMM15, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM15, Register_Relative_Position(YMM14, DR0));
#else
mRegisterMapping.insert(YMM7, "YMM7");
mRegisterPlaces.insert(YMM7, Register_Position(offset++, 0, 6, 32 * 2));
mRegisterRelativePlaces.insert(YMM7, Register_Relative_Position(YMM6, DR0));
#endif
}
else
{
mRegisterRelativePlaces.insert(CS, Register_Relative_Position(DS, SS, ES, DR0));
mRegisterRelativePlaces.insert(SS, Register_Relative_Position(CS, DR0, DS, DR0));
}
offset++;
if(mShowFpu)
{
#ifdef _WIN64
mRegisterRelativePlaces.insert(DR0, Register_Relative_Position(YMM15, DR1));
#else
mRegisterRelativePlaces.insert(DR0, Register_Relative_Position(YMM7, DR1));
#endif
}
else
{
mRegisterRelativePlaces.insert(DR0, Register_Relative_Position(SS, DR1));
}
mRegisterMapping.insert(DR0, "DR0");
mRegisterPlaces.insert(DR0, Register_Position(offset++, 0, 4, sizeof(duint) * 2));
mRegisterMapping.insert(DR1, "DR1");
mRegisterPlaces.insert(DR1, Register_Position(offset++, 0, 4, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(DR1, Register_Relative_Position(DR0, DR2));
mRegisterMapping.insert(DR2, "DR2");
mRegisterPlaces.insert(DR2, Register_Position(offset++, 0, 4, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(DR2, Register_Relative_Position(DR1, DR3));
mRegisterMapping.insert(DR3, "DR3");
mRegisterPlaces.insert(DR3, Register_Position(offset++, 0, 4, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(DR3, Register_Relative_Position(DR2, DR6));
mRegisterMapping.insert(DR6, "DR6");
mRegisterPlaces.insert(DR6, Register_Position(offset++, 0, 4, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(DR6, Register_Relative_Position(DR3, DR7));
mRegisterMapping.insert(DR7, "DR7");
mRegisterPlaces.insert(DR7, Register_Position(offset++, 0, 4, sizeof(duint) * 2));
mRegisterRelativePlaces.insert(DR7, Register_Relative_Position(DR6, UNKNOWN));
mRowsNeeded = offset + 1;
}
QAction* RegistersView::setupAction(const QIcon & icon, const QString & text)
{
QAction* action = new QAction(icon, text, this);
action->setShortcutContext(Qt::WidgetShortcut);
addAction(action);
return action;
}
QAction* RegistersView::setupAction(const QString & text)
{
QAction* action = new QAction(text, this);
action->setShortcutContext(Qt::WidgetShortcut);
addAction(action);
return action;
}
RegistersView::RegistersView(QWidget* parent) : QScrollArea(parent), mVScrollOffset(0)
{
setWindowTitle("Registers");
mChangeViewButton = NULL;
mFpuMode = 0;
isActive = false;
// general purposes register (we allow the user to modify the value)
mGPR.insert(CAX);
mCANSTOREADDRESS.insert(CAX);
mUINTDISPLAY.insert(CAX);
mLABELDISPLAY.insert(CAX);
mMODIFYDISPLAY.insert(CAX);
mUNDODISPLAY.insert(CAX);
mINCREMENTDECREMET.insert(CAX);
mINCREMENTDECREMET.insert(CBX);
mGPR.insert(CBX);
mUINTDISPLAY.insert(CBX);
mLABELDISPLAY.insert(CBX);
mMODIFYDISPLAY.insert(CBX);
mUNDODISPLAY.insert(CBX);
mCANSTOREADDRESS.insert(CBX);
mINCREMENTDECREMET.insert(CCX);
mGPR.insert(CCX);
mUINTDISPLAY.insert(CCX);
mLABELDISPLAY.insert(CCX);
mMODIFYDISPLAY.insert(CCX);
mUNDODISPLAY.insert(CCX);
mCANSTOREADDRESS.insert(CCX);
mINCREMENTDECREMET.insert(CDX);
mGPR.insert(CDX);
mUINTDISPLAY.insert(CDX);
mLABELDISPLAY.insert(CDX);
mMODIFYDISPLAY.insert(CDX);
mUNDODISPLAY.insert(CDX);
mCANSTOREADDRESS.insert(CDX);
mINCREMENTDECREMET.insert(CBP);
mCANSTOREADDRESS.insert(CBP);
mGPR.insert(CBP);
mUINTDISPLAY.insert(CBP);
mLABELDISPLAY.insert(CBP);
mMODIFYDISPLAY.insert(CBP);
mUNDODISPLAY.insert(CBP);
mINCREMENTDECREMET.insert(CSP);
mCANSTOREADDRESS.insert(CSP);
mGPR.insert(CSP);
mUINTDISPLAY.insert(CSP);
mLABELDISPLAY.insert(CSP);
mMODIFYDISPLAY.insert(CSP);
mUNDODISPLAY.insert(CSP);
mINCREMENTDECREMET.insert(CSI);
mCANSTOREADDRESS.insert(CSI);
mGPR.insert(CSI);
mUINTDISPLAY.insert(CSI);
mLABELDISPLAY.insert(CSI);
mMODIFYDISPLAY.insert(CSI);
mUNDODISPLAY.insert(CSI);
mINCREMENTDECREMET.insert(CDI);
mCANSTOREADDRESS.insert(CDI);
mGPR.insert(CDI);
mUINTDISPLAY.insert(CDI);
mLABELDISPLAY.insert(CDI);
mMODIFYDISPLAY.insert(CDI);
mUNDODISPLAY.insert(CDI);
#ifdef _WIN64
for(REGISTER_NAME i = R8; i <= R15; i = (REGISTER_NAME)(i + 1))
{
mINCREMENTDECREMET.insert(i);
mCANSTOREADDRESS.insert(i);
mGPR.insert(i);
mLABELDISPLAY.insert(i);
mUINTDISPLAY.insert(i);
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
}
#endif //_WIN64
mGPR.insert(EFLAGS);
mMODIFYDISPLAY.insert(EFLAGS);
mUNDODISPLAY.insert(EFLAGS);
mUINTDISPLAY.insert(EFLAGS);
// flags (we allow the user to toggle them)
mFlags.insert(CF);
mBOOLDISPLAY.insert(CF);
mFlags.insert(PF);
mBOOLDISPLAY.insert(PF);
mFlags.insert(AF);
mBOOLDISPLAY.insert(AF);
mFlags.insert(ZF);
mBOOLDISPLAY.insert(ZF);
mFlags.insert(SF);
mBOOLDISPLAY.insert(SF);
mFlags.insert(TF);
mBOOLDISPLAY.insert(TF);
mFlags.insert(IF);
mBOOLDISPLAY.insert(IF);
mFlags.insert(DF);
mBOOLDISPLAY.insert(DF);
mFlags.insert(OF);
mBOOLDISPLAY.insert(OF);
// FPU: XMM, x87 and MMX registers
mDWORDDISPLAY.insert(MxCsr);
mMODIFYDISPLAY.insert(MxCsr);
mUNDODISPLAY.insert(MxCsr);
mFPU.insert(MxCsr);
for(REGISTER_NAME i = x87r0; i <= x87r7; i = (REGISTER_NAME)(i + 1))
{
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
mFPUx87.insert(i);
mFPUx87_80BITSDISPLAY.insert(i);
mFPU.insert(i);
}
for(REGISTER_NAME i = x87st0; i <= x87st7; i = (REGISTER_NAME)(i + 1))
{
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
mFPUx87.insert(i);
mFPUx87_80BITSDISPLAY.insert(i);
mFPU.insert(i);
}
mFPUx87.insert(x87TagWord);
mMODIFYDISPLAY.insert(x87TagWord);
mUNDODISPLAY.insert(x87TagWord);
mUSHORTDISPLAY.insert(x87TagWord);
mFPU.insert(x87TagWord);
mUSHORTDISPLAY.insert(x87StatusWord);
mMODIFYDISPLAY.insert(x87StatusWord);
mUNDODISPLAY.insert(x87StatusWord);
mFPUx87.insert(x87StatusWord);
mFPU.insert(x87StatusWord);
mFPUx87.insert(x87ControlWord);
mMODIFYDISPLAY.insert(x87ControlWord);
mUNDODISPLAY.insert(x87ControlWord);
mUSHORTDISPLAY.insert(x87ControlWord);
mFPU.insert(x87ControlWord);
mFPUx87.insert(x87SW_B);
mBOOLDISPLAY.insert(x87SW_B);
mFPU.insert(x87SW_B);
mFPUx87.insert(x87SW_C3);
mBOOLDISPLAY.insert(x87SW_C3);
mFPU.insert(x87SW_C3);
mFPUx87.insert(x87SW_TOP);
mFIELDVALUE.insert(x87SW_TOP);
mFPU.insert(x87SW_TOP);
mMODIFYDISPLAY.insert(x87SW_TOP);
mUNDODISPLAY.insert(x87SW_TOP);
mFPUx87.insert(x87SW_C2);
mBOOLDISPLAY.insert(x87SW_C2);
mFPU.insert(x87SW_C2);
mFPUx87.insert(x87SW_C1);
mBOOLDISPLAY.insert(x87SW_C1);
mFPU.insert(x87SW_C1);
mFPUx87.insert(x87SW_C0);
mBOOLDISPLAY.insert(x87SW_C0);
mFPU.insert(x87SW_C0);
mFPUx87.insert(x87SW_ES);
mBOOLDISPLAY.insert(x87SW_ES);
mFPU.insert(x87SW_ES);
mFPUx87.insert(x87SW_SF);
mBOOLDISPLAY.insert(x87SW_SF);
mFPU.insert(x87SW_SF);
mFPUx87.insert(x87SW_P);
mBOOLDISPLAY.insert(x87SW_P);
mFPU.insert(x87SW_P);
mFPUx87.insert(x87SW_U);
mBOOLDISPLAY.insert(x87SW_U);
mFPU.insert(x87SW_U);
mFPUx87.insert(x87SW_O);
mBOOLDISPLAY.insert(x87SW_O);
mFPU.insert(x87SW_O);
mFPUx87.insert(x87SW_Z);
mBOOLDISPLAY.insert(x87SW_Z);
mFPU.insert(x87SW_Z);
mFPUx87.insert(x87SW_D);
mBOOLDISPLAY.insert(x87SW_D);
mFPU.insert(x87SW_D);
mFPUx87.insert(x87SW_I);
mBOOLDISPLAY.insert(x87SW_I);
mFPU.insert(x87SW_I);
mFPUx87.insert(x87CW_IC);
mBOOLDISPLAY.insert(x87CW_IC);
mFPU.insert(x87CW_IC);
mFPUx87.insert(x87CW_RC);
mFIELDVALUE.insert(x87CW_RC);
mFPU.insert(x87CW_RC);
mMODIFYDISPLAY.insert(x87CW_RC);
mUNDODISPLAY.insert(x87CW_RC);
for(REGISTER_NAME i = x87TW_0; i <= x87TW_7; i = (REGISTER_NAME)(i + 1))
{
mFPUx87.insert(i);
mFIELDVALUE.insert(i);
mTAGWORD.insert(i);
mFPU.insert(i);
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
}
mFPUx87.insert(x87CW_PC);
mFIELDVALUE.insert(x87CW_PC);
mFPU.insert(x87CW_PC);
mMODIFYDISPLAY.insert(x87CW_PC);
mUNDODISPLAY.insert(x87CW_PC);
mFPUx87.insert(x87CW_PM);
mBOOLDISPLAY.insert(x87CW_PM);
mFPU.insert(x87CW_PM);
mFPUx87.insert(x87CW_UM);
mBOOLDISPLAY.insert(x87CW_UM);
mFPU.insert(x87CW_UM);
mFPUx87.insert(x87CW_OM);
mBOOLDISPLAY.insert(x87CW_OM);
mFPU.insert(x87CW_OM);
mFPUx87.insert(x87CW_ZM);
mBOOLDISPLAY.insert(x87CW_ZM);
mFPU.insert(x87CW_ZM);
mFPUx87.insert(x87CW_DM);
mBOOLDISPLAY.insert(x87CW_DM);
mFPU.insert(x87CW_DM);
mFPUx87.insert(x87CW_IM);
mBOOLDISPLAY.insert(x87CW_IM);
mFPU.insert(x87CW_IM);
mBOOLDISPLAY.insert(MxCsr_FZ);
mFPU.insert(MxCsr_FZ);
mBOOLDISPLAY.insert(MxCsr_PM);
mFPU.insert(MxCsr_PM);
mBOOLDISPLAY.insert(MxCsr_UM);
mFPU.insert(MxCsr_UM);
mBOOLDISPLAY.insert(MxCsr_OM);
mFPU.insert(MxCsr_OM);
mBOOLDISPLAY.insert(MxCsr_ZM);
mFPU.insert(MxCsr_ZM);
mBOOLDISPLAY.insert(MxCsr_IM);
mFPU.insert(MxCsr_IM);
mBOOLDISPLAY.insert(MxCsr_DM);
mFPU.insert(MxCsr_DM);
mBOOLDISPLAY.insert(MxCsr_DAZ);
mFPU.insert(MxCsr_DAZ);
mBOOLDISPLAY.insert(MxCsr_PE);
mFPU.insert(MxCsr_PE);
mBOOLDISPLAY.insert(MxCsr_UE);
mFPU.insert(MxCsr_UE);
mBOOLDISPLAY.insert(MxCsr_OE);
mFPU.insert(MxCsr_OE);
mBOOLDISPLAY.insert(MxCsr_ZE);
mFPU.insert(MxCsr_ZE);
mBOOLDISPLAY.insert(MxCsr_DE);
mFPU.insert(MxCsr_DE);
mBOOLDISPLAY.insert(MxCsr_IE);
mFPU.insert(MxCsr_IE);
mFIELDVALUE.insert(MxCsr_RC);
mFPU.insert(MxCsr_RC);
mMODIFYDISPLAY.insert(MxCsr_RC);
mUNDODISPLAY.insert(MxCsr_RC);
for(REGISTER_NAME i = MM0; i <= MM7; i = (REGISTER_NAME)(i + 1))
{
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
mFPUMMX.insert(i);
mFPU.insert(i);
}
for(REGISTER_NAME i = XMM0; i <= ArchValue(XMM7, XMM15); i = (REGISTER_NAME)(i + 1))
{
mFPUXMM.insert(i);
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
mFPU.insert(i);
}
for(REGISTER_NAME i = YMM0; i <= ArchValue(YMM7, YMM15); i = (REGISTER_NAME)(i + 1))
{
mFPUYMM.insert(i);
mMODIFYDISPLAY.insert(i);
mUNDODISPLAY.insert(i);
mFPU.insert(i);
}
//registers that should not be changed
mNoChange.insert(LastError);
mNoChange.insert(LastStatus);
mNoChange.insert(GS);
mUSHORTDISPLAY.insert(GS);
mSEGMENTREGISTER.insert(GS);
mNoChange.insert(FS);
mUSHORTDISPLAY.insert(FS);
mSEGMENTREGISTER.insert(FS);
mNoChange.insert(ES);
mUSHORTDISPLAY.insert(ES);
mSEGMENTREGISTER.insert(ES);
mNoChange.insert(DS);
mUSHORTDISPLAY.insert(DS);
mSEGMENTREGISTER.insert(DS);
mNoChange.insert(CS);
mUSHORTDISPLAY.insert(CS);
mSEGMENTREGISTER.insert(CS);
mNoChange.insert(SS);
mUSHORTDISPLAY.insert(SS);
mSEGMENTREGISTER.insert(SS);
mNoChange.insert(DR0);
mUINTDISPLAY.insert(DR0);
mLABELDISPLAY.insert(DR0);
mONLYMODULEANDLABELDISPLAY.insert(DR0);
mCANSTOREADDRESS.insert(DR0);
mNoChange.insert(DR1);
mONLYMODULEANDLABELDISPLAY.insert(DR1);
mUINTDISPLAY.insert(DR1);
mCANSTOREADDRESS.insert(DR1);
mLABELDISPLAY.insert(DR2);
mONLYMODULEANDLABELDISPLAY.insert(DR2);
mNoChange.insert(DR2);
mUINTDISPLAY.insert(DR2);
mCANSTOREADDRESS.insert(DR2);
mNoChange.insert(DR3);
mONLYMODULEANDLABELDISPLAY.insert(DR3);
mLABELDISPLAY.insert(DR3);
mUINTDISPLAY.insert(DR3);
mCANSTOREADDRESS.insert(DR3);
mNoChange.insert(DR6);
mUINTDISPLAY.insert(DR6);
mNoChange.insert(DR7);
mUINTDISPLAY.insert(DR7);
mNoChange.insert(CIP);
mUINTDISPLAY.insert(CIP);
mLABELDISPLAY.insert(CIP);
mONLYMODULEANDLABELDISPLAY.insert(CIP);
mCANSTOREADDRESS.insert(CIP);
mMODIFYDISPLAY.insert(CIP);
mUNDODISPLAY.insert(CIP);
fontsUpdatedSlot();
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(fontsUpdatedSlot()));
// self communication for repainting (maybe some other widgets needs this information, too)
connect(this, SIGNAL(refresh()), this, SLOT(reload()));
connect(Bridge::getBridge(), SIGNAL(shutdown()), this, SLOT(shutdownSlot()));
InitMappings();
// Context Menu
this->setContextMenuPolicy(Qt::CustomContextMenu);
wCM_CopyToClipboard = setupAction(DIcon("copy"), tr("Copy value"));
wCM_CopyFloatingPointValueToClipboard = setupAction(DIcon("copy"), tr("Copy floating point value"));
wCM_CopySymbolToClipboard = setupAction(DIcon("pdb"), tr("Copy Symbol Value"));
wCM_CopyAll = setupAction(DIcon("copy-alt"), tr("Copy all registers"));
wCM_ChangeFPUView = new QAction(DIcon("change-view"), tr("Change view"), this);
mSwitchSIMDDispMode = new QMenu(tr("Change SIMD Register Display Mode"), this);
mSwitchSIMDDispMode->setIcon(DIcon("simdmode"));
mDisplaySTX = new QAction(tr("Display ST(x)"), this);
mDisplayx87rX = new QAction(tr("Display x87rX"), this);
mDisplayMMX = new QAction(tr("Display MMX"), this);
// Create the SIMD display mode actions
SIMDHex = new QAction(tr("Hexadecimal"), mSwitchSIMDDispMode);
SIMDFloat = new QAction(tr("Float"), mSwitchSIMDDispMode);
SIMDDouble = new QAction(tr("Double"), mSwitchSIMDDispMode);
SIMDSWord = new QAction(tr("Signed Word"), mSwitchSIMDDispMode);
SIMDSDWord = new QAction(tr("Signed Dword"), mSwitchSIMDDispMode);
SIMDSQWord = new QAction(tr("Signed Qword"), mSwitchSIMDDispMode);
SIMDUWord = new QAction(tr("Unsigned Word"), mSwitchSIMDDispMode);
SIMDUDWord = new QAction(tr("Unsigned Dword"), mSwitchSIMDDispMode);
SIMDUQWord = new QAction(tr("Unsigned Qword"), mSwitchSIMDDispMode);
SIMDHWord = new QAction(tr("Hexadecimal Word"), mSwitchSIMDDispMode);
SIMDHDWord = new QAction(tr("Hexadecimal Dword"), mSwitchSIMDDispMode);
SIMDHQWord = new QAction(tr("Hexadecimal Qword"), mSwitchSIMDDispMode);
// Set the user data of these actions to the config value
SIMDHex->setData(QVariant(0));
SIMDFloat->setData(QVariant(1));
SIMDDouble->setData(QVariant(2));
SIMDSWord->setData(QVariant(3));
SIMDUWord->setData(QVariant(6));
SIMDHWord->setData(QVariant(9));
SIMDSDWord->setData(QVariant(4));
SIMDUDWord->setData(QVariant(7));
SIMDHDWord->setData(QVariant(10));
SIMDSQWord->setData(QVariant(5));
SIMDUQWord->setData(QVariant(8));
SIMDHQWord->setData(QVariant(11));
mDisplaySTX->setData(QVariant(0));
mDisplayx87rX->setData(QVariant(1));
mDisplayMMX->setData(QVariant(2));
connect(SIMDHex, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDFloat, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDDouble, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDSWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDUWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDHWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDSDWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDUDWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDHDWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDSQWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDUQWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(SIMDHQWord, SIGNAL(triggered()), this, SLOT(onSIMDMode()));
connect(mDisplaySTX, SIGNAL(triggered()), this, SLOT(onFpuMode()));
connect(mDisplayx87rX, SIGNAL(triggered()), this, SLOT(onFpuMode()));
connect(mDisplayMMX, SIGNAL(triggered()), this, SLOT(onFpuMode()));
// Make SIMD display mode actions checkable and unchecked
SIMDHex->setCheckable(true);
SIMDFloat->setCheckable(true);
SIMDDouble->setCheckable(true);
SIMDSWord->setCheckable(true);
SIMDUWord->setCheckable(true);
SIMDHWord->setCheckable(true);
SIMDSDWord->setCheckable(true);
SIMDUDWord->setCheckable(true);
SIMDHDWord->setCheckable(true);
SIMDSQWord->setCheckable(true);
SIMDUQWord->setCheckable(true);
SIMDHQWord->setCheckable(true);
SIMDHex->setChecked(true);
SIMDFloat->setChecked(false);
SIMDDouble->setChecked(false);
SIMDSWord->setChecked(false);
SIMDUWord->setChecked(false);
SIMDHWord->setChecked(false);
SIMDSDWord->setChecked(false);
SIMDUDWord->setChecked(false);
SIMDHDWord->setChecked(false);
SIMDSQWord->setChecked(false);
SIMDUQWord->setChecked(false);
SIMDHQWord->setChecked(false);
mSwitchSIMDDispMode->addAction(SIMDHex);
mSwitchSIMDDispMode->addAction(SIMDFloat);
mSwitchSIMDDispMode->addAction(SIMDDouble);
mSwitchSIMDDispMode->addAction(SIMDSWord);
mSwitchSIMDDispMode->addAction(SIMDSDWord);
mSwitchSIMDDispMode->addAction(SIMDSQWord);
mSwitchSIMDDispMode->addAction(SIMDUWord);
mSwitchSIMDDispMode->addAction(SIMDUDWord);
mSwitchSIMDDispMode->addAction(SIMDUQWord);
mSwitchSIMDDispMode->addAction(SIMDHWord);
mSwitchSIMDDispMode->addAction(SIMDHDWord);
mSwitchSIMDDispMode->addAction(SIMDHQWord);
connect(wCM_CopyToClipboard, SIGNAL(triggered()), this, SLOT(onCopyToClipboardAction()));
connect(wCM_CopyFloatingPointValueToClipboard, SIGNAL(triggered()), this, SLOT(onCopyFloatingPointToClipboardAction()));
connect(wCM_CopySymbolToClipboard, SIGNAL(triggered()), this, SLOT(onCopySymbolToClipboardAction()));
connect(wCM_CopyAll, SIGNAL(triggered()), this, SLOT(onCopyAllAction()));
connect(wCM_ChangeFPUView, SIGNAL(triggered()), this, SLOT(onChangeFPUViewAction()));
memset(&wRegDumpStruct, 0, sizeof(REGDUMP));
memset(&wCipRegDumpStruct, 0, sizeof(REGDUMP));
mCip = 0;
mRegisterUpdates.clear();
mButtonHeight = 0;
yTopSpacing = 4; //set top spacing (in pixels)
this->setMouseTracking(true);
}
void RegistersView::refreshShortcutsSlot()
{
wCM_CopyToClipboard->setShortcut(ConfigShortcut("ActionCopy"));
wCM_CopySymbolToClipboard->setShortcut(ConfigShortcut("ActionCopySymbol"));
wCM_CopyAll->setShortcut(ConfigShortcut("ActionCopyAllRegisters"));
}
/**
* @brief RegistersView::~RegistersView The destructor.
*/
RegistersView::~RegistersView()
{
}
void RegistersView::fontsUpdatedSlot()
{
auto font = ConfigFont("Registers");
setFont(font);
if(mChangeViewButton)
mChangeViewButton->setFont(font);
//update metrics information
int wRowsHeight = QFontMetrics(this->font()).height();
wRowsHeight = (wRowsHeight * 105) / 100;
wRowsHeight = (wRowsHeight % 2) == 0 ? wRowsHeight : wRowsHeight + 1;
mRowHeight = wRowsHeight;
mCharWidth = QFontMetrics(this->font()).averageCharWidth();
//reload layout because the layout is dependent on the font.
InitMappings();
//adjust the height of the area.
setFixedHeight(getEstimateHeight());
reload();
}
void RegistersView::shutdownSlot()
{
isActive = false;
}
void RegistersView::displayCustomContextMenuSlot(QPoint pos)
{
Q_UNUSED(pos);
}
void RegistersView::ShowFPU(bool set_showfpu)
{
mShowFpu = set_showfpu;
InitMappings();
setFixedHeight(getEstimateHeight());
reload();
}
/**
* @brief retrieves the register id from given corrdinates of the viewport
* @param line
* @param offset (x-coord)
* @param resulting register-id
* @return true if register found
*/
bool RegistersView::identifyRegister(const int line, const int offset, REGISTER_NAME* clickedReg)
{
// we start by an unknown register id
if(clickedReg)
*clickedReg = UNKNOWN;
bool found_flag = false;
QMap<REGISTER_NAME, Register_Position>::const_iterator it = mRegisterPlaces.begin();
// iterate all registers that being displayed
while(it != mRegisterPlaces.end())
{
if((it.value().line == (line - mVScrollOffset)) /* same line ? */
&& ((1 + it.value().start) <= offset) /* between start ... ? */
&& (offset <= (1 + it.value().start + it.value().labelwidth + it.value().valuesize)) /* ... and end ? */
)
{
// we found a matching register in the viewport
if(clickedReg)
*clickedReg = (REGISTER_NAME)it.key();
found_flag = true;
break;
}
++it;
}
return found_flag;
}
/**
* @brief RegistersView::helpRegister Get the help information of a register. The help information is from Intel's manual.
* @param reg The register name
* @return The help information, possibly translated to the native language, or empty if the help information is not available yet.
*/
QString RegistersView::helpRegister(REGISTER_NAME reg)
{
switch(reg)
{
//We don't display help messages for general purpose registers as they are very well-known.
case CF:
return tr("CF (bit 0) : Carry flag - Set if an arithmetic operation generates a carry or a borrow out of the mostsignificant bit of the result; cleared otherwise.\n"
"This flag indicates an overflow condition for unsigned-integer arithmetic. It is also used in multiple-precision arithmetic.");
case PF:
return tr("PF (bit 2) : Parity flag - Set if the least-significant byte of the result contains an even number of 1 bits; cleared otherwise.");
case AF:
return tr("AF (bit 4) : Auxiliary Carry flag - Set if an arithmetic operation generates a carry or a borrow out of bit\n"
"3 of the result; cleared otherwise. This flag is used in binary-coded decimal (BCD) arithmetic.");
case ZF:
return tr("ZF (bit 6) : Zero flag - Set if the result is zero; cleared otherwise.");
case SF:
return tr("SF (bit 7) : Sign flag - Set equal to the most-significant bit of the result, which is the sign bit of a signed\n"
"integer. (0 indicates a positive value and 1 indicates a negative value.)");
case OF:
return tr("OF (bit 11) : Overflow flag - Set if the integer result is too large a positive number or too small a negative\n"
"number (excluding the sign-bit) to fit in the destination operand; cleared otherwise. This flag indicates an overflow\n"
"condition for signed-integer (two’s complement) arithmetic.");
case DF:
return tr("DF (bit 10) : The direction flag controls string instructions (MOVS, CMPS, SCAS, LODS, and STOS). Setting the DF flag causes the string instructions\n"
"to auto-decrement (to process strings from high addresses to low addresses). Clearing the DF flag causes the string instructions to auto-increment\n"
"(process strings from low addresses to high addresses).");
case TF:
return tr("TF (bit 8) : Trap flag - Set to enable single-step mode for debugging; clear to disable single-step mode.");
case IF:
return tr("IF (bit 9) : Interrupt enable flag - Controls the response of the processor to maskable interrupt requests. Set to respond to maskable interrupts; cleared to inhibit maskable interrupts.");
case x87ControlWord:
return tr("The 16-bit x87 FPU control word controls the precision of the x87 FPU and rounding method used. It also contains the x87 FPU floating-point exception mask bits.");
case x87StatusWord:
return tr("The 16-bit x87 FPU status register indicates the current state of the x87 FPU.");
case x87TagWord:
return tr("The 16-bit tag word indicates the contents of each the 8 registers in the x87 FPU data-register stack (one 2-bit tag per register).");
case x87CW_PC:
return tr("The precision-control (PC) field (bits 8 and 9 of the x87 FPU control word) determines the precision (64, 53, or 24 bits) of floating-point calculations made by the x87 FPU");
case x87CW_RC:
return tr("The rounding-control (RC) field of the x87 FPU control register (bits 10 and 11) controls how the results of x87 FPU floating-point instructions are rounded.");
case x87CW_IC:
return tr("The infinity control flag (bit 12 of the x87 FPU control word) is provided for compatibility with the Intel 287 Math Coprocessor;\n"
"it is not meaningful for later version x87 FPU coprocessors or IA-32 processors.");
case x87CW_IM:
return tr("The invalid operation exception mask (bit 0). When the mask bit is set, its corresponding exception is blocked from being generated.");
case x87CW_DM:
return tr("The denormal-operand exception mask (bit 2). When the mask bit is set, its corresponding exception is blocked from being generated.");
case x87CW_ZM:
return tr("The floating-point divide-by-zero exception mask (bit 3). When the mask bit is set, its corresponding exception is blocked from being generated.");
case x87CW_OM:
return tr("The floating-point numeric overflow exception mask (bit 4). When the mask bit is set, its corresponding exception is blocked from being generated.");
case x87CW_UM:
return tr("The potential floating-point numeric underflow condition mask (bit 5). When the mask bit is set, its corresponding exception is blocked from being generated.");
case x87CW_PM:
return tr("The inexact-result/precision exception mask (bit 6). When the mask bit is set, its corresponding exception is blocked from being generated.");
case x87SW_B:
return tr("The busy flag (bit 15) indicates if the FPU is busy (B=1) while executing an instruction, or is idle (B=0).\n"
"The B-bit (bit 15) is included for 8087 compatibility only. It reflects the contents of the ES flag.");
case x87SW_C0:
return tr("The C%1 condition code flag (bit %2) is used to indicate the results of floating-point comparison and arithmetic operations.").arg(0).arg(8);
case x87SW_C1:
return tr("The C%1 condition code flag (bit %2) is used to indicate the results of floating-point comparison and arithmetic operations.").arg(1).arg(9);
case x87SW_C2:
return tr("The C%1 condition code flag (bit %2) is used to indicate the results of floating-point comparison and arithmetic operations.").arg(2).arg(10);
case x87SW_C3:
return tr("The C%1 condition code flag (bit %2) is used to indicate the results of floating-point comparison and arithmetic operations.").arg(3).arg(14);
case x87SW_ES:
return tr("The error/exception summary status flag (bit 7) is set when any of the unmasked exception flags are set.");
case x87SW_SF:
return tr("The stack fault flag (bit 6 of the x87 FPU status word) indicates that stack overflow or stack underflow has occurred with data\nin the x87 FPU data register stack.");
case x87SW_TOP:
return tr("A pointer to the x87 FPU data register that is currently at the top of the x87 FPU register stack is contained in bits 11 through 13\n"
"of the x87 FPU status word. This pointer, which is commonly referred to as TOP (for top-of-stack), is a binary value from 0 to 7.");
case x87SW_I:
return tr("The processor reports an invalid operation exception (bit 0) in response to one or more invalid arithmetic operands.");
case x87SW_D:
return tr("The processor reports the denormal-operand exception (bit 2) if an arithmetic instruction attempts to operate on a denormal operand.");
case x87SW_Z:
return tr("The processor reports the floating-point divide-by-zero exception (bit 3) whenever an instruction attempts to divide a finite non-zero operand by 0.");
case x87SW_O:
return tr("The processor reports a floating-point numeric overflow exception (bit 4) whenever the rounded result of an instruction exceeds the largest allowable finite value that will fit into the destination operand.");
case x87SW_U:
return tr("The processor detects a potential floating-point numeric underflow condition (bit 5) whenever the result of rounding with unbounded exponent is non-zero and tiny.");
case x87SW_P:
return tr("The inexact-result/precision exception (bit 6) occurs if the result of an operation is not exactly representable in the destination format.");
case MxCsr:
return tr("The 32-bit MXCSR register contains control and status information for SIMD floating-point operations.");
case MxCsr_IE:
return tr("Bit 0 (IE) : Invalid Operation Flag; indicate whether a SIMD floating-point exception has been detected.");
case MxCsr_DE:
return tr("Bit 1 (DE) : Denormal Flag; indicate whether a SIMD floating-point exception has been detected.");
case MxCsr_ZE:
return tr("Bit 2 (ZE) : Divide-by-Zero Flag; indicate whether a SIMD floating-point exception has been detected.");
case MxCsr_OE:
return tr("Bit 3 (OE) : Overflow Flag; indicate whether a SIMD floating-point exception has been detected.");
case MxCsr_UE:
return tr("Bit 4 (UE) : Underflow Flag; indicate whether a SIMD floating-point exception has been detected.");
case MxCsr_PE:
return tr("Bit 5 (PE) : Precision Flag; indicate whether a SIMD floating-point exception has been detected.");
case MxCsr_IM:
return tr("Bit 7 (IM) : Invalid Operation Mask. When the mask bit is set, its corresponding exception is blocked from being generated.");
case MxCsr_DM:
return tr("Bit 8 (DM) : Denormal Mask. When the mask bit is set, its corresponding exception is blocked from being generated.");
case MxCsr_ZM:
return tr("Bit 9 (ZM) : Divide-by-Zero Mask. When the mask bit is set, its corresponding exception is blocked from being generated.");
case MxCsr_OM:
return tr("Bit 10 (OM) : Overflow Mask. When the mask bit is set, its corresponding exception is blocked from being generated.");
case MxCsr_UM:
return tr("Bit 11 (UM) : Underflow Mask. When the mask bit is set, its corresponding exception is blocked from being generated.");
case MxCsr_PM:
return tr("Bit 12 (PM) : Precision Mask. When the mask bit is set, its corresponding exception is blocked from being generated.");
case MxCsr_FZ:
return tr("Bit 15 (FZ) of the MXCSR register enables the flush-to-zero mode, which controls the masked response to a SIMD floating-point underflow condition.");
case MxCsr_DAZ:
return tr("Bit 6 (DAZ) of the MXCSR register enables the denormals-are-zeros mode, which controls the processor’s response to a SIMD floating-point\n"
"denormal operand condition.");
case MxCsr_RC:
return tr("Bits 13 and 14 of the MXCSR register (the rounding control [RC] field) control how the results of SIMD floating-point instructions are rounded.");
case LastError:
{
char dat[1024];
LASTERROR* error;
error = (LASTERROR*)registerValue(&wRegDumpStruct, LastError);
if(DbgFunctions()->StringFormatInline(QString().sprintf("{winerror@%X}", error->code).toUtf8().constData(), sizeof(dat), dat))
return dat;
else
return tr("The value of GetLastError(). This value is stored in the TEB.");
}
case LastStatus:
{
char dat[1024];
LASTSTATUS* error;
error = (LASTSTATUS*)registerValue(&wRegDumpStruct, LastStatus);
if(DbgFunctions()->StringFormatInline(QString().sprintf("{ntstatus@%X}", error->code).toUtf8().constData(), sizeof(dat), dat))
return dat;
else
return tr("The NTSTATUS in the LastStatusValue field of the TEB.");
}
#ifdef _WIN64
case GS:
return tr("The TEB of the current thread can be accessed as an offset of segment register GS (x64).\nThe TEB can be used to get a lot of information on the process without calling Win32 API.");
#else //x86
case FS:
return tr("The TEB of the current thread can be accessed as an offset of segment register FS (x86).\nThe TEB can be used to get a lot of information on the process without calling Win32 API.");
#endif //_WIN64
default:
return QString();
}
}
void RegistersView::mousePressEvent(QMouseEvent* event)
{
if(!isActive)
return;
if(event->y() < yTopSpacing - mButtonHeight)
{
onChangeFPUViewAction();
}
else
{
// get mouse position
const int y = (event->y() - yTopSpacing) / (double)mRowHeight;
const int x = event->x() / (double)mCharWidth;
REGISTER_NAME r;
// do we find a corresponding register?
if(identifyRegister(y, x, &r))
{
mSelected = r;
emit refresh();
}
else
mSelected = UNKNOWN;
}
}
void RegistersView::mouseMoveEvent(QMouseEvent* event)
{
if(!isActive)
{
QScrollArea::mouseMoveEvent(event);
setCursor(QCursor(Qt::ArrowCursor));
return;
}
REGISTER_NAME r = REGISTER_NAME::UNKNOWN;
QString registerHelpInformation;
// do we find a corresponding register?
if(identifyRegister((event->y() - yTopSpacing) / (double)mRowHeight, event->x() / (double)mCharWidth, &r))
{
registerHelpInformation = helpRegister(r).replace(" : ", ": ");
setCursor(QCursor(Qt::PointingHandCursor));
}
else
{
registerHelpInformation = "";
setCursor(QCursor(Qt::ArrowCursor));
}
if(!registerHelpInformation.isEmpty())
QToolTip::showText(event->globalPos(), registerHelpInformation);
else
QToolTip::hideText();
QScrollArea::mouseMoveEvent(event);
}
void RegistersView::mouseDoubleClickEvent(QMouseEvent* event)
{
Q_UNUSED(event);
}
void RegistersView::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
if(mChangeViewButton != NULL)
{
if(mShowFpu)
mChangeViewButton->setText(tr("Hide FPU"));
else
mChangeViewButton->setText(tr("Show FPU"));
}
QPainter wPainter(this->viewport());
wPainter.setFont(font());
wPainter.fillRect(wPainter.viewport(), QBrush(ConfigColor("RegistersBackgroundColor")));
// Don't draw the registers if a program isn't actually running
if(!isActive)
return;
// Iterate all registers
for(auto itr = mRegisterMapping.begin(); itr != mRegisterMapping.end(); itr++)
{
// Paint register at given position
drawRegister(&wPainter, itr.key(), registerValue(&wRegDumpStruct, itr.key()));
}
}
void RegistersView::keyPressEvent(QKeyEvent* event)
{
if(isActive)
{
int key = event->key();
REGISTER_NAME newRegister = UNKNOWN;
switch(key)
{
case Qt::Key_Left:
newRegister = mRegisterRelativePlaces[mSelected].left;
break;
case Qt::Key_Right:
newRegister = mRegisterRelativePlaces[mSelected].right;
break;
case Qt::Key_Up:
newRegister = mRegisterRelativePlaces[mSelected].up;
break;
case Qt::Key_Down:
newRegister = mRegisterRelativePlaces[mSelected].down;
break;
}
if(newRegister != UNKNOWN)
{
mSelected = newRegister;
ensureRegisterVisible(newRegister);
emit refresh();
}
}
QScrollArea::keyPressEvent(event);
}
//QSize RegistersView::sizeHint() const
//{
// // 32 character width
// return QSize(32 * mCharWidth, this->viewport()->height());
//}
void* RegistersView::operator new(size_t size)
{
return _aligned_malloc(size, 16);
}
void RegistersView::operator delete(void* p)
{
_aligned_free(p);
}
/**
* @brief Get the label associated with the register
* @param register_selected the register
* @return the label
*/
QString RegistersView::getRegisterLabel(REGISTER_NAME register_selected)
{
char label_text[MAX_LABEL_SIZE] = "";
char module_text[MAX_MODULE_SIZE] = "";
char string_text[MAX_STRING_SIZE] = "";
char status_text[MAX_STRING_SIZE] = "";
QString valueText = QString("%1").arg((* ((duint*) registerValue(&wRegDumpStruct, register_selected))), mRegisterPlaces[register_selected].valuesize, 16, QChar('0')).toUpper();
duint register_value = (* ((duint*) registerValue(&wRegDumpStruct, register_selected)));
QString newText = QString("");
bool hasString = DbgGetStringAt(register_value, string_text);
bool hasLabel = DbgGetLabelAt(register_value, SEG_DEFAULT, label_text);
bool hasModule = DbgGetModuleAt(register_value, module_text);
bool hasStatusCode = register_selected == REGISTER_NAME::CAX && (register_value & ArchValue(0xF0000000, 0xFFFFFFFFF0000000)) == 0xC0000000;
hasStatusCode = hasStatusCode && DbgFunctions()->StringFormatInline(QString().sprintf("{ntstatus@%X}", register_value).toUtf8().constData(), sizeof(status_text), status_text);
if(hasString && !mONLYMODULEANDLABELDISPLAY.contains(register_selected))
{
newText = string_text;
}
else if(hasStatusCode)
{
auto colon = strchr(status_text, ':');
if(colon)
*colon = '\0';
newText = status_text;
}
else if(hasLabel && hasModule)
{
newText = "<" + QString(module_text) + "." + QString(label_text) + ">";
}
else if(hasModule)
{
newText = QString(module_text) + "." + valueText;
}
else if(hasLabel)
{
newText = "<" + QString(label_text) + ">";
}
else if(!mONLYMODULEANDLABELDISPLAY.contains(register_selected))
{
if(register_value == (register_value & 0xFF))
{
QChar c = QChar((char)register_value);
if(c.isPrint())
{
newText = QString("'%1'").arg((char)register_value);
}
}
else if(register_value == (register_value & 0xFFF)) //UNICODE?
{
QChar c = QChar((wchar_t)register_value);
if(c.isPrint())
{
newText = "L'" + QString(c) + "'";
}
}
}
return std::move(newText);
}
/**
* @brief RegistersView::GetRegStringValueFromValue Get the textual representation of the register value.
* @param reg The name of the register
* @param value The current value of the register
* @return The textual representation of the register value
*
* This value does not return hex representation all the times for SIMD registers. The actual representation of SIMD registers depends on the user settings.
*/
QString RegistersView::GetRegStringValueFromValue(REGISTER_NAME reg, const char* value)
{
QString valueText;
if(mUINTDISPLAY.contains(reg))
valueText = QString("%1").arg((* ((const duint*) value)), mRegisterPlaces[reg].valuesize, 16, QChar('0')).toUpper();
else if(mUSHORTDISPLAY.contains(reg))
valueText = QString("%1").arg((* ((const unsigned short*) value)), mRegisterPlaces[reg].valuesize, 16, QChar('0')).toUpper();
else if(mDWORDDISPLAY.contains(reg))
valueText = QString("%1").arg((* ((const DWORD*) value)), mRegisterPlaces[reg].valuesize, 16, QChar('0')).toUpper();
else if(mBOOLDISPLAY.contains(reg))
valueText = QString("%1").arg((* ((const bool*) value)), mRegisterPlaces[reg].valuesize, 16, QChar('0')).toUpper();
else if(mFIELDVALUE.contains(reg))
{
if(mTAGWORD.contains(reg))
{
valueText = QString("%1").arg((* ((const unsigned short*) value)), 1, 16, QChar('0')).toUpper();
valueText += QString(" (");
valueText += GetTagWordStateString((* ((const unsigned short*) value)));
valueText += QString(")");
}
if(reg == MxCsr_RC)
{
valueText = QString("%1").arg((* ((const unsigned short*) value)), 1, 16, QChar('0')).toUpper();
valueText += QString(" (");
valueText += GetMxCsrRCStateString((* ((const unsigned short*) value)));
valueText += QString(")");
}
else if(reg == x87CW_RC)
{
valueText = QString("%1").arg((* ((const unsigned short*) value)), 1, 16, QChar('0')).toUpper();
valueText += QString(" (");
valueText += GetControlWordRCStateString((* ((const unsigned short*) value)));
valueText += QString(")");
}
else if(reg == x87CW_PC)
{
valueText = QString("%1").arg((* ((const unsigned short*) value)), 1, 16, QChar('0')).toUpper();
valueText += QString(" (");
valueText += GetControlWordPCStateString((* ((const unsigned short*) value)));
valueText += QString(")");
}
else if(reg == x87SW_TOP)
{
valueText = QString("%1").arg((* ((const unsigned short*) value)), 1, 16, QChar('0')).toUpper();
valueText += QString(" (ST0=");
valueText += GetStatusWordTOPStateString((* ((const unsigned short*) value)));
valueText += QString(")");
}
}
else if(reg == LastError)
{
LASTERROR* data = (LASTERROR*)value;
if(*data->name)
valueText = QString().sprintf("%08X (%s)", data->code, data->name);
else
valueText = QString().sprintf("%08X", data->code);
mRegisterPlaces[LastError].valuesize = valueText.length();
}
else if(reg == LastStatus)
{
LASTSTATUS* data = (LASTSTATUS*)value;
if(*data->name)
valueText = QString().sprintf("%08X (%s)", data->code, data->name);
else
valueText = QString().sprintf("%08X", data->code);
mRegisterPlaces[LastStatus].valuesize = valueText.length();
}
else
{
SIZE_T size = GetSizeRegister(reg);
bool bFpuRegistersLittleEndian = ConfigBool("Gui", "FpuRegistersLittleEndian");
if(size != 0)
{
if(mFPUXMM.contains(reg))
valueText = GetDataTypeString(value, size, enc_xmmword);
else if(mFPUYMM.contains(reg))
valueText = GetDataTypeString(value, size, enc_ymmword);
else
valueText = fillValue(value, size, bFpuRegistersLittleEndian);
}
else
valueText = QString("???");
}
return std::move(valueText);
}
#define MxCsr_RC_NEAR 0
#define MxCsr_RC_NEGATIVE 1
#define MxCsr_RC_POSITIVE 2
#define MxCsr_RC_TOZERO 3
STRING_VALUE_TABLE_t MxCsrRCValueStringTable[] =
{
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Toward Zero"), MxCsr_RC_TOZERO},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Toward Positive"), MxCsr_RC_POSITIVE},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Toward Negative"), MxCsr_RC_NEGATIVE},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Round Near"), MxCsr_RC_NEAR}
};
//WARNING: The following function is commented out because it is not used currently. If it is used again, it should be modified to keep working under internationized environment.
/*
unsigned int RegistersView::GetMxCsrRCValueFromString(const char* string)
{
int i;
for(i = 0; i < (sizeof(MxCsrRCValueStringTable) / sizeof(*MxCsrRCValueStringTable)); i++)
{
if(MxCsrRCValueStringTable[i].string == string)
return MxCsrRCValueStringTable[i].value;
}
return i;
}
*/
QString RegistersView::GetMxCsrRCStateString(unsigned short state)
{
int i;
for(i = 0; i < (sizeof(MxCsrRCValueStringTable) / sizeof(*MxCsrRCValueStringTable)); i++)
{
if(MxCsrRCValueStringTable[i].value == state)
return QApplication::translate("RegistersView_ConstantsOfRegisters", MxCsrRCValueStringTable[i].string);
}
return tr("Unknown");
}
#define x87CW_RC_NEAR 0
#define x87CW_RC_DOWN 1
#define x87CW_RC_UP 2
#define x87CW_RC_TRUNCATE 3
STRING_VALUE_TABLE_t ControlWordRCValueStringTable[] =
{
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Truncate"), x87CW_RC_TRUNCATE},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Round Up"), x87CW_RC_UP},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Round Down"), x87CW_RC_DOWN},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Round Near"), x87CW_RC_NEAR}
};
//WARNING: The following function is commented out because it is not used currently. If it is used again, it should be modified to keep working under internationized environment.
/*
unsigned int RegistersView::GetControlWordRCValueFromString(const char* string)
{
int i;
for(i = 0; i < (sizeof(ControlWordRCValueStringTable) / sizeof(*ControlWordRCValueStringTable)); i++)
{
if(tr(ControlWordRCValueStringTable[i].string) == string)
return ControlWordRCValueStringTable[i].value;
}
return i;
}
*/
QString RegistersView::GetControlWordRCStateString(unsigned short state)
{
int i;
for(i = 0; i < (sizeof(ControlWordRCValueStringTable) / sizeof(*ControlWordRCValueStringTable)); i++)
{
if(ControlWordRCValueStringTable[i].value == state)
return QApplication::translate("RegistersView_ConstantsOfRegisters", ControlWordRCValueStringTable[i].string);
}
return tr("Unknown");
}
#define x87SW_TOP_0 0
#define x87SW_TOP_1 1
#define x87SW_TOP_2 2
#define x87SW_TOP_3 3
#define x87SW_TOP_4 4
#define x87SW_TOP_5 5
#define x87SW_TOP_6 6
#define x87SW_TOP_7 7
// This string needs not to be internationalized.
STRING_VALUE_TABLE_t StatusWordTOPValueStringTable[] =
{
{"x87r0", x87SW_TOP_0},
{"x87r1", x87SW_TOP_1},
{"x87r2", x87SW_TOP_2},
{"x87r3", x87SW_TOP_3},
{"x87r4", x87SW_TOP_4},
{"x87r5", x87SW_TOP_5},
{"x87r6", x87SW_TOP_6},
{"x87r7", x87SW_TOP_7}
};
//WARNING: The following function is commented out because it is not used currently. If it is used again, it should be modified to keep working under internationized environment.
/*
unsigned int RegistersView::GetStatusWordTOPValueFromString(const char* string)
{
int i;
for(i = 0; i < (sizeof(StatusWordTOPValueStringTable) / sizeof(*StatusWordTOPValueStringTable)); i++)
{
if(StatusWordTOPValueStringTable[i].string == string)
return StatusWordTOPValueStringTable[i].value;
}
return i;
}
*/
QString RegistersView::GetStatusWordTOPStateString(unsigned short state)
{
int i;
for(i = 0; i < (sizeof(StatusWordTOPValueStringTable) / sizeof(*StatusWordTOPValueStringTable)); i++)
{
if(StatusWordTOPValueStringTable[i].value == state)
return StatusWordTOPValueStringTable[i].string;
}
return tr("Unknown");
}
#define x87CW_PC_REAL4 0
#define x87CW_PC_NOTUSED 1
#define x87CW_PC_REAL8 2
#define x87CW_PC_REAL10 3
STRING_VALUE_TABLE_t ControlWordPCValueStringTable[] =
{
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Real4"), x87CW_PC_REAL4},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Not Used"), x87CW_PC_NOTUSED},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Real8"), x87CW_PC_REAL8},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Real10"), x87CW_PC_REAL10}
};
/*
//WARNING: The following function is commented out because it is not used currently. If it is used again, it should be modified to keep working under internationized environment.
unsigned int RegistersView::GetControlWordPCValueFromString(const char* string)
{
int i;
for(i = 0; i < (sizeof(ControlWordPCValueStringTable) / sizeof(*ControlWordPCValueStringTable)); i++)
{
if(tr(ControlWordPCValueStringTable[i].string) == string)
return ControlWordPCValueStringTable[i].value;
}
return i;
}
*/
QString RegistersView::GetControlWordPCStateString(unsigned short state)
{
int i;
for(i = 0; i < (sizeof(ControlWordPCValueStringTable) / sizeof(*ControlWordPCValueStringTable)); i++)
{
if(ControlWordPCValueStringTable[i].value == state)
return QApplication::translate("RegistersView_ConstantsOfRegisters", ControlWordPCValueStringTable[i].string);
}
return tr("Unknown");
}
#define X87FPU_TAGWORD_NONZERO 0
#define X87FPU_TAGWORD_ZERO 1
#define X87FPU_TAGWORD_SPECIAL 2
#define X87FPU_TAGWORD_EMPTY 3
STRING_VALUE_TABLE_t TagWordValueStringTable[] =
{
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Nonzero"), X87FPU_TAGWORD_NONZERO},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Zero"), X87FPU_TAGWORD_ZERO},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Special"), X87FPU_TAGWORD_SPECIAL},
{QT_TRANSLATE_NOOP("RegistersView_ConstantsOfRegisters", "Empty"), X87FPU_TAGWORD_EMPTY}
};
//WARNING: The following function is commented out because it is not used currently. If it is used again, it should be modified to keep working under internationized environment.
/*
unsigned int RegistersView::GetTagWordValueFromString(const char* string)
{
int i;
for(i = 0; i < (sizeof(TagWordValueStringTable) / sizeof(*TagWordValueStringTable)); i++)
{
if(tr(TagWordValueStringTable[i].string) == string)
return TagWordValueStringTable[i].value;
}
return i;
}
*/
QString RegistersView::GetTagWordStateString(unsigned short state)
{
int i;
for(i = 0; i < (sizeof(TagWordValueStringTable) / sizeof(*TagWordValueStringTable)); i++)
{
if(TagWordValueStringTable[i].value == state)
return QApplication::translate("RegistersView_ConstantsOfRegisters", TagWordValueStringTable[i].string);
}
return tr("Unknown");
}
void RegistersView::drawRegister(QPainter* p, REGISTER_NAME reg, char* value)
{
QFontMetrics fontMetrics(font());
// is the register-id known?
if(mRegisterMapping.contains(reg))
{
// padding to the left is at least one character (looks better)
int x = mCharWidth * (1 + mRegisterPlaces[reg].start);
int ySpace = yTopSpacing;
if(mVScrollOffset != 0)
ySpace = 0;
int y = mRowHeight * (mRegisterPlaces[reg].line + mVScrollOffset) + ySpace;
//draw raster
/*
p->save();
p->setPen(QColor("#FF0000"));
p->drawLine(0, y, this->viewport()->width(), y);
p->restore();
*/
// draw name of value
int width = fontMetrics.width(mRegisterMapping[reg]);
// set the color of the register label
#ifdef _WIN64
switch(reg)
{
case CCX: //arg1
case CDX: //arg2
case R8: //arg3
case R9: //arg4
case XMM0:
case XMM1:
case XMM2:
case XMM3:
p->setPen(ConfigColor("RegistersArgumentLabelColor"));
break;
default:
#endif //_WIN64
p->setPen(ConfigColor("RegistersLabelColor"));
#ifdef _WIN64
break;
}
#endif //_WIN64
//draw the register name
auto regName = mRegisterMapping[reg];
p->drawText(x, y, width, mRowHeight, Qt::AlignVCenter, regName);
//highlight the register based on access
uint8_t highlight = 0;
for(const auto & reg : mHighlightRegs)
{
if(!ZydisTokenizer::tokenTextPoolEquals(regName, reg.first))
continue;
highlight = reg.second;
break;
}
if(highlight)
{
const char* name = "";
switch(highlight & ~(Zydis::RAIImplicit | Zydis::RAIExplicit))
{
case Zydis::RAIRead:
name = "RegistersHighlightReadColor";
break;
case Zydis::RAIWrite:
name = "RegistersHighlightWriteColor";
break;
case Zydis::RAIRead | Zydis::RAIWrite:
name = "RegistersHighlightReadWriteColor";
break;
}
auto highlightColor = ConfigColor(name);
if(highlightColor.alpha())
{
QPen highlightPen(highlightColor);
highlightPen.setWidth(2);
p->setPen(highlightPen);
p->drawLine(x + 1, y + mRowHeight - 1, x + mCharWidth * regName.length() - 1, y + mRowHeight - 1);
}
}
x += (mRegisterPlaces[reg].labelwidth) * mCharWidth;
//p->drawText(offset,mRowHeight*(mRegisterPlaces[reg].line+1),mRegisterMapping[reg]);
//set highlighting
if(isActive && mRegisterUpdates.contains(reg))
p->setPen(ConfigColor("RegistersModifiedColor"));
else
p->setPen(ConfigColor("RegistersColor"));
//get register value
QString valueText = GetRegStringValueFromValue(reg, value);
//selection
width = fontMetrics.width(valueText);
if(mSelected == reg)
{
p->fillRect(x, y, width, mRowHeight, QBrush(ConfigColor("RegistersSelectionColor")));
//p->fillRect(QRect(x + (mRegisterPlaces[reg].labelwidth)*mCharWidth ,mRowHeight*(mRegisterPlaces[reg].line)+2, mRegisterPlaces[reg].valuesize*mCharWidth, mRowHeight), QBrush(ConfigColor("RegistersSelectionColor")));
}
// draw value
p->drawText(x, y, width, mRowHeight, Qt::AlignVCenter, valueText);
//p->drawText(x + (mRegisterPlaces[reg].labelwidth)*mCharWidth ,mRowHeight*(mRegisterPlaces[reg].line+1),QString("%1").arg(value, mRegisterPlaces[reg].valuesize, 16, QChar('0')).toUpper());
x += width;
if(mFPUx87_80BITSDISPLAY.contains(reg) && isActive)
{
p->setPen(ConfigColor("RegistersExtraInfoColor"));
x += 1 * mCharWidth; //1 space
QString newText;
if(mRegisterUpdates.contains(x87SW_TOP))
p->setPen(ConfigColor("RegistersModifiedColor"));
if(reg >= x87r0 && reg <= x87r7)
{
newText = QString("ST%1 ").arg(((X87FPUREGISTER*) registerValue(&wRegDumpStruct, reg))->st_value);
}
else
{
newText = QString("x87r%1 ").arg((wRegDumpStruct.x87StatusWordFields.TOP + (reg - x87st0)) & 7);
}
width = fontMetrics.width(newText);
p->drawText(x, y, width, mRowHeight, Qt::AlignVCenter, newText);
x += width;
newText = QString("");
p->setPen(ConfigColor("RegistersExtraInfoColor"));
if(reg >= x87r0 && reg <= x87r7 && mRegisterUpdates.contains((REGISTER_NAME)(x87TW_0 + (reg - x87r0))))
p->setPen(ConfigColor("RegistersModifiedColor"));
newText += GetTagWordStateString(((X87FPUREGISTER*) registerValue(&wRegDumpStruct, reg))->tag) + QString(" ");
width = fontMetrics.width(newText);
p->drawText(x, y, width, mRowHeight, Qt::AlignVCenter, newText);
x += width;
newText = QString("");
p->setPen(ConfigColor("RegistersExtraInfoColor"));
if(isActive && mRegisterUpdates.contains(reg))
p->setPen(ConfigColor("RegistersModifiedColor"));
newText += ToLongDoubleString(((X87FPUREGISTER*) registerValue(&wRegDumpStruct, reg))->data);
width = fontMetrics.width(newText);
p->drawText(x, y, width, mRowHeight, Qt::AlignVCenter, newText);
}
// do we have a label ?
if(mLABELDISPLAY.contains(reg))
{
x += 5 * mCharWidth; //5 spaces
QString newText = getRegisterLabel(reg);
// are there additional informations?
if(newText != "")
{
width = fontMetrics.width(newText);
p->setPen(ConfigColor("RegistersExtraInfoColor"));
p->drawText(x, y, width, mRowHeight, Qt::AlignVCenter, newText);
//p->drawText(x,mRowHeight*(mRegisterPlaces[reg].line+1),newText);
}
}
}
}
void RegistersView::appendRegister(QString & text, REGISTER_NAME reg, const char* name64, const char* name32)
{
QString symbol;
#ifdef _WIN64
Q_UNUSED(name32);
text.append(name64);
#else //x86
Q_UNUSED(name64);
text.append(name32);
#endif //_WIN64
text.append(GetRegStringValueFromValue(reg, registerValue(&wRegDumpStruct, reg)));
symbol = getRegisterLabel(reg);
if(symbol != "")
{
text.append(" ");
text.append(symbol);
}
text.append("\r\n");
}
void RegistersView::setupSIMDModeMenu()
{
const QAction* selectedAction = nullptr;
// Find out which mode is selected by the user
switch(ConfigUint("Gui", "SIMDRegistersDisplayMode"))
{
case 0:
selectedAction = SIMDHex;
break;
case 1:
selectedAction = SIMDFloat;
break;
case 2:
selectedAction = SIMDDouble;
break;
case 3:
selectedAction = SIMDSWord;
break;
case 6:
selectedAction = SIMDUWord;
break;
case 9:
selectedAction = SIMDHWord;
break;
case 4:
selectedAction = SIMDSDWord;
break;
case 7:
selectedAction = SIMDUDWord;
break;
case 10:
selectedAction = SIMDHDWord;
break;
case 5:
selectedAction = SIMDSQWord;
break;
case 8:
selectedAction = SIMDUQWord;
break;
case 11:
selectedAction = SIMDHQWord;
break;
}
// Check that action if it is selected, uncheck otherwise
SIMDHex->setChecked(SIMDHex == selectedAction);
SIMDFloat->setChecked(SIMDFloat == selectedAction);
SIMDDouble->setChecked(SIMDDouble == selectedAction);
SIMDSWord->setChecked(SIMDSWord == selectedAction);
SIMDUWord->setChecked(SIMDUWord == selectedAction);
SIMDHWord->setChecked(SIMDHWord == selectedAction);
SIMDSDWord->setChecked(SIMDSDWord == selectedAction);
SIMDUDWord->setChecked(SIMDUDWord == selectedAction);
SIMDHDWord->setChecked(SIMDHDWord == selectedAction);
SIMDSQWord->setChecked(SIMDSQWord == selectedAction);
SIMDUQWord->setChecked(SIMDUQWord == selectedAction);
SIMDHQWord->setChecked(SIMDHQWord == selectedAction);
}
void RegistersView::onChangeFPUViewAction()
{
ShowFPU(!mShowFpu);
}
void RegistersView::onSIMDMode()
{
Config()->setUint("Gui", "SIMDRegistersDisplayMode", dynamic_cast<QAction*>(sender())->data().toInt());
emit refresh();
GuiUpdateDisassemblyView(); // refresh display mode for data in disassembly
}
void RegistersView::onFpuMode()
{
mFpuMode = (char)(dynamic_cast<QAction*>(sender())->data().toInt());
InitMappings();
emit refresh();
}
void RegistersView::onCopyToClipboardAction()
{
Bridge::CopyToClipboard(GetRegStringValueFromValue(mSelected, registerValue(&wRegDumpStruct, mSelected)));
}
void RegistersView::onCopyFloatingPointToClipboardAction()
{
Bridge::CopyToClipboard(ToLongDoubleString(((X87FPUREGISTER*) registerValue(&wRegDumpStruct, mSelected))->data));
}
void RegistersView::onCopySymbolToClipboardAction()
{
if(mLABELDISPLAY.contains(mSelected))
{
QString symbol = getRegisterLabel(mSelected);
if(symbol != "")
Bridge::CopyToClipboard(symbol);
}
}
void RegistersView::onCopyAllAction()
{
QString text;
appendRegister(text, REGISTER_NAME::CAX, "RAX : ", "EAX : ");
appendRegister(text, REGISTER_NAME::CBX, "RBX : ", "EBX : ");
appendRegister(text, REGISTER_NAME::CCX, "RCX : ", "ECX : ");
appendRegister(text, REGISTER_NAME::CDX, "RDX : ", "EDX : ");
appendRegister(text, REGISTER_NAME::CBP, "RBP : ", "EBP : ");
appendRegister(text, REGISTER_NAME::CSP, "RSP : ", "ESP : ");
appendRegister(text, REGISTER_NAME::CSI, "RSI : ", "ESI : ");
appendRegister(text, REGISTER_NAME::CDI, "RDI : ", "EDI : ");
#ifdef _WIN64
appendRegister(text, REGISTER_NAME::R8, "R8 : ", "R8 : ");
appendRegister(text, REGISTER_NAME::R9, "R9 : ", "R9 : ");
appendRegister(text, REGISTER_NAME::R10, "R10 : ", "R10 : ");
appendRegister(text, REGISTER_NAME::R11, "R11 : ", "R11 : ");
appendRegister(text, REGISTER_NAME::R12, "R12 : ", "R12 : ");
appendRegister(text, REGISTER_NAME::R13, "R13 : ", "R13 : ");
appendRegister(text, REGISTER_NAME::R14, "R14 : ", "R14 : ");
appendRegister(text, REGISTER_NAME::R15, "R15 : ", "R15 : ");
#endif
appendRegister(text, REGISTER_NAME::CIP, "RIP : ", "EIP : ");
appendRegister(text, REGISTER_NAME::EFLAGS, "RFLAGS : ", "EFLAGS : ");
appendRegister(text, REGISTER_NAME::ZF, "ZF : ", "ZF : ");
appendRegister(text, REGISTER_NAME::OF, "OF : ", "OF : ");
appendRegister(text, REGISTER_NAME::CF, "CF : ", "CF : ");
appendRegister(text, REGISTER_NAME::PF, "PF : ", "PF : ");
appendRegister(text, REGISTER_NAME::SF, "SF : ", "SF : ");
appendRegister(text, REGISTER_NAME::TF, "TF : ", "TF : ");
appendRegister(text, REGISTER_NAME::AF, "AF : ", "AF : ");
appendRegister(text, REGISTER_NAME::DF, "DF : ", "DF : ");
appendRegister(text, REGISTER_NAME::IF, "IF : ", "IF : ");
appendRegister(text, REGISTER_NAME::LastError, "LastError : ", "LastError : ");
appendRegister(text, REGISTER_NAME::LastStatus, "LastStatus : ", "LastStatus : ");
appendRegister(text, REGISTER_NAME::GS, "GS : ", "GS : ");
appendRegister(text, REGISTER_NAME::ES, "ES : ", "ES : ");
appendRegister(text, REGISTER_NAME::CS, "CS : ", "CS : ");
appendRegister(text, REGISTER_NAME::FS, "FS : ", "FS : ");
appendRegister(text, REGISTER_NAME::DS, "DS : ", "DS : ");
appendRegister(text, REGISTER_NAME::SS, "SS : ", "SS : ");
if(mShowFpu)
{
switch(mFpuMode)
{
case 0:
appendRegister(text, REGISTER_NAME::x87st0, "ST(0) : ", "ST(0) : ");
appendRegister(text, REGISTER_NAME::x87st1, "ST(1) : ", "ST(1) : ");
appendRegister(text, REGISTER_NAME::x87st2, "ST(2) : ", "ST(2) : ");
appendRegister(text, REGISTER_NAME::x87st3, "ST(3) : ", "ST(3) : ");
appendRegister(text, REGISTER_NAME::x87st4, "ST(4) : ", "ST(4) : ");
appendRegister(text, REGISTER_NAME::x87st5, "ST(5) : ", "ST(5) : ");
appendRegister(text, REGISTER_NAME::x87st6, "ST(6) : ", "ST(6) : ");
appendRegister(text, REGISTER_NAME::x87st7, "ST(7) : ", "ST(7) : ");
break;
case 1:
appendRegister(text, REGISTER_NAME::x87r0, "x87r0 : ", "x87r0 : ");
appendRegister(text, REGISTER_NAME::x87r1, "x87r1 : ", "x87r1 : ");
appendRegister(text, REGISTER_NAME::x87r2, "x87r2 : ", "x87r2 : ");
appendRegister(text, REGISTER_NAME::x87r3, "x87r3 : ", "x87r3 : ");
appendRegister(text, REGISTER_NAME::x87r4, "x87r4 : ", "x87r4 : ");
appendRegister(text, REGISTER_NAME::x87r5, "x87r5 : ", "x87r5 : ");
appendRegister(text, REGISTER_NAME::x87r6, "x87r6 : ", "x87r6 : ");
appendRegister(text, REGISTER_NAME::x87r7, "x87r7 : ", "x87r7 : ");
break;
case 2:
appendRegister(text, REGISTER_NAME::MM0, "MM0 : ", "MM0 : ");
appendRegister(text, REGISTER_NAME::MM1, "MM1 : ", "MM1 : ");
appendRegister(text, REGISTER_NAME::MM2, "MM2 : ", "MM2 : ");
appendRegister(text, REGISTER_NAME::MM3, "MM3 : ", "MM3 : ");
appendRegister(text, REGISTER_NAME::MM4, "MM4 : ", "MM4 : ");
appendRegister(text, REGISTER_NAME::MM5, "MM5 : ", "MM5 : ");
appendRegister(text, REGISTER_NAME::MM6, "MM6 : ", "MM6 : ");
appendRegister(text, REGISTER_NAME::MM7, "MM7 : ", "MM7 : ");
break;
}
appendRegister(text, REGISTER_NAME::x87TagWord, "x87TagWord : ", "x87TagWord : ");
appendRegister(text, REGISTER_NAME::x87ControlWord, "x87ControlWord : ", "x87ControlWord : ");
appendRegister(text, REGISTER_NAME::x87StatusWord, "x87StatusWord : ", "x87StatusWord : ");
appendRegister(text, REGISTER_NAME::x87TW_0, "x87TW_0 : ", "x87TW_0 : ");
appendRegister(text, REGISTER_NAME::x87TW_1, "x87TW_1 : ", "x87TW_1 : ");
appendRegister(text, REGISTER_NAME::x87TW_2, "x87TW_2 : ", "x87TW_2 : ");
appendRegister(text, REGISTER_NAME::x87TW_3, "x87TW_3 : ", "x87TW_3 : ");
appendRegister(text, REGISTER_NAME::x87TW_4, "x87TW_4 : ", "x87TW_4 : ");
appendRegister(text, REGISTER_NAME::x87TW_5, "x87TW_5 : ", "x87TW_5 : ");
appendRegister(text, REGISTER_NAME::x87TW_6, "x87TW_6 : ", "x87TW_6 : ");
appendRegister(text, REGISTER_NAME::x87TW_7, "x87TW_7 : ", "x87TW_7 : ");
appendRegister(text, REGISTER_NAME::x87SW_B, "x87SW_B : ", "x87SW_B : ");
appendRegister(text, REGISTER_NAME::x87SW_C3, "x87SW_C3 : ", "x87SW_C3 : ");
appendRegister(text, REGISTER_NAME::x87SW_TOP, "x87SW_TOP : ", "x87SW_TOP : ");
appendRegister(text, REGISTER_NAME::x87SW_C2, "x87SW_C2 : ", "x87SW_C2 : ");
appendRegister(text, REGISTER_NAME::x87SW_C1, "x87SW_C1 : ", "x87SW_C1 : ");
appendRegister(text, REGISTER_NAME::x87SW_O, "x87SW_O : ", "x87SW_O : ");
appendRegister(text, REGISTER_NAME::x87SW_ES, "x87SW_ES : ", "x87SW_ES : ");
appendRegister(text, REGISTER_NAME::x87SW_SF, "x87SW_SF : ", "x87SW_SF : ");
appendRegister(text, REGISTER_NAME::x87SW_P, "x87SW_P : ", "x87SW_P : ");
appendRegister(text, REGISTER_NAME::x87SW_U, "x87SW_U : ", "x87SW_U : ");
appendRegister(text, REGISTER_NAME::x87SW_Z, "x87SW_Z : ", "x87SW_Z : ");
appendRegister(text, REGISTER_NAME::x87SW_D, "x87SW_D : ", "x87SW_D : ");
appendRegister(text, REGISTER_NAME::x87SW_I, "x87SW_I : ", "x87SW_I : ");
appendRegister(text, REGISTER_NAME::x87SW_C0, "x87SW_C0 : ", "x87SW_C0 : ");
appendRegister(text, REGISTER_NAME::x87CW_IC, "x87CW_IC : ", "x87CW_IC : ");
appendRegister(text, REGISTER_NAME::x87CW_RC, "x87CW_RC : ", "x87CW_RC : ");
appendRegister(text, REGISTER_NAME::x87CW_PC, "x87CW_PC : ", "x87CW_PC : ");
appendRegister(text, REGISTER_NAME::x87CW_PM, "x87CW_PM : ", "x87CW_PM : ");
appendRegister(text, REGISTER_NAME::x87CW_UM, "x87CW_UM : ", "x87CW_UM : ");
appendRegister(text, REGISTER_NAME::x87CW_OM, "x87CW_OM : ", "x87CW_OM : ");
appendRegister(text, REGISTER_NAME::x87CW_ZM, "x87CW_ZM : ", "x87CW_ZM : ");
appendRegister(text, REGISTER_NAME::x87CW_DM, "x87CW_DM : ", "x87CW_DM : ");
appendRegister(text, REGISTER_NAME::x87CW_IM, "x87CW_IM : ", "x87CW_IM : ");
appendRegister(text, REGISTER_NAME::MxCsr, "MxCsr : ", "MxCsr : ");
appendRegister(text, REGISTER_NAME::MxCsr_FZ, "MxCsr_FZ : ", "MxCsr_FZ : ");
appendRegister(text, REGISTER_NAME::MxCsr_PM, "MxCsr_PM : ", "MxCsr_PM : ");
appendRegister(text, REGISTER_NAME::MxCsr_UM, "MxCsr_UM : ", "MxCsr_UM : ");
appendRegister(text, REGISTER_NAME::MxCsr_OM, "MxCsr_OM : ", "MxCsr_OM : ");
appendRegister(text, REGISTER_NAME::MxCsr_ZM, "MxCsr_ZM : ", "MxCsr_ZM : ");
appendRegister(text, REGISTER_NAME::MxCsr_IM, "MxCsr_IM : ", "MxCsr_IM : ");
appendRegister(text, REGISTER_NAME::MxCsr_DM, "MxCsr_DM : ", "MxCsr_DM : ");
appendRegister(text, REGISTER_NAME::MxCsr_DAZ, "MxCsr_DAZ : ", "MxCsr_DAZ : ");
appendRegister(text, REGISTER_NAME::MxCsr_PE, "MxCsr_PE : ", "MxCsr_PE : ");
appendRegister(text, REGISTER_NAME::MxCsr_UE, "MxCsr_UE : ", "MxCsr_UE : ");
appendRegister(text, REGISTER_NAME::MxCsr_OE, "MxCsr_OE : ", "MxCsr_OE : ");
appendRegister(text, REGISTER_NAME::MxCsr_ZE, "MxCsr_ZE : ", "MxCsr_ZE : ");
appendRegister(text, REGISTER_NAME::MxCsr_DE, "MxCsr_DE : ", "MxCsr_DE : ");
appendRegister(text, REGISTER_NAME::MxCsr_IE, "MxCsr_IE : ", "MxCsr_IE : ");
appendRegister(text, REGISTER_NAME::MxCsr_RC, "MxCsr_RC : ", "MxCsr_RC : ");
appendRegister(text, REGISTER_NAME::XMM0, "XMM0 : ", "XMM0 : ");
appendRegister(text, REGISTER_NAME::XMM1, "XMM1 : ", "XMM1 : ");
appendRegister(text, REGISTER_NAME::XMM2, "XMM2 : ", "XMM2 : ");
appendRegister(text, REGISTER_NAME::XMM3, "XMM3 : ", "XMM3 : ");
appendRegister(text, REGISTER_NAME::XMM4, "XMM4 : ", "XMM4 : ");
appendRegister(text, REGISTER_NAME::XMM5, "XMM5 : ", "XMM5 : ");
appendRegister(text, REGISTER_NAME::XMM6, "XMM6 : ", "XMM6 : ");
appendRegister(text, REGISTER_NAME::XMM7, "XMM7 : ", "XMM7 : ");
#ifdef _WIN64
appendRegister(text, REGISTER_NAME::XMM8, "XMM8 : ", "XMM8 : ");
appendRegister(text, REGISTER_NAME::XMM9, "XMM9 : ", "XMM9 : ");
appendRegister(text, REGISTER_NAME::XMM10, "XMM10 : ", "XMM10 : ");
appendRegister(text, REGISTER_NAME::XMM11, "XMM11 : ", "XMM11 : ");
appendRegister(text, REGISTER_NAME::XMM12, "XMM12 : ", "XMM12 : ");
appendRegister(text, REGISTER_NAME::XMM13, "XMM13 : ", "XMM13 : ");
appendRegister(text, REGISTER_NAME::XMM14, "XMM14 : ", "XMM14 : ");
appendRegister(text, REGISTER_NAME::XMM15, "XMM15 : ", "XMM15 : ");
#endif
appendRegister(text, REGISTER_NAME::YMM0, "YMM0 : ", "YMM0 : ");
appendRegister(text, REGISTER_NAME::YMM1, "YMM1 : ", "YMM1 : ");
appendRegister(text, REGISTER_NAME::YMM2, "YMM2 : ", "YMM2 : ");
appendRegister(text, REGISTER_NAME::YMM3, "YMM3 : ", "YMM3 : ");
appendRegister(text, REGISTER_NAME::YMM4, "YMM4 : ", "YMM4 : ");
appendRegister(text, REGISTER_NAME::YMM5, "YMM5 : ", "YMM5 : ");
appendRegister(text, REGISTER_NAME::YMM6, "YMM6 : ", "YMM6 : ");
appendRegister(text, REGISTER_NAME::YMM7, "YMM7 : ", "YMM7 : ");
#ifdef _WIN64
appendRegister(text, REGISTER_NAME::YMM8, "YMM8 : ", "YMM8 : ");
appendRegister(text, REGISTER_NAME::YMM9, "YMM9 : ", "YMM9 : ");
appendRegister(text, REGISTER_NAME::YMM10, "YMM10 : ", "YMM10 : ");
appendRegister(text, REGISTER_NAME::YMM11, "YMM11 : ", "YMM11 : ");
appendRegister(text, REGISTER_NAME::YMM12, "YMM12 : ", "YMM12 : ");
appendRegister(text, REGISTER_NAME::YMM13, "YMM13 : ", "YMM13 : ");
appendRegister(text, REGISTER_NAME::YMM14, "YMM14 : ", "YMM14 : ");
appendRegister(text, REGISTER_NAME::YMM15, "YMM15 : ", "YMM15 : ");
#endif
}
appendRegister(text, REGISTER_NAME::DR0, "DR0 : ", "DR0 : ");
appendRegister(text, REGISTER_NAME::DR1, "DR1 : ", "DR1 : ");
appendRegister(text, REGISTER_NAME::DR2, "DR2 : ", "DR2 : ");
appendRegister(text, REGISTER_NAME::DR3, "DR3 : ", "DR3 : ");
appendRegister(text, REGISTER_NAME::DR6, "DR6 : ", "DR6 : ");
appendRegister(text, REGISTER_NAME::DR7, "DR7 : ", "DR7 : ");
Bridge::CopyToClipboard(text);
}
void RegistersView::debugStateChangedSlot(DBGSTATE state)
{
Q_UNUSED(state);
}
void RegistersView::reload()
{
this->viewport()->update();
}
SIZE_T RegistersView::GetSizeRegister(const REGISTER_NAME reg_name)
{
SIZE_T size;
if(mUINTDISPLAY.contains(reg_name))
size = sizeof(duint);
else if(mUSHORTDISPLAY.contains(reg_name) || mFIELDVALUE.contains(reg_name))
size = sizeof(unsigned short);
else if(mDWORDDISPLAY.contains(reg_name))
size = sizeof(DWORD);
else if(mBOOLDISPLAY.contains(reg_name))
size = sizeof(bool);
else if(mFPUx87_80BITSDISPLAY.contains(reg_name))
size = 10;
else if(mFPUMMX.contains(reg_name))
size = 8;
else if(mFPUXMM.contains(reg_name))
size = 16;
else if(mFPUYMM.contains(reg_name))
size = 32;
else if(reg_name == LastError)
size = sizeof(DWORD);
else if(reg_name == LastStatus)
size = sizeof(NTSTATUS);
else
size = 0;
return size;
}
int RegistersView::CompareRegisters(const REGISTER_NAME reg_name, REGDUMP* regdump1, REGDUMP* regdump2)
{
SIZE_T size = GetSizeRegister(reg_name);
char* reg1_data = registerValue(regdump1, reg_name);
char* reg2_data = registerValue(regdump2, reg_name);
if(size != 0)
return memcmp(reg1_data, reg2_data, size);
else
return -1;
}
char* RegistersView::registerValue(const REGDUMP* regd, const REGISTER_NAME reg)
{
static int null_value = 0;
// this is probably the most efficient general method to access the values of the struct
// TODO: add an array with something like: return array[reg].data, this is more fast :-)
switch(reg)
{
case CAX:
return (char*) ®d->regcontext.cax;
case CBX:
return (char*) ®d->regcontext.cbx;
case CCX:
return (char*) ®d->regcontext.ccx;
case CDX:
return (char*) ®d->regcontext.cdx;
case CSI:
return (char*) ®d->regcontext.csi;
case CDI:
return (char*) ®d->regcontext.cdi;
case CBP:
return (char*) ®d->regcontext.cbp;
case CSP:
return (char*) ®d->regcontext.csp;
case CIP:
return (char*) ®d->regcontext.cip;
case EFLAGS:
return (char*) ®d->regcontext.eflags;
#ifdef _WIN64
case R8:
return (char*) ®d->regcontext.r8;
case R9:
return (char*) ®d->regcontext.r9;
case R10:
return (char*) ®d->regcontext.r10;
case R11:
return (char*) ®d->regcontext.r11;
case R12:
return (char*) ®d->regcontext.r12;
case R13:
return (char*) ®d->regcontext.r13;
case R14:
return (char*) ®d->regcontext.r14;
case R15:
return (char*) ®d->regcontext.r15;
#endif
// CF,PF,AF,ZF,SF,TF,IF,DF,OF
case CF:
return (char*) ®d->flags.c;
case PF:
return (char*) ®d->flags.p;
case AF:
return (char*) ®d->flags.a;
case ZF:
return (char*) ®d->flags.z;
case SF:
return (char*) ®d->flags.s;
case TF:
return (char*) ®d->flags.t;
case IF:
return (char*) ®d->flags.i;
case DF:
return (char*) ®d->flags.d;
case OF:
return (char*) ®d->flags.o;
// GS,FS,ES,DS,CS,SS
case GS:
return (char*) ®d->regcontext.gs;
case FS:
return (char*) ®d->regcontext.fs;
case ES:
return (char*) ®d->regcontext.es;
case DS:
return (char*) ®d->regcontext.ds;
case CS:
return (char*) ®d->regcontext.cs;
case SS:
return (char*) ®d->regcontext.ss;
case LastError:
return (char*) ®d->lastError;
case LastStatus:
return (char*) ®d->lastStatus;
case DR0:
return (char*) ®d->regcontext.dr0;
case DR1:
return (char*) ®d->regcontext.dr1;
case DR2:
return (char*) ®d->regcontext.dr2;
case DR3:
return (char*) ®d->regcontext.dr3;
case DR6:
return (char*) ®d->regcontext.dr6;
case DR7:
return (char*) ®d->regcontext.dr7;
case MM0:
return (char*) ®d->mmx[0];
case MM1:
return (char*) ®d->mmx[1];
case MM2:
return (char*) ®d->mmx[2];
case MM3:
return (char*) ®d->mmx[3];
case MM4:
return (char*) ®d->mmx[4];
case MM5:
return (char*) ®d->mmx[5];
case MM6:
return (char*) ®d->mmx[6];
case MM7:
return (char*) ®d->mmx[7];
case x87r0:
return (char*) ®d->x87FPURegisters[0];
case x87r1:
return (char*) ®d->x87FPURegisters[1];
case x87r2:
return (char*) ®d->x87FPURegisters[2];
case x87r3:
return (char*) ®d->x87FPURegisters[3];
case x87r4:
return (char*) ®d->x87FPURegisters[4];
case x87r5:
return (char*) ®d->x87FPURegisters[5];
case x87r6:
return (char*) ®d->x87FPURegisters[6];
case x87r7:
return (char*) ®d->x87FPURegisters[7];
case x87st0:
return (char*) ®d->x87FPURegisters[regd->x87StatusWordFields.TOP & 7];
case x87st1:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 1) & 7];
case x87st2:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 2) & 7];
case x87st3:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 3) & 7];
case x87st4:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 4) & 7];
case x87st5:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 5) & 7];
case x87st6:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 6) & 7];
case x87st7:
return (char*) ®d->x87FPURegisters[(regd->x87StatusWordFields.TOP + 7) & 7];
case x87TagWord:
return (char*) ®d->regcontext.x87fpu.TagWord;
case x87ControlWord:
return (char*) ®d->regcontext.x87fpu.ControlWord;
case x87TW_0:
return (char*) ®d->x87FPURegisters[0].tag;
case x87TW_1:
return (char*) ®d->x87FPURegisters[1].tag;
case x87TW_2:
return (char*) ®d->x87FPURegisters[2].tag;
case x87TW_3:
return (char*) ®d->x87FPURegisters[3].tag;
case x87TW_4:
return (char*) ®d->x87FPURegisters[4].tag;
case x87TW_5:
return (char*) ®d->x87FPURegisters[5].tag;
case x87TW_6:
return (char*) ®d->x87FPURegisters[6].tag;
case x87TW_7:
return (char*) ®d->x87FPURegisters[7].tag;
case x87CW_IC:
return (char*) ®d->x87ControlWordFields.IC;
case x87CW_PM:
return (char*) ®d->x87ControlWordFields.PM;
case x87CW_UM:
return (char*) ®d->x87ControlWordFields.UM;
case x87CW_OM:
return (char*) ®d->x87ControlWordFields.OM;
case x87CW_ZM:
return (char*) ®d->x87ControlWordFields.ZM;
case x87CW_DM:
return (char*) ®d->x87ControlWordFields.DM;
case x87CW_IM:
return (char*) ®d->x87ControlWordFields.IM;
case x87CW_RC:
return (char*) ®d->x87ControlWordFields.RC;
case x87CW_PC:
return (char*) ®d->x87ControlWordFields.PC;
case x87StatusWord:
return (char*) ®d->regcontext.x87fpu.StatusWord;
case x87SW_B:
return (char*) ®d->x87StatusWordFields.B;
case x87SW_C3:
return (char*) ®d->x87StatusWordFields.C3;
case x87SW_C2:
return (char*) ®d->x87StatusWordFields.C2;
case x87SW_C1:
return (char*) ®d->x87StatusWordFields.C1;
case x87SW_O:
return (char*) ®d->x87StatusWordFields.O;
case x87SW_ES:
return (char*) ®d->x87StatusWordFields.ES;
case x87SW_SF:
return (char*) ®d->x87StatusWordFields.SF;
case x87SW_P:
return (char*) ®d->x87StatusWordFields.P;
case x87SW_U:
return (char*) ®d->x87StatusWordFields.U;
case x87SW_Z:
return (char*) ®d->x87StatusWordFields.Z;
case x87SW_D:
return (char*) ®d->x87StatusWordFields.D;
case x87SW_I:
return (char*) ®d->x87StatusWordFields.I;
case x87SW_C0:
return (char*) ®d->x87StatusWordFields.C0;
case x87SW_TOP:
return (char*) ®d->x87StatusWordFields.TOP;
case MxCsr:
return (char*) ®d->regcontext.MxCsr;
case MxCsr_FZ:
return (char*) ®d->MxCsrFields.FZ;
case MxCsr_PM:
return (char*) ®d->MxCsrFields.PM;
case MxCsr_UM:
return (char*) ®d->MxCsrFields.UM;
case MxCsr_OM:
return (char*) ®d->MxCsrFields.OM;
case MxCsr_ZM:
return (char*) ®d->MxCsrFields.ZM;
case MxCsr_IM:
return (char*) ®d->MxCsrFields.IM;
case MxCsr_DM:
return (char*) ®d->MxCsrFields.DM;
case MxCsr_DAZ:
return (char*) ®d->MxCsrFields.DAZ;
case MxCsr_PE:
return (char*) ®d->MxCsrFields.PE;
case MxCsr_UE:
return (char*) ®d->MxCsrFields.UE;
case MxCsr_OE:
return (char*) ®d->MxCsrFields.OE;
case MxCsr_ZE:
return (char*) ®d->MxCsrFields.ZE;
case MxCsr_DE:
return (char*) ®d->MxCsrFields.DE;
case MxCsr_IE:
return (char*) ®d->MxCsrFields.IE;
case MxCsr_RC:
return (char*) ®d->MxCsrFields.RC;
case XMM0:
return (char*) ®d->regcontext.XmmRegisters[0];
case XMM1:
return (char*) ®d->regcontext.XmmRegisters[1];
case XMM2:
return (char*) ®d->regcontext.XmmRegisters[2];
case XMM3:
return (char*) ®d->regcontext.XmmRegisters[3];
case XMM4:
return (char*) ®d->regcontext.XmmRegisters[4];
case XMM5:
return (char*) ®d->regcontext.XmmRegisters[5];
case XMM6:
return (char*) ®d->regcontext.XmmRegisters[6];
case XMM7:
return (char*) ®d->regcontext.XmmRegisters[7];
#ifdef _WIN64
case XMM8:
return (char*) ®d->regcontext.XmmRegisters[8];
case XMM9:
return (char*) ®d->regcontext.XmmRegisters[9];
case XMM10:
return (char*) ®d->regcontext.XmmRegisters[10];
case XMM11:
return (char*) ®d->regcontext.XmmRegisters[11];
case XMM12:
return (char*) ®d->regcontext.XmmRegisters[12];
case XMM13:
return (char*) ®d->regcontext.XmmRegisters[13];
case XMM14:
return (char*) ®d->regcontext.XmmRegisters[14];
case XMM15:
return (char*) ®d->regcontext.XmmRegisters[15];
#endif //_WIN64
case YMM0:
return (char*) ®d->regcontext.YmmRegisters[0];
case YMM1:
return (char*) ®d->regcontext.YmmRegisters[1];
case YMM2:
return (char*) ®d->regcontext.YmmRegisters[2];
case YMM3:
return (char*) ®d->regcontext.YmmRegisters[3];
case YMM4:
return (char*) ®d->regcontext.YmmRegisters[4];
case YMM5:
return (char*) ®d->regcontext.YmmRegisters[5];
case YMM6:
return (char*) ®d->regcontext.YmmRegisters[6];
case YMM7:
return (char*) ®d->regcontext.YmmRegisters[7];
#ifdef _WIN64
case YMM8:
return (char*) ®d->regcontext.YmmRegisters[8];
case YMM9:
return (char*) ®d->regcontext.YmmRegisters[9];
case YMM10:
return (char*) ®d->regcontext.YmmRegisters[10];
case YMM11:
return (char*) ®d->regcontext.YmmRegisters[11];
case YMM12:
return (char*) ®d->regcontext.YmmRegisters[12];
case YMM13:
return (char*) ®d->regcontext.YmmRegisters[13];
case YMM14:
return (char*) ®d->regcontext.YmmRegisters[14];
case YMM15:
return (char*) ®d->regcontext.YmmRegisters[15];
#endif //_WIN64
}
return (char*) &null_value;
}
void RegistersView::setRegisters(REGDUMP* reg)
{
// tests if new-register-value == old-register-value holds
if(mCip != reg->regcontext.cip) //CIP changed
{
wCipRegDumpStruct = wRegDumpStruct;
mRegisterUpdates.clear();
mCip = reg->regcontext.cip;
}
// iterate all ids (CAX, CBX, ...)
for(auto itr = mRegisterMapping.begin(); itr != mRegisterMapping.end(); itr++)
{
if(CompareRegisters(itr.key(), reg, &wCipRegDumpStruct) != 0)
mRegisterUpdates.insert(itr.key());
else if(mRegisterUpdates.contains(itr.key())) //registers are equal
mRegisterUpdates.remove(itr.key());
}
// now we can save the values
wRegDumpStruct = (*reg);
if(mCip != reg->regcontext.cip)
wCipRegDumpStruct = wRegDumpStruct;
// force repaint
emit refresh();
}
// Scroll the viewport so that the register will be visible on the screen
void RegistersView::ensureRegisterVisible(REGISTER_NAME reg)
{
QScrollArea* upperScrollArea = (QScrollArea*)this->parentWidget()->parentWidget();
int ySpace = yTopSpacing;
if(mVScrollOffset != 0)
ySpace = 0;
int y = mRowHeight * (mRegisterPlaces[reg].line + mVScrollOffset) + ySpace;
upperScrollArea->ensureVisible(0, y);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/RegistersView.h | #pragma once
#include <QScrollArea>
#include <QSet>
#include <QMap>
#include "Bridge.h"
class CPUWidget;
class CPUMultiDump;
class QPushButton;
typedef struct
{
const char* string;
unsigned int value;
} STRING_VALUE_TABLE_t;
#define SIZE_TABLE(table) (sizeof(table) / sizeof(*table))
namespace Ui
{
class RegistersView;
}
class RegistersView : public QScrollArea
{
Q_OBJECT
public:
// all possible register ids
enum REGISTER_NAME : int
{
CAX, CCX, CDX, CBX, CDI, CBP, CSI, CSP,
#ifdef _WIN64
R8, R9, R10, R11, R12, R13, R14, R15,
#endif //_WIN64
CIP,
EFLAGS, CF, PF, AF, ZF, SF, TF, IF, DF, OF,
GS, FS, ES, DS, CS, SS,
LastError, LastStatus,
DR0, DR1, DR2, DR3, DR6, DR7,
// x87 stuff
x87r0, x87r1, x87r2, x87r3, x87r4, x87r5, x87r6, x87r7,
x87st0, x87st1, x87st2, x87st3, x87st4, x87st5, x87st6, x87st7,
x87TagWord, x87ControlWord, x87StatusWord,
// x87 Tag Word fields
x87TW_0, x87TW_1, x87TW_2, x87TW_3, x87TW_4, x87TW_5,
x87TW_6, x87TW_7,
// x87 Status Word fields
x87SW_B, x87SW_C3, x87SW_TOP, x87SW_C2, x87SW_C1, x87SW_O,
x87SW_ES, x87SW_SF, x87SW_P, x87SW_U, x87SW_Z,
x87SW_D, x87SW_I, x87SW_C0,
// x87 Control Word fields
x87CW_IC, x87CW_RC, x87CW_PC, x87CW_PM,
x87CW_UM, x87CW_OM, x87CW_ZM, x87CW_DM, x87CW_IM,
//MxCsr
MxCsr, MxCsr_FZ, MxCsr_PM, MxCsr_UM, MxCsr_OM, MxCsr_ZM,
MxCsr_IM, MxCsr_DM, MxCsr_DAZ, MxCsr_PE, MxCsr_UE, MxCsr_OE,
MxCsr_ZE, MxCsr_DE, MxCsr_IE, MxCsr_RC,
// MMX and XMM
MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7,
#ifdef _WIN64
XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15,
#endif //_WIN64
// YMM
YMM0, YMM1, YMM2, YMM3, YMM4, YMM5, YMM6, YMM7,
#ifdef _WIN64
YMM8, YMM9, YMM10, YMM11, YMM12, YMM13, YMM14, YMM15,
#endif //_WIN64
UNKNOWN
};
// contains viewport position of register
struct Register_Position
{
int line;
int start;
int valuesize;
int labelwidth;
Register_Position(int l, int s, int w, int v)
{
line = l;
start = s;
valuesize = v;
labelwidth = w;
}
Register_Position()
{
line = 0;
start = 0;
valuesize = 0;
labelwidth = 0;
}
};
// tracks position of a register relative to other registers
struct Register_Relative_Position
{
REGISTER_NAME left;
REGISTER_NAME right;
REGISTER_NAME up;
REGISTER_NAME down;
Register_Relative_Position(REGISTER_NAME l, REGISTER_NAME r)
{
left = l;
right = r;
up = left;
down = right;
}
Register_Relative_Position(REGISTER_NAME l, REGISTER_NAME r, REGISTER_NAME u, REGISTER_NAME d)
{
left = l;
right = r;
up = u;
down = d;
}
Register_Relative_Position()
{
left = UNKNOWN;
right = UNKNOWN;
up = UNKNOWN;
down = UNKNOWN;
}
};
explicit RegistersView(QWidget* parent);
~RegistersView();
//QSize sizeHint() const;
static void* operator new(size_t size);
static void operator delete(void* p);
int getEstimateHeight();
public slots:
virtual void refreshShortcutsSlot();
virtual void displayCustomContextMenuSlot(QPoint pos);
virtual void debugStateChangedSlot(DBGSTATE state);
void reload();
void ShowFPU(bool set_showfpu);
void onChangeFPUViewAction();
void SetChangeButton(QPushButton* push_button);
signals:
void refresh();
protected:
QAction* setupAction(const QIcon & icon, const QString & text);
QAction* setupAction(const QString & text);
// events
virtual void mousePressEvent(QMouseEvent* event);
virtual void mouseDoubleClickEvent(QMouseEvent* event);
virtual void mouseMoveEvent(QMouseEvent* event);
virtual void paintEvent(QPaintEvent* event);
virtual void keyPressEvent(QKeyEvent* event);
// use-in-class-only methods
void drawRegister(QPainter* p, REGISTER_NAME reg, char* value);
char* registerValue(const REGDUMP* regd, const REGISTER_NAME reg);
bool identifyRegister(const int y, const int x, REGISTER_NAME* clickedReg);
QString helpRegister(REGISTER_NAME reg);
void ensureRegisterVisible(REGISTER_NAME reg);
protected slots:
void InitMappings();
void fontsUpdatedSlot();
void shutdownSlot();
QString getRegisterLabel(REGISTER_NAME);
int CompareRegisters(const REGISTER_NAME reg_name, REGDUMP* regdump1, REGDUMP* regdump2);
SIZE_T GetSizeRegister(const REGISTER_NAME reg_name);
QString GetRegStringValueFromValue(REGISTER_NAME reg, const char* value);
QString GetTagWordStateString(unsigned short);
//unsigned int GetTagWordValueFromString(const char* string);
QString GetControlWordPCStateString(unsigned short);
//unsigned int GetControlWordPCValueFromString(const char* string);
QString GetControlWordRCStateString(unsigned short);
//unsigned int GetControlWordRCValueFromString(const char* string);
QString GetMxCsrRCStateString(unsigned short);
//unsigned int GetMxCsrRCValueFromString(const char* string);
//unsigned int GetStatusWordTOPValueFromString(const char* string);
QString GetStatusWordTOPStateString(unsigned short state);
void setRegisters(REGDUMP* reg);
void appendRegister(QString & text, REGISTER_NAME reg, const char* name64, const char* name32);
void onCopyToClipboardAction();
void onCopyFloatingPointToClipboardAction();
void onCopySymbolToClipboardAction();
// switch SIMD display modes
void onSIMDMode();
void onFpuMode();
void onCopyAllAction();
protected:
bool isActive;
QPushButton* mChangeViewButton;
bool mShowFpu;
int mVScrollOffset;
int mRowsNeeded;
int yTopSpacing;
int mButtonHeight;
QSet<REGISTER_NAME> mUINTDISPLAY;
QSet<REGISTER_NAME> mUSHORTDISPLAY;
QSet<REGISTER_NAME> mDWORDDISPLAY;
QSet<REGISTER_NAME> mBOOLDISPLAY;
QSet<REGISTER_NAME> mLABELDISPLAY;
QSet<REGISTER_NAME> mONLYMODULEANDLABELDISPLAY;
QSet<REGISTER_NAME> mUNDODISPLAY;
QSet<REGISTER_NAME> mMODIFYDISPLAY;
QSet<REGISTER_NAME> mFIELDVALUE;
QSet<REGISTER_NAME> mTAGWORD;
QSet<REGISTER_NAME> mCANSTOREADDRESS;
QSet<REGISTER_NAME> mSEGMENTREGISTER;
QSet<REGISTER_NAME> mINCREMENTDECREMET;
QSet<REGISTER_NAME> mFPUx87_80BITSDISPLAY;
QSet<REGISTER_NAME> mFPU;
// holds current selected register
REGISTER_NAME mSelected;
// general purposes register id s (cax, ..., r8, ....)
QSet<REGISTER_NAME> mGPR;
// all flags
QSet<REGISTER_NAME> mFlags;
// FPU x87, XMM and MMX registers
QSet<REGISTER_NAME> mFPUx87;
QSet<REGISTER_NAME> mFPUMMX;
QSet<REGISTER_NAME> mFPUXMM;
QSet<REGISTER_NAME> mFPUYMM;
// contains all id's of registers if there occurs a change
QSet<REGISTER_NAME> mRegisterUpdates;
// registers that do not allow changes
QSet<REGISTER_NAME> mNoChange;
// maps from id to name
QMap<REGISTER_NAME, QString> mRegisterMapping;
// contains viewport positions
QMap<REGISTER_NAME, Register_Position> mRegisterPlaces;
// contains names of closest registers in view
QMap<REGISTER_NAME, Register_Relative_Position> mRegisterRelativePlaces;
// contains a dump of the current register values
REGDUMP wRegDumpStruct;
REGDUMP wCipRegDumpStruct;
// font measures (TODO: create a class that calculates all thos values)
unsigned int mRowHeight, mCharWidth;
// SIMD registers display mode
char mFpuMode; //0 = order by ST(X), 1 = order by x87rX, 2 = MMX registers
dsint mCip;
std::vector<std::pair<const char*, uint8_t>> mHighlightRegs;
// menu actions
QAction* mDisplaySTX;
QAction* mDisplayx87rX;
QAction* mDisplayMMX;
QAction* wCM_CopyToClipboard;
QAction* wCM_CopyFloatingPointValueToClipboard;
QAction* wCM_CopySymbolToClipboard;
QAction* wCM_CopyAll;
QAction* wCM_ChangeFPUView;
QMenu* mSwitchSIMDDispMode;
void setupSIMDModeMenu();
QAction* SIMDHex;
QAction* SIMDFloat;
QAction* SIMDDouble;
QAction* SIMDSWord;
QAction* SIMDUWord;
QAction* SIMDHWord;
QAction* SIMDSDWord;
QAction* SIMDUDWord;
QAction* SIMDHDWord;
QAction* SIMDSQWord;
QAction* SIMDUQWord;
QAction* SIMDHQWord;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/RichTextItemDelegate.cpp | #include "RichTextItemDelegate.h"
#include <QTextDocument>
#include <QPainter>
#include <QAbstractTextDocumentLayout>
#include <QApplication>
RichTextItemDelegate::RichTextItemDelegate(QColor* textColor, QObject* parent)
: QStyledItemDelegate(parent),
mTextColor(textColor)
{
}
void RichTextItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem & inOption, const QModelIndex & index) const
{
QStyleOptionViewItem option = inOption;
initStyleOption(&option, index);
if(option.text.isEmpty())
{
// This is nothing this function is supposed to handle
QStyledItemDelegate::paint(painter, inOption, index);
return;
}
QStyle* style = option.widget ? option.widget->style() : QApplication::style();
QTextOption textOption;
textOption.setWrapMode(option.features & QStyleOptionViewItem::WrapText ? QTextOption::WordWrap
: QTextOption::ManualWrap);
textOption.setTextDirection(option.direction);
QTextDocument doc;
doc.setDefaultTextOption(textOption);
doc.setHtml(QString("<font color=\"%1\">%2</font>").arg(mTextColor->name(), option.text));
doc.setDefaultFont(option.font);
doc.setDocumentMargin(0);
doc.setTextWidth(option.rect.width());
doc.adjustSize();
if(doc.size().width() > option.rect.width())
{
// Elide text
QTextCursor cursor(&doc);
cursor.movePosition(QTextCursor::End);
const QString elidedPostfix = "...";
QFontMetrics metric(option.font);
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
int postfixWidth = metric.horizontalAdvance(elidedPostfix);
#else
int postfixWidth = metric.width(elidedPostfix);
#endif
while(doc.size().width() > option.rect.width() - postfixWidth)
{
cursor.deletePreviousChar();
doc.adjustSize();
}
cursor.insertText(elidedPostfix);
}
// Painting item without text (this takes care of painting e.g. the highlighted for selected
// or hovered over items in an ItemView)
option.text = QString();
style->drawControl(QStyle::CE_ItemViewItem, &option, painter, inOption.widget);
// Figure out where to render the text in order to follow the requested alignment
QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &option);
QSize documentSize(doc.size().width(), doc.size().height()); // Convert QSizeF to QSize
QRect layoutRect = QStyle::alignedRect(Qt::LayoutDirectionAuto, option.displayAlignment, documentSize, textRect);
painter->save();
// Translate the painter to the origin of the layout rectangle in order for the text to be
// rendered at the correct position
painter->translate(layoutRect.topLeft());
doc.drawContents(painter, textRect.translated(-textRect.topLeft()));
painter->restore();
}
QSize RichTextItemDelegate::sizeHint(const QStyleOptionViewItem & inOption, const QModelIndex & index) const
{
QStyleOptionViewItem option = inOption;
initStyleOption(&option, index);
if(option.text.isEmpty())
{
// This is nothing this function is supposed to handle
return QStyledItemDelegate::sizeHint(inOption, index);
}
QTextDocument doc;
doc.setHtml(option.text);
doc.setTextWidth(option.rect.width());
doc.setDefaultFont(option.font);
doc.setDocumentMargin(0);
return QSize(doc.idealWidth(), doc.size().height());
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/RichTextItemDelegate.h | #pragma once
#include <QStyledItemDelegate>
// Based on: https://stackoverflow.com/a/66412883/1806760
class RichTextItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit RichTextItemDelegate(QColor* textColor, QObject* parent = nullptr);
protected:
void paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const override;
QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const override;
private:
QColor* mTextColor = nullptr;
}; |
C++ | x64dbg-development/src/gui/Src/Gui/ScriptView.cpp | #include "ScriptView.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QDesktopServices>
#include <QClipboard>
#include <QMimeData>
#include "Configuration.h"
#include "Bridge.h"
#include "RichTextPainter.h"
#include "LineEditDialog.h"
#include "MRUList.h"
ScriptView::ScriptView(StdTable* parent) : StdTable(parent)
{
mEnableSyntaxHighlighting = false;
enableMultiSelection(false);
enableColumnSorting(false);
setDrawDebugOnly(false);
setDisassemblyPopupEnabled(false);
int charwidth = getCharWidth();
addColumnAt(8 + charwidth * 4, tr("Line"), false);
addColumnAt(8 + charwidth * 60, tr("Text"), false);
addColumnAt(8 + charwidth * 40, tr("Info"), false);
loadColumnFromConfig("Script");
setIp(0); //no IP
setupContextMenu();
//message box
msg = new QMessageBox(this);
msg->setWindowFlags(msg->windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg->setModal(false);
connect(msg, SIGNAL(finished(int)), this, SLOT(messageResult(int)));
// recent script
mMRUList = new MRUList(this, "Recent Scripts");
connect(mMRUList, SIGNAL(openFile(QString)), this, SLOT(openRecentFile(QString)));
mMRUList->load();
// command line edit dialog
mCmdLineEdit = new LineEditDialog(this);
mCmdLineEdit->setWindowTitle(tr("Execute Script Command..."));
// Slots
connect(Bridge::getBridge(), SIGNAL(scriptAdd(int, const char**)), this, SLOT(add(int, const char**)));
connect(Bridge::getBridge(), SIGNAL(scriptClear()), this, SLOT(clear()));
connect(Bridge::getBridge(), SIGNAL(scriptSetIp(int)), this, SLOT(setIp(int)));
connect(Bridge::getBridge(), SIGNAL(scriptError(int, QString)), this, SLOT(error(int, QString)));
connect(Bridge::getBridge(), SIGNAL(scriptSetTitle(QString)), this, SLOT(setTitle(QString)));
connect(Bridge::getBridge(), SIGNAL(scriptSetInfoLine(int, QString)), this, SLOT(setInfoLine(int, QString)));
connect(Bridge::getBridge(), SIGNAL(scriptMessage(QString)), this, SLOT(message(QString)));
connect(Bridge::getBridge(), SIGNAL(scriptQuestion(QString)), this, SLOT(question(QString)));
connect(Bridge::getBridge(), SIGNAL(scriptEnableHighlighting(bool)), this, SLOT(enableHighlighting(bool)));
connect(Bridge::getBridge(), SIGNAL(shutdown()), this, SLOT(shutdownSlot()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
Initialize();
}
void ScriptView::updateColors()
{
StdTable::updateColors();
mSelectionColor = ConfigColor("DisassemblySelectionColor");
mBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
}
QString ScriptView::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
bool wIsSelected = isSelected(rowBase, rowOffset);
// Highlight if selected
if(wIsSelected)
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor)); //ScriptViewSelectionColor
QString returnString;
int line = rowBase + rowOffset + 1;
SCRIPTLINETYPE linetype = DbgScriptGetLineType(line);
switch(col)
{
case 0: //line number
{
returnString = returnString.sprintf("%.4d", line);
if(line == mIpLine) //IP
{
painter->fillRect(QRect(x, y, w, h), QBrush(ConfigColor("DisassemblyCipBackgroundColor")));
if(DbgScriptBpGet(line)) //breakpoint
{
QColor bpColor = ConfigColor("DisassemblyBreakpointBackgroundColor");
if(!bpColor.alpha()) //we don't want transparent text
bpColor = ConfigColor("DisassemblyBreakpointColor");
painter->setPen(QPen(bpColor));
}
else
painter->setPen(QPen(ConfigColor("DisassemblyCipColor"))); //white address (ScriptViewIpTextColor)
}
else if(DbgScriptBpGet(line)) //breakpoint
{
painter->fillRect(QRect(x, y, w, h), QBrush(ConfigColor("DisassemblyBreakpointBackgroundColor")));
painter->setPen(QPen(ConfigColor("DisassemblyBreakpointColor"))); //black address //ScripViewMainBpTextColor
}
else
{
QColor background;
if(linetype == linecommand || linetype == linebranch)
{
background = ConfigColor("DisassemblySelectedAddressBackgroundColor");
painter->setPen(QPen(ConfigColor("DisassemblySelectedAddressColor"))); //black address (DisassemblySelectedAddressColor)
}
else
{
background = ConfigColor("DisassemblyAddressBackgroundColor");
painter->setPen(QPen(ConfigColor("DisassemblyAddressColor"))); //grey address
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background
}
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, returnString);
returnString = "";
}
break;
case 1: //command
{
if(mEnableSyntaxHighlighting)
{
//initialize
int charwidth = getCharWidth();
int xadd = charwidth; //for testing
RichTextPainter::List richText;
RichTextPainter::CustomRichText_t newRichText;
newRichText.underline = false;
QString command = getCellContent(rowBase + rowOffset, col);
//handle comments
int comment_idx = command.indexOf("\1"); //find the index of the comment
QString comment = "";
if(comment_idx != -1 && command.at(0) != QChar('/')) //there is a comment
{
comment = command.right(command.length() - comment_idx - 1);
if(command.at(comment_idx - 1) == QChar(' '))
command.truncate(comment_idx - 1);
else
command.truncate(comment_idx);
}
QString mnemonic, argument;
//setup the richText list
switch(linetype)
{
case linecommand:
{
if(isScriptCommand(command, "ret", mnemonic, argument))
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionRetColor");
newRichText.textBackground = ConfigColor("InstructionRetBackgroundColor");
newRichText.text = mnemonic;
richText.push_back(newRichText);
if(argument.length())
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionUncategorizedColor");
newRichText.textBackground = ConfigColor("InstructionUncategorizedBackgroundColor");
newRichText.text = argument;
richText.push_back(newRichText);
}
}
else if(isScriptCommand(command, "invalid", mnemonic, argument) || isScriptCommand(command, "error", mnemonic, argument))
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionUnusualColor");
newRichText.textBackground = ConfigColor("InstructionUnusualBackgroundColor");
newRichText.text = mnemonic;
richText.push_back(newRichText);
if(argument.length())
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionUncategorizedColor");
newRichText.textBackground = ConfigColor("InstructionUncategorizedBackgroundColor");
newRichText.text = argument;
richText.push_back(newRichText);
}
}
else if(isScriptCommand(command, "nop", mnemonic, argument))
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionNopColor");
newRichText.textBackground = ConfigColor("InstructionNopBackgroundColor");
newRichText.text = mnemonic;
richText.push_back(newRichText);
}
else
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionUncategorizedColor");
newRichText.textBackground = ConfigColor("InstructionUncategorizedBackgroundColor");
newRichText.text = command;
richText.push_back(newRichText);
}
}
break;
case linebranch:
{
SCRIPTBRANCH branchinfo;
DbgScriptGetBranchInfo(line, &branchinfo);
//jumps
int i = command.indexOf(" "); //find the index of the space
switch(branchinfo.type)
{
case scriptjmp: //unconditional jumps
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionUnconditionalJumpColor");
newRichText.textBackground = ConfigColor("InstructionUnconditionalJumpBackgroundColor");
break;
case scriptjnejnz: //conditional jumps
case scriptjejz:
case scriptjbjl:
case scriptjajg:
case scriptjbejle:
case scriptjaejge:
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionConditionalJumpColor");
newRichText.textBackground = ConfigColor("InstructionConditionalJumpBackgroundColor");
break;
case scriptcall: //calls
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionCallColor");
newRichText.textBackground = ConfigColor("InstructionCallBackgroundColor");
break;
default:
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionUncategorizedColor");
newRichText.textBackground = ConfigColor("InstructionUncategorizedBackgroundColor");
break;
}
newRichText.text = command.left(i);
richText.push_back(newRichText);
//space
newRichText.flags = RichTextPainter::FlagNone;
newRichText.text = " ";
richText.push_back(newRichText);
//label
QString label = branchinfo.branchlabel;
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("InstructionAddressColor");
newRichText.textBackground = ConfigColor("InstructionAddressBackgroundColor");
newRichText.text = label;
richText.push_back(newRichText);
//remainder
QString remainder = command.right(command.length() - command.indexOf(label) - label.length());
if(remainder.length())
{
newRichText.textColor = ConfigColor("InstructionUncategorizedColor");
newRichText.textBackground = ConfigColor("InstructionUncategorizedBackgroundColor");
newRichText.text = remainder;
richText.push_back(newRichText);
}
}
break;
case linelabel:
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("DisassemblyAddressColor");
newRichText.textBackground = ConfigColor("DisassemblyAddressBackgroundColor");
newRichText.text = command;
richText.push_back(newRichText);
painter->drawLine(QPoint(x + xadd + 2, y + h - 2), QPoint(x + w - 4, y + h - 2));
}
break;
case linecomment:
{
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("DisassemblyAddressColor");
newRichText.textBackground = ConfigColor("DisassemblyAddressBackgroundColor");
newRichText.text = command;
richText.push_back(newRichText);
}
break;
case lineempty:
{
}
break;
}
//append the comment (when present)
if(comment.length())
{
RichTextPainter::CustomRichText_t newRichText;
newRichText.underline = false;
newRichText.flags = RichTextPainter::FlagNone;
newRichText.text = " ";
richText.push_back(newRichText); //space
newRichText.flags = RichTextPainter::FlagAll;
newRichText.textColor = ConfigColor("DisassemblyAddressColor");
newRichText.textBackground = ConfigColor("DisassemblyAddressBackgroundColor");
newRichText.text = comment;
richText.push_back(newRichText); //comment
}
//paint the rich text
RichTextPainter::paintRichText(painter, x + 1, y, w, h, xadd, richText, mFontMetrics);
returnString = "";
}
else //no syntax highlighting
returnString = getCellContent(rowBase + rowOffset, col);
}
break;
case 2: //info
{
returnString = getCellContent(rowBase + rowOffset, col);
}
break;
}
return returnString;
}
void ScriptView::contextMenuSlot(const QPoint & pos)
{
QMenu wMenu(this);
mMenu->build(&wMenu);
wMenu.exec(mapToGlobal(pos));
}
void ScriptView::mouseDoubleClickEvent(QMouseEvent* event)
{
AbstractTableView::mouseDoubleClickEvent(event);
if(event->button() != Qt::LeftButton)
return;
Q_UNUSED(event);
if(!getRowCount())
return;
newIp();
}
void ScriptView::keyPressEvent(QKeyEvent* event)
{
int key = event->key();
if(key == Qt::Key_Up || key == Qt::Key_Down)
{
dsint botRVA = getTableOffset();
dsint topRVA = botRVA + getNbrOfLineToPrint() - 1;
if(key == Qt::Key_Up)
selectPrevious();
else
selectNext();
if(getInitialSelection() < botRVA)
{
setTableOffset(getInitialSelection());
}
else if(getInitialSelection() >= topRVA)
{
setTableOffset(getInitialSelection() - getNbrOfLineToPrint() + 2);
}
reloadData();
}
else if(key == Qt::Key_Return || key == Qt::Key_Enter)
{
int line = getInitialSelection() + 1;
SCRIPTBRANCH branchinfo;
memset(&branchinfo, 0, sizeof(SCRIPTBRANCH));
if(DbgScriptGetBranchInfo(line, &branchinfo))
setSelection(branchinfo.dest);
}
else
{
AbstractTableView::keyPressEvent(event);
}
}
void ScriptView::setupContextMenu()
{
mMenu = new MenuBuilder(this);
MenuBuilder* loadMenu = new MenuBuilder(this);
loadMenu->addAction(makeShortcutAction(DIcon("folder-horizontal-open"), tr("&Open..."), SLOT(openFile()), "ActionLoadScript"));
loadMenu->addAction(makeShortcutAction(DIcon("binary_paste"), tr("&Paste"), SLOT(paste()), "ActionBinaryPaste"), [](QMenu*)
{
return QApplication::clipboard()->mimeData()->hasText();
});
loadMenu->addSeparator();
loadMenu->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
mMRUList->appendMenu(menu);
return true;
}));
mMenu->addMenu(makeMenu(DIcon("load-script"), tr("Load Script")), loadMenu);
auto isempty = [this](QMenu*)
{
return getRowCount() != 0;
};
auto isemptyclipboard = [this](QMenu*)
{
return getRowCount() != 0 && !filename.isEmpty();
};
mMenu->addAction(makeShortcutAction(DIcon("arrow-restart"), tr("Re&load Script"), SLOT(reload()), "ActionReloadScript"), isemptyclipboard);
mMenu->addAction(makeShortcutAction(DIcon("control-exit"), tr("&Unload Script"), SLOT(unload()), "ActionUnloadScript"), isempty);
mMenu->addAction(makeShortcutAction(DIcon("edit-script"), tr("&Edit Script"), SLOT(edit()), "ActionEditScript"), isemptyclipboard);
mMenu->addSeparator();
mMenu->addAction(makeShortcutAction(DIcon("breakpoint_toggle"), tr("Toggle &BP"), SLOT(bpToggle()), "ActionToggleBreakpointScript"), isempty);
mMenu->addAction(makeShortcutAction(DIcon("arrow-run-cursor"), tr("Ru&n until selection"), SLOT(runCursor()), "ActionRunToCursorScript"), isempty);
mMenu->addAction(makeShortcutAction(DIcon("arrow-step-into"), tr("&Step"), SLOT(step()), "ActionStepScript"), isempty);
mMenu->addAction(makeShortcutAction(DIcon("arrow-run"), tr("&Run"), SLOT(run()), "ActionRunScript"), isempty);
mMenu->addAction(makeShortcutAction(DIcon("control-stop"), tr("&Abort"), SLOT(abort()), "ActionAbortScript"), isempty);
mMenu->addAction(makeAction(DIcon("neworigin"), tr("&Continue here..."), SLOT(newIp())), isempty);
mMenu->addSeparator();
MenuBuilder* copyMenu = new MenuBuilder(this);
setupCopyMenu(copyMenu);
mMenu->addMenu(makeMenu(DIcon("copy"), tr("Copy")), copyMenu);
mMenu->addAction(makeShortcutAction(DIcon("terminal-command"), tr("E&xecute Command..."), SLOT(cmdExec()), "ActionExecuteCommandScript"));
}
bool ScriptView::isScriptCommand(QString text, QString cmd, QString & mnemonic, QString & argument)
{
mnemonic = cmd;
argument.clear();
int len = text.length();
int cmdlen = cmd.length();
if(cmdlen > len)
return false;
else if(cmdlen == len)
return (text.compare(cmd, Qt::CaseInsensitive) == 0);
else if(text.at(cmdlen) == ' ')
{
argument = text.mid(cmdlen);
return (text.left(cmdlen).compare(cmd, Qt::CaseInsensitive) == 0);
}
return false;
}
//slots
void ScriptView::add(int count, const char** lines)
{
setRowCount(count);
for(int i = 0; i < count; i++)
setCellContent(i, 1, QString(lines[i]));
BridgeFree(lines);
reloadData(); //repaint
Bridge::getBridge()->setResult(BridgeResult::ScriptAdd, 1);
}
void ScriptView::clear()
{
setRowCount(0);
mIpLine = 0;
reloadData(); //repaint
}
void ScriptView::setIp(int line)
{
mIpLine = scrollSelect(line - 1) ? line : 0;
reloadData(); //repaint
}
void ScriptView::setSelection(int line)
{
scrollSelect(line - 1);
reloadData(); //repaint
}
void ScriptView::error(int line, QString message)
{
QString title;
if(isValidIndex(line - 1, 0))
title = tr("Error on line") + title.sprintf(" %.4d!", line);
else
title = tr("Script Error!");
msg->setIcon(QMessageBox::Critical);
msg->setWindowTitle(title);
msg->setText(message);
msg->setStandardButtons(QMessageBox::Ok);
msg->setWindowIcon(DIcon("script-error"));
msg->show();
}
void ScriptView::setTitle(QString title)
{
setWindowTitle(title);
}
void ScriptView::setInfoLine(int line, QString info)
{
setCellContent(line - 1, 2, info);
reloadData(); //repaint
}
void ScriptView::openRecentFile(QString file)
{
filename = file;
DbgScriptUnload();
DbgScriptLoad(filename.toUtf8().constData());
mMRUList->addEntry(filename);
mMRUList->save();
}
void ScriptView::openFile()
{
filename = QFileDialog::getOpenFileName(this, tr("Select script"), 0, tr("Script files (*.txt *.scr);;All files (*.*)"));
if(!filename.length())
return;
filename = QDir::toNativeSeparators(filename); //convert to native path format (with backlashes)
openRecentFile(filename);
}
void ScriptView::paste()
{
filename.clear();
DbgScriptUnload();
DbgScriptLoad("x64dbg://localhost/clipboard");
}
void ScriptView::reload()
{
if(!filename.isEmpty())
openRecentFile(filename);
}
void ScriptView::unload()
{
filename.clear();
DbgScriptUnload();
}
void ScriptView::edit()
{
if(!filename.isEmpty())
if(!QDesktopServices::openUrl(QUrl("file:///" + QDir::fromNativeSeparators(filename))))
SimpleWarningBox(this, tr("Error!"), tr("File open failed! Please open the file yourself..."));
}
void ScriptView::run()
{
if(!getRowCount())
return;
DbgScriptRun(0);
}
void ScriptView::bpToggle()
{
if(!getRowCount())
return;
int selected = getInitialSelection() + 1;
if(!DbgScriptBpToggle(selected))
error(selected, tr("Error setting script breakpoint!"));
reloadData();
}
void ScriptView::runCursor()
{
if(!getRowCount())
return;
int selected = getInitialSelection() + 1;
DbgScriptRun(selected);
}
void ScriptView::step()
{
if(!getRowCount())
return;
DbgScriptStep();
}
void ScriptView::abort()
{
if(!getRowCount())
return;
DbgScriptAbort();
}
void ScriptView::cmdExec()
{
if(mCmdLineEdit->exec() != QDialog::Accepted)
return;
if(!DbgScriptCmdExec(mCmdLineEdit->editText.toUtf8().constData()))
error(0, tr("Error executing command!"));
}
void ScriptView::message(QString message)
{
msg->setIcon(QMessageBox::Information);
msg->setWindowTitle(tr("Message"));
msg->setText(message);
msg->setStandardButtons(QMessageBox::Ok);
msg->setWindowIcon(DIcon("information"));
msg->show();
}
void ScriptView::newIp()
{
if(!getRowCount())
return;
int selected = getInitialSelection() + 1;
if(isValidIndex(selected - 1, 0))
DbgScriptSetIp(selected);
}
void ScriptView::question(QString message)
{
msg->setIcon(QMessageBox::Question);
msg->setWindowTitle(tr("Question"));
msg->setText(message);
msg->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg->setWindowIcon(DIcon("question"));
msg->show();
}
void ScriptView::enableHighlighting(bool enable)
{
mEnableSyntaxHighlighting = enable;
}
void ScriptView::messageResult(int result)
{
Bridge::getBridge()->setResult(BridgeResult::ScriptMessage, result == QMessageBox::Yes);
}
void ScriptView::shutdownSlot()
{
msg->close();
unload();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/ScriptView.h | #pragma once
#include "StdTable.h"
class QMessageBox;
class MRUList;
class LineEditDialog;
class ScriptView : public StdTable
{
Q_OBJECT
public:
explicit ScriptView(StdTable* parent = 0);
// Configuration
void updateColors();
// Reimplemented Functions
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h);
void mouseDoubleClickEvent(QMouseEvent* event);
void keyPressEvent(QKeyEvent* event);
public slots:
void contextMenuSlot(const QPoint & pos);
void add(int count, const char** lines);
void clear();
void setIp(int line);
void error(int line, QString message);
void setTitle(QString title);
void setInfoLine(int line, QString info);
void openRecentFile(QString file);
void openFile();
void paste();
void reload();
void unload();
void edit();
void run();
void bpToggle();
void runCursor();
void step();
void abort();
void cmdExec();
void message(QString message);
void newIp();
void question(QString message);
void enableHighlighting(bool enable);
void messageResult(int result);
void shutdownSlot();
private:
//private functions
void setupContextMenu();
void setSelection(int line);
bool isScriptCommand(QString text, QString cmd, QString & mnemonic, QString & argument);
//private variables
int mIpLine;
bool mEnableSyntaxHighlighting;
QString filename;
MenuBuilder* mMenu;
QMessageBox* msg;
MRUList* mMRUList;
LineEditDialog* mCmdLineEdit;
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.