id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,597
|
CommentsWidget.cpp
|
rizinorg_cutter/src/widgets/CommentsWidget.cpp
|
#include "CommentsWidget.h"
#include "ui_ListDockWidget.h"
#include "core/MainWindow.h"
#include "common/Helpers.h"
#include <QMenu>
#include <QShortcut>
#include <QActionGroup>
CommentsModel::CommentsModel(QList<CommentDescription> *comments,
QList<CommentGroup> *nestedComments, QObject *parent)
: AddressableItemModel<>(parent),
comments(comments),
nestedComments(nestedComments),
nested(false)
{
}
bool CommentsModel::isNested() const
{
return nested;
}
void CommentsModel::setNested(bool nested)
{
beginResetModel();
this->nested = nested;
endResetModel();
}
RVA CommentsModel::address(const QModelIndex &index) const
{
if (isNested()) {
if (index.internalId() != 0) {
auto &group = nestedComments->at(index.parent().row());
return group.comments.at(index.row()).offset;
} else {
return nestedComments->at(index.row()).offset;
}
} else {
return comments->at(index.row()).offset;
}
}
QModelIndex CommentsModel::index(int row, int column, const QModelIndex &parent) const
{
if (!parent.isValid()) {
return createIndex(row, column, (quintptr)0);
}
return createIndex(row, column, (quintptr)(parent.row() + 1));
}
QModelIndex CommentsModel::parent(const QModelIndex &index) const
{
/* Ignore invalid indexes and root nodes */
if (!index.isValid() || index.internalId() == 0) {
return QModelIndex();
}
return this->index((int)(index.internalId() - 1), 0);
}
int CommentsModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return (isNested() ? nestedComments->size() : comments->count());
if (isNested() && parent.internalId() == 0) {
return nestedComments->at(parent.row()).comments.size();
}
return 0;
}
int CommentsModel::columnCount(const QModelIndex &) const
{
return (isNested() ? static_cast<int>(CommentsModel::NestedColumnCount)
: static_cast<int>(CommentsModel::ColumnCount));
}
QVariant CommentsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || (index.internalId() != 0 && !index.parent().isValid()))
return QVariant();
int commentIndex;
bool isSubnode;
if (index.internalId() != 0) {
/* Subnode */
commentIndex = index.parent().row();
isSubnode = true;
} else {
/* Root node */
commentIndex = index.row();
isSubnode = false;
}
QString groupName;
CommentDescription comment;
if (isNested()) {
auto &group = nestedComments->at(commentIndex);
groupName = group.name;
if (isSubnode) {
comment = group.comments.at(index.row());
}
} else {
comment = comments->at(commentIndex);
}
switch (role) {
case Qt::DisplayRole:
if (isNested()) {
if (isSubnode) {
switch (index.column()) {
case OffsetNestedColumn:
return RzAddressString(comment.offset);
case CommentNestedColumn:
return comment.name;
default:
break;
}
} else if (index.column() == OffsetNestedColumn) {
return groupName;
}
} else {
switch (index.column()) {
case CommentsModel::OffsetColumn:
return RzAddressString(comment.offset);
case CommentsModel::FunctionColumn:
return Core()->flagAt(comment.offset);
case CommentsModel::CommentColumn:
return comment.name;
default:
break;
}
}
break;
case CommentsModel::CommentDescriptionRole:
if (isNested() && index.internalId() == 0) {
break;
}
return QVariant::fromValue(comment);
default:
break;
}
return QVariant();
}
QVariant CommentsModel::headerData(int section, Qt::Orientation, int role) const
{
if (role == Qt::DisplayRole) {
if (isNested()) {
switch (section) {
case CommentsModel::OffsetNestedColumn:
return tr("Function/Offset");
case CommentsModel::CommentNestedColumn:
return tr("Comment");
default:
break;
}
} else {
switch (section) {
case CommentsModel::OffsetColumn:
return tr("Offset");
case CommentsModel::FunctionColumn:
return tr("Function");
case CommentsModel::CommentColumn:
return tr("Comment");
default:
break;
}
}
}
return QVariant();
}
CommentsProxyModel::CommentsProxyModel(CommentsModel *sourceModel, QObject *parent)
: AddressableFilterProxyModel(sourceModel, parent)
{
setFilterCaseSensitivity(Qt::CaseInsensitive);
setSortCaseSensitivity(Qt::CaseInsensitive);
}
bool CommentsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const
{
CommentsModel *srcModel = static_cast<CommentsModel *>(sourceModel());
if (srcModel->isNested()) {
// Disable filtering
return true;
}
QModelIndex index = sourceModel()->index(row, 0, parent);
auto comment = index.data(CommentsModel::CommentDescriptionRole).value<CommentDescription>();
return qhelpers::filterStringContains(comment.name, this);
}
bool CommentsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
CommentsModel *srcModel = static_cast<CommentsModel *>(sourceModel());
if (srcModel->isNested()) {
// Disable sorting
return false;
}
if (!left.isValid() || !right.isValid())
return false;
if (left.parent().isValid() || right.parent().isValid())
return false;
auto leftComment = left.data(CommentsModel::CommentDescriptionRole).value<CommentDescription>();
auto rightComment =
right.data(CommentsModel::CommentDescriptionRole).value<CommentDescription>();
switch (left.column()) {
case CommentsModel::OffsetColumn:
return leftComment.offset < rightComment.offset;
case CommentsModel::FunctionColumn:
return Core()->flagAt(leftComment.offset) < Core()->flagAt(rightComment.offset);
case CommentsModel::CommentColumn:
return leftComment.name < rightComment.name;
default:
break;
}
return false;
}
CommentsWidget::CommentsWidget(MainWindow *main)
: ListDockWidget(main),
actionHorizontal(tr("Horizontal"), this),
actionVertical(tr("Vertical"), this)
{
setWindowTitle(tr("Comments"));
setObjectName("CommentsWidget");
commentsModel = new CommentsModel(&comments, &nestedComments, this);
commentsProxyModel = new CommentsProxyModel(commentsModel, this);
setModels(commentsProxyModel);
ui->treeView->sortByColumn(CommentsModel::CommentColumn, Qt::AscendingOrder);
titleContextMenu = new QMenu(this);
auto viewTypeGroup = new QActionGroup(titleContextMenu);
actionHorizontal.setCheckable(true);
actionHorizontal.setActionGroup(viewTypeGroup);
connect(&actionHorizontal, &QAction::toggled, this, &CommentsWidget::onActionHorizontalToggled);
actionVertical.setCheckable(true);
actionVertical.setActionGroup(viewTypeGroup);
connect(&actionVertical, &QAction::toggled, this, &CommentsWidget::onActionVerticalToggled);
titleContextMenu->addActions(viewTypeGroup->actions());
actionHorizontal.setChecked(true);
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, this,
&CommentsWidget::showTitleContextMenu);
connect(Core(), &CutterCore::codeRebased, this, &CommentsWidget::refreshTree);
connect(Core(), &CutterCore::commentsChanged, this, &CommentsWidget::refreshTree);
connect(Core(), &CutterCore::refreshAll, this, &CommentsWidget::refreshTree);
}
CommentsWidget::~CommentsWidget() {}
void CommentsWidget::onActionHorizontalToggled(bool checked)
{
if (checked) {
commentsModel->setNested(false);
ui->treeView->setIndentation(8);
}
}
void CommentsWidget::onActionVerticalToggled(bool checked)
{
if (checked) {
commentsModel->setNested(true);
ui->treeView->setIndentation(20);
}
}
void CommentsWidget::showTitleContextMenu(const QPoint &pt)
{
titleContextMenu->exec(this->mapToGlobal(pt));
}
void CommentsWidget::refreshTree()
{
commentsModel->beginResetModel();
comments = Core()->getAllComments("CCu");
nestedComments.clear();
QMap<QString, size_t> nestedCommentMapping;
for (const CommentDescription &comment : comments) {
RVA offset = RVA_INVALID;
QString fcnName = Core()->nearestFlag(comment.offset, &offset);
auto nestedCommentIt = nestedCommentMapping.find(fcnName);
if (nestedCommentIt == nestedCommentMapping.end()) {
nestedCommentMapping.insert(fcnName, nestedComments.size());
nestedComments.push_back({ fcnName, offset, { comment } });
} else {
auto &commentGroup = nestedComments[nestedCommentIt.value()];
commentGroup.comments.append(comment);
}
}
commentsModel->endResetModel();
qhelpers::adjustColumns(ui->treeView, 3, 0);
}
| 9,490
|
C++
|
.cpp
| 269
| 28.223048
| 100
| 0.655589
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,598
|
ColorPicker.cpp
|
rizinorg_cutter/src/widgets/ColorPicker.cpp
|
#include "ColorPicker.h"
#include "ui_ColorPicker.h"
#include "common/Helpers.h"
#include <QPaintEvent>
#include <QPainter>
#include <QPainterPath>
#include <QMouseEvent>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
# include <QDesktopWidget>
#else
# include <QWindow>
#endif
#include <QPixmap>
#include <QCursor>
#include <QScreen>
using namespace ColorPickerHelpers;
ColorPickArea::ColorPickArea(QWidget *parent) : ColorPickerWidget(parent)
{
setMouseTracking(false);
}
void ColorPickArea::paintEvent(QPaintEvent *event)
{
QPainter p(this);
for (int x = event->rect().x(); x <= event->rect().right(); x++) {
for (int y = event->rect().y(); y <= event->rect().bottom(); y++) {
qhelpers::ColorFloat h, s, v;
QColor c = pointToColor(x, y);
c.getHsvF(&h, &s, &v);
c.setHsvF(h, s, 1);
p.setPen(c);
p.drawPoint(x, y);
}
}
p.setPen(QPen(Qt::black, 3));
QPoint curr = colorToPoint(currColor);
p.drawLine(curr - QPoint(0, 8), curr + QPoint(0, 8));
p.drawLine(curr - QPoint(8, 0), curr + QPoint(8, 0));
p.end();
}
void ColorPickArea::setColor(const QColor &c)
{
if (c == currColor) {
return;
}
QPoint p1 = colorToPoint(currColor);
QPoint p2 = colorToPoint(c);
currColor = c;
repaint(QRect(p2 - QPoint(10, 10), p2 + QPoint(10, 10)));
repaint(QRect(p1 - QPoint(10, 10), p1 + QPoint(10, 10)));
emit colorChanged(currColor);
}
ColorPickerWidget::ColorPickerWidget(QWidget *parent) : ColorPickWidgetAbstract(parent) {}
void ColorPickerWidget::mouseReleaseEvent(QMouseEvent *event)
{
mouseEvent(event);
}
void ColorPickerWidget::mousePressEvent(QMouseEvent *event)
{
mouseEvent(event);
}
void ColorPickerWidget::mouseMoveEvent(QMouseEvent *event)
{
mouseEvent(event);
}
QColor ColorPickArea::pointToColor(int x, int y) const
{
QColor color;
qhelpers::ColorFloat h, s, v, a;
currColor.getHsvF(&h, &s, &v, &a);
color.setHsvF(qreal(x) / width(), 1.0 - qreal(y) / height(), v, a);
return color;
}
QPoint ColorPickArea::colorToPoint(const QColor &color) const
{
qhelpers::ColorFloat h, s, v;
color.getHsvF(&h, &s, &v);
return QPointF(h * width(), (1.0 - s) * height()).toPoint();
}
void ColorPickerWidget::mouseEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
if (!rect().contains(pos.x(), rect().y())) {
pos.setX(rect().x() < pos.x() ? rect().right() + 1 : rect().x());
}
if (!rect().contains(rect().x(), pos.y())) {
pos.setY(rect().y() < pos.y() ? rect().bottom() + 1 : rect().y());
}
setColor(pointToColor(pos.x(), pos.y()));
}
void ColorValueBar::setColor(const QColor &c)
{
if (c == currColor) {
return;
}
currColor = c;
repaint();
emit colorChanged(currColor);
}
void ColorValueBar::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QColor color = currColor;
qhelpers::ColorFloat h, s, v;
currColor.getHsvF(&h, &s, &v);
v = 1.0 - v;
const int triangleSize = 10;
QRect barRect = rect();
barRect.setWidth(barRect.width() - triangleSize);
for (int y = barRect.y(); y <= barRect.bottom(); y++) {
color.setHsvF(h, s, 1.0 - qreal(y) / height());
p.setPen(color);
p.drawLine(barRect.x(), y, barRect.right(), y);
}
QRectF triangleRect =
QRectF(barRect.right(), v * height() - triangleSize / 2, triangleSize, triangleSize);
QPainterPath path;
path.moveTo(triangleRect.left(), triangleRect.top() + triangleRect.height() / 2);
path.lineTo(triangleRect.topRight());
path.lineTo(triangleRect.bottomRight());
path.lineTo(triangleRect.left(), triangleRect.top() + triangleRect.height() / 2);
p.fillPath(path, palette().text().color());
p.end();
QWidget::paintEvent(event);
}
QColor ColorValueBar::pointToColor(int x, int y) const
{
Q_UNUSED(x)
QColor color = currColor;
qhelpers::ColorFloat h, s, v, a;
color.getHsvF(&h, &s, &v, &a);
color.setHsvF(h, s, 1.0 - qreal(y) / height(), a);
return color;
}
QPoint ColorValueBar::colorToPoint(const QColor &color) const
{
qhelpers::ColorFloat h, s, v;
color.getHsvF(&h, &s, &v);
return QPoint(rect().x(), int((1.0 - v) * height()));
}
ColorPicker::ColorPicker(QWidget *parent)
: ColorPickWidgetAbstract(parent), ui(new Ui::ColorPicker), pickingFromScreen(false)
{
ui->setupUi(this);
connect(ui->colorPickArea, &ColorPickArea::colorChanged, this, &ColorPicker::setColor);
connect(ui->valuePickBar, &ColorValueBar::colorChanged, this, &ColorPicker::setColor);
connect(ui->alphaChannelBar, &AlphaChannelBar::colorChanged, this,
[this](const QColor &color) { emit colorChanged(color); });
connect(this, &ColorPicker::colorChanged, ui->colorPickArea, &ColorPickArea::setColor);
connect(this, &ColorPicker::colorChanged, ui->valuePickBar, &ColorValueBar::setColor);
connect(this, &ColorPicker::colorChanged, ui->colorShow, &ColorShowWidget::setColor);
connect(this, &ColorPicker::colorChanged, ui->alphaChannelBar, &AlphaChannelBar::setColor);
connect(ui->hueSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&ColorPicker::colorChannelChanged);
connect(ui->satSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&ColorPicker::colorChannelChanged);
connect(ui->valSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&ColorPicker::colorChannelChanged);
connect(ui->redSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&ColorPicker::colorChannelChanged);
connect(ui->blueSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&ColorPicker::colorChannelChanged);
connect(ui->greenSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&ColorPicker::colorChannelChanged);
connect(ui->hexLineEdit, &QLineEdit::textChanged, this, &ColorPicker::colorChannelChanged);
connect(ui->pickColorFromScreenButton, &QPushButton::clicked, this,
&ColorPicker::startPickingFromScreen);
}
ColorPicker::~ColorPicker()
{
if (pickingFromScreen) {
setColor(getColorAtMouse());
stopPickingFromScreen();
}
}
void ColorPicker::setColor(const QColor &color)
{
updateColor(color);
emit colorChanged(currColor);
}
void ColorPicker::colorChannelChanged()
{
QString txt = ui->hexLineEdit->text();
// Regex pattern below mimics the behaviour of former RegExp::exactMatch()
if (!QRegularExpression("\\A(?:#[0-9a-fA-F]{6})\\z").match(txt).hasMatch()) {
return;
}
QColor hexColor = txt;
int h, s, v;
h = ui->hueSpinBox->value();
s = ui->satSpinBox->value();
v = ui->valSpinBox->value();
QColor hsvColor;
hsvColor.setHsv(h, s, v);
int r, g, b;
r = ui->redSpinBox->value();
g = ui->greenSpinBox->value();
b = ui->blueSpinBox->value();
QColor rgbColor;
rgbColor.setRgb(r, g, b);
if (hexColor.isValid() && hexColor != currColor) {
setColor(hexColor);
} else if (rgbColor.isValid() && rgbColor != currColor) {
setColor(rgbColor);
} else if (hsvColor.isValid() && hsvColor != currColor) {
setColor(hsvColor);
}
}
void ColorPicker::updateColor(const QColor &color)
{
QSignalBlocker s0(ui->redSpinBox);
QSignalBlocker s1(ui->blueSpinBox);
QSignalBlocker s2(ui->greenSpinBox);
QSignalBlocker s3(ui->valSpinBox);
QSignalBlocker s4(ui->satSpinBox);
QSignalBlocker s5(ui->hueSpinBox);
QSignalBlocker s6(ui->hexLineEdit);
QSignalBlocker s7(ui->alphaChannelBar);
QSignalBlocker s8(ui->colorPickArea);
QSignalBlocker s9(ui->colorShow);
QSignalBlocker s10(ui->valuePickBar);
currColor = color;
ui->hexLineEdit->setText(currColor.name());
int h, s, v;
currColor.getHsv(&h, &s, &v);
ui->hueSpinBox->setValue(h);
ui->satSpinBox->setValue(s);
ui->valSpinBox->setValue(v);
int r, g, b;
currColor.getRgb(&r, &g, &b);
ui->redSpinBox->setValue(r);
ui->greenSpinBox->setValue(g);
ui->blueSpinBox->setValue(b);
ui->valuePickBar->setColor(color);
ui->colorPickArea->setColor(color);
ui->colorShow->setColor(color);
ui->alphaChannelBar->setColor(color);
}
void ColorPicker::startPickingFromScreen()
{
if (!pickingFromScreen) {
setMouseTracking(true);
pickingFromScreen = true;
bufferColor = currColor;
}
}
void ColorPicker::mouseReleaseEvent(QMouseEvent *event)
{
if (pickingFromScreen) {
setColor(getColorAtMouse());
pickingFromScreen = false;
setMouseTracking(false);
}
QWidget::mouseReleaseEvent(event);
}
void ColorPicker::mouseMoveEvent(QMouseEvent *event)
{
if (pickingFromScreen) {
updateColor(getColorAtMouse());
}
QWidget::mouseMoveEvent(event);
}
QColor ColorPicker::getColorAtMouse()
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
const QDesktopWidget *desktop = QApplication::desktop();
const QPixmap pixmap =
QGuiApplication::screens()
.at(desktop->screenNumber())
->grabWindow(desktop->winId(), QCursor::pos().x(), QCursor::pos().y(), 1, 1);
return QColor(pixmap.toImage().pixel(0, 0));
#else
QPoint pos = QCursor::pos();
auto screen = QGuiApplication::screenAt(pos);
if (!screen) {
screen = QGuiApplication::primaryScreen();
}
if (screen) {
auto screenRelativePos = pos - screen->geometry().topLeft();
const QPixmap pixmap =
screen->grabWindow(0, screenRelativePos.x(), screenRelativePos.y(), 1, 1);
return QColor(pixmap.toImage().pixel(0, 0));
}
return QColorConstants::Red;
#endif
}
bool ColorPicker::isPickingFromScreen() const
{
return pickingFromScreen;
}
void ColorPicker::setAlphaEnabled(bool enabled)
{
ui->alphaChannelBar->setVisible(enabled);
}
void ColorPicker::stopPickingFromScreen()
{
if (pickingFromScreen) {
pickingFromScreen = false;
updateColor(bufferColor);
releaseMouse();
setMouseTracking(false);
}
}
ColorShowWidget::ColorShowWidget(QWidget *parent) : ColorPickWidgetAbstract(parent) {}
void ColorShowWidget::setColor(const QColor &c)
{
currColor = c;
repaint();
}
void ColorShowWidget::paintEvent(QPaintEvent *event)
{
QPainter p(this);
const int miniRectWidth = rect().width() / 2;
for (int y = rect().topLeft().ry(); y < rect().bottomRight().ry(); y++) {
for (int x = rect().topLeft().rx(); x < rect().bottomRight().rx(); x++) {
p.setPen(((x % miniRectWidth) / (miniRectWidth / 2))
== ((y % miniRectWidth) / (miniRectWidth / 2))
? Qt::white
: Qt::black);
p.drawPoint(x, y);
}
}
p.setPen(currColor);
p.setBrush(QBrush(currColor));
p.drawRect(event->rect());
p.end();
}
void AlphaChannelBar::setColor(const QColor &c)
{
if (c == currColor) {
return;
}
currColor = c;
repaint();
emit colorChanged(currColor);
}
void AlphaChannelBar::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QRect barRect = rect();
qhelpers::ColorFloat h, s, v, a;
currColor.getHsvF(&h, &s, &v, &a);
a = 1.0 - a;
const int triangleSize = 10;
barRect.setWidth(barRect.width() - triangleSize);
const int miniRectWidth = barRect.width() / 2;
for (int y = barRect.topLeft().ry(); y < barRect.bottomRight().ry(); y++) {
for (int x = barRect.topLeft().rx(); x < barRect.bottomRight().rx(); x++) {
p.setPen(((x % miniRectWidth) / (miniRectWidth / 2))
== ((y % miniRectWidth) / (miniRectWidth / 2))
? Qt::white
: Qt::black);
p.drawPoint(x, y);
p.setPen(pointToColor(x, y));
p.drawPoint(x, y);
}
}
QRectF triangleRect =
QRectF(barRect.right(), a * height() - triangleSize / 2, triangleSize, triangleSize);
QPainterPath path;
path.moveTo(triangleRect.left(), triangleRect.top() + triangleRect.height() / 2);
path.lineTo(triangleRect.topRight());
path.lineTo(triangleRect.bottomRight());
path.lineTo(triangleRect.left(), triangleRect.top() + triangleRect.height() / 2);
p.fillPath(path, palette().text().color());
p.end();
QWidget::paintEvent(event);
}
QColor AlphaChannelBar::pointToColor(int x, int y) const
{
Q_UNUSED(x)
QColor color = currColor;
qhelpers::ColorFloat h, s, v;
color.getHsvF(&h, &s, &v);
color.setHsvF(h, s, v, 1.0 - qreal(y) / height());
return color;
}
QPoint AlphaChannelBar::colorToPoint(const QColor &) const
{
return QPoint();
}
| 13,027
|
C++
|
.cpp
| 380
| 28.902632
| 98
| 0.646769
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,599
|
HeapDockWidget.cpp
|
rizinorg_cutter/src/widgets/HeapDockWidget.cpp
|
#include "HeapDockWidget.h"
#include "ui_HeapDockWidget.h"
#include "widgets/GlibcHeapWidget.h"
HeapDockWidget::HeapDockWidget(MainWindow *main)
: CutterDockWidget(main), ui(new Ui::HeapDockWidget), main(main)
{
ui->setupUi(this);
ui->allocatorSelector->addItem("Glibc Heap");
ui->verticalLayout->setContentsMargins(0, 0, 0, 0);
connect<void (QComboBox::*)(int)>(ui->allocatorSelector, &QComboBox::currentIndexChanged, this,
&HeapDockWidget::onAllocatorSelected);
// select Glibc heap by default
onAllocatorSelected(0);
}
HeapDockWidget::~HeapDockWidget()
{
delete ui;
}
void HeapDockWidget::onAllocatorSelected(int index)
{
if (index >= AllocatorCount)
return;
// remove the current heap widget from layout
if (currentHeapWidget) {
ui->verticalLayout->removeWidget(currentHeapWidget);
delete currentHeapWidget;
}
// change widget depending upon selected allocator
if (index == Glibc) {
currentHeapWidget = new GlibcHeapWidget(main, this);
}
ui->verticalLayout->addWidget(currentHeapWidget);
}
| 1,136
|
C++
|
.cpp
| 33
| 29.121212
| 99
| 0.706849
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,600
|
HeapBinsGraphView.cpp
|
rizinorg_cutter/src/widgets/HeapBinsGraphView.cpp
|
#include <Configuration.h>
#include <dialogs/GlibcHeapInfoDialog.h>
#include "HeapBinsGraphView.h"
HeapBinsGraphView::HeapBinsGraphView(QWidget *parent, RzHeapBin *bin, MainWindow *main)
: SimpleTextGraphView(parent, main), heapBin(bin)
{
chunkInfoAction = new QAction(tr("Detailed Chunk Info"), this);
addressableItemContextMenu.addAction(chunkInfoAction);
addAction(chunkInfoAction);
connect(chunkInfoAction, &QAction::triggered, this, &HeapBinsGraphView::viewChunkInfo);
bits = Core()->getArchBits();
enableAddresses(true);
}
void HeapBinsGraphView::viewChunkInfo()
{
GlibcHeapInfoDialog heapInfoDialog(selectedBlock, QString(), this);
heapInfoDialog.exec();
}
void HeapBinsGraphView::loadCurrentGraph()
{
blockContent.clear();
blocks.clear();
RzListIter *iter;
RzHeapChunkListItem *item;
QVector<GraphHeapChunk> chunks;
// if the bin is a fastbin or not
bool singleLinkedBin = QString(heapBin->type) == QString("Fast")
|| QString(heapBin->type) == QString("Tcache");
// store info about the chunks in a vector for easy access
CutterRzListForeach (heapBin->chunks, iter, RzHeapChunkListItem, item) {
GraphHeapChunk graphHeapChunk;
graphHeapChunk.addr = item->addr;
RzHeapChunkSimple *chunkInfo = Core()->getHeapChunk(item->addr);
if (!chunkInfo) {
break;
}
QString content = "Chunk @ " + RzAddressString(chunkInfo->addr) + "\nSize: "
+ RzHexString(chunkInfo->size) + "\nFd: " + RzAddressString(chunkInfo->fd);
// fastbins lack bk pointer
if (!singleLinkedBin) {
content += "\nBk: " + RzAddressString(chunkInfo->bk);
}
graphHeapChunk.fd = chunkInfo->fd;
graphHeapChunk.bk = chunkInfo->bk;
graphHeapChunk.content = content;
chunks.append(graphHeapChunk);
free(chunkInfo);
}
// fast and tcache bins have single linked list and other bins have double linked list
if (singleLinkedBin) {
display_single_linked_list(chunks);
} else {
display_double_linked_list(chunks);
}
cleanupEdges(blocks);
computeGraphPlacement();
}
void HeapBinsGraphView::display_single_linked_list(QVector<GraphHeapChunk> chunks)
{
bool tcache = QString(heapBin->type) == QString("Tcache");
int ptrSize = bits;
// add the graph block for the bin
GraphLayout::GraphBlock gbBin;
gbBin.entry = 1;
gbBin.edges.emplace_back(heapBin->fd);
QString content = tr(heapBin->type) + tr("bin ") + QString::number(heapBin->bin_num);
if (tcache) {
content += "\nEntry: " + RzAddressString(heapBin->fd);
} else {
content += "\nFd: " + RzAddressString(heapBin->fd);
}
addBlock(gbBin, content);
// add the graph blocks for the chunks
for (int i = 0; i < chunks.size(); i++) {
GraphLayout::GraphBlock gbChunk;
gbChunk.entry = chunks[i].addr;
if (tcache && chunks[i].fd) {
// base_address = address - 2 * PTR_SIZE
gbChunk.edges.emplace_back(chunks[i].fd - 2 * ptrSize);
} else {
gbChunk.edges.emplace_back(chunks[i].fd);
}
if (i == chunks.size() - 1 && heapBin->message) {
chunks[i].content += "\n" + QString(heapBin->message);
}
addBlock(gbChunk, chunks[i].content, chunks[i].addr);
}
// add the END block if no message
if (!heapBin->message) {
GraphLayout::GraphBlock gbEnd;
gbEnd.entry = 0;
addBlock(gbEnd, "END", 0);
}
}
void HeapBinsGraphView::display_double_linked_list(QVector<GraphHeapChunk> chunks)
{
// add the graph block for the bin
GraphLayout::GraphBlock gbBin;
gbBin.entry = heapBin->addr;
gbBin.edges.emplace_back(heapBin->fd);
gbBin.edges.emplace_back(heapBin->bk);
QString content = tr(heapBin->type) + tr("bin ") + QString::number(heapBin->bin_num) + tr(" @ ")
+ RzAddressString(heapBin->addr);
content += "\nFd: " + RzAddressString(heapBin->fd);
content += "\nBk: " + RzAddressString(heapBin->bk);
addBlock(gbBin, content, heapBin->addr);
// add the blocks for the chunks
for (int i = 0; i < chunks.size(); i++) {
GraphLayout::GraphBlock gbChunk;
gbChunk.entry = chunks[i].addr;
gbChunk.edges.emplace_back(chunks[i].fd);
gbChunk.edges.emplace_back(chunks[i].bk);
// if last chunk and there is message then show it in the chunk
if (i == chunks.size() - 1 && heapBin->message) {
chunks[i].content += "\n" + QString(heapBin->message);
}
addBlock(gbChunk, chunks[i].content, chunks[i].addr);
}
}
// overriding this function from SimpleTextGraphView to support multiline text in graph block
// most code is shared from that implementation
void HeapBinsGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, bool interactive)
{
QRectF blockRect(block.x, block.y, block.width, block.height);
p.setPen(Qt::black);
p.setBrush(Qt::gray);
p.setFont(Config()->getFont());
p.drawRect(blockRect);
// Render node
auto &content = blockContent[block.entry];
p.setPen(QColor(0, 0, 0, 0));
p.setBrush(QColor(0, 0, 0, 100));
p.setPen(QPen(graphNodeColor, 1));
bool blockSelected = interactive && (block.entry == selectedBlock);
if (blockSelected) {
p.setBrush(disassemblySelectedBackgroundColor);
} else {
p.setBrush(disassemblyBackgroundColor);
}
// Draw basic block background
p.drawRect(blockRect);
// Stop rendering text when it's too small
auto transform = p.combinedTransform();
QRect screenChar = transform.mapRect(QRect(0, 0, ACharWidth, charHeight));
if (screenChar.width() < Config()->getGraphMinFontSize()) {
return;
}
p.setPen(palette().color(QPalette::WindowText));
// Render node text
// the only change from SimpleTextGraphView implementation
p.drawText(blockRect, Qt::AlignCenter, content.text);
}
// overriding this function to support multiline text in graph blocks
void HeapBinsGraphView::addBlock(GraphLayout::GraphBlock block, const QString &text, RVA address)
{
auto &content = blockContent[block.entry];
content.text = text;
content.address = address;
int height = 1;
double width = 0;
// split text into different lines
auto lines = text.split("\n", CUTTER_QT_SKIP_EMPTY_PARTS);
// width of the block is the maximum width of a line
for (QString &line : lines) {
width = std::max(mFontMetrics->width(line), width);
}
block.width = static_cast<int>(width + padding);
block.height = (height * charHeight) * lines.length() + padding;
GraphView::addBlock(std::move(block));
}
// overriding to support detailed heap info action in context menu
void HeapBinsGraphView::blockContextMenuRequested(GraphView::GraphBlock &block,
QContextMenuEvent *event, QPoint /*pos*/)
{
if (haveAddresses) {
const auto &content = blockContent[block.entry];
selectedBlock = content.address;
addressableItemContextMenu.setTarget(content.address, content.text);
QPoint pos = event->globalPos();
if (event->reason() != QContextMenuEvent::Mouse) {
QPoint blockPosition(block.x + block.width / 2, block.y + block.height / 2);
blockPosition = logicalToViewCoordinates(blockPosition);
if (viewport()->rect().contains(blockPosition)) {
pos = mapToGlobal(blockPosition);
}
}
addressableItemContextMenu.exec(pos);
event->accept();
}
}
| 7,726
|
C++
|
.cpp
| 190
| 34.168421
| 100
| 0.660843
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,601
|
EntrypointWidget.cpp
|
rizinorg_cutter/src/widgets/EntrypointWidget.cpp
|
#include "EntrypointWidget.h"
#include "ui_EntrypointWidget.h"
#include "core/MainWindow.h"
#include "common/Helpers.h"
#include <QTreeWidget>
#include <QPen>
/*
* Entrypoint Widget
*/
EntrypointWidget::EntrypointWidget(MainWindow *main)
: CutterDockWidget(main), ui(new Ui::EntrypointWidget)
{
ui->setupUi(this);
setScrollMode();
connect(Core(), &CutterCore::codeRebased, this, &EntrypointWidget::fillEntrypoint);
connect(Core(), &CutterCore::refreshAll, this, &EntrypointWidget::fillEntrypoint);
}
EntrypointWidget::~EntrypointWidget() {}
void EntrypointWidget::fillEntrypoint()
{
ui->entrypointTreeWidget->clear();
for (const EntrypointDescription &i : Core()->getAllEntrypoint()) {
QTreeWidgetItem *item = new QTreeWidgetItem();
item->setText(0, RzAddressString(i.vaddr));
item->setText(1, i.type);
item->setData(0, Qt::UserRole, QVariant::fromValue(i));
ui->entrypointTreeWidget->addTopLevelItem(item);
}
qhelpers::adjustColumns(ui->entrypointTreeWidget, 0, 10);
}
void EntrypointWidget::setScrollMode()
{
qhelpers::setVerticalScrollMode(ui->entrypointTreeWidget);
}
void EntrypointWidget::on_entrypointTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
if (column < 0)
return;
EntrypointDescription ep = item->data(0, Qt::UserRole).value<EntrypointDescription>();
Core()->seekAndShow(ep.vaddr);
}
| 1,432
|
C++
|
.cpp
| 41
| 31.146341
| 99
| 0.737491
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,602
|
AddressableItemContextMenu.cpp
|
rizinorg_cutter/src/menus/AddressableItemContextMenu.cpp
|
#include "AddressableItemContextMenu.h"
#include "dialogs/XrefsDialog.h"
#include "MainWindow.h"
#include "dialogs/CommentsDialog.h"
#include <QtCore>
#include <QShortcut>
#include <QJsonArray>
#include <QClipboard>
#include <QApplication>
#include <QPushButton>
AddressableItemContextMenu::AddressableItemContextMenu(QWidget *parent, MainWindow *mainWindow)
: QMenu(parent), mainWindow(mainWindow)
{
actionShowInMenu = new QAction(tr("Show in"), this);
actionCopyAddress = new QAction(tr("Copy address"), this);
actionShowXrefs = new QAction(tr("Show X-Refs"), this);
actionAddcomment = new QAction(tr("Add comment"), this);
connect(actionCopyAddress, &QAction::triggered, this,
&AddressableItemContextMenu::onActionCopyAddress);
actionCopyAddress->setShortcuts({ Qt::CTRL | Qt::SHIFT | Qt::Key_C });
actionCopyAddress->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut);
connect(actionShowXrefs, &QAction::triggered, this,
&AddressableItemContextMenu::onActionShowXrefs);
actionShowXrefs->setShortcut({ Qt::Key_X });
actionShowXrefs->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut);
connect(actionAddcomment, &QAction::triggered, this,
&AddressableItemContextMenu::onActionAddComment);
actionAddcomment->setShortcut({ Qt::Key_Semicolon });
actionAddcomment->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut);
addAction(actionShowInMenu);
addAction(actionCopyAddress);
addAction(actionShowXrefs);
addSeparator();
addAction(actionAddcomment);
addSeparator();
pluginMenu = mainWindow->getContextMenuExtensions(MainWindow::ContextMenuType::Addressable);
pluginMenuAction = addMenu(pluginMenu);
addSeparator();
setHasTarget(hasTarget);
connect(this, &QMenu::aboutToShow, this, &AddressableItemContextMenu::aboutToShowSlot);
}
AddressableItemContextMenu::~AddressableItemContextMenu() {}
void AddressableItemContextMenu::setWholeFunction(bool wholeFunciton)
{
this->wholeFunction = wholeFunciton;
}
void AddressableItemContextMenu::setOffset(RVA offset)
{
setTarget(offset);
}
void AddressableItemContextMenu::setTarget(RVA offset, QString name)
{
this->offset = offset;
this->name = name;
setHasTarget(true);
}
void AddressableItemContextMenu::clearTarget()
{
setHasTarget(false);
}
void AddressableItemContextMenu::onActionCopyAddress()
{
auto clipboard = QApplication::clipboard();
clipboard->setText(RzAddressString(offset));
}
void AddressableItemContextMenu::onActionShowXrefs()
{
emit xrefsTriggered();
XrefsDialog dialog(mainWindow, true);
QString tmpName = name;
if (name.isEmpty()) {
name = RzAddressString(offset);
}
dialog.fillRefsForAddress(offset, name, wholeFunction);
dialog.exec();
}
void AddressableItemContextMenu::onActionAddComment()
{
CommentsDialog::addOrEditComment(offset, this);
}
void AddressableItemContextMenu::aboutToShowSlot()
{
if (actionShowInMenu->menu()) {
actionShowInMenu->menu()->deleteLater();
}
actionShowInMenu->setMenu(mainWindow->createShowInMenu(this, offset));
pluginMenuAction->setVisible(!pluginMenu->isEmpty());
for (QAction *pluginAction : pluginMenu->actions()) {
pluginAction->setData(QVariant::fromValue(offset));
}
}
void AddressableItemContextMenu::setHasTarget(bool hasTarget)
{
this->hasTarget = hasTarget;
actionShowInMenu->setEnabled(hasTarget);
actionCopyAddress->setEnabled(hasTarget);
actionShowXrefs->setEnabled(hasTarget);
actionAddcomment->setEnabled(hasTarget);
}
| 3,668
|
C++
|
.cpp
| 99
| 33.141414
| 96
| 0.768104
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,603
|
DisassemblyContextMenu.cpp
|
rizinorg_cutter/src/menus/DisassemblyContextMenu.cpp
|
#include "DisassemblyContextMenu.h"
#include "dialogs/preferences/PreferencesDialog.h"
#include "dialogs/EditInstructionDialog.h"
#include "dialogs/CommentsDialog.h"
#include "dialogs/FlagDialog.h"
#include "dialogs/GlobalVariableDialog.h"
#include "dialogs/XrefsDialog.h"
#include "dialogs/EditVariablesDialog.h"
#include "dialogs/SetToDataDialog.h"
#include "dialogs/EditFunctionDialog.h"
#include "dialogs/EditStringDialog.h"
#include "dialogs/BreakpointsDialog.h"
#include "MainWindow.h"
#include <QtCore>
#include <QShortcut>
#include <QJsonArray>
#include <QClipboard>
#include <QApplication>
#include <QPushButton>
#include <QInputDialog>
DisassemblyContextMenu::DisassemblyContextMenu(QWidget *parent, MainWindow *mainWindow)
: QMenu(parent),
offset(0),
canCopy(false),
mainWindow(mainWindow),
actionEditInstruction(this),
actionNopInstruction(this),
actionJmpReverse(this),
actionEditBytes(this),
actionCopy(this),
actionCopyAddr(this),
actionCopyInstrBytes(this),
actionAddComment(this),
actionAnalyzeFunction(this),
actionEditFunction(this),
actionRename(this),
actionGlobalVar(this),
actionSetFunctionVarTypes(this),
actionXRefs(this),
actionXRefsForVariables(this),
actionDisplayOptions(this),
actionDeleteComment(this),
actionDeleteFlag(this),
actionDeleteFunction(this),
actionSetBaseBinary(this),
actionSetBaseOctal(this),
actionSetBaseDecimal(this),
actionSetBaseHexadecimal(this),
actionSetBasePort(this),
actionSetBaseIPAddr(this),
actionSetBaseSyscall(this),
actionSetBaseString(this),
actionSetBits16(this),
actionSetBits32(this),
actionSetBits64(this),
actionContinueUntil(this),
actionSetPC(this),
actionAddBreakpoint(this),
actionAdvancedBreakpoint(this),
actionSetToCode(this),
actionSetAsStringAuto(this),
actionSetAsStringRemove(this),
actionSetAsStringAdvanced(this),
actionSetToDataEx(this),
actionSetToDataByte(this),
actionSetToDataWord(this),
actionSetToDataDword(this),
actionSetToDataQword(this),
showInSubmenu(this)
{
initAction(&actionCopy, tr("Copy"), SLOT(on_actionCopy_triggered()), getCopySequence());
addAction(&actionCopy);
initAction(&actionCopyAddr, tr("Copy address"), SLOT(on_actionCopyAddr_triggered()),
getCopyAddressSequence());
addAction(&actionCopyAddr);
initAction(&actionCopyInstrBytes, tr("Copy instruction bytes"),
SLOT(on_actionCopyInstrBytes_triggered()), getCopyInstrBytesSequence());
addAction(&actionCopyInstrBytes);
initAction(&showInSubmenu, tr("Show in"), nullptr);
addAction(&showInSubmenu);
copySeparator = addSeparator();
initAction(&actionAddComment, tr("Add Comment"), SLOT(on_actionAddComment_triggered()),
getCommentSequence());
addAction(&actionAddComment);
initAction(&actionSetFunctionVarTypes, tr("Re-type Local Variables"),
SLOT(on_actionSetFunctionVarTypes_triggered()), getRetypeSequence());
addAction(&actionSetFunctionVarTypes);
initAction(&actionEditFunction, tr("Edit function"), SLOT(on_actionEditFunction_triggered()),
getEditFunctionSequence());
addAction(&actionEditFunction);
initAction(&actionDeleteComment, tr("Delete comment"),
SLOT(on_actionDeleteComment_triggered()));
addAction(&actionDeleteComment);
initAction(&actionDeleteFlag, tr("Delete flag"), SLOT(on_actionDeleteFlag_triggered()));
addAction(&actionDeleteFlag);
initAction(&actionDeleteFunction, tr("Undefine function"),
SLOT(on_actionDeleteFunction_triggered()), getUndefineFunctionSequence());
addAction(&actionDeleteFunction);
initAction(&actionAnalyzeFunction, tr("Define function here"),
SLOT(on_actionAnalyzeFunction_triggered()), getDefineNewFunctionSequence());
addAction(&actionAnalyzeFunction);
addSeparator();
addAddAtMenu();
addSetBaseMenu();
addSetBitsMenu();
structureOffsetMenu = addMenu(tr("Structure offset"));
connect(structureOffsetMenu, &QMenu::triggered, this,
&DisassemblyContextMenu::on_actionStructureOffsetMenu_triggered);
addSetAsMenu();
addSeparator();
initAction(&actionXRefs, tr("Show X-Refs"), SLOT(on_actionXRefs_triggered()),
getXRefSequence());
addAction(&actionXRefs);
initAction(&actionXRefsForVariables, tr("X-Refs for local variables"),
SLOT(on_actionXRefsForVariables_triggered()), QKeySequence(Qt::SHIFT | Qt::Key_X));
addAction(&actionXRefsForVariables);
initAction(&actionDisplayOptions, tr("Show Options"), SLOT(on_actionDisplayOptions_triggered()),
getDisplayOptionsSequence());
addSeparator();
addEditMenu();
addSeparator();
addBreakpointMenu();
addDebugMenu();
addSeparator();
if (mainWindow) {
pluginMenu = mainWindow->getContextMenuExtensions(MainWindow::ContextMenuType::Disassembly);
pluginActionMenuAction = addMenu(pluginMenu);
}
addSeparator();
connect(this, &DisassemblyContextMenu::aboutToShow, this,
&DisassemblyContextMenu::aboutToShowSlot);
connect(this, &DisassemblyContextMenu::aboutToHide, this,
&DisassemblyContextMenu::aboutToHideSlot);
}
DisassemblyContextMenu::~DisassemblyContextMenu() {}
QWidget *DisassemblyContextMenu::parentForDialog()
{
return parentWidget();
}
void DisassemblyContextMenu::addAddAtMenu()
{
setAsMenu = addMenu(tr("Add at..."));
initAction(&actionRename, tr("Rename or add flag"), SLOT(on_actionRename_triggered()),
getRenameSequence());
setAsMenu->addAction(&actionRename);
initAction(&actionGlobalVar, tr("Modify or add global variable"),
SLOT(on_actionGlobalVar_triggered()), getGlobalVarSequence());
setAsMenu->addAction(&actionGlobalVar);
}
void DisassemblyContextMenu::addSetBaseMenu()
{
setBaseMenu = addMenu(tr("Set base of immediate value to.."));
initAction(&actionSetBaseBinary, tr("Binary"));
setBaseMenu->addAction(&actionSetBaseBinary);
connect(&actionSetBaseBinary, &QAction::triggered, this, [this] { setBase("b"); });
initAction(&actionSetBaseOctal, tr("Octal"));
setBaseMenu->addAction(&actionSetBaseOctal);
connect(&actionSetBaseOctal, &QAction::triggered, this, [this] { setBase("o"); });
initAction(&actionSetBaseDecimal, tr("Decimal"));
setBaseMenu->addAction(&actionSetBaseDecimal);
connect(&actionSetBaseDecimal, &QAction::triggered, this, [this] { setBase("d"); });
initAction(&actionSetBaseHexadecimal, tr("Hexadecimal"));
setBaseMenu->addAction(&actionSetBaseHexadecimal);
connect(&actionSetBaseHexadecimal, &QAction::triggered, this, [this] { setBase("h"); });
initAction(&actionSetBasePort, tr("Network Port"));
setBaseMenu->addAction(&actionSetBasePort);
connect(&actionSetBasePort, &QAction::triggered, this, [this] { setBase("p"); });
initAction(&actionSetBaseIPAddr, tr("IP Address"));
setBaseMenu->addAction(&actionSetBaseIPAddr);
connect(&actionSetBaseIPAddr, &QAction::triggered, this, [this] { setBase("i"); });
initAction(&actionSetBaseSyscall, tr("Syscall"));
setBaseMenu->addAction(&actionSetBaseSyscall);
connect(&actionSetBaseSyscall, &QAction::triggered, this, [this] { setBase("S"); });
initAction(&actionSetBaseString, tr("String"));
setBaseMenu->addAction(&actionSetBaseString);
connect(&actionSetBaseString, &QAction::triggered, this, [this] { setBase("s"); });
}
void DisassemblyContextMenu::addSetBitsMenu()
{
setBitsMenu = addMenu(tr("Set current bits to..."));
initAction(&actionSetBits16, "16");
setBitsMenu->addAction(&actionSetBits16);
connect(&actionSetBits16, &QAction::triggered, this, [this] { setBits(16); });
initAction(&actionSetBits32, "32");
setBitsMenu->addAction(&actionSetBits32);
connect(&actionSetBits32, &QAction::triggered, this, [this] { setBits(32); });
initAction(&actionSetBits64, "64");
setBitsMenu->addAction(&actionSetBits64);
connect(&actionSetBits64, &QAction::triggered, this, [this] { setBits(64); });
}
void DisassemblyContextMenu::addSetAsMenu()
{
setAsMenu = addMenu(tr("Set as..."));
initAction(&actionSetToCode, tr("Code"), SLOT(on_actionSetToCode_triggered()),
getSetToCodeSequence());
setAsMenu->addAction(&actionSetToCode);
setAsString = setAsMenu->addMenu(tr("String..."));
initAction(&actionSetAsStringAuto, tr("Auto-detect"), SLOT(on_actionSetAsString_triggered()),
getSetAsStringSequence());
initAction(&actionSetAsStringRemove, tr("Remove"),
SLOT(on_actionSetAsStringRemove_triggered()));
initAction(&actionSetAsStringAdvanced, tr("Advanced"),
SLOT(on_actionSetAsStringAdvanced_triggered()), getSetAsStringAdvanced());
setAsString->addAction(&actionSetAsStringAuto);
setAsString->addAction(&actionSetAsStringRemove);
setAsString->addAction(&actionSetAsStringAdvanced);
addSetToDataMenu();
}
void DisassemblyContextMenu::addSetToDataMenu()
{
setToDataMenu = setAsMenu->addMenu(tr("Data..."));
initAction(&actionSetToDataByte, tr("Byte"));
setToDataMenu->addAction(&actionSetToDataByte);
connect(&actionSetToDataByte, &QAction::triggered, this, [this] { setToData(1); });
initAction(&actionSetToDataWord, tr("Word"));
setToDataMenu->addAction(&actionSetToDataWord);
connect(&actionSetToDataWord, &QAction::triggered, this, [this] { setToData(2); });
initAction(&actionSetToDataDword, tr("Dword"));
setToDataMenu->addAction(&actionSetToDataDword);
connect(&actionSetToDataDword, &QAction::triggered, this, [this] { setToData(4); });
initAction(&actionSetToDataQword, tr("Qword"));
setToDataMenu->addAction(&actionSetToDataQword);
connect(&actionSetToDataQword, &QAction::triggered, this, [this] { setToData(8); });
initAction(&actionSetToDataEx, "...", SLOT(on_actionSetToDataEx_triggered()),
getSetToDataExSequence());
setToDataMenu->addAction(&actionSetToDataEx);
auto switchAction = new QAction(this);
initAction(switchAction, "Switch Data", SLOT(on_actionSetToData_triggered()),
getSetToDataSequence());
}
void DisassemblyContextMenu::addEditMenu()
{
editMenu = addMenu(tr("Edit"));
initAction(&actionEditInstruction, tr("Instruction"),
SLOT(on_actionEditInstruction_triggered()));
editMenu->addAction(&actionEditInstruction);
initAction(&actionNopInstruction, tr("Nop Instruction"),
SLOT(on_actionNopInstruction_triggered()));
editMenu->addAction(&actionNopInstruction);
initAction(&actionEditBytes, tr("Bytes"), SLOT(on_actionEditBytes_triggered()));
editMenu->addAction(&actionEditBytes);
initAction(&actionJmpReverse, tr("Reverse Jump"), SLOT(on_actionJmpReverse_triggered()));
editMenu->addAction(&actionJmpReverse);
}
void DisassemblyContextMenu::addBreakpointMenu()
{
breakpointMenu = addMenu(tr("Breakpoint"));
initAction(&actionAddBreakpoint, tr("Add/remove breakpoint"),
SLOT(on_actionAddBreakpoint_triggered()), getAddBPSequence());
breakpointMenu->addAction(&actionAddBreakpoint);
initAction(&actionAdvancedBreakpoint, tr("Advanced breakpoint"),
SLOT(on_actionAdvancedBreakpoint_triggered()), QKeySequence(Qt::CTRL | Qt::Key_F2));
breakpointMenu->addAction(&actionAdvancedBreakpoint);
}
void DisassemblyContextMenu::addDebugMenu()
{
debugMenu = addMenu(tr("Debug"));
initAction(&actionContinueUntil, tr("Continue until line"),
SLOT(on_actionContinueUntil_triggered()));
debugMenu->addAction(&actionContinueUntil);
initAction(&actionSetPC, "Set PC", SLOT(on_actionSetPC_triggered()));
debugMenu->addAction(&actionSetPC);
}
QVector<DisassemblyContextMenu::ThingUsedHere> DisassemblyContextMenu::getThingUsedHere(RVA offset)
{
RzCoreLocked core(Core());
auto p = fromOwned(rz_core_analysis_name(core, offset), rz_core_analysis_name_free);
if (!p) {
return {};
}
QVector<ThingUsedHere> result;
ThingUsedHere th;
th.offset = p->offset;
th.name = Config()->getConfigBool("asm.flags.real") && p->realname ? p->realname : p->name;
switch (p->type) {
case RZ_CORE_ANALYSIS_NAME_TYPE_FLAG:
th.type = ThingUsedHere::Type::Flag;
break;
case RZ_CORE_ANALYSIS_NAME_TYPE_FUNCTION:
th.type = ThingUsedHere::Type::Function;
break;
case RZ_CORE_ANALYSIS_NAME_TYPE_VAR:
th.type = ThingUsedHere::Type::Var;
break;
case RZ_CORE_ANALYSIS_NAME_TYPE_ADDRESS:
default:
th.type = ThingUsedHere::Type::Address;
break;
}
result.push_back(th);
return result;
}
void DisassemblyContextMenu::setOffset(RVA offset)
{
this->offset = offset;
this->actionSetFunctionVarTypes.setVisible(true);
}
void DisassemblyContextMenu::setCanCopy(bool enabled)
{
this->canCopy = enabled;
}
void DisassemblyContextMenu::setCurHighlightedWord(const QString &text)
{
this->curHighlightedWord = text;
// Update the renaming options only when a new word is selected
setupRenaming();
}
DisassemblyContextMenu::ThingUsedHere DisassemblyContextMenu::getThingAt(ut64 address)
{
ThingUsedHere tuh;
RzAnalysisFunction *fcn = Core()->functionAt(address);
RzFlagItem *flag = rz_flag_get_i(Core()->core()->flags, address);
// We will lookup through existing rizin types to find something relevant
if (fcn != nullptr) {
// It is a function
tuh.type = ThingUsedHere::Type::Function;
tuh.name = fcn->name;
} else if (flag != nullptr) {
// It is a flag
tuh.type = ThingUsedHere::Type::Flag;
if (Config()->getConfigBool("asm.flags.real") && flag->realname) {
tuh.name = flag->realname;
} else {
tuh.name = flag->name;
}
} else {
// Consider it an address
tuh.type = ThingUsedHere::Type::Address;
}
tuh.offset = address;
return tuh;
}
void DisassemblyContextMenu::buildRenameMenu(ThingUsedHere *tuh)
{
if (!tuh) {
qWarning() << "Unexpected behavior null pointer passed to "
"DisassemblyContextMenu::buildRenameMenu";
doRenameAction = RENAME_DO_NOTHING;
return;
}
actionDeleteFlag.setVisible(false);
if (tuh->type == ThingUsedHere::Type::Address) {
doRenameAction = RENAME_ADD_FLAG;
doRenameInfo.name = RzAddressString(tuh->offset);
doRenameInfo.addr = tuh->offset;
actionRename.setText(tr("Add flag at %1 (used here)").arg(doRenameInfo.name));
} else if (tuh->type == ThingUsedHere::Type::Function) {
doRenameAction = RENAME_FUNCTION;
doRenameInfo.name = tuh->name;
doRenameInfo.addr = tuh->offset;
actionRename.setText(tr("Rename \"%1\"").arg(doRenameInfo.name));
} else if (tuh->type == ThingUsedHere::Type::Var) {
doRenameAction = RENAME_LOCAL;
doRenameInfo.name = tuh->name;
doRenameInfo.addr = tuh->offset;
actionRename.setText(tr("Rename local \"%1\"").arg(tuh->name));
} else if (tuh->type == ThingUsedHere::Type::Flag) {
doRenameAction = RENAME_FLAG;
doRenameInfo.name = tuh->name;
doRenameInfo.addr = tuh->offset;
actionRename.setText(tr("Rename flag \"%1\" (used here)").arg(doRenameInfo.name));
actionDeleteFlag.setVisible(true);
} else {
qWarning() << "Unexpected renaming type";
doRenameAction = RENAME_DO_NOTHING;
}
}
void DisassemblyContextMenu::setupRenaming()
{
// We parse our highlighted word as an address
ut64 selection = Core()->num(curHighlightedWord);
// First, let's try to see if current line (offset) contains a local variable or a function
ThingUsedHere *tuh = nullptr;
ThingUsedHere thingAt;
auto things = getThingUsedHere(offset);
for (auto &thing : things) {
if (thing.offset == selection || thing.name == curHighlightedWord) {
// We matched something on current line
tuh = &thing;
break;
}
}
if (!tuh) {
// Nothing matched on current line, is there anything valid coming from our selection?
thingAt = getThingAt(selection);
if (thingAt.offset == 0) {
// We parsed something which resolved to 0, it's very likely nothing interesting was
// selected So we fallback on current line offset
thingAt = getThingAt(offset);
}
// However, since for the moment selection selects *every* lines which match a specific
// offset, make sure we didn't want to select a local variable rather than the function
// itself
if (thingAt.type == ThingUsedHere::Type::Function) {
auto vars = Core()->getVariables(offset);
for (auto v : vars) {
if (v.name == curHighlightedWord) {
// This is a local variable
thingAt.type = ThingUsedHere::Type::Var;
thingAt.name = v.name;
break;
}
}
}
// In any case, thingAt will contain something we can rename
tuh = &thingAt;
}
// Now, build the renaming menu and show it
buildRenameMenu(tuh);
auto name = RzAddressString(tuh->offset);
actionGlobalVar.setText(tr("Add or change global variable at %1 (used here)").arg(name));
actionRename.setVisible(true);
actionGlobalVar.setVisible(true);
}
void DisassemblyContextMenu::aboutToShowSlot()
{
// check if set immediate base menu makes sense
auto ab = Core()->getRzAnalysisBytesSingle(offset);
bool immBase = ab && ab->op && (ab->op->val || ab->op->ptr);
setBaseMenu->menuAction()->setVisible(immBase);
setBitsMenu->menuAction()->setVisible(true);
// Create structure offset menu if it makes sense
QString memBaseReg; // Base register
st64 memDisp = 0; // Displacement
if (ab && ab->op) {
const char *opexstr = RZ_STRBUF_SAFEGET(&ab->op->opex);
CutterJson operands = Core()->parseJson("opex", strdup(opexstr), nullptr);
// Loop through both the operands of the instruction
for (const CutterJson operand : operands) {
if (operand["type"].toString() == "mem" && !operand["base"].toString().contains("bp")
&& operand["disp"].toSt64() > 0) {
// The current operand is the one which has an immediate displacement
memBaseReg = operand["base"].toString();
memDisp = operand["disp"].toSt64();
break;
}
}
}
if (memBaseReg.isEmpty()) {
// hide structure offset menu
structureOffsetMenu->menuAction()->setVisible(false);
} else {
// show structure offset menu
structureOffsetMenu->menuAction()->setVisible(true);
structureOffsetMenu->clear();
RzCoreLocked core(Core());
RzList *typeoffs = rz_type_db_get_by_offset(core->analysis->typedb, memDisp);
if (typeoffs) {
for (const auto &ty : CutterRzList<RzTypePath>(typeoffs)) {
if (RZ_STR_ISEMPTY(ty->path)) {
continue;
}
structureOffsetMenu->addAction("[" + memBaseReg + " + " + ty->path + "]")
->setData(QString(ty->path));
}
rz_list_free(typeoffs);
}
if (structureOffsetMenu->isEmpty()) {
// No possible offset was found so hide the menu
structureOffsetMenu->menuAction()->setVisible(false);
}
}
actionAnalyzeFunction.setVisible(true);
// Show the option to remove a defined string only if a string is defined in this address
QString stringDefinition = Core()->getMetaString(offset);
actionSetAsStringRemove.setVisible(!stringDefinition.isEmpty());
QString comment = Core()->getCommentAt(offset);
if (comment.isNull() || comment.isEmpty()) {
actionDeleteComment.setVisible(false);
actionAddComment.setText(tr("Add Comment"));
} else {
actionDeleteComment.setVisible(true);
actionAddComment.setText(tr("Edit Comment"));
}
actionCopy.setVisible(canCopy);
copySeparator->setVisible(canCopy);
// Handle renaming of variable, function, flag, ...
// Note: This might be useless if we consider setCurrentHighlightedWord is always called before
setupRenaming();
// Only show retype for local vars if in a function
RzAnalysisFunction *in_fcn = Core()->functionIn(offset);
if (in_fcn) {
auto vars = Core()->getVariables(offset);
actionSetFunctionVarTypes.setVisible(!vars.empty());
actionEditFunction.setVisible(true);
actionEditFunction.setText(tr("Edit function \"%1\"").arg(in_fcn->name));
} else {
actionSetFunctionVarTypes.setVisible(false);
actionEditFunction.setVisible(false);
}
// Decide to show Reverse jmp option
showReverseJmpQuery();
if (showInSubmenu.menu() != nullptr) {
showInSubmenu.menu()->deleteLater();
}
showInSubmenu.setMenu(mainWindow->createShowInMenu(this, offset));
// Only show debug options if we are currently debugging
debugMenu->menuAction()->setVisible(Core()->currentlyDebugging);
bool hasBreakpoint = Core()->breakpointIndexAt(offset) > -1;
actionAddBreakpoint.setText(hasBreakpoint ? tr("Remove breakpoint") : tr("Add breakpoint"));
actionAdvancedBreakpoint.setText(hasBreakpoint ? tr("Edit breakpoint")
: tr("Advanced breakpoint"));
QString progCounterName = Core()->getRegisterName("PC").toUpper();
actionSetPC.setText("Set " + progCounterName + " here");
if (pluginMenu) {
pluginActionMenuAction->setVisible(!pluginMenu->isEmpty());
for (QAction *pluginAction : pluginMenu->actions()) {
pluginAction->setData(QVariant::fromValue(offset));
}
}
bool isLocalVar = isHighlightedWordLocalVar();
actionXRefsForVariables.setVisible(isLocalVar);
if (isLocalVar) {
actionXRefsForVariables.setText(tr("X-Refs for %1").arg(curHighlightedWord));
}
}
void DisassemblyContextMenu::aboutToHideSlot()
{
actionXRefsForVariables.setVisible(true);
}
QKeySequence DisassemblyContextMenu::getCopySequence() const
{
return QKeySequence::Copy;
}
QKeySequence DisassemblyContextMenu::getCommentSequence() const
{
return { Qt::Key_Semicolon };
}
QKeySequence DisassemblyContextMenu::getCopyAddressSequence() const
{
return { Qt::CTRL | Qt::SHIFT | Qt::Key_C };
}
QKeySequence DisassemblyContextMenu::getCopyInstrBytesSequence() const
{
return { Qt::CTRL | Qt::ALT | Qt::Key_C };
}
QKeySequence DisassemblyContextMenu::getSetToCodeSequence() const
{
return { Qt::Key_C };
}
QKeySequence DisassemblyContextMenu::getSetAsStringSequence() const
{
return { Qt::Key_A };
}
QKeySequence DisassemblyContextMenu::getSetAsStringAdvanced() const
{
return { Qt::SHIFT | Qt::Key_A };
}
QKeySequence DisassemblyContextMenu::getSetToDataSequence() const
{
return { Qt::Key_D };
}
QKeySequence DisassemblyContextMenu::getSetToDataExSequence() const
{
return { Qt::Key_Asterisk };
}
QKeySequence DisassemblyContextMenu::getRenameSequence() const
{
return { Qt::Key_N };
}
QKeySequence DisassemblyContextMenu::getGlobalVarSequence() const
{
return { Qt::Key_G };
}
QKeySequence DisassemblyContextMenu::getRetypeSequence() const
{
return { Qt::Key_Y };
}
QKeySequence DisassemblyContextMenu::getXRefSequence() const
{
return { Qt::Key_X };
}
QKeySequence DisassemblyContextMenu::getDisplayOptionsSequence() const
{
return {}; // TODO insert correct sequence
}
QList<QKeySequence> DisassemblyContextMenu::getAddBPSequence() const
{
return { Qt::Key_F2, Qt::CTRL | Qt::Key_B };
}
QKeySequence DisassemblyContextMenu::getDefineNewFunctionSequence() const
{
return { Qt::Key_P };
}
QKeySequence DisassemblyContextMenu::getEditFunctionSequence() const
{
return { Qt::SHIFT | Qt::Key_P };
}
QKeySequence DisassemblyContextMenu::getUndefineFunctionSequence() const
{
return { Qt::Key_U };
}
void DisassemblyContextMenu::on_actionEditInstruction_triggered()
{
if (!ioModesController.prepareForWriting()) {
return;
}
EditInstructionDialog e(EDIT_TEXT, parentForDialog());
e.setWindowTitle(tr("Edit Instruction at %1").arg(RzAddressString(offset)));
QString oldInstructionOpcode = Core()->getInstructionOpcode(offset);
QString oldInstructionBytes = Core()->getInstructionBytes(offset);
e.setInstruction(oldInstructionOpcode);
if (e.exec()) {
bool fillWithNops = e.needsNops();
QString userInstructionOpcode = e.getInstruction();
if (userInstructionOpcode != oldInstructionOpcode) {
Core()->editInstruction(offset, userInstructionOpcode, fillWithNops);
}
}
}
void DisassemblyContextMenu::on_actionNopInstruction_triggered()
{
if (!ioModesController.prepareForWriting()) {
return;
}
Core()->nopInstruction(offset);
}
void DisassemblyContextMenu::showReverseJmpQuery()
{
actionJmpReverse.setVisible(false);
auto ab = Core()->getRzAnalysisBytesSingle(offset);
if (!(ab && ab->op)) {
return;
}
if (ab->op->type == RZ_ANALYSIS_OP_TYPE_CJMP) {
actionJmpReverse.setVisible(true);
}
}
void DisassemblyContextMenu::on_actionJmpReverse_triggered()
{
if (!ioModesController.prepareForWriting()) {
return;
}
Core()->jmpReverse(offset);
}
void DisassemblyContextMenu::on_actionEditBytes_triggered()
{
if (!ioModesController.prepareForWriting()) {
return;
}
EditInstructionDialog e(EDIT_BYTES, parentForDialog());
e.setWindowTitle(tr("Edit Bytes at %1").arg(RzAddressString(offset)));
QString oldBytes = Core()->getInstructionBytes(offset);
e.setInstruction(oldBytes);
if (e.exec()) {
QString bytes = e.getInstruction();
if (bytes != oldBytes) {
Core()->editBytes(offset, bytes);
}
}
}
void DisassemblyContextMenu::on_actionCopy_triggered()
{
emit copy();
}
void DisassemblyContextMenu::on_actionCopyAddr_triggered()
{
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(RzAddressString(offset));
}
void DisassemblyContextMenu::on_actionCopyInstrBytes_triggered()
{
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(Core()->getInstructionBytes(offset));
}
void DisassemblyContextMenu::on_actionAddBreakpoint_triggered()
{
Core()->toggleBreakpoint(offset);
}
void DisassemblyContextMenu::on_actionAdvancedBreakpoint_triggered()
{
int index = Core()->breakpointIndexAt(offset);
if (index >= 0) {
BreakpointsDialog::editBreakpoint(Core()->getBreakpointAt(offset), parentForDialog());
} else {
BreakpointsDialog::createNewBreakpoint(offset, parentForDialog());
}
}
void DisassemblyContextMenu::on_actionContinueUntil_triggered()
{
Core()->continueUntilDebug(offset);
}
void DisassemblyContextMenu::on_actionSetPC_triggered()
{
QString progCounterName = Core()->getRegisterName("PC");
Core()->setRegister(progCounterName, RzAddressString(offset).toUpper());
}
void DisassemblyContextMenu::on_actionAddComment_triggered()
{
CommentsDialog::addOrEditComment(offset, parentForDialog());
}
void DisassemblyContextMenu::on_actionAnalyzeFunction_triggered()
{
RVA flagOffset;
QString name = Core()->nearestFlag(offset, &flagOffset);
if (name.isEmpty() || flagOffset != offset) {
// Create a default name for the function
QString pfx = Config()->getConfigString("analysis.fcnprefix");
if (pfx.isEmpty()) {
pfx = QString("fcn");
}
name = pfx + QString::asprintf(".%llx", offset);
}
// Create dialog
QInputDialog inputDialog(parentForDialog());
inputDialog.resize(500, 100);
inputDialog.setWindowTitle(tr("New function at %1").arg(RzAddressString(offset)));
inputDialog.setLabelText(tr("Function name:"));
inputDialog.setTextValue(name);
inputDialog.setWindowFlags(Qt::Window | Qt::WindowMinimizeButtonHint);
if (inputDialog.exec() != QDialog::Accepted) {
return;
}
QString functionName = inputDialog.textValue().trimmed();
if (!functionName.isEmpty()) {
Core()->createFunctionAt(offset, functionName);
}
}
void DisassemblyContextMenu::on_actionRename_triggered()
{
bool ok = false;
if (doRenameAction == RENAME_FUNCTION) {
QString newName = QInputDialog::getText(
this->mainWindow, tr("Rename function %2").arg(doRenameInfo.name),
tr("Function name:"), QLineEdit::Normal, doRenameInfo.name, &ok);
if (ok && !newName.isEmpty()) {
Core()->renameFunction(doRenameInfo.addr, newName);
}
} else if (doRenameAction == RENAME_FLAG || doRenameAction == RENAME_ADD_FLAG) {
FlagDialog dialog(doRenameInfo.addr, parentForDialog());
ok = dialog.exec();
} else if (doRenameAction == RENAME_LOCAL) {
RzAnalysisFunction *fcn = Core()->functionIn(offset);
if (fcn) {
EditVariablesDialog dialog(fcn->addr, curHighlightedWord, parentForDialog());
if (!dialog.empty()) {
// Don't show the dialog if there are no variables
ok = dialog.exec();
}
}
} else if (doRenameAction == RENAME_DO_NOTHING) {
// Do nothing
} else {
qWarning() << "Unhandled renaming action: " << doRenameAction;
assert(false);
}
if (ok) {
// Rebuild menu in case the user presses the rename shortcut directly before clicking
setupRenaming();
}
}
void DisassemblyContextMenu::on_actionGlobalVar_triggered()
{
bool ok = false;
GlobalVariableDialog dialog(doRenameInfo.addr, parentForDialog());
ok = dialog.exec();
if (ok) {
// Rebuild menu in case the user presses the rename shortcut directly before clicking
setupRenaming();
}
}
void DisassemblyContextMenu::on_actionSetFunctionVarTypes_triggered()
{
RzAnalysisFunction *fcn = Core()->functionIn(offset);
if (!fcn) {
QMessageBox::critical(this, tr("Re-type Local Variables"),
tr("You must be in a function to define variable types."));
return;
}
EditVariablesDialog dialog(fcn->addr, curHighlightedWord, parentForDialog());
if (dialog.empty()) { // don't show the dialog if there are no variables
return;
}
dialog.exec();
}
void DisassemblyContextMenu::on_actionXRefs_triggered()
{
XrefsDialog dialog(mainWindow);
dialog.fillRefsForAddress(offset, RzAddressString(offset), false);
dialog.exec();
}
void DisassemblyContextMenu::on_actionXRefsForVariables_triggered()
{
if (isHighlightedWordLocalVar()) {
XrefsDialog dialog(mainWindow);
dialog.fillRefsForVariable(curHighlightedWord, offset);
dialog.exec();
}
}
void DisassemblyContextMenu::on_actionDisplayOptions_triggered()
{
PreferencesDialog dialog(parentForDialog());
dialog.showSection(PreferencesDialog::Section::Disassembly);
dialog.exec();
}
void DisassemblyContextMenu::on_actionSetToCode_triggered()
{
Core()->setToCode(offset);
}
void DisassemblyContextMenu::on_actionSetAsString_triggered()
{
Core()->setAsString(offset);
}
void DisassemblyContextMenu::on_actionSetAsStringRemove_triggered()
{
Core()->removeString(offset);
}
void DisassemblyContextMenu::on_actionSetAsStringAdvanced_triggered()
{
EditStringDialog dialog(parentForDialog());
const int predictedStrSize = Core()->getString(offset).size();
dialog.setStringSizeValue(predictedStrSize);
dialog.setStringStartAddress(offset);
if (!dialog.exec()) {
return;
}
uint64_t strAddr = 0U;
if (!dialog.getStringStartAddress(strAddr)) {
QMessageBox::critical(this->window(), tr("Wrong address"),
tr("Can't edit string at this address"));
return;
}
CutterCore::StringTypeFormats coreStringType = CutterCore::StringTypeFormats::None;
const auto strSize = dialog.getStringSizeValue();
const auto strType = dialog.getStringType();
switch (strType) {
case EditStringDialog::StringType::Auto:
coreStringType = CutterCore::StringTypeFormats::None;
break;
case EditStringDialog::StringType::ASCII_LATIN1:
coreStringType = CutterCore::StringTypeFormats::ASCII_LATIN1;
break;
case EditStringDialog::StringType::UTF8:
coreStringType = CutterCore::StringTypeFormats::UTF8;
break;
};
Core()->setAsString(strAddr, strSize, coreStringType);
}
void DisassemblyContextMenu::on_actionSetToData_triggered()
{
int size = Core()->sizeofDataMeta(offset);
if (size > 8 || (size && (size & (size - 1)))) {
return;
}
if (size == 0 || size == 8) {
size = 1;
} else {
size *= 2;
}
setToData(size);
}
void DisassemblyContextMenu::on_actionSetToDataEx_triggered()
{
SetToDataDialog dialog(offset, parentForDialog());
if (!dialog.exec()) {
return;
}
setToData(dialog.getItemSize(), dialog.getItemCount());
}
void DisassemblyContextMenu::on_actionStructureOffsetMenu_triggered(QAction *action)
{
Core()->applyStructureOffset(action->data().toString(), offset);
}
void DisassemblyContextMenu::on_actionDeleteComment_triggered()
{
Core()->delComment(offset);
}
void DisassemblyContextMenu::on_actionDeleteFlag_triggered()
{
Core()->delFlag(offset);
}
void DisassemblyContextMenu::on_actionDeleteFunction_triggered()
{
Core()->delFunction(offset);
}
void DisassemblyContextMenu::on_actionEditFunction_triggered()
{
RzCore *core = Core()->core();
EditFunctionDialog dialog(parentForDialog());
RzAnalysisFunction *fcn = rz_analysis_get_fcn_in(core->analysis, offset, 0);
if (fcn) {
dialog.setWindowTitle(tr("Edit function %1").arg(fcn->name));
dialog.setNameText(fcn->name);
QString startAddrText = "0x" + QString::number(fcn->addr, 16);
dialog.setStartAddrText(startAddrText);
dialog.setStackSizeText(QString::number(fcn->stack));
QStringList callConList;
RzList *list = rz_analysis_calling_conventions(core->analysis);
if (!list) {
return;
}
RzListIter *iter;
const char *cc;
CutterRzListForeach (list, iter, const char, cc) {
callConList << cc;
}
rz_list_free(list);
dialog.setCallConList(callConList);
dialog.setCallConSelected(fcn->cc);
if (dialog.exec()) {
QString new_name = dialog.getNameText();
rz_core_analysis_function_rename(core, fcn->addr, new_name.toStdString().c_str());
QString new_start_addr = dialog.getStartAddrText();
fcn->addr = Core()->math(new_start_addr);
QString new_stack_size = dialog.getStackSizeText();
fcn->stack = int(Core()->math(new_stack_size));
QByteArray newCC = dialog.getCallConSelected().toUtf8();
if (!newCC.isEmpty() && rz_analysis_cc_exist(core->analysis, newCC.constData())) {
fcn->cc = rz_str_constpool_get(&core->analysis->constpool, newCC.constData());
}
emit Core()->functionsChanged();
}
}
}
void DisassemblyContextMenu::setBase(QString base)
{
Core()->setImmediateBase(base, offset);
}
void DisassemblyContextMenu::setBits(int bits)
{
Core()->setCurrentBits(bits, offset);
}
void DisassemblyContextMenu::setToData(int size, int repeat)
{
Core()->setToData(offset, size, repeat);
}
QAction *DisassemblyContextMenu::addAnonymousAction(QString name, const char *slot,
QKeySequence keySequence)
{
auto action = new QAction(this);
addAction(action);
anonymousActions.append(action);
initAction(action, name, slot, keySequence);
return action;
}
void DisassemblyContextMenu::initAction(QAction *action, QString name, const char *slot)
{
action->setParent(this);
parentWidget()->addAction(action);
action->setText(name);
if (slot) {
connect(action, SIGNAL(triggered(bool)), this, slot);
}
}
void DisassemblyContextMenu::initAction(QAction *action, QString name, const char *slot,
QKeySequence keySequence)
{
initAction(action, name, slot);
if (keySequence.isEmpty()) {
return;
}
action->setShortcut(keySequence);
action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
}
void DisassemblyContextMenu::initAction(QAction *action, QString name, const char *slot,
QList<QKeySequence> keySequenceList)
{
initAction(action, name, slot);
if (keySequenceList.empty()) {
return;
}
action->setShortcuts(keySequenceList);
action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
}
bool DisassemblyContextMenu::isHighlightedWordLocalVar()
{
QList<VariableDescription> variables = Core()->getVariables(offset);
for (const VariableDescription &var : variables) {
if (var.name == curHighlightedWord) {
return true;
}
}
return false;
}
| 37,912
|
C++
|
.cpp
| 974
| 32.820329
| 100
| 0.690137
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,604
|
DecompilerContextMenu.cpp
|
rizinorg_cutter/src/menus/DecompilerContextMenu.cpp
|
#include "DecompilerContextMenu.h"
#include "dialogs/preferences/PreferencesDialog.h"
#include "MainWindow.h"
#include "dialogs/BreakpointsDialog.h"
#include "dialogs/CommentsDialog.h"
#include "dialogs/EditVariablesDialog.h"
#include "dialogs/XrefsDialog.h"
#include "common/Configuration.h"
#include <QtCore>
#include <QShortcut>
#include <QJsonArray>
#include <QClipboard>
#include <QApplication>
#include <QPushButton>
#include <QInputDialog>
DecompilerContextMenu::DecompilerContextMenu(QWidget *parent, MainWindow *mainWindow)
: QMenu(parent),
mainWindow(mainWindow),
curHighlightedWord(QString()),
offset(0),
decompiledFunctionAddress(RVA_INVALID),
isTogglingBreakpoints(false),
annotationHere(nullptr),
actionCopy(tr("Copy"), this),
actionCopyInstructionAddress(tr("Copy instruction address (<address>)"), this),
actionCopyReferenceAddress(tr("Copy address of [flag] (<address>)"), this),
actionShowInSubmenu(tr("Show in"), this),
actionAddComment(tr("Add Comment"), this),
actionDeleteComment(tr("Delete comment"), this),
actionRenameThingHere(tr("Rename function at cursor"), this),
actionDeleteName(tr("Delete <name>"), this),
actionEditFunctionVariables(tr("Edit variable <name of variable>"), this),
actionXRefs(tr("Show X-Refs"), this),
actionToggleBreakpoint(tr("Add/remove breakpoint"), this),
actionAdvancedBreakpoint(tr("Advanced breakpoint"), this),
breakpointsInLineMenu(new QMenu(this)),
actionContinueUntil(tr("Continue until line"), this),
actionSetPC(tr("Set PC"), this)
{
setActionCopy(); // Sets all three copy actions
addSeparator();
setActionShowInSubmenu();
copySeparator = addSeparator();
setActionAddComment();
setActionDeleteComment();
setActionRenameThingHere();
setActionDeleteName();
setActionXRefs();
setActionEditFunctionVariables();
addSeparator();
addBreakpointMenu();
addDebugMenu();
setShortcutContextInActions(this);
connect(this, &DecompilerContextMenu::aboutToShow, this,
&DecompilerContextMenu::aboutToShowSlot);
connect(this, &DecompilerContextMenu::aboutToHide, this,
&DecompilerContextMenu::aboutToHideSlot);
}
DecompilerContextMenu::~DecompilerContextMenu() {}
QWidget *DecompilerContextMenu::parentForDialog()
{
return parentWidget();
}
void DecompilerContextMenu::setAnnotationHere(RzCodeAnnotation *annotation)
{
annotationHere = annotation;
}
void DecompilerContextMenu::setCurHighlightedWord(QString word)
{
curHighlightedWord = word;
}
void DecompilerContextMenu::setOffset(RVA newOffset)
{
offset = newOffset;
}
void DecompilerContextMenu::setDecompiledFunctionAddress(RVA functionAddr)
{
decompiledFunctionAddress = functionAddr;
}
void DecompilerContextMenu::setFirstOffsetInLine(RVA firstOffset)
{
firstOffsetInLine = firstOffset;
}
RVA DecompilerContextMenu::getFirstOffsetInLine()
{
return firstOffsetInLine;
}
void DecompilerContextMenu::setAvailableBreakpoints(QVector<RVA> offsetList)
{
availableBreakpoints = offsetList;
}
void DecompilerContextMenu::setupBreakpointsInLineMenu()
{
breakpointsInLineMenu->clear();
for (auto curOffset : this->availableBreakpoints) {
QAction *action = breakpointsInLineMenu->addAction(RzAddressString(curOffset));
connect(action, &QAction::triggered, this, [this, curOffset] {
BreakpointsDialog::editBreakpoint(Core()->getBreakpointAt(curOffset), this);
});
}
}
void DecompilerContextMenu::setShortcutContextInActions(QMenu *menu)
{
for (QAction *action : menu->actions()) {
if (action->isSeparator()) {
// Do nothing
} else if (action->menu()) {
setShortcutContextInActions(action->menu());
} else {
action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
}
}
}
void DecompilerContextMenu::setIsTogglingBreakpoints(bool isToggling)
{
isTogglingBreakpoints = isToggling;
}
bool DecompilerContextMenu::getIsTogglingBreakpoints()
{
return isTogglingBreakpoints;
}
void DecompilerContextMenu::aboutToHideSlot()
{
actionAddComment.setVisible(true);
actionRenameThingHere.setVisible(true);
actionRenameThingHere.setEnabled(true);
actionDeleteName.setVisible(false);
actionEditFunctionVariables.setVisible(true);
actionEditFunctionVariables.setEnabled(true);
actionXRefs.setVisible(true);
setToolTipsVisible(false);
}
void DecompilerContextMenu::aboutToShowSlot()
{
if (this->firstOffsetInLine != RVA_MAX) {
actionShowInSubmenu.setVisible(true);
QString comment = Core()->getCommentAt(firstOffsetInLine);
actionAddComment.setVisible(true);
if (comment.isEmpty()) {
actionDeleteComment.setVisible(false);
actionAddComment.setText(tr("Add Comment"));
} else {
actionDeleteComment.setVisible(true);
actionAddComment.setText(tr("Edit Comment"));
}
} else {
actionShowInSubmenu.setVisible(false);
actionAddComment.setVisible(false);
actionDeleteComment.setVisible(false);
}
setupBreakpointsInLineMenu();
// Only show debug options if we are currently debugging
debugMenu->menuAction()->setVisible(Core()->currentlyDebugging);
bool hasBreakpoint = !this->availableBreakpoints.isEmpty();
int numberOfBreakpoints = this->availableBreakpoints.size();
if (numberOfBreakpoints == 0) {
actionToggleBreakpoint.setText(tr("Add breakpoint"));
} else if (numberOfBreakpoints == 1) {
actionToggleBreakpoint.setText(tr("Remove breakpoint"));
} else {
actionToggleBreakpoint.setText(tr("Remove all breakpoints in line"));
}
if (numberOfBreakpoints > 1) {
actionAdvancedBreakpoint.setMenu(breakpointsInLineMenu);
} else {
actionAdvancedBreakpoint.setMenu(nullptr);
}
actionAdvancedBreakpoint.setText(hasBreakpoint ? tr("Edit breakpoint")
: tr("Advanced breakpoint"));
QString progCounterName = Core()->getRegisterName("PC").toUpper();
actionSetPC.setText(tr("Set %1 here").arg(progCounterName));
if (!annotationHere
|| annotationHere->type
== RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) { // If constant, don't show rename
// and targeted show-in
actionRenameThingHere.setVisible(false);
copySeparator->setVisible(false);
} else {
copySeparator->setVisible(true);
if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) {
actionRenameThingHere.setText(
tr("Rename function %1").arg(QString(annotationHere->reference.name)));
} else if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_GLOBAL_VARIABLE) {
RzFlagItem *flagDetails =
rz_flag_get_i(Core()->core()->flags, annotationHere->reference.offset);
if (flagDetails) {
actionRenameThingHere.setText(tr("Rename %1").arg(QString(flagDetails->name)));
actionDeleteName.setText(tr("Remove %1").arg(QString(flagDetails->name)));
actionDeleteName.setVisible(true);
} else {
actionRenameThingHere.setText(tr("Add name to %1").arg(curHighlightedWord));
}
}
}
actionCopyInstructionAddress.setText(
tr("Copy instruction address (%1)").arg(RzAddressString(offset)));
if (isReference()) {
actionCopyReferenceAddress.setVisible(true);
RVA referenceAddr = annotationHere->reference.offset;
RzFlagItem *flagDetails = rz_flag_get_i(Core()->core()->flags, referenceAddr);
if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) {
actionCopyReferenceAddress.setText(tr("Copy address of %1 (%2)")
.arg(QString(annotationHere->reference.name),
RzAddressString(referenceAddr)));
} else if (flagDetails) {
actionCopyReferenceAddress.setText(
tr("Copy address of %1 (%2)")
.arg(flagDetails->name, RzAddressString(referenceAddr)));
} else {
actionCopyReferenceAddress.setText(
tr("Copy address (%1)").arg(RzAddressString(referenceAddr)));
}
} else {
actionXRefs.setVisible(false);
actionCopyReferenceAddress.setVisible(false);
}
if (actionShowInSubmenu.menu() != nullptr) {
actionShowInSubmenu.menu()->deleteLater();
}
actionShowInSubmenu.setMenu(mainWindow->createShowInMenu(this, offset));
updateTargetMenuActions();
if (!isFunctionVariable()) {
actionEditFunctionVariables.setVisible(false);
} else {
actionEditFunctionVariables.setText(
tr("Edit variable %1").arg(QString(annotationHere->variable.name)));
actionRenameThingHere.setText(
tr("Rename variable %1").arg(QString(annotationHere->variable.name)));
if (!variablePresentInRizin()) {
actionEditFunctionVariables.setDisabled(true);
actionRenameThingHere.setDisabled(true);
setToolTipsVisible(true);
}
}
}
// Set up actions
void DecompilerContextMenu::setActionCopy() // Set all three copy actions
{
connect(&actionCopy, &QAction::triggered, this, &DecompilerContextMenu::actionCopyTriggered);
addAction(&actionCopy);
actionCopy.setShortcut(QKeySequence::Copy);
connect(&actionCopyInstructionAddress, &QAction::triggered, this,
&DecompilerContextMenu::actionCopyInstructionAddressTriggered);
addAction(&actionCopyInstructionAddress);
connect(&actionCopyReferenceAddress, &QAction::triggered, this,
&DecompilerContextMenu::actionCopyReferenceAddressTriggered);
addAction(&actionCopyReferenceAddress);
actionCopyReferenceAddress.setShortcut({ Qt::KeyboardModifier::ControlModifier
| Qt::KeyboardModifier::ShiftModifier | Qt::Key_C });
}
void DecompilerContextMenu::setActionShowInSubmenu()
{
addAction(&actionShowInSubmenu);
}
void DecompilerContextMenu::setActionAddComment()
{
connect(&actionAddComment, &QAction::triggered, this,
&DecompilerContextMenu::actionAddCommentTriggered);
addAction(&actionAddComment);
actionAddComment.setShortcut(Qt::Key_Semicolon);
}
void DecompilerContextMenu::setActionDeleteComment()
{
connect(&actionDeleteComment, &QAction::triggered, this,
&DecompilerContextMenu::actionDeleteCommentTriggered);
addAction(&actionDeleteComment);
}
void DecompilerContextMenu::setActionXRefs()
{
connect(&actionXRefs, &QAction::triggered, this, &DecompilerContextMenu::actionXRefsTriggered);
addAction(&actionXRefs);
actionXRefs.setShortcut(Qt::Key_X);
}
void DecompilerContextMenu::setActionRenameThingHere()
{
actionRenameThingHere.setShortcut({ Qt::Key_N });
connect(&actionRenameThingHere, &QAction::triggered, this,
&DecompilerContextMenu::actionRenameThingHereTriggered);
addAction(&actionRenameThingHere);
actionRenameThingHere.setToolTip(
tr("Can't rename this variable.<br>"
"Only local variables defined in disassembly can be renamed."));
}
void DecompilerContextMenu::setActionDeleteName()
{
connect(&actionDeleteName, &QAction::triggered, this,
&DecompilerContextMenu::actionDeleteNameTriggered);
addAction(&actionDeleteName);
actionDeleteName.setVisible(false);
}
void DecompilerContextMenu::setActionEditFunctionVariables()
{
connect(&actionEditFunctionVariables, &QAction::triggered, this,
&DecompilerContextMenu::actionEditFunctionVariablesTriggered);
addAction(&actionEditFunctionVariables);
actionEditFunctionVariables.setShortcut(Qt::Key_Y);
actionEditFunctionVariables.setToolTip(
tr("Can't edit this variable.<br>"
"Only local variables defined in disassembly can be edited."));
}
void DecompilerContextMenu::setActionToggleBreakpoint()
{
connect(&actionToggleBreakpoint, &QAction::triggered, this,
&DecompilerContextMenu::actionToggleBreakpointTriggered);
actionToggleBreakpoint.setShortcuts({ Qt::Key_F2, Qt::CTRL | Qt::Key_B });
}
void DecompilerContextMenu::setActionAdvancedBreakpoint()
{
connect(&actionAdvancedBreakpoint, &QAction::triggered, this,
&DecompilerContextMenu::actionAdvancedBreakpointTriggered);
actionAdvancedBreakpoint.setShortcut({ Qt::CTRL | Qt::Key_F2 });
}
void DecompilerContextMenu::setActionContinueUntil()
{
connect(&actionContinueUntil, &QAction::triggered, this,
&DecompilerContextMenu::actionContinueUntilTriggered);
}
void DecompilerContextMenu::setActionSetPC()
{
connect(&actionSetPC, &QAction::triggered, this, &DecompilerContextMenu::actionSetPCTriggered);
}
// Set up action responses
void DecompilerContextMenu::actionCopyTriggered()
{
emit copy();
}
void DecompilerContextMenu::actionCopyInstructionAddressTriggered()
{
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(RzAddressString(offset));
}
void DecompilerContextMenu::actionCopyReferenceAddressTriggered()
{
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(RzAddressString(annotationHere->reference.offset));
}
void DecompilerContextMenu::actionAddCommentTriggered()
{
CommentsDialog::addOrEditComment(this->firstOffsetInLine, parentForDialog());
}
void DecompilerContextMenu::actionDeleteCommentTriggered()
{
Core()->delComment(this->firstOffsetInLine);
}
void DecompilerContextMenu::actionRenameThingHereTriggered()
{
if (!annotationHere || annotationHere->type == RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) {
return;
}
RzCoreLocked core = Core()->core();
bool ok;
auto type = annotationHere->type;
if (type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) {
QString currentName(annotationHere->reference.name);
RVA func_addr = annotationHere->reference.offset;
RzAnalysisFunction *func = Core()->functionAt(func_addr);
if (func == NULL) {
QString function_name = QInputDialog::getText(
parentForDialog(),
tr("Define this function at %2").arg(RzAddressString(func_addr)),
tr("Function name:"), QLineEdit::Normal, currentName, &ok);
if (ok && !function_name.isEmpty()) {
Core()->createFunctionAt(func_addr, function_name);
}
} else {
QString newName = QInputDialog::getText(
parentForDialog(), tr("Rename function %2").arg(currentName),
tr("Function name:"), QLineEdit::Normal, currentName, &ok);
if (ok && !newName.isEmpty()) {
Core()->renameFunction(func_addr, newName);
}
}
} else if (type == RZ_CODE_ANNOTATION_TYPE_GLOBAL_VARIABLE) {
RVA var_addr = annotationHere->reference.offset;
RzFlagItem *flagDetails = rz_flag_get_i(core->flags, var_addr);
if (flagDetails) {
QString newName = QInputDialog::getText(
parentForDialog(), tr("Rename %2").arg(flagDetails->name), tr("Enter name"),
QLineEdit::Normal, flagDetails->name, &ok);
if (ok && !newName.isEmpty()) {
Core()->renameFlag(flagDetails->name, newName);
}
} else {
QString newName = QInputDialog::getText(
parentForDialog(), tr("Add name to %2").arg(curHighlightedWord),
tr("Enter name"), QLineEdit::Normal, curHighlightedWord, &ok);
if (ok && !newName.isEmpty()) {
Core()->addFlag(var_addr, newName, 1);
}
}
} else if (isFunctionVariable()) {
if (!variablePresentInRizin()) {
// Show can't rename this variable dialog
QMessageBox::critical(
parentForDialog(),
tr("Rename local variable %1").arg(QString(annotationHere->variable.name)),
tr("Can't rename this variable. "
"Only local variables defined in disassembly can be renamed."));
return;
}
QString oldName(annotationHere->variable.name);
QString newName = QInputDialog::getText(parentForDialog(), tr("Rename %2").arg(oldName),
tr("Enter name"), QLineEdit::Normal, oldName, &ok);
if (ok && !newName.isEmpty()) {
Core()->renameFunctionVariable(newName, oldName, decompiledFunctionAddress);
}
}
}
void DecompilerContextMenu::actionDeleteNameTriggered()
{
Core()->delFlag(annotationHere->reference.offset);
}
void DecompilerContextMenu::actionEditFunctionVariablesTriggered()
{
if (!isFunctionVariable()) {
return;
} else if (!variablePresentInRizin()) {
QMessageBox::critical(
parentForDialog(),
tr("Edit local variable %1").arg(QString(annotationHere->variable.name)),
tr("Can't edit this variable. "
"Only local variables defined in disassembly can be edited."));
return;
}
EditVariablesDialog dialog(decompiledFunctionAddress, QString(annotationHere->variable.name),
parentForDialog());
dialog.exec();
}
void DecompilerContextMenu::actionXRefsTriggered()
{
if (!isReference()) {
return;
}
XrefsDialog dialog(mainWindow);
QString displayString = (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME)
? QString(annotationHere->reference.name)
: RzAddressString(annotationHere->reference.offset);
dialog.fillRefsForAddress(annotationHere->reference.offset, displayString, false);
dialog.exec();
}
void DecompilerContextMenu::actionToggleBreakpointTriggered()
{
if (!this->availableBreakpoints.isEmpty()) {
setIsTogglingBreakpoints(true);
for (auto offsetToRemove : this->availableBreakpoints) {
Core()->toggleBreakpoint(offsetToRemove);
}
this->availableBreakpoints.clear();
setIsTogglingBreakpoints(false);
return;
}
if (this->firstOffsetInLine == RVA_MAX)
return;
Core()->toggleBreakpoint(this->firstOffsetInLine);
}
void DecompilerContextMenu::actionAdvancedBreakpointTriggered()
{
if (!availableBreakpoints.empty()) {
// Edit the earliest breakpoint in the line
BreakpointsDialog::editBreakpoint(
Core()->getBreakpointAt(this->availableBreakpoints.first()), this);
} else {
// Add a breakpoint to the earliest offset in the line
BreakpointsDialog::createNewBreakpoint(this->firstOffsetInLine, this);
}
}
void DecompilerContextMenu::actionContinueUntilTriggered()
{
Core()->continueUntilDebug(offset);
}
void DecompilerContextMenu::actionSetPCTriggered()
{
QString progCounterName = Core()->getRegisterName("PC");
Core()->setRegister(progCounterName, RzAddressString(offset).toUpper());
}
// Set up menus
void DecompilerContextMenu::addBreakpointMenu()
{
breakpointMenu = addMenu(tr("Breakpoint"));
setActionToggleBreakpoint();
breakpointMenu->addAction(&actionToggleBreakpoint);
setActionAdvancedBreakpoint();
breakpointMenu->addAction(&actionAdvancedBreakpoint);
}
void DecompilerContextMenu::addDebugMenu()
{
debugMenu = addMenu(tr("Debug"));
setActionContinueUntil();
debugMenu->addAction(&actionContinueUntil);
setActionSetPC();
debugMenu->addAction(&actionSetPC);
}
void DecompilerContextMenu::updateTargetMenuActions()
{
for (auto action : showTargetMenuActions) {
removeAction(action);
auto menu = action->menu();
if (menu) {
menu->deleteLater();
}
action->deleteLater();
}
showTargetMenuActions.clear();
RzCoreLocked core = Core()->core();
if (isReference()) {
QString name;
QMenu *menu = nullptr;
if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_GLOBAL_VARIABLE
|| annotationHere->type == RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) {
menu = mainWindow->createShowInMenu(this, annotationHere->reference.offset,
MainWindow::AddressTypeHint::Data);
RVA var_addr = annotationHere->reference.offset;
RzFlagItem *flagDetails = rz_flag_get_i(core->flags, var_addr);
if (flagDetails) {
name = tr("Show %1 in").arg(flagDetails->name);
} else {
name = tr("Show %1 in").arg(RzAddressString(annotationHere->reference.offset));
}
} else if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) {
menu = mainWindow->createShowInMenu(this, annotationHere->reference.offset,
MainWindow::AddressTypeHint::Function);
name = tr("%1 (%2)").arg(QString(annotationHere->reference.name),
RzAddressString(annotationHere->reference.offset));
}
auto action = new QAction(name, this);
showTargetMenuActions.append(action);
action->setMenu(menu);
insertActions(copySeparator, showTargetMenuActions);
}
}
bool DecompilerContextMenu::isReference()
{
return (annotationHere && rz_annotation_is_reference(annotationHere));
}
bool DecompilerContextMenu::isFunctionVariable()
{
return (annotationHere && rz_annotation_is_variable(annotationHere));
}
bool DecompilerContextMenu::variablePresentInRizin()
{
QString variableName(annotationHere->variable.name);
QList<VariableDescription> variables = Core()->getVariables(offset);
for (const VariableDescription &var : variables) {
if (var.name == variableName) {
return true;
}
}
return false;
}
| 22,358
|
C++
|
.cpp
| 549
| 33.264117
| 100
| 0.684346
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,605
|
FlirtContextMenu.cpp
|
rizinorg_cutter/src/menus/FlirtContextMenu.cpp
|
#include "FlirtContextMenu.h"
#include "MainWindow.h"
#include <QtCore>
#include <QShortcut>
#include <QJsonArray>
#include <QClipboard>
#include <QApplication>
#include <QPushButton>
FlirtContextMenu::FlirtContextMenu(QWidget *parent, MainWindow *mainWindow)
: QMenu(parent), mainWindow(mainWindow)
{
actionCopyLine = new QAction(tr("Copy Line"), this);
actionApplySignature = new QAction(tr("Apply Signature File"), this);
connect(actionCopyLine, &QAction::triggered, this, &FlirtContextMenu::onActionCopyLine);
connect(actionApplySignature, &QAction::triggered, this,
&FlirtContextMenu::onActionApplySignature);
addAction(actionCopyLine);
addSeparator();
addAction(actionApplySignature);
setHasTarget(false);
}
FlirtContextMenu::~FlirtContextMenu() {}
void FlirtContextMenu::setTarget(const FlirtDescription &flirt)
{
this->entry = flirt;
setHasTarget(true);
}
void FlirtContextMenu::clearTarget()
{
setHasTarget(false);
}
void FlirtContextMenu::onActionCopyLine()
{
auto clipboard = QApplication::clipboard();
QString text = entry.bin_name + "\t" + entry.arch_name + "\t" + entry.arch_bits + "\t"
+ entry.n_modules + "\t" + entry.base_name + "\t" + entry.details;
clipboard->setText(text);
}
void FlirtContextMenu::onActionApplySignature()
{
if (this->hasTarget) {
Core()->applySignature(entry.file_path);
}
}
void FlirtContextMenu::setHasTarget(bool hasTarget)
{
this->hasTarget = hasTarget;
for (const auto &action : this->actions()) {
action->setEnabled(hasTarget);
}
}
| 1,608
|
C++
|
.cpp
| 51
| 27.960784
| 92
| 0.727684
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,606
|
AddressableItemModel.cpp
|
rizinorg_cutter/src/common/AddressableItemModel.cpp
|
#include <stdexcept>
#include "AddressableItemModel.h"
#include <stdexcept>
AddressableFilterProxyModel::AddressableFilterProxyModel(AddressableItemModelI *sourceModel,
QObject *parent)
: AddressableItemModel<QSortFilterProxyModel>(parent)
{
setSourceModel(sourceModel);
addressableSourceModel = sourceModel;
}
RVA AddressableFilterProxyModel::address(const QModelIndex &index) const
{
if (!addressableSourceModel) {
return RVA_INVALID;
}
return addressableSourceModel->address(this->mapToSource(index));
}
QString AddressableFilterProxyModel::name(const QModelIndex &index) const
{
if (!addressableSourceModel) {
return QString();
}
return addressableSourceModel->name(this->mapToSource(index));
}
void AddressableFilterProxyModel::setSourceModel(QAbstractItemModel *)
{
throw new std::runtime_error("Not supported");
}
void AddressableFilterProxyModel::setSourceModel(AddressableItemModelI *sourceModel)
{
ParentClass::setSourceModel(sourceModel ? sourceModel->asItemModel() : nullptr);
addressableSourceModel = sourceModel;
}
| 1,156
|
C++
|
.cpp
| 33
| 30.181818
| 92
| 0.759176
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,607
|
BugReporting.cpp
|
rizinorg_cutter/src/common/BugReporting.cpp
|
#include "BugReporting.h"
#include "Cutter.h"
#include <QUrl>
#include <QJsonObject>
#include "CutterConfig.h"
#include <QDesktopServices>
void openIssue()
{
RzCoreLocked core(Core());
RzBinFile *bf = rz_bin_cur(core->bin);
RzBinObject *bobj = rz_bin_cur_object(core->bin);
const RzBinInfo *info = bobj ? rz_bin_object_get_info(bobj) : nullptr;
RzBinPlugin *plugin = rz_bin_file_cur_plugin(bf);
QString url, osInfo, format, arch, type;
// Pull in info needed for git issue
osInfo = QSysInfo::productType() + " "
+ (QSysInfo::productVersion() == "unknown" ? "" : QSysInfo::productVersion());
format = plugin && RZ_STR_ISNOTEMPTY(plugin->name) ? plugin->name : "N/A";
arch = info && RZ_STR_ISNOTEMPTY(info->arch) ? info->arch : "N/A";
type = info && RZ_STR_ISNOTEMPTY(info->type) ? info->type : "N/A";
url = "https://github.com/rizinorg/cutter/issues/new?&body=**Environment information**\n* "
"Operating System: "
+ osInfo + "\n* Cutter version: " + CUTTER_VERSION_FULL + "\n* Obtained from:\n"
+ " - [ ] Built from source\n - [ ] Downloaded release from Cutter website or GitHub "
"\n"
" - [ ] Distribution repository\n* File format: "
+ format + "\n * Arch: " + arch + "\n * Type: " + type
+ "\n\n**Describe the bug**\n\n<!-- A clear and concise description of what the bug "
"is. -->"
"\n\n**To Reproduce**\n\n"
"Steps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll "
"down to '....'\n"
"4. See error\n\n**Expected behavior**\n\n"
"<!-- A clear and concise description of what you expected to happen. -->\n\n\n"
"**Screenshots**\n\n<!-- If applicable, add screenshots to help explain your "
"problem. -->\n\n\n"
"**Additional context**\n\n<!-- Add any other context about the problem here. -->\n";
QDesktopServices::openUrl(QUrl(url, QUrl::TolerantMode));
}
| 2,070
|
C++
|
.cpp
| 39
| 44.897436
| 100
| 0.585101
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,608
|
SvgIconEngine.cpp
|
rizinorg_cutter/src/common/SvgIconEngine.cpp
|
#include "SvgIconEngine.h"
#include <QSvgRenderer>
#include <QPainter>
#include <QFile>
#include "Helpers.h"
SvgIconEngine::SvgIconEngine(const QString &filename)
{
QFile file(filename);
file.open(QFile::ReadOnly);
this->svgData = file.readAll();
}
SvgIconEngine::SvgIconEngine(const QString &filename, const QColor &tintColor)
: SvgIconEngine(filename)
{
this->svgData = qhelpers::applyColorToSvg(svgData, tintColor);
}
SvgIconEngine::SvgIconEngine(const QString &filename, QPalette::ColorRole colorRole)
: SvgIconEngine(filename, QPalette().color(colorRole))
{
}
void SvgIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode /*mode*/,
QIcon::State /*state*/)
{
QSvgRenderer renderer(svgData);
renderer.render(painter, rect);
}
QIconEngine *SvgIconEngine::clone() const
{
return new SvgIconEngine(*this);
}
QPixmap SvgIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
QImage img(size, QImage::Format_ARGB32);
img.fill(qRgba(0, 0, 0, 0));
QPixmap pix = QPixmap::fromImage(img, Qt::NoFormatConversion);
{
QPainter painter(&pix);
QRect r(QPoint(0, 0), size);
this->paint(&painter, r, mode, state);
}
return pix;
}
| 1,273
|
C++
|
.cpp
| 42
| 26.47619
| 86
| 0.708674
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,609
|
BasicBlockHighlighter.cpp
|
rizinorg_cutter/src/common/BasicBlockHighlighter.cpp
|
#include "BasicBlockHighlighter.h"
BasicBlockHighlighter::BasicBlockHighlighter() {}
/**
* @brief Highlight the basic block at address
*/
void BasicBlockHighlighter::highlight(RVA address, const QColor &color)
{
BasicBlock block;
block.address = address;
block.color = color;
bbMap[address] = block;
}
/**
* @brief Clear the basic block highlighting
*/
void BasicBlockHighlighter::clear(RVA address)
{
bbMap.erase(address);
}
/**
* @brief Return a highlighted basic block
*
* If there is nothing to highlight at specified address, returns nullptr
*/
BasicBlockHighlighter::BasicBlock *BasicBlockHighlighter::getBasicBlock(RVA address)
{
auto it = bbMap.find(address);
if (it != bbMap.end()) {
return &it->second;
}
return nullptr;
}
| 790
|
C++
|
.cpp
| 32
| 21.90625
| 84
| 0.734396
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,610
|
RichTextPainter.cpp
|
rizinorg_cutter/src/common/RichTextPainter.cpp
|
/* x64dbg RichTextPainter */
#include "RichTextPainter.h"
#include "CachedFontMetrics.h"
#include "common/Configuration.h"
#include <QPainter>
#include <QTextBlock>
#include <QTextFragment>
// TODO: fix performance (possibly use QTextLayout?)
template<typename T>
void RichTextPainter::paintRichText(QPainter *painter, T x, T y, T w, T h, T xinc,
const List &richText, CachedFontMetrics<T> *fontMetrics)
{
QPen pen;
QPen highlightPen;
QBrush brush(Qt::cyan);
for (const CustomRichText_t &curRichText : richText) {
T textWidth = fontMetrics->width(curRichText.text);
T backgroundWidth = textWidth;
if (backgroundWidth + xinc > w)
backgroundWidth = w - xinc;
if (backgroundWidth <= 0) // stop drawing when going outside the specified width
break;
switch (curRichText.flags) {
case FlagNone: // defaults
pen.setColor(ConfigColor("btext").name());
painter->setPen(pen);
break;
case FlagColor: // color only
pen.setColor(curRichText.textColor);
painter->setPen(pen);
break;
case FlagBackground: // background only
if (backgroundWidth > 0 && curRichText.textBackground.alpha()) {
brush.setColor(curRichText.textBackground);
painter->fillRect(QRectF(x + xinc, y, backgroundWidth, h), brush);
}
break;
case FlagAll: // color+background
if (backgroundWidth > 0 && curRichText.textBackground.alpha()) {
brush.setColor(curRichText.textBackground);
painter->fillRect(QRectF(x + xinc, y, backgroundWidth, h), brush);
}
pen.setColor(curRichText.textColor);
painter->setPen(pen);
break;
}
int flags = 0;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
flags = Qt::TextBypassShaping;
#endif
painter->drawText(typename Metrics<T>::Rect(x + xinc, y, w - xinc, h), flags,
curRichText.text);
if (curRichText.highlight && curRichText.highlightColor.alpha()) {
highlightPen.setColor(curRichText.highlightColor);
highlightPen.setWidth(curRichText.highlightWidth);
painter->setPen(highlightPen);
T highlightOffsetX = curRichText.highlightConnectPrev ? -1 : 1;
painter->drawLine(x + xinc + highlightOffsetX, y + h - 1,
x + xinc + backgroundWidth - 1, y + h - 1);
}
xinc += textWidth;
}
}
template void RichTextPainter::paintRichText<qreal>(QPainter *painter, qreal x, qreal y, qreal w,
qreal h, qreal xinc, const List &richText,
CachedFontMetrics<qreal> *fontMetrics);
/**
* @brief RichTextPainter::htmlRichText Convert rich text in x64dbg to HTML, for use by other
* applications
* @param richText The rich text to be converted to HTML format
* @param textHtml The HTML source. Any previous content will be preserved and new content will be
* appended at the end.
* @param textPlain The plain text. Any previous content will be preserved and new content will be
* appended at the end.
*/
void RichTextPainter::htmlRichText(const List &richText, QString &textHtml, QString &textPlain)
{
for (const CustomRichText_t &curRichText : richText) {
if (curRichText.text == " ") { // blank
textHtml += " ";
textPlain += " ";
continue;
}
switch (curRichText.flags) {
case FlagNone: // defaults
textHtml += "<span>";
break;
case FlagColor: // color only
textHtml += QString("<span style=\"color:%1\">").arg(curRichText.textColor.name());
break;
case FlagBackground: // background only
if (curRichText.textBackground
!= Qt::transparent) // QColor::name() returns "#000000" for transparent color.
// That's not desired. Leave it blank.
textHtml += QString("<span style=\"background-color:%1\">")
.arg(curRichText.textBackground.name());
else
textHtml += QString("<span>");
break;
case FlagAll: // color+background
if (curRichText.textBackground
!= Qt::transparent) // QColor::name() returns "#000000" for transparent color.
// That's not desired. Leave it blank.
textHtml += QString("<span style=\"color:%1; background-color:%2\">")
.arg(curRichText.textColor.name(),
curRichText.textBackground.name());
else
textHtml += QString("<span style=\"color:%1\">").arg(curRichText.textColor.name());
break;
}
if (curRichText.highlight) // Underline highlighted token
textHtml += "<u>";
textHtml += curRichText.text.toHtmlEscaped();
if (curRichText.highlight)
textHtml += "</u>";
textHtml += "</span>"; // Close the tag
textPlain += curRichText.text;
}
}
RichTextPainter::List RichTextPainter::fromTextDocument(const QTextDocument &doc)
{
List r;
for (QTextBlock block = doc.begin(); block != doc.end(); block = block.next()) {
for (QTextBlock::iterator it = block.begin(); it != block.end(); ++it) {
QTextFragment fragment = it.fragment();
QTextCharFormat format = fragment.charFormat();
CustomRichText_t text;
text.text = fragment.text();
text.textColor = format.foreground().color();
text.textBackground = format.background().color();
bool hasForeground = format.hasProperty(QTextFormat::ForegroundBrush);
bool hasBackground = format.hasProperty(QTextFormat::BackgroundBrush);
if (hasForeground && !hasBackground) {
text.flags = FlagColor;
} else if (!hasForeground && hasBackground) {
text.flags = FlagBackground;
} else if (hasForeground && hasBackground) {
text.flags = FlagAll;
} else {
text.flags = FlagNone;
}
r.push_back(text);
}
}
return r;
}
RichTextPainter::List RichTextPainter::cropped(const RichTextPainter::List &richText, int maxCols,
const QString &indicator, bool *croppedOut)
{
List r;
r.reserve(richText.size());
int cols = 0;
bool cropped = false;
for (const auto &text : richText) {
int textLength = text.text.size();
if (cols + textLength <= maxCols) {
r.push_back(text);
cols += textLength;
} else if (cols == maxCols) {
break;
} else {
CustomRichText_t croppedText = text;
croppedText.text.truncate(maxCols - cols);
r.push_back(croppedText);
cropped = true;
break;
}
}
if (cropped && !indicator.isEmpty()) {
int indicatorCropLength = indicator.length();
if (indicatorCropLength > maxCols) {
indicatorCropLength = maxCols;
}
while (!r.empty()) {
auto &text = r.back();
if (text.text.length() >= indicatorCropLength) {
text.text.replace(text.text.length() - indicatorCropLength, indicatorCropLength,
indicator);
break;
}
indicatorCropLength -= text.text.length();
r.pop_back();
}
}
if (croppedOut) {
*croppedOut = cropped;
}
return r;
}
| 7,949
|
C++
|
.cpp
| 189
| 30.809524
| 99
| 0.571632
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,611
|
DisassemblyPreview.cpp
|
rizinorg_cutter/src/common/DisassemblyPreview.cpp
|
#include "DisassemblyPreview.h"
#include "Configuration.h"
#include "widgets/GraphView.h"
#include <QCoreApplication>
#include <QWidget>
#include <QToolTip>
#include <QProcessEnvironment>
DisassemblyTextBlockUserData::DisassemblyTextBlockUserData(const DisassemblyLine &line)
: line { line }
{
}
DisassemblyTextBlockUserData *getUserData(const QTextBlock &block)
{
QTextBlockUserData *userData = block.userData();
if (!userData) {
return nullptr;
}
return static_cast<DisassemblyTextBlockUserData *>(userData);
}
QString DisassemblyPreview::getToolTipStyleSheet()
{
return QString { "QToolTip { border-width: 1px; max-width: %1px;"
"opacity: 230; background-color: %2;"
"color: %3; border-color: %3;}" }
.arg(400)
.arg(Config()->getColor("gui.tooltip.background").name())
.arg(Config()->getColor("gui.tooltip.foreground").name());
}
bool DisassemblyPreview::showDisasPreview(QWidget *parent, const QPoint &pointOfEvent,
const RVA offsetFrom)
{
QList<XrefDescription> refs = Core()->getXRefs(offsetFrom, false, false);
if (refs.length()) {
if (refs.length() > 1) {
qWarning() << QObject::tr(
"More than one (%1) references here. Weird behaviour expected.")
.arg(refs.length());
}
RVA offsetTo = refs.at(0).to; // This is the offset we want to preview
/*
* Only if the offset we point *to* is different from the one the cursor is currently
* on *and* the former is a valid offset, we are allowed to get a preview of offsetTo
*/
if (offsetTo != offsetFrom && offsetTo != RVA_INVALID) {
QStringList disasmPreview = Core()->getDisassemblyPreview(offsetTo, 10);
// Last check to make sure the returned preview isn't an empty text (QStringList)
if (!disasmPreview.isEmpty()) {
const QFont &fnt = Config()->getFont();
QFontMetrics fm { fnt };
QString tooltip =
QString { "<html><div style=\"font-family: %1; font-size: %2pt; "
"white-space: nowrap;\"><div style=\"margin-bottom: "
"10px;\"><strong>Disassembly Preview</strong>:<br>%3<div>" }
.arg(fnt.family())
.arg(qMax(8, fnt.pointSize() - 1))
.arg(disasmPreview.join("<br>"));
QToolTip::showText(pointOfEvent, tooltip, parent, QRect {}, 3500);
return true;
}
}
}
return false;
}
RVA DisassemblyPreview::readDisassemblyOffset(QTextCursor tc)
{
auto userData = getUserData(tc.block());
if (!userData) {
return RVA_INVALID;
}
return userData->line.offset;
}
typedef struct mmio_lookup_context
{
QString selected;
RVA mmio_address;
} mmio_lookup_context_t;
static bool lookup_mmio_addr_cb(void *user, const ut64 key, const void *value)
{
mmio_lookup_context_t *ctx = (mmio_lookup_context_t *)user;
if (ctx->selected == (const char *)value) {
ctx->mmio_address = key;
return false;
}
return true;
}
bool DisassemblyPreview::showDebugValueTooltip(QWidget *parent, const QPoint &pointOfEvent,
const QString &selectedText, const RVA offset)
{
if (selectedText.isEmpty())
return false;
if (selectedText.at(0).isLetter()) {
{
const auto registerRefs = Core()->getRegisterRefValues();
for (auto ® : registerRefs) {
if (reg.name == selectedText) {
auto msg = QString("reg %1 = %2").arg(reg.name, reg.value);
QToolTip::showText(pointOfEvent, msg, parent);
return true;
}
}
}
if (offset != RVA_INVALID) {
auto vars = Core()->getVariables(offset);
for (auto &var : vars) {
if (var.name == selectedText) {
auto msg = QString("var %1 = %2").arg(var.name, var.value);
QToolTip::showText(pointOfEvent, msg, parent);
return true;
}
}
}
{
// Lookup MMIO address
mmio_lookup_context_t ctx;
ctx.selected = selectedText;
ctx.mmio_address = RVA_INVALID;
auto core = Core()->core();
RzPlatformTarget *arch_target = core->analysis->arch_target;
if (arch_target && arch_target->profile) {
ht_up_foreach(arch_target->profile->registers_mmio, lookup_mmio_addr_cb, &ctx);
}
if (ctx.mmio_address != RVA_INVALID) {
int len = 8; // TODO: Determine proper len of mmio address for the cpu
if (char *r = rz_core_print_hexdump_or_hexdiff_str(core, RZ_OUTPUT_MODE_STANDARD,
ctx.mmio_address, len, false)) {
auto val = QString::fromUtf8(r).trimmed().split("\n").last();
auto msg = QString("mmio %1 %2").arg(selectedText, val);
free(r);
QToolTip::showText(pointOfEvent, msg, parent);
return true;
}
}
}
}
// Else show preview for value?
return false;
}
| 5,612
|
C++
|
.cpp
| 137
| 29.364964
| 99
| 0.54967
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,612
|
CutterSeekable.cpp
|
rizinorg_cutter/src/common/CutterSeekable.cpp
|
#include "core/MainWindow.h"
#include "CutterSeekable.h"
#include <QPlainTextEdit>
CutterSeekable::CutterSeekable(QObject *parent) : QObject(parent)
{
connect(Core(), &CutterCore::seekChanged, this, &CutterSeekable::onCoreSeekChanged);
}
CutterSeekable::~CutterSeekable() {}
void CutterSeekable::setSynchronization(bool sync)
{
synchronized = sync;
onCoreSeekChanged(Core()->getOffset(), CutterCore::SeekHistoryType::New);
emit syncChanged();
}
void CutterSeekable::onCoreSeekChanged(RVA addr, CutterCore::SeekHistoryType type)
{
if (synchronized && widgetOffset != addr) {
updateSeek(addr, type, true);
}
}
void CutterSeekable::updateSeek(RVA addr, CutterCore::SeekHistoryType type, bool localOnly)
{
previousOffset = widgetOffset;
widgetOffset = addr;
if (synchronized && !localOnly) {
Core()->seek(addr);
}
emit seekableSeekChanged(addr, type);
}
void CutterSeekable::seekPrev()
{
if (synchronized) {
Core()->seekPrev();
} else {
this->seek(previousOffset, CutterCore::SeekHistoryType::Undo);
}
}
RVA CutterSeekable::getOffset()
{
return (synchronized) ? Core()->getOffset() : widgetOffset;
}
void CutterSeekable::toggleSynchronization()
{
setSynchronization(!synchronized);
}
bool CutterSeekable::isSynchronized()
{
return synchronized;
}
void CutterSeekable::seekToReference(RVA offset)
{
if (offset == RVA_INVALID) {
return;
}
QList<XrefDescription> refs = Core()->getXRefs(offset, false, false);
if (refs.length()) {
if (refs.length() > 1) {
qWarning() << tr("More than one (%1) references here. Weird behaviour expected.")
.arg(refs.length());
}
// Try first call
for (auto &ref : refs) {
if (ref.to != RVA_INVALID && ref.type == "CALL") {
seek(ref.to);
return;
}
}
// Fallback to first valid, if any
for (auto &ref : refs) {
if (ref.to != RVA_INVALID) {
seek(ref.to);
return;
}
}
}
}
| 2,157
|
C++
|
.cpp
| 76
| 22.592105
| 93
| 0.630866
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,613
|
ColorThemeWorker.cpp
|
rizinorg_cutter/src/common/ColorThemeWorker.cpp
|
#include "ColorThemeWorker.h"
#include <QDir>
#include <QFile>
#include <QColor>
#include <QJsonArray>
#include <QStandardPaths>
#include <QRegularExpression>
#include <rz_util/rz_path.h>
#include "common/Configuration.h"
const QStringList ColorThemeWorker::cutterSpecificOptions = {
"wordHighlight", "lineHighlight", "gui.main",
"gui.imports", "highlightPC", "gui.navbar.err",
"gui.navbar.seek", "gui.navbar.pc", "gui.navbar.sym",
"gui.dataoffset", "gui.navbar.code", "gui.navbar.empty",
"angui.navbar.str", "gui.disass_selected", "gui.breakpoint_background",
"gui.overview.node", "gui.overview.fill", "gui.overview.border",
"gui.border", "gui.background", "gui.alt_background",
"gui.disass_selected"
};
const QStringList ColorThemeWorker::rizinUnusedOptions = {
"linehl", "wordhl", "graph.box", "graph.box2", "graph.box3",
"graph.box4", "graph.current", "graph.box2", "widget_sel", "widget_bg",
"label", "ai.write", "invalid", "ai.seq", "args",
"ai.read", "ai.exec", "ai.ascii", "prompt", "graph.traced"
};
ColorThemeWorker::ColorThemeWorker(QObject *parent) : QObject(parent)
{
char *szThemes = rz_path_home_prefix(RZ_THEMES);
customRzThemesLocationPath = szThemes;
rz_mem_free(szThemes);
if (!QDir(customRzThemesLocationPath).exists()) {
QDir().mkpath(customRzThemesLocationPath);
}
char *theme_dir = rz_path_prefix(RZ_THEMES);
QDir currDir { theme_dir };
if (currDir.exists()) {
standardRzThemesLocationPath = currDir.absolutePath();
} else {
QMessageBox::critical(nullptr, tr("Standard themes not found"),
tr("The Rizin standard themes could not be found in '%1'. "
"Most likely, Rizin is not properly installed.")
.arg(currDir.path()));
}
free(theme_dir);
}
QColor ColorThemeWorker::mergeColors(const QColor &upper, const QColor &lower) const
{
qhelpers::ColorFloat r1, g1, b1, a1;
qhelpers::ColorFloat r2, g2, b2, a2;
qhelpers::ColorFloat r, g, b, a;
upper.getRgbF(&r1, &g1, &b1, &a1);
lower.getRgbF(&r2, &g2, &b2, &a2);
a = (1.0 - a1) * a2 + a1;
r = ((1.0 - a1) * a2 * r2 + a1 * r1) / a;
g = ((1.0 - a1) * a2 * g2 + a1 * g1) / a;
b = ((1.0 - a1) * a2 * b2 + a1 * b1) / a;
QColor res;
res.setRgbF(r, g, b, a);
return res;
}
QString ColorThemeWorker::copy(const QString &srcThemeName, const QString ©ThemeName) const
{
if (!isThemeExist(srcThemeName)) {
return tr("Theme <b>%1</b> does not exist.").arg(srcThemeName);
}
return save(getTheme(srcThemeName), copyThemeName);
}
QString ColorThemeWorker::save(const Theme &theme, const QString &themeName) const
{
QFile fOut(QDir(customRzThemesLocationPath).filePath(themeName));
if (!fOut.open(QFile::WriteOnly | QFile::Truncate)) {
return tr("The file <b>%1</b> cannot be opened.").arg(QFileInfo(fOut).filePath());
}
for (auto it = theme.constBegin(); it != theme.constEnd(); it++) {
const QColor &color = it.value();
if (cutterSpecificOptions.contains(it.key())) {
fOut.write(QString("#~%1 rgb:%2\n")
.arg(it.key(), color.name(QColor::HexArgb).remove('#'))
.toUtf8());
} else {
fOut.write(QString("ec %1 rgb:%2\n")
.arg(it.key(), color.name(QColor::HexRgb).remove('#'))
.toUtf8());
}
}
fOut.close();
return "";
}
bool ColorThemeWorker::isCustomTheme(const QString &themeName) const
{
return QFile::exists(QDir(customRzThemesLocationPath).filePath(themeName));
}
bool ColorThemeWorker::isThemeExist(const QString &name) const
{
QStringList themes = Core()->getColorThemes();
return themes.contains(name);
}
ColorThemeWorker::Theme ColorThemeWorker::getTheme(const QString &themeName) const
{
Theme theme;
QString curr = Config()->getColorTheme();
if (themeName != curr) {
RzCoreLocked core(Core());
rz_core_theme_load(core, themeName.toUtf8().constData());
theme = Core()->getTheme();
rz_core_theme_load(core, curr.toUtf8().constData());
} else {
theme = Core()->getTheme();
}
ColorFlags colorFlags = ColorFlags::DarkFlag;
if (Configuration::relevantThemes.contains(themeName)) {
colorFlags = Configuration::relevantThemes[themeName];
}
for (auto &it : cutterSpecificOptions) {
theme.insert(it, QColor(Configuration::cutterOptionColors[it][colorFlags]));
}
if (isCustomTheme(themeName)) {
QFile src(QDir(customRzThemesLocationPath).filePath(themeName));
if (!src.open(QFile::ReadOnly)) {
return {};
}
QStringList sl;
for (auto &line : QString(src.readAll()).split('\n', CUTTER_QT_SKIP_EMPTY_PARTS)) {
sl = line.replace("#~", "ec ")
.replace("rgb:", "#")
.split(' ', CUTTER_QT_SKIP_EMPTY_PARTS);
if (sl.size() != 3 || sl[0][0] == '#') {
continue;
}
theme.insert(sl[1], QColor(sl[2]));
}
}
for (auto &key : rizinUnusedOptions) {
theme.remove(key);
}
return theme;
}
QString ColorThemeWorker::deleteTheme(const QString &themeName) const
{
if (!isCustomTheme(themeName)) {
return tr("You can not delete standard Rizin color themes.");
}
if (!isThemeExist(themeName)) {
return tr("Theme <b>%1</b> does not exist.").arg(themeName);
}
QFile file(QDir(customRzThemesLocationPath).filePath(themeName));
if (file.isWritable()) {
return tr("You have no permission to write to <b>%1</b>").arg(QFileInfo(file).filePath());
}
if (!file.open(QFile::ReadOnly)) {
return tr("File <b>%1</b> can not be opened.").arg(QFileInfo(file).filePath());
}
if (!file.remove()) {
return tr("File <b>%1</b> can not be removed.").arg(QFileInfo(file).filePath());
}
return "";
}
QString ColorThemeWorker::importTheme(const QString &file) const
{
QFileInfo src(file);
if (!src.exists()) {
return tr("File <b>%1</b> does not exist.").arg(file);
}
bool ok;
bool isTheme = isFileTheme(file, &ok);
if (!ok) {
return tr("File <b>%1</b> could not be opened. "
"Please make sure you have access to it and try again.")
.arg(file);
} else if (!isTheme) {
return tr("File <b>%1</b> is not a Cutter color theme").arg(file);
}
QString name = src.fileName();
if (isThemeExist(name)) {
return tr("A color theme named <b>%1</b> already exists.").arg(name);
}
if (QFile::copy(file, QDir(customRzThemesLocationPath).filePath(name))) {
return "";
} else {
return tr("Error occurred during importing. "
"Please make sure you have an access to "
"the directory <b>%1</b> and try again.")
.arg(src.dir().path());
}
}
QString ColorThemeWorker::renameTheme(const QString &themeName, const QString &newName) const
{
if (isThemeExist(newName)) {
return tr("A color theme named <b>\"%1\"</b> already exists.").arg(newName);
}
if (!isCustomTheme(themeName)) {
return tr("You can not rename standard Rizin themes.");
}
QDir dir = customRzThemesLocationPath;
bool ok = QFile::rename(dir.filePath(themeName), dir.filePath(newName));
if (!ok) {
return tr("Something went wrong during renaming. "
"Please make sure you have access to the directory <b>\"%1\"</b>.")
.arg(dir.path());
}
return "";
}
bool ColorThemeWorker::isFileTheme(const QString &filePath, bool *ok) const
{
QFile f(filePath);
if (!f.open(QFile::ReadOnly)) {
*ok = false;
return false;
}
const QString colors = "black|red|white|green|magenta|yellow|cyan|blue|gray|none";
QString options =
(Core()->getThemeKeys() << cutterSpecificOptions).join('|').replace(".", "\\.");
QString pattern =
QString("((ec\\s+(%1)\\s+(((rgb:|#)[0-9a-fA-F]{3,8})|(%2))))\\s*").arg(options, colors);
// The below construct mimics the behaviour of QRegexP::exactMatch(), which was here before
QRegularExpression regexp("\\A(?:" + pattern + ")\\z");
for (auto &line : QString(f.readAll()).split('\n', CUTTER_QT_SKIP_EMPTY_PARTS)) {
line.replace("#~", "ec ");
if (!line.isEmpty() && !regexp.match(line).hasMatch()) {
*ok = true;
return false;
}
}
*ok = true;
return true;
}
QStringList ColorThemeWorker::customThemes() const
{
QStringList themes = Core()->getColorThemes();
QStringList ret;
for (int i = 0; i < themes.size(); i++) {
if (isCustomTheme(themes[i])) {
ret.push_back(themes[i]);
}
}
return ret;
}
const QStringList &ColorThemeWorker::getRizinSpecificOptions()
{
if (rizinSpecificOptions.isEmpty()) {
rizinSpecificOptions << Core()->getThemeKeys();
}
return rizinSpecificOptions;
}
| 9,360
|
C++
|
.cpp
| 244
| 31.512295
| 100
| 0.602027
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,614
|
AnalysisTask.cpp
|
rizinorg_cutter/src/common/AnalysisTask.cpp
|
#include "core/Cutter.h"
#include "common/AnalysisTask.h"
#include "core/MainWindow.h"
#include "dialogs/InitialOptionsDialog.h"
#include <QJsonArray>
#include <QDebug>
#include <QCheckBox>
AnalysisTask::AnalysisTask() : AsyncTask() {}
AnalysisTask::~AnalysisTask() {}
void AnalysisTask::interrupt()
{
AsyncTask::interrupt();
rz_cons_singleton()->context->breaked = true;
}
QString AnalysisTask::getTitle()
{
// If no file is loaded we consider it's Initial Analysis
RzCoreLocked core(Core());
RzList *descs = rz_id_storage_list(core->io->files);
if (rz_list_empty(descs)) {
return tr("Initial Analysis");
}
return tr("Analyzing Program");
}
void AnalysisTask::runTask()
{
int perms = RZ_PERM_RX;
if (options.writeEnabled) {
perms |= RZ_PERM_W;
emit Core()->ioModeChanged();
}
// Demangle (must be before file Core()->loadFile)
Core()->setConfig("bin.demangle", options.demangle);
// Do not reload the file if already loaded
RzCoreLocked core(Core());
RzList *descs = rz_id_storage_list(core->io->files);
if (rz_list_empty(descs) && options.filename.length()) {
log(tr("Loading the file..."));
openFailed = false;
bool fileLoaded =
Core()->loadFile(options.filename, options.binLoadAddr, options.mapAddr, perms,
options.useVA, options.loadBinInfo, options.forceBinPlugin);
if (!fileLoaded) {
// Something wrong happened, fallback to open dialog
openFailed = true;
emit openFileFailed();
interrupt();
return;
}
}
// rz_core_bin_load might change asm.bits, so let's set that after the bin is loaded
Core()->setCPU(options.arch, options.cpu, options.bits);
if (isInterrupted()) {
return;
}
if (!options.os.isNull()) {
RzCoreLocked core(Core());
rz_config_set(core->config, "asm.os", options.os.toUtf8().constData());
}
if (!options.pdbFile.isNull()) {
log(tr("Loading PDB file..."));
Core()->loadPDB(options.pdbFile);
}
if (isInterrupted()) {
return;
}
if (!options.shellcode.isNull() && options.shellcode.size() / 2 > 0) {
log(tr("Loading shellcode..."));
rz_core_write_hexpair(core, core->offset, options.shellcode.toStdString().c_str());
}
if (options.endian != InitialOptions::Endianness::Auto) {
Core()->setEndianness(options.endian == InitialOptions::Endianness::Big);
}
rz_flag_space_set(core->flags, "*");
if (!options.script.isNull()) {
log(tr("Executing script..."));
Core()->loadScript(options.script);
}
if (isInterrupted()) {
return;
}
if (!options.analysisCmd.empty()) {
log(tr("Executing analysis..."));
for (const CommandDescription &cmd : options.analysisCmd) {
if (isInterrupted()) {
return;
}
log(cmd.description);
// use cmd instead of cmdRaw because commands can be unexpected
Core()->cmd(cmd.command);
}
log(tr("Analysis complete!"));
} else {
log(tr("Skipping Analysis."));
}
}
| 3,261
|
C++
|
.cpp
| 96
| 27.104167
| 95
| 0.61074
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,615
|
RunScriptTask.cpp
|
rizinorg_cutter/src/common/RunScriptTask.cpp
|
#include "core/Cutter.h"
#include "common/RunScriptTask.h"
#include "core/MainWindow.h"
RunScriptTask::RunScriptTask() : AsyncTask() {}
RunScriptTask::~RunScriptTask() {}
void RunScriptTask::interrupt()
{
AsyncTask::interrupt();
rz_cons_singleton()->context->breaked = true;
}
void RunScriptTask::runTask()
{
if (!this->fileName.isNull()) {
log(tr("Executing script..."));
Core()->functionTask([&](RzCore *core) {
rz_core_run_script(core, this->fileName.toUtf8().constData());
return nullptr;
});
if (isInterrupted()) {
return;
}
}
}
| 630
|
C++
|
.cpp
| 23
| 22.217391
| 74
| 0.621891
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,616
|
RizinTask.cpp
|
rizinorg_cutter/src/common/RizinTask.cpp
|
#include "RizinTask.h"
#include <rz_core.h>
RizinTask::~RizinTask()
{
if (task) {
rz_core_task_decref(task);
}
}
void RizinTask::startTask()
{
rz_core_task_enqueue(&Core()->core_->tasks, task);
}
void RizinTask::breakTask()
{
rz_core_task_break(&Core()->core_->tasks, task->id);
}
void RizinTask::joinTask()
{
rz_core_task_join(&Core()->core_->tasks, nullptr, task->id);
}
void RizinTask::taskFinished()
{
emit finished();
}
// RizinCmdTask
RizinCmdTask::RizinCmdTask(const QString &cmd, bool transient)
{
task = rz_core_cmd_task_new(
Core()->core(), cmd.toLocal8Bit().constData(),
static_cast<RzCoreCmdTaskFinished>(&RizinCmdTask::taskFinishedCallback), this);
task->transient = transient;
rz_core_task_incref(task);
}
void RizinCmdTask::taskFinishedCallback(const char *, void *user)
{
reinterpret_cast<RizinCmdTask *>(user)->taskFinished();
}
QString RizinCmdTask::getResult()
{
const char *res = rz_core_cmd_task_get_result(task);
if (!res) {
return nullptr;
}
return QString::fromUtf8(res);
}
CutterJson RizinCmdTask::getResultJson()
{
const char *res = rz_core_cmd_task_get_result(task);
if (!res) {
return CutterJson();
}
char *copy = static_cast<char *>(rz_mem_alloc(strlen(res) + 1));
strcpy(copy, res);
return Core()->parseJson("task", copy, nullptr);
}
const char *RizinCmdTask::getResultRaw()
{
return rz_core_cmd_task_get_result(task);
}
// RizinFunctionTask
RizinFunctionTask::RizinFunctionTask(std::function<void *(RzCore *)> fcn, bool transient)
: fcn(fcn), res(nullptr)
{
task = rz_core_function_task_new(
Core()->core(), static_cast<RzCoreTaskFunction>(&RizinFunctionTask::runner), this);
task->transient = transient;
rz_core_task_incref(task);
}
void *RizinFunctionTask::runner(RzCore *core, void *user)
{
RizinFunctionTask *task = reinterpret_cast<RizinFunctionTask *>(user);
task->res = task->fcn(core);
task->taskFinished();
return nullptr;
}
| 2,056
|
C++
|
.cpp
| 75
| 23.866667
| 95
| 0.683622
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,617
|
SelectionHighlight.cpp
|
rizinorg_cutter/src/common/SelectionHighlight.cpp
|
#include "SelectionHighlight.h"
#include "Configuration.h"
#include <QList>
#include <QTextEdit>
#include <QColor>
#include <QTextCursor>
#include <QPlainTextEdit>
#include <QRegularExpression>
QList<QTextEdit::ExtraSelection> createSameWordsSelections(QPlainTextEdit *textEdit,
const QString &word)
{
QList<QTextEdit::ExtraSelection> selections;
QTextEdit::ExtraSelection highlightSelection;
QTextDocument *document = textEdit->document();
QColor highlightWordColor = ConfigColor("wordHighlight");
if (word.isEmpty()) {
return QList<QTextEdit::ExtraSelection>();
}
highlightSelection.cursor = textEdit->textCursor();
if (word == "{" || word == "}") {
int val;
if (word == "{") {
val = 0;
} else {
val = 1;
}
selections.append(highlightSelection);
while (!highlightSelection.cursor.isNull() && !highlightSelection.cursor.atEnd()) {
if (word == "{") {
highlightSelection.cursor =
document->find(QRegularExpression("{|}"), highlightSelection.cursor);
} else {
highlightSelection.cursor =
document->find(QRegularExpression("{|}"), highlightSelection.cursor,
QTextDocument::FindBackward);
}
if (!highlightSelection.cursor.isNull()) {
if (highlightSelection.cursor.selectedText() == word) {
val++;
} else {
val--;
}
if (val == 0) {
highlightSelection.format.setBackground(highlightWordColor);
selections.append(highlightSelection);
break;
}
}
}
return selections;
}
highlightSelection.cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
while (!highlightSelection.cursor.isNull() && !highlightSelection.cursor.atEnd()) {
highlightSelection.cursor =
document->find(word, highlightSelection.cursor, QTextDocument::FindWholeWords);
if (!highlightSelection.cursor.isNull()) {
highlightSelection.format.setBackground(highlightWordColor);
selections.append(highlightSelection);
}
}
return selections;
}
QTextEdit::ExtraSelection createLineHighlight(const QTextCursor &cursor, QColor highlightColor)
{
QTextEdit::ExtraSelection highlightSelection;
highlightSelection.cursor = cursor;
highlightSelection.format.setBackground(highlightColor);
highlightSelection.format.setProperty(QTextFormat::FullWidthSelection, true);
highlightSelection.cursor.clearSelection();
return highlightSelection;
}
QTextEdit::ExtraSelection createLineHighlightSelection(const QTextCursor &cursor)
{
QColor highlightColor = ConfigColor("lineHighlight");
return createLineHighlight(cursor, highlightColor);
}
QTextEdit::ExtraSelection createLineHighlightPC(const QTextCursor &cursor)
{
QColor highlightColor = ConfigColor("highlightPC");
return createLineHighlight(cursor, highlightColor);
}
QTextEdit::ExtraSelection createLineHighlightBP(const QTextCursor &cursor)
{
QColor highlightColor = ConfigColor("gui.breakpoint_background");
return createLineHighlight(cursor, highlightColor);
}
| 3,459
|
C++
|
.cpp
| 86
| 31.162791
| 95
| 0.655152
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,618
|
QtResImporter.cpp
|
rizinorg_cutter/src/common/QtResImporter.cpp
|
#include "PythonAPI.h"
#include "QtResImporter.h"
#include <QFile>
#include <QDebug>
bool QtResExists(const char *name, QFile &file)
{
QString fname = QString::asprintf(":/python/%s.py", name);
file.setFileName(fname);
return file.exists();
}
PyObject *QtResGetCode(const char *name)
{
QFile moduleFile;
if (!QtResExists(name, moduleFile)) {
return nullptr;
}
moduleFile.open(QIODevice::ReadOnly);
QByteArray data = moduleFile.readAll();
moduleFile.close();
PyObject *codeObject = Py_CompileString(
data.constData(), moduleFile.fileName().toLocal8Bit().constData(), Py_file_input);
if (!codeObject) {
qWarning() << "Couldn't compile " << moduleFile.fileName();
}
return codeObject;
}
PyObject *QtResImport(const char *name)
{
PyObject *codeObject = QtResGetCode(name);
if (!codeObject) {
return nullptr;
}
PyObject *module = PyImport_ExecCodeModule(name, codeObject);
if (!module) {
PyErr_Print();
}
Py_DECREF(codeObject);
return module;
}
PyObject *qtres_exists(PyObject *self, PyObject *args)
{
Q_UNUSED(self)
char *name;
QFile resFile;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
return PyBool_FromLong(QtResExists(name, resFile));
}
PyObject *qtres_get_code(PyObject *self, PyObject *args)
{
Q_UNUSED(self)
char *name;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
PyObject *ret = QtResGetCode(name);
if (ret)
return ret;
Py_RETURN_NONE;
}
PyMethodDef QtResMethods[] = { { "exists", qtres_exists, METH_VARARGS, NULL },
{ "get_code", qtres_get_code, METH_VARARGS, NULL },
{ NULL, NULL, 0, NULL } };
PyModuleDef QtResModule = {
PyModuleDef_HEAD_INIT, "_qtres", NULL, -1, QtResMethods, NULL, NULL, NULL, NULL
};
PyObject *PyInit_qtres()
{
return PyModule_Create(&QtResModule);
}
| 1,976
|
C++
|
.cpp
| 69
| 23.608696
| 94
| 0.648021
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,619
|
Decompiler.cpp
|
rizinorg_cutter/src/common/Decompiler.cpp
|
#include "Decompiler.h"
#include "Cutter.h"
#include <QJsonObject>
#include <QJsonArray>
Decompiler::Decompiler(const QString &id, const QString &name, QObject *parent)
: QObject(parent), id(id), name(name)
{
}
RzAnnotatedCode *Decompiler::makeWarning(QString warningMessage)
{
std::string temporary = warningMessage.toStdString();
return rz_annotated_code_new(strdup(temporary.c_str()));
}
| 407
|
C++
|
.cpp
| 13
| 29.076923
| 79
| 0.764103
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,620
|
Configuration.cpp
|
rizinorg_cutter/src/common/Configuration.cpp
|
#include "Configuration.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QDir>
#include <QFontDatabase>
#include <QFile>
#include <QApplication>
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
# include <KSyntaxHighlighting/Repository>
# include <KSyntaxHighlighting/Theme>
# include <KSyntaxHighlighting/Definition>
#endif
#include "common/ColorThemeWorker.h"
#include "common/SyntaxHighlighter.h"
#include "common/ResourcePaths.h"
/* Map with names of themes associated with its color palette
* (Dark or Light), so for dark interface themes will be shown only Dark color themes
* and for light - only light ones.
*/
const QHash<QString, ColorFlags> Configuration::relevantThemes = {
{ "ayu", DarkFlag }, { "basic", DarkFlag }, { "behelit", DarkFlag },
{ "bold", DarkFlag }, { "bright", DarkFlag }, { "consonance", DarkFlag },
{ "darkda", DarkFlag }, { "defragger", DarkFlag }, { "focus", DarkFlag },
{ "gentoo", DarkFlag }, { "lima", DarkFlag }, { "monokai", DarkFlag },
{ "ogray", DarkFlag }, { "onedark", DarkFlag }, { "pink", DarkFlag },
{ "rasta", DarkFlag }, { "sepia", DarkFlag }, { "smyck", DarkFlag },
{ "solarized", DarkFlag }, { "twilight", DarkFlag }, { "white2", DarkFlag },
{ "xvilka", DarkFlag }, { "zenburn", DarkFlag }, { "cga", LightFlag },
{ "cutter", LightFlag }, { "dark", LightFlag }, { "gb", LightFlag },
{ "matrix", LightFlag }, { "tango", LightFlag }, { "white", LightFlag }
};
static const QString DEFAULT_LIGHT_COLOR_THEME = "cutter";
static const QString DEFAULT_DARK_COLOR_THEME = "ayu";
const QHash<QString, QHash<ColorFlags, QColor>> Configuration::cutterOptionColors = {
{ "gui.cflow",
{ { DarkFlag, QColor(0xff, 0xff, 0xff) }, { LightFlag, QColor(0x00, 0x00, 0x00) } } },
{ "gui.dataoffset",
{ { DarkFlag, QColor(0xff, 0xff, 0xff) }, { LightFlag, QColor(0x00, 0x00, 0x00) } } },
{ "gui.imports",
{ { DarkFlag, QColor(0x32, 0x8c, 0xff) }, { LightFlag, QColor(0x32, 0x8c, 0xff) } } },
{ "gui.item_invalid",
{ { DarkFlag, QColor(0x9b, 0x9b, 0x9b) }, { LightFlag, QColor(0x9b, 0x9b, 0x9b) } } },
{ "gui.main",
{ { DarkFlag, QColor(0x21, 0xd8, 0x93) }, { LightFlag, QColor(0x00, 0x80, 0x00) } } },
{ "gui.flirt",
{ { DarkFlag, QColor(0xd8, 0xbb, 0x21) }, { LightFlag, QColor(0xf1, 0xc4, 0x0f) } } },
{ "gui.item_unsafe",
{ { DarkFlag, QColor(0xff, 0x81, 0x7b) }, { LightFlag, QColor(0xff, 0x81, 0x7b) } } },
{ "gui.navbar.seek",
{ { DarkFlag, QColor(0xe9, 0x56, 0x56) }, { LightFlag, QColor(0xff, 0x00, 0x00) } } },
{ "gui.navbar.pc",
{ { DarkFlag, QColor(0x42, 0xee, 0xf4) }, { LightFlag, QColor(0x42, 0xee, 0xf4) } } },
{ "gui.navbar.code",
{ { DarkFlag, QColor(0x82, 0xc8, 0x6f) }, { LightFlag, QColor(0x68, 0xe5, 0x45) } } },
{ "gui.navbar.str",
{ { DarkFlag, QColor(0x6f, 0x86, 0xd8) }, { LightFlag, QColor(0x45, 0x68, 0xe5) } } },
{ "gui.navbar.sym",
{ { DarkFlag, QColor(0xdd, 0xa3, 0x68) }, { LightFlag, QColor(0xe5, 0x96, 0x45) } } },
{ "gui.navbar.empty",
{ { DarkFlag, QColor(0x64, 0x64, 0x64) }, { LightFlag, QColor(0xdc, 0xec, 0xf5) } } },
{ "gui.breakpoint_background",
{ { DarkFlag, QColor(0x8c, 0x4c, 0x4c) }, { LightFlag, QColor(0xe9, 0x8f, 0x8f) } } },
{ "gui.overview.node",
{ { DarkFlag, QColor(0x64, 0x64, 0x64) }, { LightFlag, QColor(0xf5, 0xfa, 0xff) } } },
{ "gui.tooltip.background",
{ { DarkFlag, QColor(0x2a, 0x2c, 0x2e) }, { LightFlag, QColor(0xfa, 0xfc, 0xfe) } } },
{ "gui.tooltip.foreground",
{ { DarkFlag, QColor(0xfa, 0xfc, 0xfe) }, { LightFlag, QColor(0x2a, 0x2c, 0x2e) } } },
{ "gui.border",
{ { DarkFlag, QColor(0x64, 0x64, 0x64) }, { LightFlag, QColor(0x91, 0xc8, 0xfa) } } },
{ "gui.background",
{ { DarkFlag, QColor(0x25, 0x28, 0x2b) }, { LightFlag, QColor(0xff, 0xff, 0xff) } } },
{ "gui.alt_background",
{ { DarkFlag, QColor(0x1c, 0x1f, 0x24) }, { LightFlag, QColor(0xf5, 0xfa, 0xff) } } },
{ "gui.disass_selected",
{ { DarkFlag, QColor(0x1f, 0x22, 0x28) }, { LightFlag, QColor(0xff, 0xff, 0xff) } } },
{ "lineHighlight",
{ { DarkFlag, QColor(0x15, 0x1d, 0x1d, 0x96) },
{ LightFlag, QColor(0xd2, 0xd2, 0xff, 0x96) } } },
{ "wordHighlight",
{ { DarkFlag, QColor(0x34, 0x3a, 0x47, 0xff) },
{ LightFlag, QColor(0xb3, 0x77, 0xd6, 0x3c) } } },
{ "highlightPC",
{ { DarkFlag, QColor(0x57, 0x1a, 0x07) }, { LightFlag, QColor(0xd6, 0xff, 0xd2) } } },
{ "gui.overview.fill",
{ { DarkFlag, QColor(0xff, 0xff, 0xff, 0x28) },
{ LightFlag, QColor(0xaf, 0xd9, 0xea, 0x41) } } },
{ "gui.overview.border",
{ { DarkFlag, QColor(0x63, 0xda, 0xe8, 0x32) },
{ LightFlag, QColor(0x63, 0xda, 0xe8, 0x32) } } },
{ "gui.navbar.err",
{ { DarkFlag, QColor(0x03, 0xaa, 0xf5) }, { LightFlag, QColor(0x03, 0xaa, 0xf5) } } }
};
Configuration *Configuration::mPtr = nullptr;
/**
* @brief All asm.* options saved as settings. Values are the default values.
*/
static const QHash<QString, QVariant> asmOptions = { { "asm.esil", false },
{ "asm.pseudo", false },
{ "asm.offset", true },
{ "asm.xrefs", false },
{ "asm.indent", false },
{ "asm.describe", false },
{ "asm.slow", true },
{ "asm.lines", true },
{ "asm.lines.fcn", true },
{ "asm.flags.offset", false },
{ "asm.emu", false },
{ "emu.str", false },
{ "asm.cmt.right", true },
{ "asm.cmt.col", 35 },
{ "asm.var.summary", false },
{ "asm.bytes", false },
{ "asm.size", false },
{ "asm.bytes.space", false },
{ "asm.lbytes", true },
{ "asm.nbytes", 10 },
{ "asm.syntax", "intel" },
{ "asm.ucase", false },
{ "asm.bb.line", false },
{ "asm.capitalize", false },
{ "asm.sub.var", true },
{ "asm.sub.varonly", true },
{ "asm.tabs", 8 },
{ "asm.tabs.off", 5 },
{ "asm.marks", false },
{ "asm.refptr", false },
{ "asm.flags.real", true },
{ "asm.reloff", false },
{ "asm.reloff.flags", false },
{ "esil.breakoninvalid", true },
{ "dbg.trace_continue", true },
{ "graph.offset", false } };
Configuration::Configuration() : QObject(), nativePalette(qApp->palette())
{
mPtr = this;
if (!s.isWritable()) {
QMessageBox::critical(
nullptr, tr("Critical Error!"),
tr("Settings are not writable! Make sure you have a write access to \"%1\".")
.arg(s.fileName()));
}
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
kSyntaxHighlightingRepository = nullptr;
#endif
}
Configuration *Configuration::instance()
{
if (!mPtr)
mPtr = new Configuration();
return mPtr;
}
void Configuration::loadInitial()
{
setInterfaceTheme(getInterfaceTheme());
setColorTheme(getColorTheme());
applySavedAsmOptions();
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
kSyntaxHighlightingRepository = new KSyntaxHighlighting::Repository();
#endif
}
QString Configuration::getRecentFolder()
{
QString recentFolder = s.value("dir.recentFolder", QDir::homePath()).toString();
return QDir::toNativeSeparators(recentFolder);
}
void Configuration::setRecentFolder(const QString &dir)
{
s.setValue("dir.recentFolder", QDir::toNativeSeparators(dir));
}
/**
* @brief Configuration::setFilesTabLastClicked
* Set the new file dialog last clicked tab
* @param lastClicked
*/
void Configuration::setNewFileLastClicked(int lastClicked)
{
s.setValue("newFileLastClicked", lastClicked);
}
int Configuration::getNewFileLastClicked()
{
return s.value("newFileLastClicked").toInt();
}
void Configuration::resetAll()
{
// Don't reset all rizin vars, that currently breaks a bunch of stuff.
// settingsFile.remove()+loadInitials() should reset all settings configurable using Cutter GUI.
Core()->setSettings();
// Delete the file so no extra configuration is in it.
QFile settingsFile(s.fileName());
settingsFile.remove();
s.clear();
loadInitial();
emit fontsUpdated();
}
bool Configuration::getAutoUpdateEnabled() const
{
return s.value("autoUpdateEnabled", false).toBool();
}
void Configuration::setAutoUpdateEnabled(bool au)
{
s.setValue("autoUpdateEnabled", au);
}
/**
* @brief get the current Locale set in Cutter's user configuration
* @return a QLocale object describes user's current locale
*/
QLocale Configuration::getCurrLocale() const
{
return s.value("locale", QLocale().system()).toLocale();
}
/**
* @brief sets Cutter's locale
* @param l - a QLocale object describes the locate to configure
*/
void Configuration::setLocale(const QLocale &l)
{
s.setValue("locale", l);
}
/**
* @brief set Cutter's interface language by a given locale name
* @param language - a string represents the name of a locale language
* @return true on success
*/
bool Configuration::setLocaleByName(const QString &language)
{
const auto &allLocales =
QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
for (auto &it : allLocales) {
if (QString::compare(it.nativeLanguageName(), language, Qt::CaseInsensitive) == 0
|| it.name() == language) {
setLocale(it);
return true;
}
}
return false;
}
bool Configuration::windowColorIsDark()
{
ColorFlags currentThemeColorFlags = getCurrentTheme()->flag;
if (currentThemeColorFlags == ColorFlags::LightFlag) {
return false;
} else if (currentThemeColorFlags == ColorFlags::DarkFlag) {
return true;
}
return nativeWindowIsDark();
}
bool Configuration::nativeWindowIsDark()
{
const QPalette &palette = qApp->palette();
auto windowColor = palette.color(QPalette::Window).toRgb();
return (windowColor.red() + windowColor.green() + windowColor.blue()) < 382;
}
void Configuration::loadNativeStylesheet()
{
/* Load Qt Theme */
QFile f(":native/native.qss");
if (!f.exists()) {
qWarning() << "Can't find Native theme stylesheet.";
} else {
f.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&f);
QString stylesheet = ts.readAll();
#ifdef Q_OS_MACOS
QFile mf(nativeWindowIsDark() ? ":native/native-macos-dark.qss"
: ":native/native-macos-light.qss");
if (mf.exists()) {
mf.open(QFile::ReadOnly | QFile::Text);
QTextStream mts(&mf);
stylesheet += "\n" + mts.readAll();
}
#endif
qApp->setStyleSheet(stylesheet);
}
qApp->setPalette(nativePalette);
/* Some widgets does not change its palette when QApplication changes one
* so this loop force all widgets do this, but all widgets take palette from
* QApplication::palette() when they are created so line above is necessary too.
*/
for (auto widget : qApp->allWidgets()) {
widget->setPalette(nativePalette);
}
}
/**
* @brief Loads the Light theme of Cutter and modify special theme colors
*/
void Configuration::loadLightStylesheet()
{
/* Load Qt Theme */
QFile f(":lightstyle/light.qss");
if (!f.exists()) {
qWarning() << "Can't find Light theme stylesheet.";
} else {
f.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&f);
QString stylesheet = ts.readAll();
QPalette p = qApp->palette();
p.setColor(QPalette::Text, Qt::black);
qApp->setPalette(p);
qApp->setStyleSheet(stylesheet);
}
}
void Configuration::loadDarkStylesheet()
{
/* Load Qt Theme */
QFile f(":qdarkstyle/style.qss");
if (!f.exists()) {
qWarning() << "Can't find Dark theme stylesheet.";
} else {
f.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&f);
QString stylesheet = ts.readAll();
#ifdef Q_OS_MACX
// see https://github.com/ColinDuquesnoy/QDarkStyleSheet/issues/22#issuecomment-96179529
stylesheet += "QDockWidget::title"
"{"
" background-color: #31363b;"
" text-align: center;"
" height: 12px;"
"}";
#endif
QPalette p = qApp->palette();
p.setColor(QPalette::Text, Qt::white);
qApp->setPalette(p);
qApp->setStyleSheet(stylesheet);
}
}
void Configuration::loadMidnightStylesheet()
{
/* Load Qt Theme */
QFile f(":midnight/style.css");
if (!f.exists()) {
qWarning() << "Can't find Midnight theme stylesheet.";
} else {
f.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&f);
QString stylesheet = ts.readAll();
QPalette p = qApp->palette();
p.setColor(QPalette::Text, Qt::white);
qApp->setPalette(p);
qApp->setStyleSheet(stylesheet);
}
}
const QFont Configuration::getBaseFont() const
{
QFont font = s.value("font", QFont("Inconsolata", 11)).value<QFont>();
return font;
}
const QFont Configuration::getFont() const
{
QFont font = getBaseFont();
font.setPointSizeF(font.pointSizeF() * getZoomFactor());
return font;
}
void Configuration::setFont(const QFont &font)
{
s.setValue("font", font);
emit fontsUpdated();
}
void Configuration::refreshFont()
{
emit fontsUpdated();
}
qreal Configuration::getZoomFactor() const
{
qreal fontZoom = s.value("zoomFactor", 1.0).value<qreal>();
return qMax(fontZoom, 0.1);
}
void Configuration::setZoomFactor(qreal zoom)
{
s.setValue("zoomFactor", qMax(zoom, 0.1));
emit fontsUpdated();
}
QString Configuration::getLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme) const
{
return s.value("lastThemeOf." + currInterfaceTheme.name, Config()->getColorTheme()).toString();
}
void Configuration::setInterfaceTheme(int theme)
{
if (theme >= cutterInterfaceThemesList().size() || theme < 0) {
theme = 0;
}
s.setValue("ColorPalette", theme);
CutterInterfaceTheme interfaceTheme = cutterInterfaceThemesList()[theme];
if (interfaceTheme.name == "Native") {
loadNativeStylesheet();
} else if (interfaceTheme.name == "Dark") {
loadDarkStylesheet();
} else if (interfaceTheme.name == "Midnight") {
loadMidnightStylesheet();
} else if (interfaceTheme.name == "Light") {
loadLightStylesheet();
} else {
loadNativeStylesheet();
}
for (auto it = cutterOptionColors.cbegin(); it != cutterOptionColors.cend(); it++) {
setColor(it.key(), it.value()[interfaceTheme.flag]);
}
adjustColorThemeDarkness();
emit interfaceThemeChanged();
emit colorsUpdated();
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
emit kSyntaxHighlightingThemeChanged();
#endif
}
const CutterInterfaceTheme *Configuration::getCurrentTheme()
{
int i = getInterfaceTheme();
if (i < 0 || i >= cutterInterfaceThemesList().size()) {
i = 0;
setInterfaceTheme(i);
}
return &cutterInterfaceThemesList()[i];
}
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
KSyntaxHighlighting::Repository *Configuration::getKSyntaxHighlightingRepository()
{
return kSyntaxHighlightingRepository;
}
KSyntaxHighlighting::Theme Configuration::getKSyntaxHighlightingTheme()
{
auto repo = getKSyntaxHighlightingRepository();
if (!repo) {
return KSyntaxHighlighting::Theme();
}
return repo->defaultTheme(getCurrentTheme()->flag & DarkFlag
? KSyntaxHighlighting::Repository::DefaultTheme::DarkTheme
: KSyntaxHighlighting::Repository::DefaultTheme::LightTheme);
}
#endif
QSyntaxHighlighter *Configuration::createSyntaxHighlighter(QTextDocument *document)
{
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
auto syntaxHighlighter = new SyntaxHighlighter(document);
auto repo = getKSyntaxHighlightingRepository();
if (repo) {
syntaxHighlighter->setDefinition(repo->definitionForName("C"));
}
return syntaxHighlighter;
#else
return new FallbackSyntaxHighlighter(document);
#endif
}
QString Configuration::getLogoFile()
{
return windowColorIsDark() ? QString(":/img/cutter_white_plain.svg")
: QString(":/img/cutter_plain.svg");
}
/**
* @brief Configuration::setColor sets the local Cutter configuration color
* @param name Color Name
* @param color The color you want to set
*/
void Configuration::setColor(const QString &name, const QColor &color)
{
s.setValue("colors." + name, color);
}
void Configuration::setLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme,
const QString &theme)
{
s.setValue("lastThemeOf." + currInterfaceTheme.name, theme);
}
const QColor Configuration::getColor(const QString &name) const
{
if (s.contains("colors." + name)) {
return s.value("colors." + name).value<QColor>();
} else {
return s.value("colors.other").value<QColor>();
}
}
void Configuration::setColorTheme(const QString &theme)
{
if (theme == "default") {
rz_cons_pal_init(Core()->core()->cons->context);
s.setValue("theme", "default");
} else {
rz_core_theme_load(Core()->core(), theme.toUtf8().constData());
s.setValue("theme", theme);
}
ColorThemeWorker::Theme colorTheme = ThemeWorker().getTheme(theme);
for (auto it = colorTheme.constBegin(); it != colorTheme.constEnd(); it++) {
setColor(it.key(), it.value());
}
emit colorsUpdated();
}
void Configuration::adjustColorThemeDarkness()
{
bool windowIsDark = windowColorIsDark();
int windowDarkness = windowIsDark ? DarkFlag : LightFlag;
int currentColorThemeDarkness = colorThemeDarkness(getColorTheme());
if ((currentColorThemeDarkness & windowDarkness) == 0) {
setColorTheme(windowIsDark ? DEFAULT_DARK_COLOR_THEME : DEFAULT_LIGHT_COLOR_THEME);
}
}
int Configuration::colorThemeDarkness(const QString &colorTheme) const
{
auto flags = relevantThemes.find(colorTheme);
if (flags != relevantThemes.end()) {
return static_cast<int>(*flags);
}
return DarkFlag | LightFlag;
}
void Configuration::resetToDefaultAsmOptions()
{
for (auto it = asmOptions.cbegin(); it != asmOptions.cend(); it++) {
setConfig(it.key(), it.value());
}
}
void Configuration::applySavedAsmOptions()
{
for (auto it = asmOptions.cbegin(); it != asmOptions.cend(); it++) {
Core()->setConfig(it.key(), s.value(it.key(), it.value()));
}
}
const QList<CutterInterfaceTheme> &Configuration::cutterInterfaceThemesList()
{
static const QList<CutterInterfaceTheme> list = {
{ "Native", Configuration::nativeWindowIsDark() ? DarkFlag : LightFlag },
{ "Dark", DarkFlag },
{ "Midnight", DarkFlag },
{ "Light", LightFlag }
};
return list;
}
QVariant Configuration::getConfigVar(const QString &key)
{
QHash<QString, QVariant>::const_iterator it = asmOptions.find(key);
if (it != asmOptions.end()) {
switch (it.value().type()) {
case QVariant::Type::Bool:
return Core()->getConfigb(key);
case QVariant::Type::Int:
return Core()->getConfigi(key);
default:
return Core()->getConfig(key);
}
}
return QVariant();
}
bool Configuration::getConfigBool(const QString &key)
{
return getConfigVar(key).toBool();
}
int Configuration::getConfigInt(const QString &key)
{
return getConfigVar(key).toInt();
}
QString Configuration::getConfigString(const QString &key)
{
return getConfigVar(key).toString();
}
/**
* @brief Configuration::setConfig
* Set Rizin configuration value (e.g. "asm.lines")
* @param key
* @param value
*/
void Configuration::setConfig(const QString &key, const QVariant &value)
{
if (asmOptions.contains(key)) {
s.setValue(key, value);
}
Core()->setConfig(key, value);
}
/**
* @brief this function will gather and return available translation for Cutter
* @return a list of all available translations
*/
QStringList Configuration::getAvailableTranslations()
{
const auto &trDirs = Cutter::getTranslationsDirectories();
QSet<QString> fileNamesSet;
for (const auto &trDir : trDirs) {
QDir dir(trDir);
if (!dir.exists()) {
continue;
}
const QStringList &currTrFileNames =
dir.entryList(QStringList("cutter_*.qm"), QDir::Files, QDir::Name);
for (const auto &trFile : currTrFileNames) {
fileNamesSet << trFile;
}
}
QStringList fileNames = fileNamesSet.values();
std::sort(fileNames.begin(), fileNames.end());
QStringList languages;
QString currLanguageName;
auto allLocales =
QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
for (auto i : fileNames) {
QString localeName = i.mid(sizeof("cutter_") - 1, 2); // TODO:#2321 don't asume 2 characters
// language code is sometimes 3 characters, and there could also be language_COUNTRY. Qt
// supports that.
QLocale locale(localeName);
if (locale.language() != QLocale::C) {
currLanguageName = locale.nativeLanguageName();
if (currLanguageName
.isEmpty()) { // Qt doesn't have native language name for some languages
currLanguageName = QLocale::languageToString(locale.language());
}
if (!currLanguageName.isEmpty()) {
languages << currLanguageName;
}
}
}
return languages << QLatin1String("English");
}
/**
* @brief check if this is the first time Cutter's is executed on this computer
* @return true if this is first execution; otherwise returns false.
*/
bool Configuration::isFirstExecution()
{
// check if a variable named firstExecution existed in the configuration
if (s.contains("firstExecution")) {
return false;
} else {
s.setValue("firstExecution", false);
return true;
}
}
QString Configuration::getSelectedDecompiler()
{
return s.value("selectedDecompiler").toString();
}
void Configuration::setSelectedDecompiler(const QString &id)
{
s.setValue("selectedDecompiler", id);
}
bool Configuration::getDecompilerAutoRefreshEnabled()
{
return s.value("decompilerAutoRefresh", true).toBool();
}
void Configuration::setDecompilerAutoRefreshEnabled(bool enabled)
{
s.setValue("decompilerAutoRefresh", enabled);
}
void Configuration::enableDecompilerAnnotationHighlighter(bool useDecompilerHighlighter)
{
s.setValue("decompilerAnnotationHighlighter", useDecompilerHighlighter);
emit colorsUpdated();
}
bool Configuration::isDecompilerAnnotationHighlighterEnabled()
{
return s.value("decompilerAnnotationHighlighter", true).value<bool>();
}
bool Configuration::getBitmapTransparentState()
{
return s.value("bitmapGraphExportTransparency", false).value<bool>();
}
double Configuration::getBitmapExportScaleFactor()
{
return s.value("bitmapGraphExportScale", 1.0).value<double>();
}
void Configuration::setBitmapTransparentState(bool inputValueGraph)
{
s.setValue("bitmapGraphExportTransparency", inputValueGraph);
}
void Configuration::setBitmapExportScaleFactor(double inputValueGraph)
{
s.setValue("bitmapGraphExportScale", inputValueGraph);
}
void Configuration::setGraphSpacing(QPoint blockSpacing, QPoint edgeSpacing)
{
s.setValue("graph.blockSpacing", blockSpacing);
s.setValue("graph.edgeSpacing", edgeSpacing);
}
QPoint Configuration::getGraphBlockSpacing()
{
return s.value("graph.blockSpacing", QPoint(20, 40)).value<QPoint>();
}
QPoint Configuration::getGraphEdgeSpacing()
{
return s.value("graph.edgeSpacing", QPoint(10, 10)).value<QPoint>();
}
void Configuration::setOutputRedirectionEnabled(bool enabled)
{
this->outputRedirectEnabled = enabled;
}
bool Configuration::getOutputRedirectionEnabled() const
{
return outputRedirectEnabled;
}
void Configuration::setPreviewValue(bool checked)
{
s.setValue("asm.preview", checked);
}
bool Configuration::getPreviewValue() const
{
return s.value("asm.preview").toBool();
}
void Configuration::setShowVarTooltips(bool enabled)
{
s.setValue("showVarTooltips", enabled);
}
bool Configuration::getShowVarTooltips() const
{
return s.value("showVarTooltips").toBool();
}
bool Configuration::getGraphBlockEntryOffset()
{
return s.value("graphBlockEntryOffset", true).value<bool>();
}
void Configuration::setGraphBlockEntryOffset(bool enabled)
{
s.setValue("graphBlockEntryOffset", enabled);
}
QStringList Configuration::getRecentFiles() const
{
return s.value("recentFileList").toStringList();
}
void Configuration::setRecentFiles(const QStringList &list)
{
s.setValue("recentFileList", list);
}
QStringList Configuration::getRecentProjects() const
{
return s.value("recentProjectsList").toStringList();
}
void Configuration::setRecentProjects(const QStringList &list)
{
s.setValue("recentProjectsList", list);
}
void Configuration::addRecentProject(QString file)
{
QStringList files = getRecentProjects();
files.removeAll(file);
files.prepend(file);
setRecentProjects(files);
}
QString Configuration::getFunctionsWidgetLayout()
{
return s.value("functionsWidgetLayout").toString();
}
void Configuration::setFunctionsWidgetLayout(const QString &layout)
{
s.setValue("functionsWidgetLayout", layout);
}
| 27,350
|
C++
|
.cpp
| 738
| 29.99729
| 100
| 0.622831
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,621
|
Colors.cpp
|
rizinorg_cutter/src/common/Colors.cpp
|
#include "Colors.h"
#include "common/Configuration.h"
Colors::Colors() {}
void Colors::colorizeAssembly(RichTextPainter::List &list, QString opcode, ut64 type_num)
{
RichTextPainter::CustomRichText_t assembly;
assembly.highlight = false;
assembly.flags = RichTextPainter::FlagColor;
// TODO cut opcode and use op["ptr"] to colorate registers and immediate values
assembly.text = opcode;
QString colorName = Colors::getColor(type_num);
assembly.textColor = ConfigColor(colorName);
list.push_back(assembly);
}
// Temporary solution
// Copied from RZ_API const char* r_print_color_op_type(RPrint *p, ut64 analysis_type) {
QString Colors::getColor(ut64 type)
{
switch (type & RZ_ANALYSIS_OP_TYPE_MASK) {
case RZ_ANALYSIS_OP_TYPE_NOP:
return "nop";
case RZ_ANALYSIS_OP_TYPE_ADD:
case RZ_ANALYSIS_OP_TYPE_SUB:
case RZ_ANALYSIS_OP_TYPE_MUL:
case RZ_ANALYSIS_OP_TYPE_DIV:
case RZ_ANALYSIS_OP_TYPE_MOD:
case RZ_ANALYSIS_OP_TYPE_LENGTH:
return "math";
case RZ_ANALYSIS_OP_TYPE_AND:
case RZ_ANALYSIS_OP_TYPE_OR:
case RZ_ANALYSIS_OP_TYPE_XOR:
case RZ_ANALYSIS_OP_TYPE_NOT:
case RZ_ANALYSIS_OP_TYPE_SHL:
case RZ_ANALYSIS_OP_TYPE_SAL:
case RZ_ANALYSIS_OP_TYPE_SAR:
case RZ_ANALYSIS_OP_TYPE_SHR:
case RZ_ANALYSIS_OP_TYPE_ROL:
case RZ_ANALYSIS_OP_TYPE_ROR:
case RZ_ANALYSIS_OP_TYPE_CPL:
return "bin";
case RZ_ANALYSIS_OP_TYPE_IO:
return "swi";
case RZ_ANALYSIS_OP_TYPE_JMP:
case RZ_ANALYSIS_OP_TYPE_UJMP:
case RZ_ANALYSIS_OP_TYPE_IJMP:
case RZ_ANALYSIS_OP_TYPE_RJMP:
case RZ_ANALYSIS_OP_TYPE_IRJMP:
case RZ_ANALYSIS_OP_TYPE_MJMP:
return "jmp";
case RZ_ANALYSIS_OP_TYPE_CJMP:
case RZ_ANALYSIS_OP_TYPE_UCJMP:
case RZ_ANALYSIS_OP_TYPE_SWITCH:
return "cjmp";
case RZ_ANALYSIS_OP_TYPE_CMP:
case RZ_ANALYSIS_OP_TYPE_ACMP:
return "cmp";
case RZ_ANALYSIS_OP_TYPE_UCALL:
case RZ_ANALYSIS_OP_TYPE_ICALL:
case RZ_ANALYSIS_OP_TYPE_RCALL:
case RZ_ANALYSIS_OP_TYPE_IRCALL:
case RZ_ANALYSIS_OP_TYPE_UCCALL:
case RZ_ANALYSIS_OP_TYPE_CALL:
case RZ_ANALYSIS_OP_TYPE_CCALL:
return "call";
case RZ_ANALYSIS_OP_TYPE_NEW:
case RZ_ANALYSIS_OP_TYPE_SWI:
return "swi";
case RZ_ANALYSIS_OP_TYPE_ILL:
case RZ_ANALYSIS_OP_TYPE_TRAP:
return "trap";
case RZ_ANALYSIS_OP_TYPE_CRET:
case RZ_ANALYSIS_OP_TYPE_RET:
return "ret";
case RZ_ANALYSIS_OP_TYPE_CAST:
case RZ_ANALYSIS_OP_TYPE_MOV:
case RZ_ANALYSIS_OP_TYPE_LEA:
case RZ_ANALYSIS_OP_TYPE_CMOV: // TODO: add cmov cathegory?
return "mov";
case RZ_ANALYSIS_OP_TYPE_PUSH:
case RZ_ANALYSIS_OP_TYPE_UPUSH:
case RZ_ANALYSIS_OP_TYPE_LOAD:
return "push";
case RZ_ANALYSIS_OP_TYPE_POP:
case RZ_ANALYSIS_OP_TYPE_STORE:
return "pop";
case RZ_ANALYSIS_OP_TYPE_CRYPTO:
return "crypto";
case RZ_ANALYSIS_OP_TYPE_NULL:
return "other";
case RZ_ANALYSIS_OP_TYPE_UNK:
default:
return "invalid";
}
}
| 3,092
|
C++
|
.cpp
| 94
| 27.585106
| 89
| 0.680922
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,622
|
HighDpiPixmap.cpp
|
rizinorg_cutter/src/common/HighDpiPixmap.cpp
|
#include "common/HighDpiPixmap.h"
#include <QGuiApplication>
#include <QScreen>
static qreal GetDevicePixelRatio(qreal devicePixelRatio)
{
if (devicePixelRatio > 0) {
return devicePixelRatio;
}
qreal ratio = 1;
for (auto screen : QGuiApplication::screens()) {
ratio = std::max(ratio, screen->devicePixelRatio());
}
return ratio;
}
HighDpiPixmap::HighDpiPixmap(int width, int height, qreal devicePixelRatio)
: QPixmap(int(width * GetDevicePixelRatio(devicePixelRatio)),
int(height * GetDevicePixelRatio(devicePixelRatio)))
{
setDevicePixelRatio(GetDevicePixelRatio(devicePixelRatio));
}
| 651
|
C++
|
.cpp
| 20
| 28.3
| 75
| 0.735669
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,623
|
SyntaxHighlighter.cpp
|
rizinorg_cutter/src/common/SyntaxHighlighter.cpp
|
#include "SyntaxHighlighter.h"
#ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING
# include "Configuration.h"
# include <KSyntaxHighlighting/Theme>
SyntaxHighlighter::SyntaxHighlighter(QTextDocument *document)
: KSyntaxHighlighting::SyntaxHighlighter(document)
{
connect(Config(), &Configuration::kSyntaxHighlightingThemeChanged, this,
&SyntaxHighlighter::updateTheme);
updateTheme();
}
void SyntaxHighlighter::updateTheme()
{
setTheme(Config()->getKSyntaxHighlightingTheme());
rehighlight();
}
#endif
FallbackSyntaxHighlighter::FallbackSyntaxHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), commentStartExpression("/\\*"), commentEndExpression("\\*/")
{
HighlightingRule rule;
QStringList keywordPatterns;
// C language keywords
keywordPatterns << "\\bauto\\b"
<< "\\bdouble\\b"
<< "\\bint\\b"
<< "\\bstruct\\b"
<< "\\bbreak\\b"
<< "\\belse\\b"
<< "\\blong\\b"
<< "\\switch\\b"
<< "\\bcase\\b"
<< "\\benum\\b"
<< "\\bregister\\b"
<< "\\btypedef\\b"
<< "\\bchar\\b"
<< "\\bextern\\b"
<< "\\breturn\\b"
<< "\\bunion\\b"
<< "\\bconst\\b"
<< "\\bfloat\\b"
<< "\\bshort\\b"
<< "\\bunsigned\\b"
<< "\\bcontinue\\b"
<< "\\bfor\\b"
<< "\\bsigned\\b"
<< "\\bvoid\\b"
<< "\\bdefault\\b"
<< "\\bgoto\\b"
<< "\\bsizeof\\b"
<< "\\bvolatile\\b"
<< "\\bdo\\b"
<< "\\bif\\b"
<< "\\static\\b"
<< "\\while\\b";
QTextCharFormat keywordFormat;
keywordFormat.setForeground(QColor(80, 200, 215));
for (const auto &pattern : keywordPatterns) {
rule.pattern.setPattern(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
// Functions
rule.pattern.setPattern("\\b[A-Za-z0-9_]+(?=\\()");
rule.format.clearBackground();
rule.format.clearForeground();
rule.format.setFontItalic(true);
rule.format.setForeground(Qt::darkCyan);
highlightingRules.append(rule);
// single-line comment
rule.pattern.setPattern("//[^\n]*");
rule.format.clearBackground();
rule.format.clearForeground();
rule.format.setForeground(Qt::gray);
highlightingRules.append(rule);
// quotation
rule.pattern.setPattern("\".*\"");
rule.format.clearBackground();
rule.format.clearForeground();
rule.format.setForeground(Qt::darkGreen);
highlightingRules.append(rule);
multiLineCommentFormat.setForeground(Qt::gray);
}
void FallbackSyntaxHighlighter::highlightBlock(const QString &text)
{
for (const auto &it : highlightingRules) {
auto matchIterator = it.pattern.globalMatch(text);
while (matchIterator.hasNext()) {
const auto match = matchIterator.next();
setFormat(match.capturedStart(), match.capturedLength(), it.format);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1) {
startIndex = text.indexOf(commentStartExpression);
}
while (startIndex >= 0) {
const auto match = commentEndExpression.match(text, startIndex);
const int endIndex = match.capturedStart();
int commentLength = 0;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex + match.capturedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = text.indexOf(commentStartExpression, startIndex + commentLength);
}
}
| 4,102
|
C++
|
.cpp
| 111
| 26.936937
| 94
| 0.559446
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,624
|
RefreshDeferrer.cpp
|
rizinorg_cutter/src/common/RefreshDeferrer.cpp
|
#include "RefreshDeferrer.h"
#include "widgets/CutterDockWidget.h"
RefreshDeferrer::RefreshDeferrer(RefreshDeferrerAccumulator *acc, QObject *parent)
: QObject(parent), acc(acc)
{
}
RefreshDeferrer::~RefreshDeferrer()
{
delete acc;
}
bool RefreshDeferrer::attemptRefresh(RefreshDeferrerParams params)
{
if (dockWidget->isVisibleToUser()) {
if (acc) {
acc->ignoreParams(params);
}
return true;
} else {
dirty = true;
if (acc) {
acc->accumulate(params);
}
return false;
}
}
void RefreshDeferrer::registerFor(CutterDockWidget *dockWidget)
{
this->dockWidget = dockWidget;
connect(dockWidget, &CutterDockWidget::becameVisibleToUser, this, [this]() {
if (dirty) {
emit refreshNow(acc ? acc->result() : nullptr);
if (acc) {
acc->clear();
}
dirty = false;
}
});
}
| 954
|
C++
|
.cpp
| 38
| 18.921053
| 82
| 0.612514
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,625
|
PythonAPI.cpp
|
rizinorg_cutter/src/common/PythonAPI.cpp
|
#include "PythonAPI.h"
#include "core/Cutter.h"
#include "CutterConfig.h"
#include <QFile>
PyObject *api_version(PyObject *self, PyObject *null)
{
Q_UNUSED(self)
Q_UNUSED(null)
return PyUnicode_FromString(CUTTER_VERSION_FULL);
}
PyObject *api_cmd(PyObject *self, PyObject *args)
{
Q_UNUSED(self);
char *command;
char *result = (char *)"";
QString cmdRes;
QByteArray cmdBytes;
if (PyArg_ParseTuple(args, "s:command", &command)) {
cmdRes = Core()->cmd(command);
cmdBytes = cmdRes.toLocal8Bit();
result = cmdBytes.data();
}
return PyUnicode_FromString(result);
}
PyObject *api_refresh(PyObject *self, PyObject *args)
{
Q_UNUSED(self);
Q_UNUSED(args);
Core()->triggerRefreshAll();
Py_RETURN_NONE;
}
PyObject *api_message(PyObject *self, PyObject *args, PyObject *kwargs)
{
Q_UNUSED(self);
char *message;
int debug = 0;
static const char *kwlist[] = { "", "debug", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i", const_cast<char **>(kwlist), &message,
&debug)) {
return NULL;
}
Core()->message(QString(message), debug);
Py_RETURN_NONE;
}
PyMethodDef CutterMethods[] = {
{ "version", api_version, METH_NOARGS, "Returns Cutter current version" },
{ "cmd", api_cmd, METH_VARARGS, "Execute a command inside Cutter" },
{ "refresh", api_refresh, METH_NOARGS, "Refresh Cutter widgets" },
{ "message", (PyCFunction)(void *)/* don't remove this double cast! */ api_message,
METH_VARARGS | METH_KEYWORDS, "Print message" },
{ NULL, NULL, 0, NULL }
};
PyModuleDef CutterModule = {
PyModuleDef_HEAD_INIT, "_cutter", NULL, -1, CutterMethods, NULL, NULL, NULL, NULL
};
PyObject *PyInit_api()
{
return PyModule_Create(&CutterModule);
}
| 1,834
|
C++
|
.cpp
| 59
| 26.627119
| 96
| 0.652322
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,626
|
IOModesController.cpp
|
rizinorg_cutter/src/common/IOModesController.cpp
|
#include "IOModesController.h"
#include "Cutter.h"
#include <QJsonArray>
#include <QPushButton>
#include <QObject>
#include <QMessageBox>
#include <QJsonObject>
bool IOModesController::canWrite()
{
return Core()->isIOCacheEnabled() || Core()->isWriteModeEnabled();
}
IOModesController::Mode IOModesController::getIOMode()
{
if (Core()->isWriteModeEnabled()) {
return Mode::WRITE;
} else if (Core()->isIOCacheEnabled()) {
return Mode::CACHE;
} else {
return Mode::READ_ONLY;
}
}
void IOModesController::setIOMode(IOModesController::Mode mode)
{
switch (mode) {
case Mode::READ_ONLY:
if (askCommitUnsavedChanges()) {
Core()->setWriteMode(false);
}
break;
case Mode::CACHE:
Core()->setIOCache(true);
break;
case Mode::WRITE:
if (askCommitUnsavedChanges()) {
Core()->setWriteMode(true);
}
break;
}
}
bool IOModesController::prepareForWriting()
{
if (canWrite()) {
return true;
}
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Icon::Critical);
msgBox.setWindowTitle(QObject::tr("Write error"));
msgBox.setText(QObject::tr(
"Your file is opened in read-only mode. "
"Editing is only available when the file is opened in either Write or Cache modes.\n\n"
"WARNING: In Write mode, any changes will be committed to the file on disk. "
"For safety, please consider using Cache mode and then commit the changes manually "
"via File -> Commit modifications to disk."));
msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole);
QAbstractButton *reopenButton =
msgBox.addButton(QObject::tr("Reopen in Write mode"), QMessageBox::YesRole);
QAbstractButton *iocacheButton =
msgBox.addButton(QObject::tr("Enable Cache mode"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton() == reopenButton) {
Core()->setWriteMode(true);
} else if (msgBox.clickedButton() == iocacheButton) {
Core()->setIOCache(true);
} else {
return false;
}
return true;
}
bool IOModesController::allChangesComitted()
{
RzCoreLocked core(Core());
for (auto c : CutterPVector<RzIOCache>(&core->io->cache)) {
if (!c->written) {
return false;
}
}
return true;
}
bool IOModesController::askCommitUnsavedChanges()
{
// Check if there are uncommitted changes
if (!allChangesComitted()) {
QMessageBox::StandardButton ret = QMessageBox::question(
NULL, QObject::tr("Uncommitted changes"),
QObject::tr("It seems that you have changes or patches that are not committed to "
"the file.\n"
"Do you want to commit them now?"),
(QMessageBox::StandardButtons)(QMessageBox::Save | QMessageBox::Discard
| QMessageBox::Cancel));
if (ret == QMessageBox::Save) {
Core()->commitWriteCache();
} else if (ret == QMessageBox::Discard) {
Core()->resetWriteCache();
emit Core()->refreshCodeViews();
} else if (ret == QMessageBox::Cancel) {
return false;
}
}
return true;
}
| 3,362
|
C++
|
.cpp
| 100
| 26.24
| 99
| 0.618271
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,627
|
CommandTask.cpp
|
rizinorg_cutter/src/common/CommandTask.cpp
|
#include "CommandTask.h"
#include "TempConfig.h"
CommandTask::CommandTask(const QString &cmd, ColorMode colorMode) : cmd(cmd), colorMode(colorMode)
{
}
void CommandTask::runTask()
{
TempConfig tempConfig;
tempConfig.set("scr.color", colorMode);
auto res = Core()->cmdTask(cmd);
emit finished(res);
}
| 319
|
C++
|
.cpp
| 12
| 24
| 98
| 0.736842
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,628
|
ResourcePaths.cpp
|
rizinorg_cutter/src/common/ResourcePaths.cpp
|
#include "common/ResourcePaths.h"
#include <QLibraryInfo>
#include <QDir>
#include <QFileInfo>
#include <QApplication>
#include <QDebug>
#include <QStandardPaths>
#ifdef APPIMAGE
static QDir appimageRoot()
{
auto dir = QDir(QCoreApplication::applicationDirPath()); // appimage/usr/bin
dir.cdUp(); // /usr
dir.cdUp(); // /
return dir;
}
#endif
static QString substitutePath(QString path)
{
#ifdef APPIMAGE
if (path.startsWith("/usr")) {
return appimageRoot().absoluteFilePath("." + path);
}
#endif
return path;
}
/**
* @brief Substitute or filter paths returned by standardLocations based on Cutter package kind.
* @param paths list of paths to process
* @return
*/
static QStringList substitutePaths(const QStringList &paths)
{
QStringList result;
result.reserve(paths.size());
for (auto &path : paths) {
// consider ignoring some of system folders for portable packages here or standardLocations
// if it depends on path type
result.push_back(substitutePath(path));
}
return result;
}
QStringList Cutter::locateAll(QStandardPaths::StandardLocation type, const QString &fileName,
QStandardPaths::LocateOptions options)
{
// This function is reimplemented here instead of forwarded to Qt becauase existence check needs
// to be done after substitutions
QStringList result;
for (auto path : standardLocations(type)) {
QString filePath = path + QLatin1Char('/') + fileName;
bool exists = false;
if (options & QStandardPaths::LocateDirectory) {
exists = QDir(filePath).exists();
} else {
exists = QFileInfo(filePath).isFile();
}
if (exists) {
result.append(filePath);
}
}
return result;
}
QStringList Cutter::standardLocations(QStandardPaths::StandardLocation type)
{
return substitutePaths(QStandardPaths::standardLocations(type));
}
QString Cutter::writableLocation(QStandardPaths::StandardLocation type)
{
return substitutePath(QStandardPaths::writableLocation(type));
}
QStringList Cutter::getTranslationsDirectories()
{
auto result = locateAll(QStandardPaths::AppDataLocation, "translations",
QStandardPaths::LocateDirectory);
result << QLibraryInfo::location(QLibraryInfo::TranslationsPath);
return result;
}
| 2,397
|
C++
|
.cpp
| 76
| 26.776316
| 100
| 0.706874
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,629
|
TempConfig.cpp
|
rizinorg_cutter/src/common/TempConfig.cpp
|
#include <cassert>
#include "core/Cutter.h"
#include "TempConfig.h"
TempConfig::~TempConfig()
{
for (auto i = resetValues.constBegin(); i != resetValues.constEnd(); ++i) {
switch (i.value().type()) {
case QVariant::String:
Core()->setConfig(i.key(), i.value().toString());
break;
case QVariant::Int:
Core()->setConfig(i.key(), i.value().toInt());
break;
case QVariant::Bool:
Core()->setConfig(i.key(), i.value().toBool());
break;
default:
assert(false);
break;
}
}
}
TempConfig &TempConfig::set(const QString &key, const QString &value)
{
if (!resetValues.contains(key)) {
resetValues[key] = Core()->getConfig(key);
}
Core()->setConfig(key, value);
return *this;
}
TempConfig &TempConfig::set(const QString &key, const char *value)
{
if (!resetValues.contains(key)) {
resetValues[key] = Core()->getConfig(key);
}
Core()->setConfig(key, value);
return *this;
}
TempConfig &TempConfig::set(const QString &key, int value)
{
if (!resetValues.contains(key)) {
resetValues[key] = Core()->getConfigi(key);
}
Core()->setConfig(key, value);
return *this;
}
TempConfig &TempConfig::set(const QString &key, bool value)
{
if (!resetValues.contains(key)) {
resetValues[key] = Core()->getConfigb(key);
}
Core()->setConfig(key, value);
return *this;
}
| 1,496
|
C++
|
.cpp
| 54
| 21.907407
| 79
| 0.596087
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,630
|
MdHighlighter.cpp
|
rizinorg_cutter/src/common/MdHighlighter.cpp
|
#include <QtGui>
#include "common/MdHighlighter.h"
MdHighlighter::MdHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
HighlightingRule rule;
keywordFormat.setForeground(Qt::gray);
keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns;
keywordPatterns << "^\\#{1,6}[ A-Za-z]+\\b"
<< "\\*\\*([^\\\\]+)\\*\\*"
<< "\\*([^\\\\]+)\\*"
<< "\\_([^\\\\]+)\\_"
<< "\\_\\_([^\\\\]+)\\_\\_";
for (const QString &pattern : keywordPatterns) {
rule.pattern.setPattern(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
singleLineCommentFormat.setFontWeight(QFont::Bold);
singleLineCommentFormat.setForeground(Qt::darkGreen);
rule.pattern.setPattern(";[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
}
void MdHighlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule &rule : highlightingRules) {
QRegularExpression expression(rule.pattern);
int index = expression.match(text).capturedStart();
while (index >= 0) {
int length = expression.match(text).capturedLength();
setFormat(index, length, rule.format);
index = expression.match(text.mid(index + length)).capturedStart();
}
}
setCurrentBlockState(0);
}
| 1,437
|
C++
|
.cpp
| 37
| 31.378378
| 80
| 0.615937
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,631
|
Helpers.cpp
|
rizinorg_cutter/src/common/Helpers.cpp
|
#include "common/Helpers.h"
#include "Configuration.h"
#include <cmath>
#include <QPlainTextEdit>
#include <QTextEdit>
#include <QFileInfo>
#include <QtCore>
#include <QCryptographicHash>
#include <QTreeWidget>
#include <QString>
#include <QAbstractItemView>
#include <QAbstractButton>
#include <QDockWidget>
#include <QMenu>
#include <QComboBox>
static QAbstractItemView::ScrollMode scrollMode()
{
const bool use_scrollperpixel = true;
return use_scrollperpixel ? QAbstractItemView::ScrollPerPixel
: QAbstractItemView::ScrollPerItem;
}
namespace qhelpers {
QString formatBytecount(const uint64_t bytecount)
{
if (bytecount == 0) {
return "0";
}
const int exp = log(bytecount) / log(1024);
constexpr char suffixes[] = { ' ', 'k', 'M', 'G', 'T', 'P', 'E' };
QString str;
QTextStream stream(&str);
stream << qSetRealNumberPrecision(3) << bytecount / pow(1024, exp) << ' ' << suffixes[exp]
<< 'B';
return stream.readAll();
}
void adjustColumns(QTreeView *tv, int columnCount, int padding)
{
for (int i = 0; i != columnCount; ++i) {
tv->resizeColumnToContents(i);
if (padding > 0) {
int width = tv->columnWidth(i);
tv->setColumnWidth(i, width + padding);
}
}
}
void adjustColumns(QTreeWidget *tw, int padding)
{
adjustColumns(tw, tw->columnCount(), padding);
}
QTreeWidgetItem *appendRow(QTreeWidget *tw, const QString &str, const QString &str2,
const QString &str3, const QString &str4, const QString &str5)
{
QTreeWidgetItem *tempItem = new QTreeWidgetItem();
// Fill dummy hidden column
tempItem->setText(0, "0");
tempItem->setText(1, str);
if (!str2.isNull())
tempItem->setText(2, str2);
if (!str3.isNull())
tempItem->setText(3, str3);
if (!str4.isNull())
tempItem->setText(4, str4);
if (!str5.isNull())
tempItem->setText(5, str5);
tw->insertTopLevelItem(0, tempItem);
return tempItem;
}
/**
* @brief Select first item of a QAbstractItemView if not empty
* @param itemView
* @return true if first item was selected
*/
bool selectFirstItem(QAbstractItemView *itemView)
{
if (!itemView) {
return false;
}
auto model = itemView->model();
if (!model) {
return false;
}
if (model->hasIndex(0, 0)) {
itemView->setCurrentIndex(model->index(0, 0));
return true;
}
return false;
}
void setVerticalScrollMode(QAbstractItemView *tw)
{
tw->setVerticalScrollMode(scrollMode());
}
void setCheckedWithoutSignals(QAbstractButton *button, bool checked)
{
bool blocked = button->signalsBlocked();
button->blockSignals(true);
button->setChecked(checked);
button->blockSignals(blocked);
}
SizePolicyMinMax forceWidth(QWidget *widget, int width)
{
SizePolicyMinMax r;
r.sizePolicy = widget->sizePolicy();
r.min = widget->minimumWidth();
r.max = widget->maximumWidth();
QSizePolicy sizePolicy = r.sizePolicy;
sizePolicy.setHorizontalPolicy(QSizePolicy::Fixed);
widget->setSizePolicy(sizePolicy);
widget->setMinimumWidth(width);
widget->setMaximumWidth(width);
return r;
}
SizePolicyMinMax forceHeight(QWidget *widget, int height)
{
SizePolicyMinMax r;
r.sizePolicy = widget->sizePolicy();
r.min = widget->minimumHeight();
r.max = widget->maximumHeight();
QSizePolicy sizePolicy = r.sizePolicy;
sizePolicy.setVerticalPolicy(QSizePolicy::Fixed);
widget->setSizePolicy(sizePolicy);
widget->setMinimumHeight(height);
widget->setMaximumHeight(height);
return r;
}
void SizePolicyMinMax::restoreWidth(QWidget *widget)
{
widget->setSizePolicy(sizePolicy.horizontalPolicy(), widget->sizePolicy().verticalPolicy());
widget->setMinimumWidth(min);
widget->setMaximumWidth(max);
}
void SizePolicyMinMax::restoreHeight(QWidget *widget)
{
widget->setSizePolicy(widget->sizePolicy().horizontalPolicy(), sizePolicy.verticalPolicy());
widget->setMinimumHeight(min);
widget->setMaximumHeight(max);
}
int getMaxFullyDisplayedLines(QTextEdit *textEdit)
{
QFontMetrics fontMetrics(textEdit->document()->defaultFont());
return (textEdit->height()
- (textEdit->contentsMargins().top() + textEdit->contentsMargins().bottom()
+ (int)(textEdit->document()->documentMargin() * 2)))
/ fontMetrics.lineSpacing();
}
int getMaxFullyDisplayedLines(QPlainTextEdit *plainTextEdit)
{
QFontMetrics fontMetrics(plainTextEdit->document()->defaultFont());
return (plainTextEdit->height()
- (plainTextEdit->contentsMargins().top() + plainTextEdit->contentsMargins().bottom()
+ (int)(plainTextEdit->document()->documentMargin() * 2)))
/ fontMetrics.lineSpacing();
}
QByteArray applyColorToSvg(const QByteArray &data, QColor color)
{
static const QRegularExpression styleRegExp(
"(?:style=\".*fill:(.*?);.*?\")|(?:fill=\"(.*?)\")");
QString replaceStr = QString("#%1").arg(color.rgb() & 0xffffff, 6, 16, QLatin1Char('0'));
int replaceStrLen = replaceStr.length();
QString xml = QString::fromUtf8(data);
int offset = 0;
while (true) {
QRegularExpressionMatch match = styleRegExp.match(xml, offset);
if (!match.hasMatch()) {
break;
}
int captureIndex = match.captured(1).isNull() ? 2 : 1;
xml.replace(match.capturedStart(captureIndex), match.capturedLength(captureIndex),
replaceStr);
offset = match.capturedStart(captureIndex) + replaceStrLen;
}
return xml.toUtf8();
}
QByteArray applyColorToSvg(const QString &filename, QColor color)
{
QFile file(filename);
file.open(QIODevice::ReadOnly);
return applyColorToSvg(file.readAll(), color);
}
/**
* @brief finds the theme-specific icon path and calls `setter` functor providing a pointer of an
* object which has to be used and loaded icon
* @param supportedIconsNames list of <object ptr, icon name>
* @param setter functor which has to be called
* for example we need to set an action icon, the functor can be just [](void* o, const QIcon
* &icon) { static_cast<QAction*>(o)->setIcon(icon); }
*/
void setThemeIcons(QList<QPair<void *, QString>> supportedIconsNames,
std::function<void(void *, const QIcon &)> setter)
{
if (supportedIconsNames.isEmpty() || !setter) {
return;
}
const QString &iconsDirPath = QStringLiteral(":/img/icons/");
const QString &currTheme = Config()->getCurrentTheme()->name;
const QString &relativeThemeDir = currTheme.toLower() + "/";
QString iconPath;
foreach (const auto &p, supportedIconsNames) {
iconPath = iconsDirPath;
// Verify that indeed there is an alternative icon in this theme
// Otherwise, fallback to the regular icon folder
if (QFile::exists(iconPath + relativeThemeDir + p.second)) {
iconPath += relativeThemeDir;
}
setter(p.first, QIcon(iconPath + p.second));
}
}
void prependQAction(QAction *action, QMenu *menu)
{
auto actions = menu->actions();
if (actions.empty()) {
menu->addAction(action);
} else {
menu->insertAction(actions.first(), action);
}
}
qreal devicePixelRatio(const QPaintDevice *p)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
return p->devicePixelRatioF();
#else
return p->devicePixelRatio();
#endif
}
void selectIndexByData(QComboBox *widget, QVariant data, int defaultIndex)
{
for (int i = 0; i < widget->count(); i++) {
if (widget->itemData(i) == data) {
widget->setCurrentIndex(i);
return;
}
}
widget->setCurrentIndex(defaultIndex);
}
void emitColumnChanged(QAbstractItemModel *model, int column)
{
if (model && model->rowCount()) {
emit model->dataChanged(model->index(0, column),
model->index(model->rowCount() - 1, column), { Qt::DisplayRole });
}
}
bool filterStringContains(const QString &string, const QSortFilterProxyModel *model)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
return string.contains(model->filterRegExp());
#else
return string.contains(model->filterRegularExpression());
#endif
}
QPointF mouseEventPos(QMouseEvent *ev)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
return ev->localPos();
#else
return ev->position();
#endif
}
QPoint mouseEventGlobalPos(QMouseEvent *ev)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
return ev->globalPos();
#else
return ev->globalPosition().toPoint();
#endif
}
} // end namespace
| 8,692
|
C++
|
.cpp
| 265
| 28.015094
| 98
| 0.679747
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,632
|
CutterLayout.cpp
|
rizinorg_cutter/src/common/CutterLayout.cpp
|
#include "CutterLayout.h"
using namespace Cutter;
bool Cutter::isBuiltinLayoutName(const QString &name)
{
return name == LAYOUT_DEFAULT || name == LAYOUT_DEBUG;
}
| 169
|
C++
|
.cpp
| 6
| 26.166667
| 58
| 0.763975
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,633
|
UpdateWorker.cpp
|
rizinorg_cutter/src/common/UpdateWorker.cpp
|
#include "UpdateWorker.h"
#if CUTTER_UPDATE_WORKER_AVAILABLE
# include <QUrl>
# include <QFile>
# include <QTimer>
# include <QEventLoop>
# include <QDataStream>
# include <QJsonObject>
# include <QApplication>
# include <QJsonDocument>
# include <QDesktopServices>
# include <QtNetwork/QNetworkReply>
# include <QtNetwork/QNetworkRequest>
# include <QStandardPaths>
# include <QProgressDialog>
# include <QPushButton>
# include <QFileDialog>
# include <QMessageBox>
# include "common/Configuration.h"
# include "CutterConfig.h"
#endif
#if CUTTER_UPDATE_WORKER_AVAILABLE
UpdateWorker::UpdateWorker(QObject *parent) : QObject(parent), pending(false)
{
connect(&t, &QTimer::timeout, this, [this]() {
if (pending) {
disconnect(checkReply, nullptr, this, nullptr);
checkReply->close();
checkReply->deleteLater();
emit checkComplete(QVersionNumber(),
tr("Time limit exceeded during version check. Please check your "
"internet connection and try again."));
}
});
}
void UpdateWorker::checkCurrentVersion(time_t timeoutMs)
{
QUrl url("https://api.github.com/repos/rizinorg/cutter/releases/latest");
QNetworkRequest request;
request.setUrl(url);
t.setInterval(timeoutMs);
t.setSingleShot(true);
t.start();
checkReply = nm.get(request);
connect(checkReply, &QNetworkReply::finished, this, &UpdateWorker::serveVersionCheckReply);
pending = true;
}
void UpdateWorker::showUpdateDialog(bool showDontCheckForUpdatesButton)
{
QMessageBox mb;
mb.setWindowTitle(tr("Version control"));
mb.setText(tr("There is an update available for Cutter.<br/>") + "<b>" + tr("Current version:")
+ "</b> " CUTTER_VERSION_FULL "<br/>" + "<b>" + tr("Latest version:") + "</b> "
+ latestVersion.toString() + "<br/><br/>"
+ tr("To update, please check the link:<br/>")
+ QString("<a href=\"https://github.com/rizinorg/cutter/releases/tag/v%1\">"
"https://github.com/rizinorg/cutter/releases/tag/v%1</a><br/>")
.arg(latestVersion.toString()));
if (showDontCheckForUpdatesButton) {
mb.setStandardButtons(QMessageBox::Reset | QMessageBox::Ok);
mb.button(QMessageBox::Reset)->setText(tr("Don't check for updates automatically"));
} else {
mb.setStandardButtons(QMessageBox::Ok);
}
mb.setDefaultButton(QMessageBox::Ok);
int ret = mb.exec();
if (ret == QMessageBox::Reset) {
Config()->setAutoUpdateEnabled(false);
}
}
void UpdateWorker::serveVersionCheckReply()
{
pending = false;
QString versionReplyStr = "";
QString errStr = "";
if (checkReply->error()) {
errStr = checkReply->errorString();
} else {
versionReplyStr = QJsonDocument::fromJson(checkReply->readAll())
.object()
.value("tag_name")
.toString();
versionReplyStr.remove('v');
}
QVersionNumber versionReply = QVersionNumber::fromString(versionReplyStr);
if (!versionReply.isNull()) {
latestVersion = versionReply;
}
checkReply->close();
checkReply->deleteLater();
emit checkComplete(versionReply, errStr);
}
QVersionNumber UpdateWorker::currentVersionNumber()
{
return QVersionNumber(CUTTER_VERSION_MAJOR, CUTTER_VERSION_MINOR, CUTTER_VERSION_PATCH);
}
#endif // CUTTER_UPDATE_WORKER_AVAILABLE
| 3,622
|
C++
|
.cpp
| 97
| 30.670103
| 99
| 0.640501
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,634
|
JsonModel.cpp
|
rizinorg_cutter/src/common/JsonModel.cpp
|
#include "JsonModel.h"
QTreeWidgetItem *Cutter::jsonTreeWidgetItem(const QString &key, const CutterJson &json)
{
QString val;
switch (json.type()) {
case RZ_JSON_STRING:
val = json.toString();
break;
case RZ_JSON_BOOLEAN:
val = json.toBool() ? "true" : "false";
break;
case RZ_JSON_DOUBLE:
val = QString::number(json.lowLevelValue()->num.dbl_value);
break;
case RZ_JSON_INTEGER:
val = QString::number(json.toUt64());
break;
case RZ_JSON_NULL:
val = "null";
break;
case RZ_JSON_OBJECT:
case RZ_JSON_ARRAY:
break;
}
auto r = new QTreeWidgetItem(QStringList({ key, val }));
if (json.type() == RZ_JSON_ARRAY) {
size_t i = 0;
for (const auto &child : json) {
r->addChild(jsonTreeWidgetItem(QString::number(i++), child));
}
} else if (json.type() == RZ_JSON_OBJECT) {
for (const auto &child : json) {
r->addChild(jsonTreeWidgetItem(child.key(), child));
}
}
return r;
}
| 1,077
|
C++
|
.cpp
| 37
| 22.351351
| 87
| 0.575553
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,635
|
SettingsUpgrade.cpp
|
rizinorg_cutter/src/common/SettingsUpgrade.cpp
|
#include "SettingsUpgrade.h"
#include <QApplication>
#include <QMessageBox>
#include "common/ColorThemeWorker.h"
/**
* @brief Migrate Settings used before Cutter 1.8
*
* @return whether any settings have been migrated
*/
static bool migrateSettingsPre18(QSettings &newSettings)
{
if (newSettings.value("settings_migrated", false).toBool()) {
return false;
}
QSettings oldSettings(QSettings::NativeFormat, QSettings::Scope::UserScope, "Cutter", "Cutter");
QStringList allKeys = oldSettings.allKeys();
if (allKeys.isEmpty()) {
return false;
}
qInfo() << "Migrating Settings from pre-1.8";
for (const QString &key : allKeys) {
newSettings.setValue(key, oldSettings.value(key));
}
oldSettings.clear();
QFile settingsFile(oldSettings.fileName());
settingsFile.remove();
newSettings.setValue("settings_migrated", true);
return true;
}
#define CUTTER_SETTINGS_VERSION_CURRENT 6
#define CUTTER_SETTINGS_VERSION_KEY "version"
/*
* How Settings migrations work:
*
* Every time settings are changed in a way that needs migration,
* CUTTER_SETTINGS_VERSION_CURRENT is raised by 1 and a function migrateSettingsToX
* is implemented and added to initializeSettings().
* This function takes care of migrating from EXACTLY version X-1 to X.
*/
static void migrateSettingsTo1(QSettings &settings)
{
settings.remove("settings_migrated"); // now handled by version
settings.remove("updated_custom_themes"); // now handled by theme_version
}
static void migrateSettingsTo2(QSettings &settings)
{
QStringList docks = settings.value("docks").toStringList(); // get current list of docks
// replace occurences of "PseudocodeWidget" with "DecompilerWidget"
settings.setValue("docks", docks.replaceInStrings("PseudocodeWidget", "DecompilerWidget"));
}
static void migrateSettingsTo3(QSettings &settings)
{
auto defaultGeometry = settings.value("geometry").toByteArray();
auto defaultState = settings.value("state").toByteArray();
auto debugGeometry = settings.value("debug.geometry").toByteArray();
auto debugState = settings.value("debug.state").toByteArray();
const auto docks = settings.value("docks", QStringList()).toStringList();
auto unsyncList = settings.value("unsync", QStringList()).toStringList();
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
QSet<QString> unsyncDocks = unsyncList.toSet();
#else
QSet<QString> unsyncDocks(unsyncList.begin(), unsyncList.end());
#endif
QVariantMap viewProperties;
for (auto &dock : docks) {
QVariantMap properties;
bool synchronized = true;
if (unsyncDocks.contains(dock)) {
synchronized = false;
}
properties.insert("synchronized", synchronized);
viewProperties.insert(dock, properties);
}
settings.beginWriteArray("layouts", 2);
settings.setArrayIndex(0);
settings.setValue("name", "Default");
settings.setValue("geometry", defaultGeometry);
settings.setValue("state", defaultState);
settings.setValue("docks", viewProperties);
settings.setArrayIndex(1);
settings.setValue("name", "Debug");
settings.setValue("geometry", debugGeometry);
settings.setValue("state", debugState);
settings.setValue("docks", viewProperties);
settings.endArray();
settings.remove("pos"); // Pos and size already stored within geometry
settings.remove("size");
// keep geometry but with slightly different usecase
settings.remove("state");
settings.remove("debug.geometry");
settings.remove("debug.state");
settings.remove("docks");
settings.remove("unsync");
}
static void renameAsmOption(QSettings &settings, const QString &oldName, const QString &newName)
{
if (settings.contains(oldName)) {
auto value = settings.value(oldName);
settings.remove(oldName);
settings.setValue(newName, value);
}
}
static void migrateSettingsTo4(QSettings &settings)
{
renameAsmOption(settings, "asm.var.subonly", "asm.sub.varonly");
renameAsmOption(settings, "asm.bytespace", "asm.bytes.space");
}
static void migrateSettingsTo5(QSettings &settings)
{
renameAsmOption(settings, "asm.var.sub", "asm.sub.var");
}
static void migrateSettingsTo6(QSettings &settings)
{
settings.remove("dir.projects");
}
void Cutter::initializeSettings()
{
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings settings;
int settingsVersion = settings.value(CUTTER_SETTINGS_VERSION_KEY, 0).toInt();
if (settingsVersion == 0) {
migrateSettingsPre18(settings);
}
if (settings.allKeys().length() > 0) {
if (settingsVersion > CUTTER_SETTINGS_VERSION_CURRENT) {
qWarning() << "Settings have a higher version than current! Skipping migration.";
} else if (settingsVersion >= 0) {
for (int v = settingsVersion + 1; v <= CUTTER_SETTINGS_VERSION_CURRENT; v++) {
qInfo() << "Migrating Settings to Version" << v;
switch (v) {
case 1:
migrateSettingsTo1(settings);
break;
case 2:
migrateSettingsTo2(settings);
break;
case 3:
migrateSettingsTo3(settings);
break;
case 4:
migrateSettingsTo4(settings);
break;
case 5:
migrateSettingsTo5(settings);
break;
case 6:
migrateSettingsTo6(settings);
break;
default:
break;
}
}
}
}
settings.setValue(CUTTER_SETTINGS_VERSION_KEY, CUTTER_SETTINGS_VERSION_CURRENT);
}
#define THEME_VERSION_CURRENT 1
#define THEME_VERSION_KEY "theme_version"
static void removeObsoleteOptionsFromCustomThemes()
{
const QStringList options = Core()->getThemeKeys() << ColorThemeWorker::cutterSpecificOptions;
QStringList themes = Core()->getColorThemes();
for (const auto &themeName : themes) {
if (!ThemeWorker().isCustomTheme(themeName)) {
continue;
}
ColorThemeWorker::Theme sch = ThemeWorker().getTheme(themeName);
ColorThemeWorker::Theme updatedTheme;
for (auto it = sch.constBegin(); it != sch.constEnd(); ++it) {
if (options.contains(it.key())) {
updatedTheme.insert(it.key(), it.value());
}
}
ThemeWorker().save(updatedTheme, themeName);
}
}
void Cutter::migrateThemes()
{
QSettings settings;
int themeVersion = settings.value(THEME_VERSION_KEY, 0).toInt();
if (themeVersion != THEME_VERSION_CURRENT) {
removeObsoleteOptionsFromCustomThemes();
settings.setValue(THEME_VERSION_KEY, THEME_VERSION_CURRENT);
}
}
static const char PRE_RIZIN_ORG[] = "RadareOrg";
static const char PRE_RIZIN_APP[] = "Cutter";
bool Cutter::shouldOfferSettingImport()
{
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings settings;
if (settings.contains("firstExecution")) {
return false;
}
QSettings r2CutterSettings(QSettings::IniFormat, QSettings::Scope::UserScope, PRE_RIZIN_ORG,
PRE_RIZIN_APP);
QString f = r2CutterSettings.fileName();
if (r2CutterSettings.value("firstExecution", true) != QVariant(false)) {
return false; // no Cutter <= 1.12 settings to import
}
int version = r2CutterSettings.value("version", -1).toInt();
if (version < 1 || version > 6) {
return false; // version too new maybe it's from r2Cutter fork instead of pre-rizin Cutter.
}
return true;
}
static void importOldSettings()
{
// QSettings
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings r2CutterSettings(QSettings::IniFormat, QSettings::Scope::UserScope, PRE_RIZIN_ORG,
PRE_RIZIN_APP);
QSettings newSettings;
for (auto key : r2CutterSettings.allKeys()) {
newSettings.setValue(key, r2CutterSettings.value(key));
}
// Color Themes
char *szThemes = rz_str_home(".local/share/radare2/cons");
QString r2ThemesPath = szThemes;
rz_mem_free(szThemes);
QDir r2ThemesDir(r2ThemesPath);
if (QFileInfo(r2ThemesPath).isDir()) {
QDir rzThemesDir(ThemeWorker().getCustomThemesPath());
if (!rzThemesDir.exists()) {
QDir().mkpath(rzThemesDir.absolutePath());
}
for (auto f : r2ThemesDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files)) {
auto dst = rzThemesDir.absoluteFilePath(f.fileName());
if (QDir(dst).exists()) {
qInfo() << "Theme" << dst << "already exists. Not overwriting with"
<< f.absoluteFilePath();
continue;
}
qInfo() << "Copying Theme" << f.absoluteFilePath() << "to" << dst;
QFile::copy(f.absoluteFilePath(), dst);
}
}
}
void Cutter::showSettingImportDialog(int &argc, char **argv)
{
// Creating temporary QApplication because this happens before anything else in Cutter is
// initialized
QApplication temporaryApp(argc, argv);
QSettings r2CutterSettings(QSettings::IniFormat, QSettings::Scope::UserScope, PRE_RIZIN_ORG,
PRE_RIZIN_APP);
QString oldFile = r2CutterSettings.fileName();
// Can't use message translations because settings have not been imported
auto result =
QMessageBox::question(nullptr, "Setting import",
QString("Do you want to import settings from %1?").arg(oldFile));
if (result == QMessageBox::Yes) {
importOldSettings();
}
}
| 9,840
|
C++
|
.cpp
| 254
| 31.712598
| 100
| 0.661923
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,636
|
DecompilerHighlighter.cpp
|
rizinorg_cutter/src/common/DecompilerHighlighter.cpp
|
#include "DecompilerHighlighter.h"
#include "common/Configuration.h"
#include <memory>
DecompilerHighlighter::DecompilerHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
setupTheme();
connect(Config(), &Configuration::colorsUpdated, this, [this]() {
setupTheme();
rehighlight();
});
}
void DecompilerHighlighter::setAnnotations(RzAnnotatedCode *code)
{
this->code = code;
}
void DecompilerHighlighter::setupTheme()
{
struct
{
RSyntaxHighlightType type;
QString name;
} mapping[] = {
{ RZ_SYNTAX_HIGHLIGHT_TYPE_KEYWORD, "pop" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_COMMENT, "comment" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_DATATYPE, "func_var_type" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_FUNCTION_NAME, "fname" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_FUNCTION_PARAMETER, "args" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_LOCAL_VARIABLE, "func_var" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_CONSTANT_VARIABLE, "num" },
{ RZ_SYNTAX_HIGHLIGHT_TYPE_GLOBAL_VARIABLE, "flag" },
};
for (const auto &pair : mapping) {
assert(pair.type < format.size());
format[pair.type].setForeground(Config()->getColor(pair.name));
}
}
void DecompilerHighlighter::highlightBlock(const QString &)
{
if (!code) {
return;
}
auto block = currentBlock();
size_t start = block.position();
size_t end = block.position() + block.length();
auto annotations = fromOwned(rz_annotated_code_annotations_range(code, start, end));
void **iter;
rz_pvector_foreach(annotations.get(), iter)
{
RzCodeAnnotation *annotation = static_cast<RzCodeAnnotation *>(*iter);
if (annotation->type != RZ_CODE_ANNOTATION_TYPE_SYNTAX_HIGHLIGHT) {
continue;
}
auto type = annotation->syntax_highlight.type;
if (size_t(type) >= HIGHLIGHT_COUNT) {
continue;
}
auto annotationStart = annotation->start;
if (annotationStart < start) {
annotationStart = 0;
} else {
annotationStart -= start;
}
auto annotationEnd = annotation->end - start;
setFormat(annotationStart, annotationEnd - annotationStart, format[type]);
}
}
| 2,262
|
C++
|
.cpp
| 66
| 27.939394
| 96
| 0.645795
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,637
|
Highlighter.cpp
|
rizinorg_cutter/src/common/Highlighter.cpp
|
#include "Highlighter.h"
#include "core/MainWindow.h"
#include <QtGui>
Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
HighlightingRule rule;
core = Core();
regFormat.setForeground(QColor(236, 100, 75));
for (const QString &pattern : this->core->regs) {
rule.pattern.setPattern("\\b" + pattern + "\\b");
rule.pattern.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
rule.format = regFormat;
highlightingRules.append(rule);
}
singleLineCommentFormat.setFontWeight(QFont::Bold);
singleLineCommentFormat.setForeground(QColor(63, 195, 128));
rule.pattern.setPattern(";[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
commentStartRegularExpression.setPattern("/\\*");
commentEndRegularExpression.setPattern("\\*/");
}
void Highlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule &rule : highlightingRules) {
QRegularExpression expression(rule.pattern);
int index = expression.match(text).capturedStart();
while (index >= 0) {
int length = expression.match(text).capturedLength();
setFormat(index, length, rule.format);
index = expression.match(text.mid(index + length)).capturedStart();
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = QRegularExpression(commentStartRegularExpression).match(text).capturedStart();
while (startIndex >= 0) {
QRegularExpressionMatch commentEndMatch =
QRegularExpression(commentEndRegularExpression).match(text.mid(startIndex));
int endIndex = commentEndMatch.capturedStart();
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex + commentEndMatch.capturedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = QRegularExpression(commentStartRegularExpression)
.match(text.mid(startIndex + commentLength))
.capturedStart();
}
}
| 2,301
|
C++
|
.cpp
| 54
| 34.796296
| 99
| 0.676799
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,638
|
BasicInstructionHighlighter.cpp
|
rizinorg_cutter/src/common/BasicInstructionHighlighter.cpp
|
#include "BasicInstructionHighlighter.h"
#include <vector>
/**
* @brief Clear the basic instruction highlighting
*/
void BasicInstructionHighlighter::clear(RVA address, RVA size)
{
BasicInstructionIt it = biMap.lower_bound(address);
if (it != biMap.begin()) {
--it;
}
std::vector<RVA> addrs;
while (it != biMap.end() && it->first < address + size) {
addrs.push_back(it->first);
++it;
}
// first and last entries may intersect, but not necessarily
// be contained in [address, address + size), so we need to
// check it and perhaps adjust their addresses.
std::vector<BasicInstruction> newInstructions;
if (!addrs.empty()) {
const BasicInstruction &prev = biMap[addrs.front()];
if (prev.address < address && prev.address + prev.size > address) {
newInstructions.push_back({ prev.address, address - prev.address, prev.color });
}
const BasicInstruction &next = biMap[addrs.back()];
if (next.address < address + size && next.address + next.size > address + size) {
const RVA offset = address + size - next.address;
newInstructions.push_back({ next.address + offset, next.size - offset, next.color });
}
}
for (RVA addr : addrs) {
const BasicInstruction &bi = biMap[addr];
if (std::max(bi.address, address) < std::min(bi.address + bi.size, address + size)) {
biMap.erase(addr);
}
}
for (BasicInstruction newInstr : newInstructions) {
biMap[newInstr.address] = newInstr;
}
}
/**
* @brief Highlight the basic instruction at address
*/
void BasicInstructionHighlighter::highlight(RVA address, RVA size, QColor color)
{
clear(address, size);
biMap[address] = { address, size, color };
}
/**
* @brief Return a highlighted basic instruction
*
* If there is nothing to highlight at specified address, returns nullptr
*/
BasicInstruction *BasicInstructionHighlighter::getBasicInstruction(RVA address)
{
BasicInstructionIt it = biMap.upper_bound(address);
if (it == biMap.begin()) {
return nullptr;
}
BasicInstruction *bi = &(--it)->second;
if (bi->address <= address && address < bi->address + bi->size) {
return bi;
}
return nullptr;
}
| 2,310
|
C++
|
.cpp
| 66
| 29.681818
| 97
| 0.651454
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,639
|
DirectionalComboBox.cpp
|
rizinorg_cutter/src/common/DirectionalComboBox.cpp
|
#include "DirectionalComboBox.h"
DirectionalComboBox::DirectionalComboBox(QWidget *parent, bool upwards)
: QComboBox(parent), popupUpwards(upwards)
{
}
void DirectionalComboBox::showPopup()
{
QComboBox::showPopup();
QWidget *popup = this->findChild<QFrame *>();
if (popupUpwards) {
popup->move(popup->x(), mapToGlobal(this->rect().bottomLeft()).y() - popup->height());
} else {
popup->move(popup->x(), mapToGlobal(this->rect().topLeft()).y());
}
}
void DirectionalComboBox::setPopupDirection(bool upwards)
{
popupUpwards = upwards;
}
| 581
|
C++
|
.cpp
| 19
| 27.105263
| 94
| 0.697674
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,640
|
PythonManager.cpp
|
rizinorg_cutter/src/common/PythonManager.cpp
|
#include <cassert>
#include "PythonAPI.h"
#include "PythonManager.h"
#include "Cutter.h"
#include <QDebug>
#include <QFile>
#include <QDebug>
#include <QCoreApplication>
#include <QDir>
#ifdef CUTTER_ENABLE_PYTHON_BINDINGS
# include <shiboken.h>
# include <pyside.h>
# ifdef HAVE_PYSIDECLEANUP
// This header is introduced in PySide 6
# include <pysidecleanup.h>
# endif
# include <signalmanager.h>
#endif
#include "QtResImporter.h"
static PythonManager *uniqueInstance = nullptr;
PythonManager *PythonManager::getInstance()
{
if (!uniqueInstance) {
uniqueInstance = new PythonManager();
}
return uniqueInstance;
}
PythonManager::PythonManager() {}
PythonManager::~PythonManager() {}
void PythonManager::initPythonHome()
{
#if defined(APPIMAGE) || defined(MACOS_PYTHON_FRAMEWORK_BUNDLED)
if (customPythonHome.isNull()) {
auto pythonHomeDir = QDir(QCoreApplication::applicationDirPath());
# ifdef APPIMAGE
// Executable is in appdir/bin
pythonHomeDir.cdUp();
qInfo() << "Setting PYTHONHOME =" << pythonHomeDir.absolutePath() << " for AppImage.";
# else // MACOS_PYTHON_FRAMEWORK_BUNDLED
// @executable_path/../Frameworks/Python.framework/Versions/Current
pythonHomeDir.cd("../Frameworks/Python.framework/Versions/Current");
qInfo() << "Setting PYTHONHOME =" << pythonHomeDir.absolutePath()
<< " for macOS Application Bundle.";
# endif
customPythonHome = pythonHomeDir.absolutePath();
}
#endif
if (!customPythonHome.isNull()) {
qInfo() << "PYTHONHOME =" << customPythonHome;
pythonHome = Py_DecodeLocale(customPythonHome.toLocal8Bit().constData(), nullptr);
Py_SetPythonHome(pythonHome);
}
}
#ifdef CUTTER_ENABLE_PYTHON_BINDINGS
extern "C" PyObject *PyInit_CutterBindings();
#endif
void PythonManager::initialize()
{
initPythonHome();
PyImport_AppendInittab("_cutter", &PyInit_api);
PyImport_AppendInittab("_qtres", &PyInit_qtres);
#ifdef CUTTER_ENABLE_PYTHON_BINDINGS
PyImport_AppendInittab("CutterBindings", &PyInit_CutterBindings);
#endif
Py_Initialize();
// This function is deprecated does nothing starting from Python 3.9
#if (PY_MAJOR_VERSION <= 3) && (PY_MICRO_VERSION < 9)
PyEval_InitThreads();
#endif
pyThreadStateCounter = 1; // we have the thread now => 1
RegQtResImporter();
saveThread();
}
#ifdef CUTTER_ENABLE_PYTHON_BINDINGS
static void pySideDestructionVisitor(SbkObject *pyObj, void *data)
{
void **realData = reinterpret_cast<void **>(data);
auto pyQApp = reinterpret_cast<SbkObject *>(realData[0]);
auto pyQObjectType = reinterpret_cast<PyTypeObject *>(realData[1]);
if (pyObj == pyQApp || !PyObject_TypeCheck(pyObj, pyQObjectType)) {
return;
}
if (!Shiboken::Object::hasOwnership(pyObj) || !Shiboken::Object::isValid(pyObj, false)) {
return;
}
const char *reprStr = "";
PyObject *repr = PyObject_Repr(reinterpret_cast<PyObject *>(pyObj));
PyObject *reprBytes;
if (repr) {
reprBytes = PyUnicode_AsUTF8String(repr);
reprStr = PyBytes_AsString(reprBytes);
}
qWarning() << "Warning: QObject from Python remaining (leaked from plugin?):" << reprStr;
if (repr) {
Py_DecRef(reprBytes);
Py_DecRef(repr);
}
Shiboken::Object::setValidCpp(pyObj, false);
Py_BEGIN_ALLOW_THREADS Shiboken::callCppDestructor<QObject>(
Shiboken::Object::cppPointer(pyObj, pyQObjectType));
Py_END_ALLOW_THREADS
};
#endif
void PythonManager::shutdown()
{
emit willShutDown();
restoreThread();
#ifdef CUTTER_ENABLE_PYTHON_BINDINGS
// This is necessary to prevent a segfault when the CutterCore instance is deleted after the
// Shiboken::BindingManager
Core()->setProperty("_PySideInvalidatePtr", QVariant());
// see PySide::destroyQCoreApplication()
PySide::SignalManager::instance().clear();
Shiboken::BindingManager &bm = Shiboken::BindingManager::instance();
SbkObject *pyQApp = bm.retrieveWrapper(QCoreApplication::instance());
PyTypeObject *pyQObjectType = Shiboken::Conversions::getPythonTypeObject("QObject*");
void *data[2] = { pyQApp, pyQObjectType };
bm.visitAllPyObjects(&pySideDestructionVisitor, &data);
PySide::runCleanupFunctions();
#endif
if (pythonHome) {
PyMem_Free(pythonHome);
}
Py_Finalize();
}
void PythonManager::addPythonPath(char *path)
{
restoreThread();
PyObject *sysModule = PyImport_ImportModule("sys");
if (!sysModule) {
return;
}
PyObject *pythonPath = PyObject_GetAttrString(sysModule, "path");
if (!pythonPath) {
return;
}
PyObject *append = PyObject_GetAttrString(pythonPath, "append");
if (!append) {
return;
}
PyObject_CallFunction(append, "(s)", path);
saveThread();
}
void PythonManager::restoreThread()
{
pyThreadStateCounter++;
if (pyThreadStateCounter == 1 && pyThreadState) {
PyEval_RestoreThread(pyThreadState);
}
}
void PythonManager::saveThread()
{
pyThreadStateCounter--;
assert(pyThreadStateCounter >= 0);
if (pyThreadStateCounter == 0) {
pyThreadState = PyEval_SaveThread();
}
}
| 5,273
|
C++
|
.cpp
| 158
| 29.012658
| 96
| 0.699056
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,641
|
ProgressIndicator.cpp
|
rizinorg_cutter/src/common/ProgressIndicator.cpp
|
#include "ProgressIndicator.h"
#include <QPainter>
static const int lineWidth = 3;
static const int paddingOuter = lineWidth + 2;
static const int paddingInner = 8;
static const int arms = 12;
static const int timerInterval = 50;
ProgressIndicator::ProgressIndicator(QWidget *parent) : QWidget(parent)
{
updateAnimationTimer();
}
ProgressIndicator::~ProgressIndicator() {}
void ProgressIndicator::setProgressIndicatorVisible(bool visible)
{
bool change = progressIndicatorVisible != visible;
progressIndicatorVisible = visible;
if (change) {
update();
}
updateAnimationTimer();
}
void ProgressIndicator::setAnimating(bool animating)
{
this->animating = animating;
updateAnimationTimer();
}
void ProgressIndicator::updateAnimationTimer()
{
bool shouldBeAnimating = animating && progressIndicatorVisible;
if (shouldBeAnimating && !animationTimerId) {
animationTimerId = startTimer(timerInterval);
} else {
killTimer(animationTimerId);
animationTimerId = 0;
}
}
QSize ProgressIndicator::minimumSizeHint() const
{
return QSize(16, 16);
}
QSize ProgressIndicator::sizeHint() const
{
return QSize(32, 32);
}
void ProgressIndicator::timerEvent(QTimerEvent *)
{
animationState = (animationState + 1) % arms;
update();
}
void ProgressIndicator::paintEvent(QPaintEvent *)
{
if (!getProgressIndicatorVisible()) {
return;
}
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QPen pen(palette().windowText(), lineWidth, Qt::SolidLine, Qt::RoundCap);
painter.setPen(pen);
QPointF origin(width() * 0.5, height() * 0.5);
QLineF line(paddingInner, 0.0, width() * 0.5 - paddingOuter, 0.0);
qreal angle = 360.0 / arms;
for (int i = 0; i < arms; i++) {
int state = (i + (arms - animationState)) % arms;
painter.setOpacity((float)state / arms);
painter.drawLine(line * QTransform().translate(origin.x(), origin.y()).rotate(angle * i));
}
}
| 2,032
|
C++
|
.cpp
| 67
| 26.537313
| 98
| 0.711282
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,642
|
AsyncTask.cpp
|
rizinorg_cutter/src/common/AsyncTask.cpp
|
#include "AsyncTask.h"
AsyncTask::AsyncTask() : QObject(nullptr), QRunnable()
{
setAutoDelete(false);
running = false;
}
AsyncTask::~AsyncTask()
{
wait();
}
void AsyncTask::wait()
{
runningMutex.lock();
runningMutex.unlock();
}
bool AsyncTask::wait(int timeout)
{
bool r = runningMutex.tryLock(timeout);
if (r) {
runningMutex.unlock();
}
return r;
}
void AsyncTask::interrupt()
{
interrupted = true;
}
void AsyncTask::prepareRun()
{
interrupted = false;
wait();
timer.start();
}
void AsyncTask::run()
{
runningMutex.lock();
running = true;
logBuffer.clear();
emit logChanged(logBuffer);
runTask();
running = false;
emit finished();
runningMutex.unlock();
}
void AsyncTask::log(QString s)
{
logBuffer += s.append(QLatin1Char('\n'));
emit logChanged(logBuffer);
}
AsyncTaskManager::AsyncTaskManager(QObject *parent) : QObject(parent)
{
threadPool = new QThreadPool(this);
}
AsyncTaskManager::~AsyncTaskManager() {}
void AsyncTaskManager::start(AsyncTask::Ptr task)
{
tasks.append(task);
task->prepareRun();
QWeakPointer<AsyncTask> weakPtr = task;
connect(task.data(), &AsyncTask::finished, this, [this, weakPtr]() {
tasks.removeOne(weakPtr);
emit tasksChanged();
});
threadPool->start(task.data());
emit tasksChanged();
}
bool AsyncTaskManager::getTasksRunning()
{
return !tasks.isEmpty();
}
| 1,461
|
C++
|
.cpp
| 70
| 17.428571
| 72
| 0.682945
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,643
|
CutterApplication.h
|
rizinorg_cutter/src/CutterApplication.h
|
#ifndef CUTTERAPPLICATION_H
#define CUTTERAPPLICATION_H
#include <QEvent>
#include <QApplication>
#include <QList>
#include <QProxyStyle>
#include "core/MainWindow.h"
enum class AutomaticAnalysisLevel { Ask, None, AAA, AAAA };
struct CutterCommandLineOptions
{
QStringList args;
AutomaticAnalysisLevel analysisLevel = AutomaticAnalysisLevel::Ask;
InitialOptions fileOpenOptions;
QString pythonHome;
bool outputRedirectionEnabled = true;
bool enableCutterPlugins = true;
bool enableRizinPlugins = true;
};
class CutterApplication : public QApplication
{
Q_OBJECT
public:
CutterApplication(int &argc, char **argv);
~CutterApplication();
MainWindow *getMainWindow() { return mainWindow; }
void launchNewInstance(const QStringList &args = {});
InitialOptions getInitialOptions() const { return clOptions.fileOpenOptions; }
void setInitialOptions(const InitialOptions &options) { clOptions.fileOpenOptions = options; }
QStringList getArgs() const;
protected:
bool event(QEvent *e);
private:
/**
* @brief Load and translations depending on Language settings
* @return true on success
*/
bool loadTranslations();
/**
* @brief Parse commandline options and store them in a structure.
* @return false if options have error
*/
bool parseCommandLineOptions();
private:
bool m_FileAlreadyDropped;
CutterCore core;
MainWindow *mainWindow;
CutterCommandLineOptions clOptions;
};
/**
* @brief CutterProxyStyle is used to force shortcuts displaying in context menu
*/
class CutterProxyStyle : public QProxyStyle
{
Q_OBJECT
public:
/**
* @brief it is enough to get notification about QMenu polishing to force shortcut displaying
*/
void polish(QWidget *widget) override;
};
#endif // CUTTERAPPLICATION_H
| 1,851
|
C++
|
.h
| 61
| 26.655738
| 98
| 0.752252
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,644
|
MainWindow.h
|
rizinorg_cutter/src/core/MainWindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "core/Cutter.h" // only needed for ut64
#include "dialogs/NewFileDialog.h"
#include "dialogs/WelcomeDialog.h"
#include "common/Configuration.h"
#include "common/InitialOptions.h"
#include "common/IOModesController.h"
#include "common/CutterLayout.h"
#include "MemoryDockWidget.h"
#include <memory>
#include <QMainWindow>
#include <QList>
class CutterCore;
class Omnibar;
class ProgressIndicator;
class PreviewWidget;
class Highlighter;
class AsciiHighlighter;
class VisualNavbar;
class FunctionsWidget;
class ImportsWidget;
class ExportsWidget;
class SymbolsWidget;
class GlobalsWidget;
class RelocsWidget;
class CommentsWidget;
class StringsWidget;
class FlagsWidget;
class Dashboard;
class QLineEdit;
class SdbWidget;
class QAction;
class SectionsWidget;
class SegmentsWidget;
class ConsoleWidget;
class EntrypointWidget;
class DisassemblerGraphView;
class ClassesWidget;
class ResourcesWidget;
class VTablesWidget;
class TypesWidget;
class HeadersWidget;
class FlirtWidget;
class SearchWidget;
class QDockWidget;
class DisassemblyWidget;
class GraphWidget;
class HexdumpWidget;
class DecompilerWidget;
class OverviewWidget;
class RizinGraphWidget;
class CallGraphWidget;
class HeapWidget;
namespace Ui {
class MainWindow;
}
class CUTTER_EXPORT MainWindow : public QMainWindow
{
Q_OBJECT
public:
bool responsive;
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
void openNewFile(InitialOptions &options, bool skipOptionsDialog = false);
void displayNewFileDialog();
void displayWelcomeDialog();
void closeNewFileDialog();
bool openProject(const QString &project_name);
RzProjectErr saveProject(bool *canceled);
RzProjectErr saveProjectAs(bool *canceled);
void showProjectSaveError(RzProjectErr err);
void closeEvent(QCloseEvent *event) override;
void paintEvent(QPaintEvent *event) override;
void readSettings();
void saveSettings();
void setFilename(const QString &fn);
void refreshOmniBar(const QStringList &flags);
void addWidget(CutterDockWidget *widget);
void addMemoryDockWidget(MemoryDockWidget *widget);
void removeWidget(CutterDockWidget *widget);
void addExtraWidget(CutterDockWidget *extraDock);
MemoryDockWidget *addNewMemoryWidget(MemoryWidgetType type, RVA address,
bool synchronized = true);
CUTTER_DEPRECATED("Action will be ignored. Use addPluginDockWidget(CutterDockWidget*) instead.")
void addPluginDockWidget(CutterDockWidget *dockWidget, QAction *)
{
addPluginDockWidget(dockWidget);
}
void addPluginDockWidget(CutterDockWidget *dockWidget);
enum class MenuType { File, Edit, View, Windows, Debug, Help, Plugins };
/**
* @brief Getter for MainWindow's different menus
* @param type The type which represents the desired menu
* @return The requested menu or nullptr if "type" is invalid
*/
QMenu *getMenuByType(MenuType type);
void addMenuFileAction(QAction *action);
QString getFilename() const { return filename; }
void messageBoxWarning(QString title, QString message);
QString getUniqueObjectName(const QString &widgetType) const;
void showMemoryWidget();
void showMemoryWidget(MemoryWidgetType type);
enum class AddressTypeHint { Function, Data, Unknown };
QMenu *createShowInMenu(QWidget *parent, RVA address,
AddressTypeHint addressType = AddressTypeHint::Unknown);
void setCurrentMemoryWidget(MemoryDockWidget *memoryWidget);
MemoryDockWidget *getLastMemoryWidget();
/* Context menu plugins */
enum class ContextMenuType { Disassembly, Addressable };
/**
* @brief Fetches the pointer to a context menu extension of type
* @param type - the type of the context menu
* @return plugins submenu of the selected context menu
*/
QMenu *getContextMenuExtensions(ContextMenuType type);
public slots:
void finalizeOpen();
void refreshAll();
void seekToFunctionLastInstruction();
void seekToFunctionStart();
void setTabLocation();
void on_actionTabs_triggered();
void on_actionAnalyze_triggered();
void lockDocks(bool lock);
void on_actionRun_Script_triggered();
void toggleResponsive(bool maybe);
void openNewFileFailed();
void toggleOverview(bool visibility, GraphWidget *targetGraph);
private slots:
void on_actionBaseFind_triggered();
void on_actionAbout_triggered();
void on_actionIssue_triggered();
void documentationClicked();
void addExtraGraph();
void addExtraHexdump();
void addExtraDisassembly();
void addExtraDecompiler();
void on_actionRefresh_Panels_triggered();
void on_actionDisasAdd_comment_triggered();
void on_actionDefault_triggered();
void on_actionNew_triggered();
void on_actionSave_triggered();
void on_actionSaveAs_triggered();
void on_actionBackward_triggered();
void on_actionForward_triggered();
void on_actionMap_triggered();
void on_actionTabs_on_Top_triggered();
void on_actionReset_settings_triggered();
void on_actionQuit_triggered();
void on_actionRefresh_contents_triggered();
void on_actionPreferences_triggered();
void on_actionImportPDB_triggered();
void on_actionExport_as_code_triggered();
void on_actionApplySigFromFile_triggered();
void on_actionCreateNewSig_triggered();
void on_actionGrouped_dock_dragging_triggered(bool checked);
void updateTasksIndicator();
void mousePressEvent(QMouseEvent *event) override;
bool eventFilter(QObject *object, QEvent *event) override;
bool event(QEvent *event) override;
void toggleDebugView();
void chooseThemeIcons();
void onZoomIn();
void onZoomOut();
void onZoomReset();
void setAvailableIOModeOptions();
private:
CutterCore *core;
bool tabsOnTop;
ut64 hexdumpTopOffset;
ut64 hexdumpBottomOffset;
QString filename;
std::unique_ptr<Ui::MainWindow> ui;
Highlighter *highlighter;
VisualNavbar *visualNavbar;
Omnibar *omnibar;
ProgressIndicator *tasksProgressIndicator;
QByteArray emptyState;
IOModesController ioModesController;
Configuration *configuration;
QList<CutterDockWidget *> dockWidgets;
QList<CutterDockWidget *> pluginDocks;
OverviewWidget *overviewDock = nullptr;
QAction *actionOverview = nullptr;
EntrypointWidget *entrypointDock = nullptr;
FunctionsWidget *functionsDock = nullptr;
ImportsWidget *importsDock = nullptr;
ExportsWidget *exportsDock = nullptr;
HeadersWidget *headersDock = nullptr;
TypesWidget *typesDock = nullptr;
SearchWidget *searchDock = nullptr;
SymbolsWidget *symbolsDock = nullptr;
GlobalsWidget *globalsDock = nullptr;
RelocsWidget *relocsDock = nullptr;
CommentsWidget *commentsDock = nullptr;
StringsWidget *stringsDock = nullptr;
FlagsWidget *flagsDock = nullptr;
Dashboard *dashboardDock = nullptr;
SdbWidget *sdbDock = nullptr;
SectionsWidget *sectionsDock = nullptr;
SegmentsWidget *segmentsDock = nullptr;
FlirtWidget *flirtDock = nullptr;
ConsoleWidget *consoleDock = nullptr;
ClassesWidget *classesDock = nullptr;
ResourcesWidget *resourcesDock = nullptr;
VTablesWidget *vTablesDock = nullptr;
CutterDockWidget *stackDock = nullptr;
CutterDockWidget *threadsDock = nullptr;
CutterDockWidget *processesDock = nullptr;
CutterDockWidget *registersDock = nullptr;
CutterDockWidget *backtraceDock = nullptr;
CutterDockWidget *memoryMapDock = nullptr;
NewFileDialog *newFileDialog = nullptr;
CutterDockWidget *breakpointDock = nullptr;
CutterDockWidget *registerRefsDock = nullptr;
RizinGraphWidget *rzGraphDock = nullptr;
CallGraphWidget *callGraphDock = nullptr;
CallGraphWidget *globalCallGraphDock = nullptr;
CutterDockWidget *heapDock = nullptr;
QMenu *disassemblyContextMenuExtensions = nullptr;
QMenu *addressableContextMenuExtensions = nullptr;
QMap<QString, Cutter::CutterLayout> layouts;
void initUI();
void initToolBar();
void initDocks();
void initBackForwardMenu();
void displayInitialOptionsDialog(const InitialOptions &options = InitialOptions(),
bool skipOptionsDialog = false);
Cutter::CutterLayout getViewLayout();
Cutter::CutterLayout getViewLayout(const QString &name);
void setViewLayout(const Cutter::CutterLayout &layout);
void loadLayouts(QSettings &settings);
void saveLayouts(QSettings &settings);
void updateMemberPointers();
void restoreDocks();
void showZenDocks();
void showDebugDocks();
/**
* @brief Try to guess which is the "main" section of layout and dock there.
* @param widget that needs to be docked
*/
void dockOnMainArea(QDockWidget *widget);
void enableDebugWidgetsMenu(bool enable);
/**
* @brief Fill menu with seek history entries.
* @param menu
* @param redo set to false for undo history, true for redo.
*/
void updateHistoryMenu(QMenu *menu, bool redo = false);
void updateLayoutsMenu();
void saveNamedLayout();
void manageLayouts();
void setOverviewData();
bool isOverviewActive();
/**
* @brief Check if a widget is one of debug specific dock widgets.
* @param dock
* @return true for debug specific widgets, false for all other including common dock widgets.
*/
bool isDebugWidget(QDockWidget *dock) const;
bool isExtraMemoryWidget(QDockWidget *dock) const;
MemoryWidgetType getMemoryWidgetTypeToRestore();
/**
* @brief Map from a widget type (e.g. DisassemblyWidget::getWidgetType()) to the respective
* contructor of the widget
*/
QMap<QString, std::function<CutterDockWidget *(MainWindow *)>> widgetTypeToConstructorMap;
MemoryDockWidget *lastSyncMemoryWidget = nullptr;
MemoryDockWidget *lastMemoryWidget = nullptr;
int functionDockWidthToRestore = 0;
};
#endif // MAINWINDOW_H
| 10,159
|
C++
|
.h
| 273
| 32.501832
| 100
| 0.754606
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,645
|
CutterJson.h
|
rizinorg_cutter/src/core/CutterJson.h
|
#ifndef CUTTER_JSON_H
#define CUTTER_JSON_H
#include "core/CutterCommon.h"
#include <QSharedPointer>
#include <QString>
#include <QStringList>
#include <rz_project.h>
class CutterJsonOwner;
class CUTTER_EXPORT CutterJson
{
public:
class iterator
{
public:
iterator(const RzJson *value, QSharedPointer<CutterJsonOwner> owner)
: value(value), owner(owner)
{
}
CutterJson operator*() const { return CutterJson(value, owner); }
bool operator!=(const iterator &other) const { return value != other.value; }
iterator &operator++()
{
value = value->next;
return *this;
}
private:
const RzJson *value;
QSharedPointer<CutterJsonOwner> owner;
};
CutterJson() : value(nullptr), owner(nullptr) {}
CutterJson(const RzJson *value, QSharedPointer<CutterJsonOwner> owner)
: value(value), owner(owner)
{
}
CutterJson first() const
{
return CutterJson(has_children() ? value->children.first : nullptr, owner);
}
CutterJson last() const;
CutterJson operator[](const QString &key) const
{
QByteArray utf8 = key.toUtf8();
return (*this)[utf8.data()];
}
CutterJson operator[](const char *key) const
{
return CutterJson(
value && value->type == RZ_JSON_OBJECT ? rz_json_get(value, key) : nullptr, owner);
}
iterator begin() const
{
return iterator(has_children() ? value->children.first : nullptr, owner);
}
iterator end() const { return iterator(nullptr, nullptr); }
bool toBool() const { return value && value->type == RZ_JSON_BOOLEAN && value->num.u_value; }
st64 toSt64() const { return value && value->type == RZ_JSON_INTEGER ? value->num.s_value : 0; }
ut64 toUt64() const { return value && value->type == RZ_JSON_INTEGER ? value->num.u_value : 0; }
RVA toRVA() const
{
return value && value->type == RZ_JSON_INTEGER ? value->num.u_value : RVA_INVALID;
}
QString toString() const
{
return value && value->type == RZ_JSON_STRING ? QString(value->str_value) : QString();
}
QString key() const { return value ? value->key : QString(); }
QStringList keys() const;
size_t size() const { return has_children() ? value->children.count : 0; }
RzJsonType type() const { return value ? value->type : RZ_JSON_NULL; }
bool valid() const { return value ? true : false; }
const RzJson *lowLevelValue() const { return value; }
private:
bool has_children() const
{
return value && (value->type == RZ_JSON_OBJECT || value->type == RZ_JSON_ARRAY);
}
const RzJson *value;
QSharedPointer<CutterJsonOwner> owner;
};
class CUTTER_EXPORT CutterJsonOwner
{
public:
CutterJsonOwner(RzJson *value, char *text) : value(value), text(text) {}
virtual ~CutterJsonOwner()
{
rz_json_free(value);
rz_mem_free(text);
}
private:
RzJson *value;
char *text;
};
#endif // CUTTER_JSON_H
| 3,073
|
C++
|
.h
| 93
| 27.290323
| 100
| 0.634394
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,646
|
RizinCpp.h
|
rizinorg_cutter/src/core/RizinCpp.h
|
/** \file RizinCpp.h
* Various utilities for easier and safer interactions with Rizin
* from C++ code.
*/
#ifndef RIZINCPP_H
#define RIZINCPP_H
#include "rz_core.h"
#include <QString>
#include <memory>
static inline QString fromOwnedCharPtr(char *str)
{
QString result(str ? str : "");
rz_mem_free(str);
return result;
}
template<class T, class F>
std::unique_ptr<T, F *> fromOwned(T *data, F *freeFunction)
{
return std::unique_ptr<T, F *> { data, freeFunction };
}
static inline std::unique_ptr<char, decltype(&rz_mem_free)> fromOwned(char *text)
{
return { text, rz_mem_free };
}
template<class T, void (*func)(T *)>
class FreeBinder
{
public:
void operator()(T *data) { func(data); }
};
template<class T, void (*func)(T *)>
using UniquePtrC = std::unique_ptr<T, FreeBinder<T, func>>;
template<typename T, void (*func)(T)>
using UniquePtrCP = UniquePtrC<typename std::remove_pointer<T>::type, func>;
static inline auto fromOwned(RZ_OWN RzPVector *data)
-> UniquePtrCP<decltype(data), &rz_pvector_free>
{
return { data, {} };
}
static inline auto fromOwned(RZ_OWN RzList *data) -> UniquePtrCP<decltype(data), &rz_list_free>
{
return { data, {} };
}
// Rizin list iteration macros
// deprecated, prefer using CutterPVector and CutterRzList instead
#define CutterRzListForeach(list, it, type, x) \
if (list) \
for (it = list->head; it && ((x = static_cast<type *>(it->elem))); it = it->next)
#define CutterRzVectorForeach(vec, it, type) \
if ((vec) && (vec)->a) \
for (it = (type *)(vec)->a; \
(char *)it != (char *)(vec)->a + ((vec)->len * (vec)->elem_size); \
it = (type *)((char *)it + (vec)->elem_size))
template<typename T>
class CutterPVector
{
private:
const RzPVector *const vec;
public:
class iterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = T *;
using difference_type = ptrdiff_t;
using pointer = T **;
using reference = T *&;
private:
T **p;
public:
iterator(T **p) : p(p) {}
iterator(const iterator &o) : p(o.p) {}
iterator &operator++()
{
p++;
return *this;
}
iterator operator++(int)
{
iterator tmp(*this);
operator++();
return tmp;
}
bool operator==(const iterator &rhs) const { return p == rhs.p; }
bool operator!=(const iterator &rhs) const { return p != rhs.p; }
T *operator*() { return *p; }
};
CutterPVector(const RzPVector *vec) : vec(vec) {}
iterator begin() const { return iterator(reinterpret_cast<T **>(vec->v.a)); }
iterator end() const { return iterator(reinterpret_cast<T **>(vec->v.a) + vec->v.len); }
};
template<typename T>
class CutterRzList
{
private:
const RzList *const list;
public:
class iterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = T *;
using difference_type = ptrdiff_t;
using pointer = T **;
using reference = T *&;
private:
RzListIter *iter;
public:
explicit iterator(RzListIter *iter) : iter(iter) {}
iterator(const iterator &o) : iter(o.iter) {}
iterator &operator++()
{
if (!iter) {
return *this;
}
iter = iter->next;
return *this;
}
iterator operator++(int)
{
iterator tmp(*this);
operator++();
return tmp;
}
bool operator==(const iterator &rhs) const { return iter == rhs.iter; }
bool operator!=(const iterator &rhs) const { return iter != rhs.iter; }
T *operator*()
{
if (!iter) {
return nullptr;
}
return reinterpret_cast<T *>(iter->elem);
}
};
explicit CutterRzList(const RzList *l) : list(l) {}
iterator begin() const
{
if (!list) {
return iterator(nullptr);
}
return iterator(list->head);
}
iterator end() const { return iterator(nullptr); }
};
template<typename T>
class CutterRzIter
{
UniquePtrC<RzIterator, &rz_iterator_free> rzIter;
public:
CutterRzIter(RzIterator *rzIter) : rzIter(rzIter)
{
// immediately attempt advancing by 1, otherwise it's hard to distinguish whether current
// element is null due to not having called next, or due to having run out of elements
if (rzIter) {
++*this;
}
}
CutterRzIter<T> &operator++()
{
rz_iterator_next(rzIter.get());
return *this;
}
operator bool() { return rzIter && rzIter->cur; }
T &operator*() { return *reinterpret_cast<RzAnalysisBytes *>(rzIter->cur); }
T *get() { return reinterpret_cast<RzAnalysisBytes *>(rzIter->cur); }
T *operator->() { return reinterpret_cast<RzAnalysisBytes *>(rzIter->cur); }
};
#endif // RIZINCPP_H
| 5,406
|
C++
|
.h
| 168
| 26.142857
| 100
| 0.553424
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,647
|
CutterCommon.h
|
rizinorg_cutter/src/core/CutterCommon.h
|
/** \file CutterCommon.h
* This file contains any definition that is useful in the whole project.
* For example, it may contain custom types (RVA, ut64), list iterators, etc.
*/
#ifndef CUTTERCORE_H
#define CUTTERCORE_H
#include "rz_core.h"
#include <QString>
#include "RizinCpp.h"
// Workaround for compile errors on Windows
#ifdef Q_OS_WIN
# undef min
# undef max
#endif // Q_OS_WIN
// Global information for Cutter
#define APPNAME "Cutter"
/**
* @brief Type to be used for all kinds of addresses/offsets in rizin address space.
*/
typedef ut64 RVA;
/**
* @brief Maximum value of RVA. Do NOT use this for specifying invalid values, use RVA_INVALID
* instead.
*/
#define RVA_MAX UT64_MAX
/**
* @brief Value for specifying an invalid RVA.
*/
#define RVA_INVALID RVA_MAX
inline QString RzAddressString(RVA addr)
{
return QString::asprintf("%#010llx", addr);
}
inline QString RzSizeString(RVA size)
{
return QString::asprintf("%#llx", size);
}
inline QString RzHexString(RVA size)
{
return QString::asprintf("%#llx", size);
}
#ifdef CUTTER_SOURCE_BUILD
# define CUTTER_EXPORT Q_DECL_EXPORT
#else
# define CUTTER_EXPORT Q_DECL_IMPORT
#endif
#if defined(__has_cpp_attribute)
# if __has_cpp_attribute(deprecated)
# define CUTTER_DEPRECATED(msg) [[deprecated(msg)]]
# endif
#endif
#if !defined(CUTTER_DEPRECATED)
# define CUTTER_DEPRECATED(msg)
#endif
#endif // CUTTERCORE_H
| 1,431
|
C++
|
.h
| 55
| 24.4
| 94
| 0.737537
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,648
|
Cutter.h
|
rizinorg_cutter/src/core/Cutter.h
|
#ifndef CUTTER_H
#define CUTTER_H
#include "core/CutterCommon.h"
#include "core/CutterDescriptions.h"
#include "core/CutterJson.h"
#include "core/Basefind.h"
#include "common/BasicInstructionHighlighter.h"
#include <QMap>
#include <QMenu>
#include <QDebug>
#include <QObject>
#include <QSharedPointer>
#include <QStringList>
#include <QMessageBox>
#include <QErrorMessage>
#include <QMutex>
#include <QDir>
#include <functional>
#include <memory>
class AsyncTaskManager;
class BasicInstructionHighlighter;
class CutterCore;
class Decompiler;
class RizinTask;
class RizinCmdTask;
class RizinFunctionTask;
class RizinTaskDialog;
#include "common/BasicBlockHighlighter.h"
#include "common/Helpers.h"
#include <rz_project.h>
#include <memory>
#define Core() (CutterCore::instance())
class RzCoreLocked;
struct CUTTER_EXPORT AddrRefs
{
RVA addr;
QString mapname;
QString section;
QString reg;
QString fcn;
QString type;
QString asm_op;
QString perms;
ut64 value;
bool has_value;
QString string;
QSharedPointer<AddrRefs> ref;
};
struct CUTTER_EXPORT RegisterRef
{
ut64 value;
AddrRefs ref;
QString name;
};
class CUTTER_EXPORT CutterCore : public QObject
{
Q_OBJECT
friend class RzCoreLocked;
friend class RizinTask;
friend class Basefind;
public:
explicit CutterCore(QObject *parent = nullptr);
~CutterCore();
static CutterCore *instance();
void initialize(bool loadPlugins = true);
void loadCutterRC();
void loadDefaultCutterRC();
QDir getCutterRCDefaultDirectory() const;
AsyncTaskManager *getAsyncTaskManager() { return asyncTaskManager; }
RVA getOffset() const { return core_->offset; }
/* Core functions (commands) */
/* Almost the same as core_cmd_raw,
* only executes std::function<bool(RzCore *)> instead of char* */
QString getFunctionExecOut(const std::function<bool(RzCore *)> &fcn,
const RVA addr = RVA_INVALID);
static QString sanitizeStringForCommand(QString s);
/**
* @brief send a command to Rizin
* @param str the command you want to execute
* @return command output
* @note if you want to seek to an address, you should use CutterCore::seek.
*/
QString cmd(const char *str);
QString cmd(const QString &str) { return cmd(str.toUtf8().constData()); }
/**
* @brief send a task to Rizin
* @param fcn the task you want to execute
* @return execute successful?
*/
bool asyncTask(std::function<void *(RzCore *)> fcn, QSharedPointer<RizinTask> &task);
void functionTask(std::function<void *(RzCore *)> fcn);
/**
* @brief Execute a Rizin command \a cmd. By nature, the API
* is executing raw commands, and thus ignores multiple commands and overcome command
* injections.
* @param cmd - a raw command to execute. Passing multiple commands (e.g "px 5; pd 7 && pdf")
* will result in them treated as arguments to first command.
* @return the output of the command
*/
QString cmdRaw(const char *cmd);
/**
* @brief a wrapper around cmdRaw(const char *cmd,).
*/
QString cmdRaw(const QString &cmd) { return cmdRaw(cmd.toUtf8().constData()); };
/**
* @brief Execute a Rizin command \a cmd at \a address. The function will preform a silent seek
* to the address without triggering the seekChanged event nor adding new entries to the seek
* history. By nature, the API is executing a single command without going through Rizin shell,
* and thus ignores multiple commands and tries to overcome command injections.
* @param cmd - a raw command to execute. If multiple commands will be passed (e.g "px 5; pd 7
* && pdf") then only the first command will be executed.
* @param address - an address to which Cutter will temporarily seek.
* @return the output of the command
*/
QString cmdRawAt(const char *cmd, RVA address);
/**
* @brief a wrapper around cmdRawAt(const char *cmd, RVA address).
*/
QString cmdRawAt(const QString &str, RVA address)
{
return cmdRawAt(str.toUtf8().constData(), address);
}
class SeekReturn
{
RVA returnAddress;
bool empty = true;
public:
SeekReturn(RVA returnAddress) : returnAddress(returnAddress), empty(false) {}
~SeekReturn()
{
if (!empty) {
Core()->seekSilent(returnAddress);
}
}
SeekReturn(SeekReturn &&from)
{
if (this != &from) {
returnAddress = from.returnAddress;
empty = from.empty;
from.empty = true;
}
};
};
SeekReturn seekTemp(RVA address)
{
SeekReturn returner(getOffset());
seekSilent(address);
return returner;
}
enum class SeekHistoryType { New, Undo, Redo };
CutterJson cmdj(const char *str);
CutterJson cmdj(const QString &str) { return cmdj(str.toUtf8().constData()); }
QString cmdTask(const QString &str);
QString getRizinVersionReadable(const char *program = nullptr);
QString getVersionInformation();
CutterJson parseJson(const char *name, char *res, const char *cmd = nullptr);
CutterJson parseJson(const char *name, char *res, const QString &cmd = QString())
{
return parseJson(name, res, cmd.isNull() ? nullptr : cmd.toLocal8Bit().constData());
}
QStringList autocomplete(const QString &cmd, RzLinePromptType promptType);
/* Functions methods */
void renameFunction(const RVA offset, const QString &newName);
void delFunction(RVA addr);
void renameFlag(QString old_name, QString new_name);
/**
* @brief Renames the specified local variable in the function specified by the
* address given.
* @param newName Specifies the name to which the current name of the variable
* should be renamed.
* @param oldName Specifies the current name of the function variable.
* @param functionAddress Specifies the exact address of the function.
*/
void renameFunctionVariable(QString newName, QString oldName, RVA functionAddress);
/**
* @param addr
* @return a function that contains addr or nullptr
*/
RzAnalysisFunction *functionIn(ut64 addr);
/**
* @param addr
* @return the function that has its entrypoint at addr or nullptr
*/
RzAnalysisFunction *functionAt(ut64 addr);
RVA getFunctionStart(RVA addr);
RVA getFunctionEnd(RVA addr);
RVA getLastFunctionInstruction(RVA addr);
QString flagAt(RVA addr);
void createFunctionAt(RVA addr);
void createFunctionAt(RVA addr, QString name);
QStringList getDisassemblyPreview(RVA address, int num_of_lines);
/* Flags */
void delFlag(RVA addr);
void delFlag(const QString &name);
void addFlag(RVA offset, QString name, RVA size);
QString listFlagsAsStringAt(RVA addr);
/**
* @brief Get nearest flag at or before offset.
* @param offset search position
* @param flagOffsetOut address of returned flag
* @return flag name
*/
QString nearestFlag(RVA offset, RVA *flagOffsetOut);
void triggerFlagsChanged();
/* Global Variables */
void addGlobalVariable(RVA offset, QString name, QString typ);
void delGlobalVariable(QString name);
void delGlobalVariable(RVA offset);
void modifyGlobalVariable(RVA offset, QString name, QString typ);
QString getGlobalVariableType(QString name);
QString getGlobalVariableType(RVA offset);
/* Edition functions */
CutterRzIter<RzAnalysisBytes> getRzAnalysisBytesSingle(RVA addr);
QString getInstructionBytes(RVA addr);
QString getInstructionOpcode(RVA addr);
void editInstruction(RVA addr, const QString &inst, bool fillWithNops = false);
void nopInstruction(RVA addr);
void jmpReverse(RVA addr);
void editBytes(RVA addr, const QString &inst);
void editBytesEndian(RVA addr, const QString &bytes);
/* Code/Data */
void setToCode(RVA addr);
enum class StringTypeFormats { None, ASCII_LATIN1, UTF8 };
/**
* @brief Adds string at address
* That function calls the 'Cs' command
* \param addr The address of the array where the string will be applied
* \param size The size of string
* \param type The type of string
*/
void setAsString(RVA addr, int size = 0, StringTypeFormats type = StringTypeFormats::None);
/**
* @brief Removes string at address
* That function calls the 'Cs-' command
* \param addr The address of the array where the string will be applied
*/
void removeString(RVA addr);
/**
* @brief Gets string at address
* That function correspond the 'Cs.' command
* \param addr The address of the string
* @return string at requested address
*/
QString getMetaString(RVA addr);
/**
* @brief Gets string at address
* That function calls the 'ps' command
* \param addr The address of the first byte of the array
* @return string at requested address
*/
QString getString(RVA addr);
QString getString(RVA addr, uint64_t len, RzStrEnc encoding, bool escape_nl = false);
void setToData(RVA addr, int size, int repeat = 1);
int sizeofDataMeta(RVA addr);
/* Comments */
void setComment(RVA addr, const QString &cmt);
void delComment(RVA addr);
QString getCommentAt(RVA addr);
void setImmediateBase(const QString &rzBaseName, RVA offset = RVA_INVALID);
void setCurrentBits(int bits, RVA offset = RVA_INVALID);
/**
* @brief Changes immediate displacement to structure offset
* This function makes use of the "aht" command of Rizin to apply structure
* offset to the immediate displacement used in the given instruction
* \param structureOffset The name of struct which will be applied
* \param offset The address of the instruction where the struct will be applied
*/
void applyStructureOffset(const QString &structureOffset, RVA offset = RVA_INVALID);
/* Classes */
QList<QString> getAllAnalysisClasses(bool sorted);
QList<AnalysisMethodDescription> getAnalysisClassMethods(const QString &cls);
QList<AnalysisBaseClassDescription> getAnalysisClassBaseClasses(const QString &cls);
QList<AnalysisVTableDescription> getAnalysisClassVTables(const QString &cls);
void createNewClass(const QString &cls);
void renameClass(const QString &oldName, const QString &newName);
void deleteClass(const QString &cls);
bool getAnalysisMethod(const QString &cls, const QString &meth,
AnalysisMethodDescription *desc);
void renameAnalysisMethod(const QString &className, const QString &oldMethodName,
const QString &newMethodName);
void setAnalysisMethod(const QString &cls, const AnalysisMethodDescription &meth);
/* File related methods */
bool loadFile(QString path, ut64 baddr = 0LL, ut64 mapaddr = 0LL, int perms = RZ_PERM_R,
int va = 0, bool loadbin = false, const QString &forceBinPlugin = QString());
bool tryFile(QString path, bool rw);
bool mapFile(QString path, RVA mapaddr);
void loadScript(const QString &scriptname);
/* Seek functions */
void seek(QString thing);
void seek(ut64 offset);
void seekSilent(ut64 offset);
void seekSilent(QString thing) { seekSilent(math(thing)); }
void seekPrev();
void seekNext();
void updateSeek(SeekHistoryType type = SeekHistoryType::New);
/**
* @brief Raise a memory widget showing current offset, prefer last active
* memory widget.
*/
void showMemoryWidget();
/**
* @brief Seek to \p offset and raise a memory widget showing it.
* @param offset
*/
void seekAndShow(ut64 offset);
/**
* @brief \see CutterCore::show(ut64)
* @param thing - addressable expression
*/
void seekAndShow(QString thing);
RVA getOffset();
RVA prevOpAddr(RVA startAddr, int count);
RVA nextOpAddr(RVA startAddr, int count);
/* SigDB / Flirt functions */
void applySignature(const QString &filepath);
void createSignature(const QString &filepath);
/* Math functions */
ut64 math(const QString &expr);
ut64 num(const QString &expr);
QString itoa(ut64 num, int rdx = 16);
/* Config functions */
void setConfig(const char *k, const char *v);
void setConfig(const QString &k, const char *v);
void setConfig(const char *k, const QString &v);
void setConfig(const QString &k, const QString &v) { setConfig(k.toUtf8().constData(), v); }
void setConfig(const char *k, int v);
void setConfig(const QString &k, int v) { setConfig(k.toUtf8().constData(), v); }
void setConfig(const char *k, bool v);
void setConfig(const QString &k, bool v) { setConfig(k.toUtf8().constData(), v); }
void setConfig(const char *k, const QVariant &v);
void setConfig(const QString &k, const QVariant &v) { setConfig(k.toUtf8().constData(), v); }
int getConfigi(const char *k);
int getConfigi(const QString &k) { return getConfigi(k.toUtf8().constData()); }
ut64 getConfigut64(const char *k);
ut64 getConfigut64(const QString &k) { return getConfigut64(k.toUtf8().constData()); }
bool getConfigb(const char *k);
bool getConfigb(const QString &k) { return getConfigb(k.toUtf8().constData()); }
QString getConfig(const char *k);
QString getConfig(const QString &k) { return getConfig(k.toUtf8().constData()); }
QString getConfigDescription(const char *k);
QStringList getConfigOptions(const char *k);
QStringList getColorThemes();
QHash<QString, QColor> getTheme();
QStringList getThemeKeys();
bool setColor(const QString &key, const QString &color);
QStringList getConfigVariableSpaces(const QString &key = "");
/* Assembly\Hexdump related methods */
QByteArray assemble(const QString &code);
QString disassemble(const QByteArray &data);
QString disassembleSingleInstruction(RVA addr);
QList<DisassemblyLine> disassembleLines(RVA offset, int lines);
static QByteArray hexStringToBytes(const QString &hex);
static QString bytesToHexString(const QByteArray &bytes);
enum class HexdumpFormats { Normal, Half, Word, Quad, Signed, Octal };
QString hexdump(RVA offset, int size, HexdumpFormats format);
QString getHexdumpPreview(RVA offset, int size);
void setCPU(QString arch, QString cpu, int bits);
void setEndianness(bool big);
/* SDB */
QList<QString> sdbList(QString path);
QList<QString> sdbListKeys(QString path);
QString sdbGet(QString path, QString key);
bool sdbSet(QString path, QString key, QString val);
/* Debug */
QString getRegisterName(QString registerRole);
RVA getProgramCounterValue();
void setRegister(QString regName, QString regValue);
void setCurrentDebugThread(int tid);
/**
* @brief Attach to a given pid from a debug session
*/
void setCurrentDebugProcess(int pid);
/**
* @brief Returns a list of stack address and their telescoped references
* @param size number of bytes to scan
* @param depth telescoping depth
*/
QList<AddrRefs> getStack(int size = 0x100, int depth = 6);
/**
* @brief Recursively dereferences pointers starting at the specified address
* up to a given depth
* @param addr telescoping addr
* @param depth telescoping depth
*/
AddrRefs getAddrRefs(RVA addr, int depth);
/**
* @brief return a RefDescription with a formatted ref string and configured colors
* @param ref the "ref" JSON node from getAddrRefs
*/
RefDescription formatRefDesc(const QSharedPointer<AddrRefs> &ref);
/**
* @brief Get a list of a given process's threads
* @param pid The pid of the process, -1 for the currently debugged process
* @return List of ProcessDescription
*/
QList<ProcessDescription> getProcessThreads(int pid);
/**
* @brief Get a list of heap chunks
* Uses RZ_API rz_heap_chunks_list to get vector of chunks
* If arena_addr is zero return the chunks for main arena
* @param arena_addr base address for the arena
* @return Vector of heap chunks for the given arena
*/
QVector<Chunk> getHeapChunks(RVA arena_addr);
/**
* @brief Get a list of heap arenas
* Uses RZ_API rz_heap_arenas_list to get list of arenas
* @return Vector of arenas
*/
QVector<Arena> getArenas();
/**
* @brief Get detailed information about a heap chunk
* Uses RZ_API rz_heap_chunk
* @return RzHeapChunkSimple struct pointer for the heap chunk
*/
RzHeapChunkSimple *getHeapChunk(ut64 addr);
/**
* @brief Get heap bins of an arena with given base address
* (including large, small, fast, unsorted, tcache)
* @param arena_addr Base address of the arena
* @return QVector of non empty RzHeapBin pointers
*/
QVector<RzHeapBin *> getHeapBins(ut64 arena_addr);
/**
* @brief Write the given chunk header to memory
* @param chunkSimple RzHeapChunkSimple pointer of the chunk to be written
* @return true if the write succeeded else false
*/
bool writeHeapChunk(RzHeapChunkSimple *chunkSimple);
int getArchBits();
void startDebug();
void startEmulation();
/**
* @brief attach to a remote debugger
* @param uri remote debugger uri
* @note attachedRemote(bool) signals the result
*/
void attachRemote(const QString &uri);
void attachDebug(int pid);
void stopDebug();
void suspendDebug();
void syncAndSeekProgramCounter();
void continueDebug();
void continueBackDebug();
void continueUntilCall();
void continueUntilSyscall();
void continueUntilDebug(ut64 offset);
void stepDebug();
void stepOverDebug();
void stepOutDebug();
void stepBackDebug();
void startTraceSession();
void stopTraceSession();
void addBreakpoint(const BreakpointDescription &config);
void updateBreakpoint(int index, const BreakpointDescription &config);
void toggleBreakpoint(RVA addr);
void delBreakpoint(RVA addr);
void delAllBreakpoints();
void enableBreakpoint(RVA addr);
void disableBreakpoint(RVA addr);
/**
* @brief Enable or disable breakpoint tracing.
* @param index - breakpoint index to modify
* @param enabled - true if tracing should be enabled
*/
void setBreakpointTrace(int index, bool enabled);
int breakpointIndexAt(RVA addr);
BreakpointDescription getBreakpointAt(RVA addr);
bool isBreakpoint(const QList<RVA> &breakpoints, RVA addr);
QList<RVA> getBreakpointsAddresses();
/**
* @brief Get all breakpoinst that are belong to a functions at this address
*/
QList<RVA> getBreakpointsInFunction(RVA funcAddr);
QString getActiveDebugPlugin();
QStringList getDebugPlugins();
void setDebugPlugin(QString plugin);
bool isDebugTaskInProgress();
/**
* @brief Check if we can use output/input redirection with the currently debugged process
*/
bool isRedirectableDebugee();
bool currentlyDebugging = false;
bool currentlyEmulating = false;
bool currentlyTracing = false;
bool currentlyRemoteDebugging = false;
int currentlyAttachedToPID = -1;
QString currentlyOpenFile;
/* Decompilers */
QList<Decompiler *> getDecompilers();
Decompiler *getDecompilerById(const QString &id);
/**
* Register a new decompiler
*
* The decompiler must have a unique id, otherwise this method will fail.
* The decompiler's parent will be set to this CutterCore instance, so it will automatically be
* freed later.
*
* @return whether the decompiler was registered successfully
*/
bool registerDecompiler(Decompiler *decompiler);
RVA getOffsetJump(RVA addr);
CutterJson getSignatureInfo();
bool existsFileInfo();
void setGraphEmpty(bool empty);
bool isGraphEmpty();
bool rebaseBin(RVA base_address);
void getRegs();
QList<QString> regs;
void setSettings();
void loadPDB(const QString &file);
QByteArray ioRead(RVA addr, int len);
QList<RVA> getSeekHistory();
/* Plugins */
QStringList getAsmPluginNames();
QStringList getAnalysisPluginNames();
/* Widgets */
QList<RzBinPluginDescription> getBinPluginDescriptions(bool bin = true, bool xtr = true);
QList<RzIOPluginDescription> getRIOPluginDescriptions();
QList<RzCorePluginDescription> getRCorePluginDescriptions();
QList<RzAsmPluginDescription> getRAsmPluginDescriptions();
QList<FunctionDescription> getAllFunctions();
QList<ImportDescription> getAllImports();
QList<ExportDescription> getAllExports();
QList<SymbolDescription> getAllSymbols();
QList<HeaderDescription> getAllHeaders();
QList<GlobalDescription> getAllGlobals();
QList<FlirtDescription> getSignaturesDB();
QList<CommentDescription> getAllComments(const QString &filterType);
QList<RelocDescription> getAllRelocs();
QList<StringDescription> getAllStrings();
QList<FlagspaceDescription> getAllFlagspaces();
QList<FlagDescription> getAllFlags(QString flagspace = QString());
QList<SectionDescription> getAllSections();
QList<SegmentDescription> getAllSegments();
QList<EntrypointDescription> getAllEntrypoint();
QList<BinClassDescription> getAllClassesFromBin();
QList<BinClassDescription> getAllClassesFromFlags();
QList<ResourcesDescription> getAllResources();
QList<VTableDescription> getAllVTables();
/**
* @return all loaded types
*/
QList<TypeDescription> getAllTypes();
/**
* @return all loaded primitive types
*/
QList<TypeDescription> getAllPrimitiveTypes();
/**
* @return all loaded unions
*/
QList<TypeDescription> getAllUnions();
/**
* @return all loaded structs
*/
QList<TypeDescription> getAllStructs();
/**
* @return all loaded enums
*/
QList<TypeDescription> getAllEnums();
/**
* @return all loaded typedefs
*/
QList<TypeDescription> getAllTypedefs();
/**
* @brief Fetching the C representation of a given Type
* @param name - the name or the type of the given Type
* @return The type decleration as C output
*/
QString getTypeAsC(QString name);
/**
* @brief Checks if the given address is mapped to a region
* @param addr The address to be checked
* @return true if addr is mapped, false otherwise
*/
bool isAddressMapped(RVA addr);
QList<MemoryMapDescription> getMemoryMap();
QList<SearchDescription> getAllSearch(QString searchFor, QString space, QString in);
QList<BreakpointDescription> getBreakpoints();
QList<ProcessDescription> getAllProcesses();
/**
* @brief Get the right RzReg object based on the cutter state (debugging vs emulating)
*/
RzReg *getReg();
/**
* @brief returns a list of reg values and their telescoped references
* @param depth telescoping depth
*/
QList<RegisterRef> getRegisterRefs(int depth = 6);
QVector<RegisterRefValueDescription> getRegisterRefValues();
QList<VariableDescription> getVariables(RVA at);
/**
* @brief Fetches all the writes or reads to the specified local variable 'variableName'
* in the function in which the specified offset is a part of.
* @param variableName Name of the local variable.
* @param findWrites If this is true, then locations at which modification happen to the
* specified local variable is fetched. Else, the locations at which the local is variable is
* read is fetched.
* @param offset An offset in the function in which the specified local variable exist.
* @return A list of XrefDescriptions that contains details of all the writes or reads that
* happen to the variable 'variableName'.
*/
QList<XrefDescription> getXRefsForVariable(QString variableName, bool findWrites, RVA offset);
QList<XrefDescription> getXRefs(RVA addr, bool to, bool whole_function,
const QString &filterType = QString());
void handleREvent(int type, void *data);
/* Signals related */
void triggerVarsChanged();
void triggerFunctionRenamed(const RVA offset, const QString &newName);
void triggerRefreshAll();
void triggerAsmOptionsChanged();
void triggerGraphOptionsChanged();
void message(const QString &msg, bool debug = false);
QStringList getSectionList();
RzCoreLocked core();
static QString ansiEscapeToHtml(const QString &text);
BasicBlockHighlighter *getBBHighlighter();
BasicInstructionHighlighter *getBIHighlighter();
/**
* @brief Enable or dsiable Cache mode. Cache mode is used to imagine writing to the opened file
* without committing the changes to the disk.
* @param enabled
*/
void setIOCache(bool enabled);
/**
* @brief Check if Cache mode is enabled.
* @return true if Cache is enabled, otherwise return false.
*/
bool isIOCacheEnabled() const;
/**
* @brief Commit write cache to the file on disk.
*/
void commitWriteCache();
/**
* @brief Reset write cache.
*/
void resetWriteCache();
/**
* @brief Enable or disable Write mode. When the file is opened in write mode, any changes to it
* will be immediately committed to the file on disk, thus modify the file. This function wrap
* Rizin function which re-open the file with the desired permissions.
* @param enabled
*/
void setWriteMode(bool enabled);
/**
* @brief Check if the file is opened in write mode.
* @return true if write mode is enabled, otherwise return false.
*/
bool isWriteModeEnabled();
/**
* @brief Returns the textual version of global or specific graph.
* @param type Graph type, example RZ_CORE_GRAPH_TYPE_FUNCALL or RZ_CORE_GRAPH_TYPE_IMPORT
* @param format Graph format, example RZ_CORE_GRAPH_FORMAT_DOT or RZ_CORE_GRAPH_FORMAT_GML
* @param address The object address (if global set it to RVA_INVALID)
* @return The textual graph string.
*/
char *getTextualGraphAt(RzCoreGraphType type, RzCoreGraphFormat format, RVA address);
/**
* @brief Writes a graphviz graph to a file.
* @param path The file output path
* @param format The output format (see graph.gv.format)
* @param type The graph type, example RZ_CORE_GRAPH_TYPE_FUNCALL or
* RZ_CORE_GRAPH_TYPE_IMPORT
* @param address The object address (if global set it to RVA_INVALID)
*/
void writeGraphvizGraphToFile(QString path, QString format, RzCoreGraphType type, RVA address);
signals:
void refreshAll();
void functionRenamed(const RVA offset, const QString &new_name);
void varsChanged();
void globalVarsChanged();
void functionsChanged();
void flagsChanged();
void commentsChanged(RVA addr);
void registersChanged();
void instructionChanged(RVA offset);
void breakpointsChanged(RVA offset);
void refreshCodeViews();
void stackChanged();
/**
* @brief update all the widgets that are affected by rebasing in debug mode
*/
void codeRebased();
void switchedThread();
void switchedProcess();
void classNew(const QString &cls);
void classDeleted(const QString &cls);
void classRenamed(const QString &oldName, const QString &newName);
void classAttrsChanged(const QString &cls);
/**
* @brief end of current debug event received
*/
void debugProcessFinished(int pid);
void attachedRemote(bool successfully);
void ioCacheChanged(bool newval);
void writeModeChanged(bool newval);
void ioModeChanged();
/**
* emitted when debugTask started or finished running
*/
void debugTaskStateChanged();
/**
* emitted when config regarding disassembly display changes
*/
void asmOptionsChanged();
/**
* emitted when config regarding graph display changes
*/
void graphOptionsChanged();
/**
* @brief seekChanged is emitted each time Rizin's seek value is modified
* @param offset
* @param historyType
*/
void seekChanged(RVA offset, SeekHistoryType type = SeekHistoryType::New);
void toggleDebugView();
void newMessage(const QString &msg);
void newDebugMessage(const QString &msg);
void showMemoryWidgetRequested();
private:
/**
* Internal reference to the RzCore.
* NEVER use this directly! Always use the CORE_LOCK(); macro and access it like core->...
*/
RzCore *core_ = nullptr;
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
QMutex coreMutex;
#else
QRecursiveMutex coreMutex;
#endif
int coreLockDepth = 0;
void *coreBed = nullptr;
AsyncTaskManager *asyncTaskManager;
RVA offsetPriorDebugging = RVA_INVALID;
QErrorMessage msgBox;
QList<Decompiler *> decompilers;
bool emptyGraph = false;
BasicBlockHighlighter *bbHighlighter;
bool iocache = false;
BasicInstructionHighlighter biHighlighter;
QSharedPointer<RizinTask> debugTask;
RizinTaskDialog *debugTaskDialog;
QVector<QString> getCutterRCFilePaths() const;
QList<TypeDescription> getBaseType(RzBaseTypeKind kind, const char *category);
};
class CUTTER_EXPORT RzCoreLocked
{
CutterCore *const core;
public:
explicit RzCoreLocked(CutterCore *core);
RzCoreLocked(const RzCoreLocked &) = delete;
RzCoreLocked &operator=(const RzCoreLocked &) = delete;
RzCoreLocked(RzCoreLocked &&);
~RzCoreLocked();
operator RzCore *() const;
RzCore *operator->() const;
};
#endif // CUTTER_H
| 30,010
|
C++
|
.h
| 758
| 34.084433
| 100
| 0.703932
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,649
|
Basefind.h
|
rizinorg_cutter/src/core/Basefind.h
|
#ifndef CUTTER_BASEFIND_CORE_H
#define CUTTER_BASEFIND_CORE_H
#include <QThread>
#include <QMutex>
#include "Cutter.h"
#include "CutterDescriptions.h"
#include <rz_basefind.h>
class CutterCore;
class Basefind : public QThread
{
Q_OBJECT
public:
explicit Basefind(CutterCore *core);
virtual ~Basefind();
void run();
bool setOptions(const RzBaseFindOpt *opts);
QList<BasefindResultDescription> results();
public slots:
void cancel();
signals:
void progress(BasefindCoreStatusDescription status);
void complete();
private:
CutterCore *const core;
RzList *scores;
bool continue_run;
RzBaseFindOpt options;
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
QMutex mutex;
#else
QRecursiveMutex mutex;
#endif
bool updateProgress(const RzBaseFindThreadInfo *info);
static bool threadCallback(const RzBaseFindThreadInfo *info, void *user);
};
#endif // CUTTER_BASEFIND_CORE_H
| 940
|
C++
|
.h
| 36
| 22.916667
| 77
| 0.755879
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,650
|
CutterDescriptions.h
|
rizinorg_cutter/src/core/CutterDescriptions.h
|
/** \file CutterDescriptions.h
* This file contains every structure description that are used in widgets.
* The descriptions are used for the Qt metatypes.
*/
#ifndef DESCRIPTIONS_H
#define DESCRIPTIONS_H
#include <QString>
#include <QList>
#include <QStringList>
#include <QMetaType>
#include <QColor>
#include "core/CutterCommon.h"
struct FunctionDescription
{
RVA offset;
RVA linearSize;
RVA nargs;
RVA nbbs;
RVA nlocals;
QString calltype;
QString name;
RVA edges;
RVA stackframe;
bool contains(RVA addr) const
{
// TODO: this is not exactly correct in edge cases.
// rz_analysis_function_contains() does it right.
return addr >= offset && addr < offset + linearSize;
}
};
struct ImportDescription
{
RVA plt;
int ordinal;
QString bind;
QString type;
QString name;
QString libname;
};
struct ExportDescription
{
RVA vaddr;
RVA paddr;
RVA size;
QString type;
QString name;
QString flag_name;
};
struct HeaderDescription
{
RVA vaddr;
RVA paddr;
QString value;
QString name;
};
struct FlirtDescription
{
QString bin_name;
QString arch_name;
QString arch_bits;
QString base_name;
QString short_path;
QString file_path;
QString details;
QString n_modules;
};
struct TypeDescription
{
QString type;
int size;
QString format;
QString category;
};
struct SearchDescription
{
RVA offset;
int size;
QString code;
QString data;
};
struct SymbolDescription
{
RVA vaddr;
QString bind;
QString type;
QString name;
};
struct CommentDescription
{
RVA offset;
QString name;
};
struct RelocDescription
{
RVA vaddr;
RVA paddr;
QString type;
QString name;
};
struct StringDescription
{
RVA vaddr;
QString string;
QString type;
QString section;
ut32 length;
ut32 size;
};
struct FlagspaceDescription
{
QString name;
};
struct FlagDescription
{
RVA offset;
RVA size;
QString name;
QString realname;
};
struct SectionDescription
{
RVA vaddr;
RVA paddr;
RVA size;
RVA vsize;
QString name;
QString perm;
QString entropy;
};
struct SegmentDescription
{
RVA vaddr;
RVA paddr;
RVA size;
RVA vsize;
QString name;
QString perm;
};
struct EntrypointDescription
{
RVA vaddr;
RVA paddr;
RVA baddr;
RVA laddr;
RVA haddr;
QString type;
};
struct XrefDescription
{
RVA from;
QString from_str;
RVA to;
QString to_str;
QString type;
};
struct RzBinPluginDescription
{
QString name;
QString description;
QString license;
QString type;
};
struct RzIOPluginDescription
{
QString name;
QString description;
QString license;
QString permissions;
QList<QString> uris;
};
struct RzCorePluginDescription
{
QString name;
QString description;
QString license;
};
struct RzAsmPluginDescription
{
QString name;
QString architecture;
QString author;
QString version;
QString cpus;
QString description;
QString license;
};
struct DisassemblyLine
{
RVA offset;
QString text;
RVA arrow;
};
struct BinClassBaseClassDescription
{
QString name;
RVA offset;
};
struct BinClassMethodDescription
{
QString name;
RVA addr = RVA_INVALID;
st64 vtableOffset = -1;
};
struct BinClassFieldDescription
{
QString name;
RVA addr = RVA_INVALID;
};
struct BinClassDescription
{
QString name;
RVA addr = RVA_INVALID;
RVA vtableAddr = RVA_INVALID;
QList<BinClassBaseClassDescription> baseClasses;
QList<BinClassMethodDescription> methods;
QList<BinClassFieldDescription> fields;
};
struct AnalysisMethodDescription
{
QString name;
QString realName;
RVA addr;
st64 vtableOffset;
};
struct AnalysisBaseClassDescription
{
QString id;
RVA offset;
QString className;
};
struct AnalysisVTableDescription
{
QString id;
ut64 offset;
ut64 addr;
};
struct ResourcesDescription
{
QString name;
RVA vaddr;
ut64 index;
QString type;
ut64 size;
QString lang;
};
struct VTableDescription
{
RVA addr;
QList<BinClassMethodDescription> methods;
};
struct BlockDescription
{
RVA addr;
RVA size;
int flags;
int functions;
int inFunctions;
int comments;
int symbols;
int strings;
ut8 rwx;
};
struct BlockStatistics
{
RVA from;
RVA to;
RVA blocksize;
QList<BlockDescription> blocks;
};
struct MemoryMapDescription
{
RVA addrStart;
RVA addrEnd;
QString name;
QString fileName;
QString type;
QString permission;
};
struct BreakpointDescription
{
enum PositionType {
Address,
Named,
Module,
};
RVA addr = 0;
int64_t moduleDelta = 0;
int index = -1;
PositionType type = Address;
int size = 0;
int permission = 0;
QString positionExpression;
QString name;
QString command;
QString condition;
bool hw = false;
bool trace = false;
bool enabled = true;
};
struct ProcessDescription
{
bool current;
int pid;
int uid;
int ppid;
RzDebugPidState status;
QString path;
};
struct RefDescription
{
QString ref;
QColor refColor;
};
struct VariableDescription
{
RzAnalysisVarStorageType storageType;
QString name;
QString type;
QString value;
};
struct GlobalDescription
{
RVA addr;
QString type;
QString name;
};
struct RegisterRefValueDescription
{
QString name;
QString value;
QString ref;
};
struct Chunk
{
RVA offset;
QString status;
int size;
};
struct Arena
{
RVA offset;
QString type;
ut64 top;
ut64 last_remainder;
ut64 next;
ut64 next_free;
ut64 system_mem;
ut64 max_system_mem;
};
struct BasefindCoreStatusDescription
{
size_t index;
ut32 percentage;
};
struct BasefindResultDescription
{
RVA candidate;
ut32 score;
};
Q_DECLARE_METATYPE(FunctionDescription)
Q_DECLARE_METATYPE(ImportDescription)
Q_DECLARE_METATYPE(ExportDescription)
Q_DECLARE_METATYPE(SymbolDescription)
Q_DECLARE_METATYPE(CommentDescription)
Q_DECLARE_METATYPE(RelocDescription)
Q_DECLARE_METATYPE(StringDescription)
Q_DECLARE_METATYPE(FlagspaceDescription)
Q_DECLARE_METATYPE(FlagDescription)
Q_DECLARE_METATYPE(GlobalDescription)
Q_DECLARE_METATYPE(XrefDescription)
Q_DECLARE_METATYPE(EntrypointDescription)
Q_DECLARE_METATYPE(RzBinPluginDescription)
Q_DECLARE_METATYPE(RzIOPluginDescription)
Q_DECLARE_METATYPE(RzCorePluginDescription)
Q_DECLARE_METATYPE(RzAsmPluginDescription)
Q_DECLARE_METATYPE(BinClassMethodDescription)
Q_DECLARE_METATYPE(BinClassFieldDescription)
Q_DECLARE_METATYPE(BinClassDescription)
Q_DECLARE_METATYPE(const BinClassDescription *)
Q_DECLARE_METATYPE(const BinClassMethodDescription *)
Q_DECLARE_METATYPE(const BinClassFieldDescription *)
Q_DECLARE_METATYPE(AnalysisBaseClassDescription)
Q_DECLARE_METATYPE(AnalysisMethodDescription)
Q_DECLARE_METATYPE(AnalysisVTableDescription)
Q_DECLARE_METATYPE(ResourcesDescription)
Q_DECLARE_METATYPE(VTableDescription)
Q_DECLARE_METATYPE(TypeDescription)
Q_DECLARE_METATYPE(HeaderDescription)
Q_DECLARE_METATYPE(FlirtDescription)
Q_DECLARE_METATYPE(SearchDescription)
Q_DECLARE_METATYPE(SectionDescription)
Q_DECLARE_METATYPE(SegmentDescription)
Q_DECLARE_METATYPE(MemoryMapDescription)
Q_DECLARE_METATYPE(BreakpointDescription)
Q_DECLARE_METATYPE(BreakpointDescription::PositionType)
Q_DECLARE_METATYPE(ProcessDescription)
Q_DECLARE_METATYPE(RefDescription)
Q_DECLARE_METATYPE(VariableDescription)
Q_DECLARE_METATYPE(BasefindCoreStatusDescription)
Q_DECLARE_METATYPE(BasefindResultDescription)
#endif // DESCRIPTIONS_H
| 7,796
|
C++
|
.h
| 401
| 16.107232
| 75
| 0.748298
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,651
|
GlibcHeapBinsDialog.h
|
rizinorg_cutter/src/dialogs/GlibcHeapBinsDialog.h
|
#ifndef GLIBCHEAPBINSDIALOG_H
#define GLIBCHEAPBINSDIALOG_H
#include <QDialog>
#include <QAbstractTableModel>
#include "core/Cutter.h"
#include <MainWindow.h>
#include <HeapBinsGraphView.h>
namespace Ui {
class GlibcHeapBinsDialog;
}
class BinsModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit BinsModel(RVA arena_addr, QObject *parent = nullptr);
enum Column {
TypeColumn = 0,
BinNumColumn,
FdColumn,
BkColumn,
CountColumn,
SizeColumn,
ColumnCount
};
void reload();
int rowCount(const QModelIndex &parent) const override;
int columnCount(const QModelIndex &parent) const override;
void clearData();
QVariant data(const QModelIndex &index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
RVA arena_addr = 0;
RzList *getChunks(int index);
QString getBinMessage(int index);
QVector<RzHeapBin *> values;
private:
};
class GlibcHeapBinsDialog : public QDialog
{
Q_OBJECT
public:
explicit GlibcHeapBinsDialog(RVA i, MainWindow *main, QWidget *parent);
~GlibcHeapBinsDialog();
void onCurrentChanged(const QModelIndex ¤t, const QModelIndex &prev);
void setChainInfo(int index);
void setGraphView(int index);
private slots:
void showHeapInfoDialog();
private:
Ui::GlibcHeapBinsDialog *ui;
RVA m_state;
BinsModel *binsModel {};
HeapBinsGraphView *graphView;
MainWindow *main;
};
#endif // GLIBCHEAPBINSDIALOG_H
| 1,555
|
C++
|
.h
| 55
| 24.218182
| 91
| 0.737265
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,652
|
EditMethodDialog.h
|
rizinorg_cutter/src/dialogs/EditMethodDialog.h
|
#ifndef EDITMETHODDIALOG_H
#define EDITMETHODDIALOG_H
#include <QDialog>
#include <memory>
#include "core/Cutter.h"
namespace Ui {
class EditMethodDialog;
}
class QComboBox;
class EditMethodDialog : public QDialog
{
Q_OBJECT
public:
/**
* @param classFixed whether the user should be able to change the class. If false, a QComboBox
* will be shown, otherwise a plain QLabel.
*/
explicit EditMethodDialog(bool classFixed, QWidget *parent = nullptr);
~EditMethodDialog();
void setClass(const QString &className);
void setMethod(const AnalysisMethodDescription &desc);
QString getClass() const;
AnalysisMethodDescription getMethod() const;
/**
* @brief Helper function to display the dialog
*
* @param title title of the dialog
* @param classFixed whether the user should be able to change the class
* @param className initial class name, will be overwritten if the user changed the class
* @param desc initial data for the method information
* @return whether the dialog was accepted by the user
*/
static bool showDialog(const QString &title, bool classFixed, QString *className,
AnalysisMethodDescription *desc, QWidget *parent = nullptr);
/**
* @brief Show the dialog to add a new method a given class
*/
static void newMethod(QString className = nullptr, const QString &meth = QString(),
QWidget *parent = nullptr);
/**
* @brief Show the dialog to edit a given method of a given class
*/
static void editMethod(const QString &className, const QString &meth,
QWidget *parent = nullptr);
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void updateVirtualUI();
void validateInput();
void updateName();
void updateAutoRenameEnabled();
private:
std::unique_ptr<Ui::EditMethodDialog> ui;
QComboBox *classComboBox = nullptr;
QLabel *classLabel = nullptr;
/**
* This will only be used when the dialog was created with classFixed = true in order to
* remember the class name.
*/
QString fixedClass;
bool inputValid();
static QString convertRealNameToName(const QString &realName);
};
#endif // EDITMETHODDIALOG_H
| 2,327
|
C++
|
.h
| 64
| 30.765625
| 99
| 0.699154
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,653
|
EditFunctionDialog.h
|
rizinorg_cutter/src/dialogs/EditFunctionDialog.h
|
#ifndef EDITFUNCTIONDIALOG_H
#define EDITFUNCTIONDIALOG_H
#include <QDialog>
#include <memory>
namespace Ui {
class EditFunctionDialog;
}
class EditFunctionDialog : public QDialog
{
Q_OBJECT
public:
explicit EditFunctionDialog(QWidget *parent = nullptr);
~EditFunctionDialog();
QString getNameText();
void setNameText(const QString &name);
QString getStartAddrText();
void setStartAddrText(const QString &startAddr);
QString getEndAddrText();
void setEndAddrText(const QString &endAddr);
QString getStackSizeText();
void setStackSizeText(const QString &stackSize);
void setCallConList(const QStringList &callConList);
void setCallConSelected(const QString &selected);
QString getCallConSelected();
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
private:
std::unique_ptr<Ui::EditFunctionDialog> ui;
};
#endif // EDITFUNCTIONDIALOG_H
| 936
|
C++
|
.h
| 31
| 26.741935
| 59
| 0.77369
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,654
|
InitialOptionsDialog.h
|
rizinorg_cutter/src/dialogs/InitialOptionsDialog.h
|
#ifndef OPTIONSDIALOG_H
#define OPTIONSDIALOG_H
#include <QDialog>
#include <QCheckBox>
#include <memory>
#include "common/InitialOptions.h"
namespace Ui {
class InitialOptionsDialog;
}
class CutterCore;
class MainWindow;
class InitialOptionsDialog : public QDialog
{
Q_OBJECT
public:
explicit InitialOptionsDialog(MainWindow *main);
~InitialOptionsDialog();
void setupAndStartAnalysis();
private slots:
void on_okButton_clicked();
void on_analysisSlider_valueChanged(int value);
void on_AdvOptButton_clicked();
void on_analysisCheckBox_clicked(bool checked);
void on_archComboBox_currentIndexChanged(int index);
void on_pdbSelectButton_clicked();
void on_scriptSelectButton_clicked();
void updatePDBLayout();
void updateScriptLayout();
protected:
void closeEvent(QCloseEvent *event) override;
private:
std::unique_ptr<Ui::InitialOptionsDialog> ui;
MainWindow *main;
CutterCore *core;
QString analysisDescription(int level);
QString shellcode;
int analysisLevel;
QList<RzAsmPluginDescription> asmPlugins;
void updateCPUComboBox();
struct AnalysisCommands
{
CommandDescription commandDesc;
QCheckBox *checkbox;
bool checked;
};
QList<AnalysisCommands> analysisCommands;
QList<QString> getAnalysisCommands(const InitialOptions &options);
QString getSelectedArch() const;
QString getSelectedCPU() const;
int getSelectedBits() const;
InitialOptions::Endianness getSelectedEndianness() const;
QString getSelectedOS() const;
QList<CommandDescription> getSelectedAdvancedAnalCmds() const;
/**
* @brief setTooltipWithConfigHelp is an helper function that add a tolltip to a widget with
* a description of a given Rizin eval config.
* @param w - a widget to which to add the tooltip
* @param config - name of a configuration variable such as "asm.bits".
*/
void setTooltipWithConfigHelp(QWidget *w, const char *config);
public:
void loadOptions(const InitialOptions &options);
void reject() override;
};
#endif // OPTIONSDIALOG_H
| 2,135
|
C++
|
.h
| 65
| 28.553846
| 96
| 0.75548
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,655
|
RizinPluginsDialog.h
|
rizinorg_cutter/src/dialogs/RizinPluginsDialog.h
|
#ifndef PLUGINSDIALOG_H
#define PLUGINSDIALOG_H
#include <QDialog>
#include <QAbstractTableModel>
#include "core/Cutter.h"
namespace Ui {
class RizinPluginsDialog;
}
class RizinPluginsDialog : public QDialog
{
Q_OBJECT
public:
explicit RizinPluginsDialog(QWidget *parent = nullptr);
~RizinPluginsDialog();
private:
Ui::RizinPluginsDialog *ui;
};
#endif // PLUGINSDIALOG_H
| 395
|
C++
|
.h
| 18
| 19.666667
| 59
| 0.791892
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,656
|
GlibcHeapInfoDialog.h
|
rizinorg_cutter/src/dialogs/GlibcHeapInfoDialog.h
|
#ifndef HEAPINFODIALOG_H
#define HEAPINFODIALOG_H
#include <QDialog>
#include "core/Cutter.h"
namespace Ui {
class GlibcHeapInfoDialog;
}
class GlibcHeapInfoDialog : public QDialog
{
Q_OBJECT
public:
explicit GlibcHeapInfoDialog(RVA offset, QString status, QWidget *parent = nullptr);
~GlibcHeapInfoDialog();
private slots:
void saveChunkInfo();
private:
Ui::GlibcHeapInfoDialog *ui;
void updateFields();
RVA offset;
QString status;
};
#endif // HEAPINFODIALOG_H
| 502
|
C++
|
.h
| 22
| 20.045455
| 88
| 0.769556
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,657
|
FlagDialog.h
|
rizinorg_cutter/src/dialogs/FlagDialog.h
|
#ifndef FLAGDIALOG_H
#define FLAGDIALOG_H
#include <QDialog>
#include <memory>
#include "core/CutterCommon.h"
namespace Ui {
class FlagDialog;
}
class FlagDialog : public QDialog
{
Q_OBJECT
public:
explicit FlagDialog(RVA offset, QWidget *parent = nullptr);
~FlagDialog();
private slots:
void buttonBoxAccepted();
void buttonBoxRejected();
private:
std::unique_ptr<Ui::FlagDialog> ui;
RVA offset;
QString flagName;
ut64 flagOffset;
};
#endif // FLAGDIALOG_H
| 501
|
C++
|
.h
| 24
| 18.083333
| 63
| 0.744681
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,658
|
WriteCommandsDialogs.h
|
rizinorg_cutter/src/dialogs/WriteCommandsDialogs.h
|
#ifndef WRITECOMMANDSDIALOGS_H
#define WRITECOMMANDSDIALOGS_H
#include <QDialog>
#include "CutterCommon.h"
namespace Ui {
class Base64EnDecodedWriteDialog;
class IncrementDecrementDialog;
class DuplicateFromOffsetDialog;
}
class Base64EnDecodedWriteDialog : public QDialog
{
Q_OBJECT
public:
explicit Base64EnDecodedWriteDialog(QWidget *parent = nullptr);
enum Mode { Encode, Decode };
Mode getMode() const;
QByteArray getData() const;
private:
Ui::Base64EnDecodedWriteDialog *ui;
};
class IncrementDecrementDialog : public QDialog
{
Q_OBJECT
public:
explicit IncrementDecrementDialog(QWidget *parent = nullptr);
enum Mode { Increase, Decrease };
Mode getMode() const;
uint8_t getNBytes() const;
uint64_t getValue() const;
private:
Ui::IncrementDecrementDialog *ui;
};
class DuplicateFromOffsetDialog : public QDialog
{
Q_OBJECT
public:
explicit DuplicateFromOffsetDialog(QWidget *parent = nullptr);
RVA getOffset() const;
size_t getNBytes() const;
private:
Ui::DuplicateFromOffsetDialog *ui;
private slots:
void refresh();
};
#endif // WRITECOMMANDSDIALOGS_H
| 1,146
|
C++
|
.h
| 45
| 22.555556
| 67
| 0.776352
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,659
|
MultitypeFileSaveDialog.h
|
rizinorg_cutter/src/dialogs/MultitypeFileSaveDialog.h
|
#ifndef MULTITYPEFILESAVEDIALOG_H
#define MULTITYPEFILESAVEDIALOG_H
#include <QDialog>
#include <QFileDialog>
#include <QVariant>
class MultitypeFileSaveDialog : public QFileDialog
{
Q_OBJECT
public:
struct TypeDescription
{
QString description;
QString extension;
QVariant data;
};
explicit MultitypeFileSaveDialog(QWidget *parent = nullptr, const QString &caption = QString(),
const QString &directory = QString());
void setTypes(const QVector<TypeDescription> types, bool useDetection = true);
TypeDescription selectedType() const;
protected:
void done(int r) override;
private:
void onFilterSelected(const QString &filter);
QVector<TypeDescription>::const_iterator findType(const QString &description) const;
QVector<TypeDescription> types;
bool hasTypeDetection;
};
#endif // MULTITYPEFILESAVEDIALOG_H
| 925
|
C++
|
.h
| 28
| 27.821429
| 99
| 0.736486
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,660
|
VersionInfoDialog.h
|
rizinorg_cutter/src/dialogs/VersionInfoDialog.h
|
#ifndef VERSIONINFODIALOG_H
#define VERSIONINFODIALOG_H
#include <QDialog>
#include <memory>
#include "core/Cutter.h"
namespace Ui {
class VersionInfoDialog;
}
class VersionInfoDialog : public QDialog
{
Q_OBJECT
public:
explicit VersionInfoDialog(QWidget *parent = nullptr);
~VersionInfoDialog();
private:
std::unique_ptr<Ui::VersionInfoDialog> ui;
CutterCore *core;
void fillVersionInfo();
};
#endif // VERSIONINFODIALOG_H
| 456
|
C++
|
.h
| 20
| 20.2
| 58
| 0.775701
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,661
|
HexdumpRangeDialog.h
|
rizinorg_cutter/src/dialogs/HexdumpRangeDialog.h
|
#ifndef HEXDUMPRANGEDIALOG_H
#define HEXDUMPRANGEDIALOG_H
#include "core/CutterCommon.h"
#include <QDialog>
namespace Ui {
class HexdumpRangeDialog;
}
class HexdumpRangeDialog : public QDialog
{
Q_OBJECT
public:
explicit HexdumpRangeDialog(QWidget *parent = nullptr, bool allowEmpty = false);
~HexdumpRangeDialog();
bool empty();
ut64 getStartAddress() const;
ut64 getEndAddress() const;
void setStartAddress(ut64 start);
void open(ut64 start);
public slots:
void textEdited();
private:
bool getEndAddressRadioButtonChecked() const;
bool getLengthRadioButtonChecked() const;
bool validate();
Ui::HexdumpRangeDialog *ui;
bool emptyRange = true;
ut64 startAddress;
ut64 endAddress;
bool allowEmpty = false;
private slots:
void on_radioButtonClicked(bool checked);
};
#endif // HEXDUMPRANGEDIALOG_H
| 878
|
C++
|
.h
| 33
| 23.121212
| 84
| 0.759281
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,662
|
XrefsDialog.h
|
rizinorg_cutter/src/dialogs/XrefsDialog.h
|
#ifndef XREFSDIALOG_H
#define XREFSDIALOG_H
#include <QDialog>
#include <QTreeWidgetItem>
#include <memory>
#include "common/Highlighter.h"
#include "core/Cutter.h"
#include "common/AddressableItemModel.h"
class XrefModel : public AddressableItemModel<QAbstractListModel>
{
private:
QList<XrefDescription> xrefs;
bool to;
public:
enum Columns { OFFSET = 0, TYPE, CODE, COMMENT, COUNT };
static const int FlagDescriptionRole = Qt::UserRole;
XrefModel(QObject *parent = nullptr);
void readForOffset(RVA offset, bool to, bool whole_function);
void readForVariable(QString nameOfVariable, bool write, RVA offset);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
RVA address(const QModelIndex &index) const override;
static QString xrefTypeString(const QString &type);
};
class MainWindow;
namespace Ui {
class XrefsDialog;
}
class XrefsDialog : public QDialog
{
Q_OBJECT
public:
explicit XrefsDialog(MainWindow *parent, bool hideXrefFrom = false);
~XrefsDialog();
void fillRefsForAddress(RVA addr, QString name, bool whole_function);
/**
* @brief Initializes toModel and fromModel with the details about the references to the
* specified local variable 'nameOfVariable'.
* @param nameOfVarible Name of the local variable for which the references are being
* initialized.
* @param offset An offset in the function in which the specified local variable exist.
*/
void fillRefsForVariable(QString nameOfVariable, RVA offset);
private slots:
QString normalizeAddr(const QString &addr) const;
void setupPreviewFont();
void setupPreviewColors();
void highlightCurrentLine();
void onFromTreeWidgetItemSelectionChanged();
void onToTreeWidgetItemSelectionChanged();
private:
RVA addr;
QString func_name;
XrefModel toModel;
XrefModel fromModel;
std::unique_ptr<Ui::XrefsDialog> ui;
void updateLabels(QString name);
void updateLabelsForVariables(QString name);
void updatePreview(RVA addr);
void hideXrefFromSection();
};
#endif // XREFSDIALOG_H
| 2,412
|
C++
|
.h
| 65
| 32.876923
| 92
| 0.755479
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,663
|
EditStringDialog.h
|
rizinorg_cutter/src/dialogs/EditStringDialog.h
|
#ifndef EDITSTRINGDIALOG_H
#define EDITSTRINGDIALOG_H
#include <memory>
#include <QDialog>
namespace Ui {
class EditStringDialog;
}
class EditStringDialog : public QDialog
{
Q_OBJECT
public:
enum class StringType { Auto, ASCII_LATIN1, UTF8 };
explicit EditStringDialog(QWidget *parent = nullptr);
~EditStringDialog();
/**
* @brief Sets the address of the first byte of potential string in the dialog
*
* @param address The address of the bytearray where string is located
*/
void setStringStartAddress(uint64_t address);
/**
* @brief Returns the address of the first byte of potential string in the dialog
*
* @param[out] returnValue The address of the bytearray where string is located
* @return whether the call successful or not
*/
bool getStringStartAddress(uint64_t &returnValue) const;
/**
* @brief Sets the size of string in the dialog
*
* @param size The size of string in the dialog
*/
void setStringSizeValue(uint32_t size);
/**
* @brief Returns the size of string in the dialog
*
* @return -1 on error otherwise the size of string from the dialog
*/
int getStringSizeValue() const;
/**
* @brief Returns the type of string from the dialog
*
* @return The type of string from the dialog
*/
StringType getStringType() const;
private:
std::unique_ptr<Ui::EditStringDialog> ui;
};
#endif // EDITSTRINGDIALOG_H
| 1,490
|
C++
|
.h
| 49
| 25.857143
| 85
| 0.696229
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,664
|
NativeDebugDialog.h
|
rizinorg_cutter/src/dialogs/NativeDebugDialog.h
|
#ifndef NATIVEDEBUGDIALOG_H
#define NATIVEDEBUGDIALOG_H
#include <QDialog>
#include <memory>
namespace Ui {
class NativeDebugDialog;
}
/**
* @brief Dialog for connecting to native debug
*/
class NativeDebugDialog : public QDialog
{
Q_OBJECT
public:
explicit NativeDebugDialog(QWidget *parent = nullptr);
~NativeDebugDialog();
QString getArgs() const;
void setArgs(const QString &args);
private:
std::unique_ptr<Ui::NativeDebugDialog> ui;
};
#endif // NATIVE_DEBUG_DIALOG
| 504
|
C++
|
.h
| 22
| 20.409091
| 58
| 0.764211
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,665
|
SetToDataDialog.h
|
rizinorg_cutter/src/dialogs/SetToDataDialog.h
|
#ifndef SETTODATADIALOG_H
#define SETTODATADIALOG_H
#include <QDialog>
#include "core/Cutter.h"
namespace Ui {
class SetToDataDialog;
}
class SetToDataDialog : public QDialog
{
Q_OBJECT
public:
explicit SetToDataDialog(RVA startAddr, QWidget *parent = nullptr);
~SetToDataDialog();
int getItemSize();
int getItemCount();
private slots:
void on_sizeEdit_textChanged(const QString &arg1);
void on_repeatEdit_textChanged(const QString &arg1);
private:
void updateEndAddress();
Ui::SetToDataDialog *ui;
RVA startAddress;
};
#endif // SETTODATADIALOG_H
| 597
|
C++
|
.h
| 24
| 21.833333
| 71
| 0.762411
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,666
|
BreakpointsDialog.h
|
rizinorg_cutter/src/dialogs/BreakpointsDialog.h
|
#pragma once
#include <QDialog>
#include <memory>
#include "CutterDescriptions.h"
namespace Ui {
class BreakpointsDialog;
}
class BreakpointsDialog : public QDialog
{
Q_OBJECT
public:
explicit BreakpointsDialog(bool editMode = false, QWidget *parent = nullptr);
BreakpointsDialog(const BreakpointDescription &editableBreakpoint, QWidget *parent = nullptr);
BreakpointsDialog(RVA address, QWidget *parent = nullptr);
~BreakpointsDialog();
BreakpointDescription getDescription();
static void createNewBreakpoint(RVA address = RVA_INVALID, QWidget *parent = nullptr);
static void editBreakpoint(const BreakpointDescription &breakpoint, QWidget *parent = nullptr);
private:
std::unique_ptr<Ui::BreakpointsDialog> ui;
bool editMode = false;
void refreshOkButton();
void onTypeChanged();
void configureCheckboxRestrictions();
int getHwPermissions();
};
| 911
|
C++
|
.h
| 26
| 31.576923
| 99
| 0.775371
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,667
|
NewFileDialog.h
|
rizinorg_cutter/src/dialogs/NewFileDialog.h
|
#ifndef NEWFILEDIALOG_H
#define NEWFILEDIALOG_H
#include <QDialog>
#include <QListWidgetItem>
#include <memory>
namespace Ui {
class NewFileDialog;
}
class MainWindow;
class NewFileDialog : public QDialog
{
Q_OBJECT
public:
explicit NewFileDialog(MainWindow *main);
~NewFileDialog();
private slots:
void on_loadFileButton_clicked();
void on_selectFileButton_clicked();
void on_selectProjectFileButton_clicked();
void on_loadProjectButton_clicked();
void on_shellcodeButton_clicked();
void on_aboutButton_clicked();
void on_recentsListWidget_itemClicked(QListWidgetItem *item);
void on_recentsListWidget_itemDoubleClicked(QListWidgetItem *item);
void on_projectFileEdit_textChanged();
void on_projectsListWidget_itemClicked(QListWidgetItem *item);
void on_projectsListWidget_itemDoubleClicked(QListWidgetItem *item);
void on_actionRemove_item_triggered();
void on_actionClear_all_triggered();
void on_actionRemove_project_triggered();
void on_actionClearProjects_triggered();
void on_tabWidget_currentChanged(int index);
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
private:
std::unique_ptr<Ui::NewFileDialog> ui;
MainWindow *main;
/**
* @return true if list is not empty
*/
bool fillRecentFilesList();
/**
* @return true if list is not empty
*/
bool fillProjectsList();
void fillIOPluginsList();
void updateLoadProjectButton();
void loadFile(const QString &filename);
void loadProject(const QString &project);
void loadShellcode(const QString &shellcode, const int size);
bool eventFilter(QObject *obj, QEvent *event);
static const int MaxRecentFiles = 5;
};
#endif // NEWFILEDIALOG_H
| 1,809
|
C++
|
.h
| 55
| 28.654545
| 72
| 0.751732
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,668
|
AsyncTaskDialog.h
|
rizinorg_cutter/src/dialogs/AsyncTaskDialog.h
|
#ifndef ASYNCTASKDIALOG_H
#define ASYNCTASKDIALOG_H
#include <memory>
#include <QDialog>
#include <QTimer>
#include "common/AsyncTask.h"
namespace Ui {
class AsyncTaskDialog;
}
class AsyncTaskDialog : public QDialog
{
Q_OBJECT
public:
AsyncTaskDialog(AsyncTask::Ptr task, QWidget *parent = nullptr);
~AsyncTaskDialog();
void setInterruptOnClose(bool v) { interruptOnClose = v; }
bool getInterruptOnClose() { return interruptOnClose; }
public slots:
void reject() override;
private slots:
void updateLog(const QString &log);
void updateProgressTimer();
protected:
void closeEvent(QCloseEvent *event) override;
private:
std::unique_ptr<Ui::AsyncTaskDialog> ui;
AsyncTask::Ptr task;
QTimer timer;
bool interruptOnClose = false;
};
#endif // ASYNCTASKDIALOG_H
| 822
|
C++
|
.h
| 31
| 23.387097
| 68
| 0.759331
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,669
|
TypesInteractionDialog.h
|
rizinorg_cutter/src/dialogs/TypesInteractionDialog.h
|
#ifndef TYPESINTERACTIONDIALOG_H
#define TYPESINTERACTIONDIALOG_H
#include <QDialog>
#include <memory>
namespace Ui {
class TypesInteractionDialog;
}
class QSyntaxHighlighter;
class TypesInteractionDialog : public QDialog
{
Q_OBJECT
public:
explicit TypesInteractionDialog(QWidget *parent = nullptr, bool readOnly = false);
~TypesInteractionDialog();
/**
* @brief Fill the Dialog's TextEdit object with the content
* passed to the function. The content will most likely be a C
* representation of a Type.
* @param content - The content which should be in the TextEdit object.
* most likely will be a C representation of a Type.
* @param readonly - Will be set as "true" for viewing mode
*/
void fillTextArea(QString content);
/**
* @brief Set the name of the type that is going to be changed
* @param name - name of the type
*/
void setTypeName(QString name);
private slots:
/**
* @brief Executed when the user clicks the selectFileButton
* Opens a File Dialog from where the user can select a file from where
* the types will be loaded.
*/
void on_selectFileButton_clicked();
/**
* @brief Executed whenever the text inside the textbox changes
* When the text box is empty, the OK button is disabled.
*/
void on_plainTextEdit_textChanged();
/**
* @brief done Closes the dialog and sets its result code to r
* @param r The value which will be returned by exec()
*/
void done(int r) override;
private:
std::unique_ptr<Ui::TypesInteractionDialog> ui;
QSyntaxHighlighter *syntaxHighLighter;
QString typeName;
signals:
/**
* @brief Emitted when new types are loaded
*/
void newTypesLoaded();
};
#endif // TYPESINTERACTIONDIALOG_H
| 1,819
|
C++
|
.h
| 56
| 28.017857
| 86
| 0.706453
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,670
|
EditVariablesDialog.h
|
rizinorg_cutter/src/dialogs/EditVariablesDialog.h
|
#ifndef EDITVARIABLESDIALOG_H
#define EDITVARIABLESDIALOG_H
#include "core/Cutter.h"
#include <QDialog>
namespace Ui {
class EditVariablesDialog;
}
class EditVariablesDialog : public QDialog
{
Q_OBJECT
public:
explicit EditVariablesDialog(RVA offset, QString initialVar = QString(),
QWidget *parent = nullptr);
~EditVariablesDialog();
bool empty() const;
private slots:
void applyFields();
void updateFields();
private:
Ui::EditVariablesDialog *ui;
RVA functionAddress;
QList<VariableDescription> variables;
void populateTypesComboBox();
};
#endif // EDITVARIABLESDIALOG_H
| 654
|
C++
|
.h
| 25
| 21.92
| 76
| 0.7343
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,671
|
GlobalVariableDialog.h
|
rizinorg_cutter/src/dialogs/GlobalVariableDialog.h
|
#ifndef GLOBALVARIABLEDIALOG_H
#define GLOBALVARIABLEDIALOG_H
#include <QDialog>
#include <memory>
#include "core/CutterCommon.h"
namespace Ui {
class GlobalVariableDialog;
}
class GlobalVariableDialog : public QDialog
{
Q_OBJECT
public:
explicit GlobalVariableDialog(RVA offset, QWidget *parent = nullptr);
~GlobalVariableDialog();
private slots:
void buttonBoxAccepted();
void buttonBoxRejected();
private:
std::unique_ptr<Ui::GlobalVariableDialog> ui;
RVA offset;
QString globalVariableName;
RVA globalVariableOffset;
QString typ;
};
#endif // GLOBALVARIABLEDIALOG_H
| 617
|
C++
|
.h
| 25
| 21.8
| 73
| 0.784615
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,672
|
EditInstructionDialog.h
|
rizinorg_cutter/src/dialogs/EditInstructionDialog.h
|
#ifndef EDITINSTRUCTIONDIALOG_H
#define EDITINSTRUCTIONDIALOG_H
#include <QDialog>
#include <memory>
namespace Ui {
class EditInstructionDialog;
}
enum InstructionEditMode { EDIT_NONE, EDIT_BYTES, EDIT_TEXT };
class EditInstructionDialog : public QDialog
{
Q_OBJECT
public:
explicit EditInstructionDialog(InstructionEditMode isEditingBytes, QWidget *parent = nullptr);
~EditInstructionDialog();
QString getInstruction() const;
void setInstruction(const QString &instruction);
bool needsNops() const;
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void updatePreview(const QString &input);
private:
std::unique_ptr<Ui::EditInstructionDialog> ui;
// defines if the user is editing bytes or asm
InstructionEditMode editMode;
};
#endif // EDITINSTRUCTIONDIALOG_H
| 845
|
C++
|
.h
| 27
| 28.148148
| 98
| 0.783416
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,673
|
RemoteDebugDialog.h
|
rizinorg_cutter/src/dialogs/RemoteDebugDialog.h
|
#ifndef REMOTEDEBUGDIALOG_H
#define REMOTEDEBUGDIALOG_H
#include <QDialog>
#include <QListWidgetItem>
#include <memory>
namespace Ui {
class RemoteDebugDialog;
}
/**
* @brief Dialog for connecting to remote debuggers
*/
class RemoteDebugDialog : public QDialog
{
Q_OBJECT
public:
explicit RemoteDebugDialog(QWidget *parent = nullptr);
~RemoteDebugDialog();
/**
* @brief Generate a URI for given UI input
*/
QString getUri() const;
bool validate();
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
/**
* @brief Clears the list of recent connections.
* Triggers when you right click and click on "Clear All" in remote debug dialog.
*/
void clearAll();
/**
* @brief Clears the selected item in the list of recent connections.
* Triggers when you right click and click on "Remove Item" in remote debug dialog.
*/
void removeItem();
/**
* @brief Fills the form with the selected item's data.
*/
void itemClicked(QListWidgetItem *item);
private:
std::unique_ptr<Ui::RemoteDebugDialog> ui;
int getPort() const;
int getDebugger() const;
QString getIpOrPath() const;
bool validatePath();
bool validateIp();
bool validatePort();
/**
* @brief Fills recent remote connections.
*/
bool fillRecentIpList();
/**
* @brief Fills the remote debug dialog form from a given URI
* Eg: gdb://127.0.0.1:8754 or windbg:///tmp/abcd
*/
void fillFormData(QString formdata);
/**
* @brief Checks if the recent connection list is empty or and hide/unhide the table view
*/
void checkIfEmpty();
};
#endif // REMOTE_DEBUG_DIALOG
| 1,733
|
C++
|
.h
| 62
| 23.564516
| 93
| 0.682971
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,674
|
LayoutManager.h
|
rizinorg_cutter/src/dialogs/LayoutManager.h
|
#ifndef LAYOUT_MANAGER_H
#define LAYOUT_MANAGER_H
#include <QDialog>
#include <memory>
#include "core/Cutter.h"
#include "common/CutterLayout.h"
namespace Ui {
class LayoutManager;
}
class LayoutManager : public QDialog
{
Q_OBJECT
public:
LayoutManager(QMap<QString, Cutter::CutterLayout> &layouts, QWidget *parent);
~LayoutManager();
private:
void refreshNameList(QString selection = "");
void renameCurrentLayout();
void deleteLayout();
void updateButtons();
std::unique_ptr<Ui::LayoutManager> ui;
QMap<QString, Cutter::CutterLayout> &layouts;
};
#endif // LAYOUT_MANAGER_H
| 618
|
C++
|
.h
| 24
| 23
| 81
| 0.75
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,675
|
MapFileDialog.h
|
rizinorg_cutter/src/dialogs/MapFileDialog.h
|
#ifndef MAPFILEDIALOG_H
#define MAPFILEDIALOG_H
#include <QDialog>
#include <memory>
#include "core/Cutter.h"
namespace Ui {
class MapFileDialog;
}
class MapFileDialog : public QDialog
{
Q_OBJECT
public:
explicit MapFileDialog(QWidget *parent = nullptr);
~MapFileDialog();
private slots:
void on_selectFileButton_clicked();
void on_buttonBox_accepted();
void on_buttonBox_rejected();
private:
std::unique_ptr<Ui::MapFileDialog> ui;
};
#endif // MAPFILEDIALOG_H
| 496
|
C++
|
.h
| 22
| 19.954545
| 54
| 0.75803
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,676
|
AboutDialog.h
|
rizinorg_cutter/src/dialogs/AboutDialog.h
|
#ifndef ABOUTDIALOG_H
#define ABOUTDIALOG_H
#include <QDialog>
#include <memory>
#include <QtNetwork/QNetworkReply>
namespace Ui {
class AboutDialog;
}
class AboutDialog : public QDialog
{
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent = nullptr);
~AboutDialog();
private slots:
void on_buttonBox_rejected();
void on_showVersionButton_clicked();
void on_showPluginsButton_clicked();
void on_Issue_clicked();
/**
* @fn AboutDialog::on_checkForUpdatesButton_clicked()
*
* @brief Initiates process of checking for updates.
*/
void on_checkForUpdatesButton_clicked();
/**
* @fn AboutDialog::on_updatesCheckBox_stateChanged(int state)
*
* @brief Changes value of autoUpdateEnabled option in settings.
*/
void on_updatesCheckBox_stateChanged(int state);
private:
std::unique_ptr<Ui::AboutDialog> ui;
QString buildQtVersionString(void);
};
#endif // ABOUTDIALOG_H
| 966
|
C++
|
.h
| 36
| 23
| 68
| 0.725
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,677
|
ArenaInfoDialog.h
|
rizinorg_cutter/src/dialogs/ArenaInfoDialog.h
|
#ifndef ARENAINFODIALOG_H
#define ARENAINFODIALOG_H
#include <QDialog>
#include <CutterDescriptions.h>
namespace Ui {
class ArenaInfoDialog;
}
class ArenaInfoDialog : public QDialog
{
Q_OBJECT
public:
explicit ArenaInfoDialog(Arena &arena, QWidget *parent = nullptr);
~ArenaInfoDialog();
void updateContents();
private:
Ui::ArenaInfoDialog *ui;
Arena arena;
};
#endif // ARENAINFODIALOG_H
| 419
|
C++
|
.h
| 19
| 19.473684
| 70
| 0.771574
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,678
|
RizinTaskDialog.h
|
rizinorg_cutter/src/dialogs/RizinTaskDialog.h
|
#ifndef RZTASKDIALOG_H
#define RZTASKDIALOG_H
#include <memory>
#include <QDialog>
#include <QTimer>
#include <QElapsedTimer>
#include "common/RizinTask.h"
#include "core/CutterCommon.h"
class RizinTask;
namespace Ui {
class RizinTaskDialog;
}
class CUTTER_EXPORT RizinTaskDialog : public QDialog
{
Q_OBJECT
public:
using Ptr = QSharedPointer<RizinTask>;
RizinTaskDialog(Ptr task, QWidget *parent = nullptr);
~RizinTaskDialog();
void setBreakOnClose(bool v) { breakOnClose = v; }
bool getBreakOnClose() { return breakOnClose; }
void setDesc(const QString &label);
public slots:
void reject() override;
private slots:
void updateProgressTimer();
protected:
void closeEvent(QCloseEvent *event) override;
private:
std::unique_ptr<Ui::RizinTaskDialog> ui;
QSharedPointer<RizinTask> task;
QTimer timer;
QElapsedTimer elapsedTimer;
bool breakOnClose = false;
};
#endif // RZTASKDIALOG_H
| 955
|
C++
|
.h
| 36
| 23.472222
| 57
| 0.761326
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,679
|
AttachProcDialog.h
|
rizinorg_cutter/src/dialogs/AttachProcDialog.h
|
#pragma once
#include "core/Cutter.h"
#include <QDialog>
#include <memory>
#include <QAbstractListModel>
#include <QSortFilterProxyModel>
#include <QTimer>
namespace Ui {
class AttachProcDialog;
}
class MainWindow;
class QTreeWidget;
class QTreeWidgetItem;
class ProcessModel : public QAbstractListModel
{
Q_OBJECT
private:
QList<ProcessDescription> processes;
public:
enum Column { PidColumn = 0, UidColumn, StatusColumn, PathColumn, ColumnCount };
enum Role { ProcDescriptionRole = Qt::UserRole };
ProcessModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
static bool lessThan(const ProcessDescription &left, const ProcessDescription &right,
int column);
public slots:
void updateData();
};
class ProcessProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
ProcessProxyModel(ProcessModel *sourceModel, QObject *parent = nullptr);
protected:
bool filterAcceptsRow(int row, const QModelIndex &parent) const override;
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override;
};
class ProcessBeingAnalysedProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
ProcessBeingAnalysedProxyModel(ProcessModel *sourceModel, QObject *parent = nullptr);
protected:
bool filterAcceptsRow(int row, const QModelIndex &parent) const override;
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override;
private:
QString processBeingAnalysedFilename;
QString processPathToFilename(const QString &path) const;
};
class AttachProcDialog : public QDialog
{
Q_OBJECT
public:
explicit AttachProcDialog(QWidget *parent = nullptr);
~AttachProcDialog();
int getPID();
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void on_allProcView_doubleClicked(const QModelIndex &index);
void on_procBeingAnalyzedView_doubleClicked(const QModelIndex &index);
void updateModelData();
private:
std::unique_ptr<Ui::AttachProcDialog> ui;
bool eventFilter(QObject *obj, QEvent *event);
ProcessModel *processModel;
ProcessProxyModel *processProxyModel;
ProcessBeingAnalysedProxyModel *processBeingAnalyzedProxyModel;
// whether the 'small table' or 'table with all procs' was last focused
bool wasAllProcViewLastPressed = false;
QTimer *timer;
const int updateIntervalMs = 1000;
};
| 2,694
|
C++
|
.h
| 76
| 31.736842
| 100
| 0.774778
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,680
|
CommentsDialog.h
|
rizinorg_cutter/src/dialogs/CommentsDialog.h
|
#ifndef COMMENTSDIALOG_H
#define COMMENTSDIALOG_H
#include <QDialog>
#include <memory>
#include "core/CutterCommon.h"
namespace Ui {
class CommentsDialog;
}
class CommentsDialog : public QDialog
{
Q_OBJECT
public:
explicit CommentsDialog(QWidget *parent = nullptr);
~CommentsDialog();
QString getComment();
void setComment(const QString &comment);
static void addOrEditComment(RVA offset, QWidget *parent);
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
private:
std::unique_ptr<Ui::CommentsDialog> ui;
bool eventFilter(QObject *obj, QEvent *event);
};
#endif // COMMENTSDIALOG_H
| 659
|
C++
|
.h
| 25
| 23.32
| 62
| 0.75923
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,681
|
WelcomeDialog.h
|
rizinorg_cutter/src/dialogs/WelcomeDialog.h
|
#ifndef WELCOMEDIALOG_H
#define WELCOMEDIALOG_H
#include <QDialog>
namespace Ui {
/**
* @class WelcomeDialog
* @brief The WelcomeDialog class will show the user the Welcome windows
* upon first execution of Cutter.
*
* Upon first execution of Cutter, the WelcomeDialog would be showed to the user.
* The Welcome dialog would be showed after a reset of Cutter's preferences by the user.
*/
class WelcomeDialog;
}
class WelcomeDialog : public QDialog
{
Q_OBJECT
public:
explicit WelcomeDialog(QWidget *parent = 0);
~WelcomeDialog();
private slots:
void on_themeComboBox_currentIndexChanged(int index);
void onLanguageComboBox_currentIndexChanged(int index);
void on_checkUpdateButton_clicked();
void on_continueButton_clicked();
void on_updatesCheckBox_stateChanged(int state);
private:
Ui::WelcomeDialog *ui;
};
#endif // WELCOMEDIALOG_H
| 890
|
C++
|
.h
| 30
| 26.933333
| 88
| 0.773208
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,682
|
PreferencesDialog.h
|
rizinorg_cutter/src/dialogs/preferences/PreferencesDialog.h
|
#ifndef PREFERENCESDIALOG_H
#define PREFERENCESDIALOG_H
#include "core/Cutter.h"
#include <QDialog>
#include <memory>
class QTreeWidgetItem;
namespace Ui {
class PreferencesDialog;
}
class PreferencesDialog : public QDialog
{
Q_OBJECT
public:
enum class Section { Appearance, Disassembly };
explicit PreferencesDialog(QWidget *parent = nullptr);
~PreferencesDialog();
void showSection(Section section);
public slots:
void changePage(QTreeWidgetItem *current, QTreeWidgetItem *previous);
private:
std::unique_ptr<Ui::PreferencesDialog> ui;
void chooseThemeIcons();
};
#endif // PREFERENCESDIALOG_H
| 642
|
C++
|
.h
| 24
| 23.875
| 73
| 0.785124
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,683
|
GraphOptionsWidget.h
|
rizinorg_cutter/src/dialogs/preferences/GraphOptionsWidget.h
|
#ifndef GRAPHOPTIONSWIDGET_H
#define GRAPHOPTIONSWIDGET_H
#include <QDialog>
#include <QPushButton>
#include <memory>
#include "core/Cutter.h"
class PreferencesDialog;
namespace Ui {
class GraphOptionsWidget;
}
class GraphOptionsWidget : public QDialog
{
Q_OBJECT
public:
explicit GraphOptionsWidget(PreferencesDialog *dialog);
~GraphOptionsWidget();
private:
std::unique_ptr<Ui::GraphOptionsWidget> ui;
void triggerOptionsChanged();
private slots:
void updateOptionsFromVars();
void on_maxColsSpinBox_valueChanged(int value);
void on_minFontSizeSpinBox_valueChanged(int value);
void on_graphOffsetCheckBox_toggled(bool checked);
void on_graphPreviewCheckBox_toggled(bool checked);
void checkTransparentStateChanged(int checked);
void bitmapGraphScaleValueChanged(double value);
void checkGraphBlockEntryOffsetChanged(bool checked);
void layoutSpacingChanged();
};
#endif // GRAPHOPTIONSWIDGET_H
| 965
|
C++
|
.h
| 31
| 27.903226
| 59
| 0.803474
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,684
|
InitializationFileEditor.h
|
rizinorg_cutter/src/dialogs/preferences/InitializationFileEditor.h
|
#ifndef INITIALIZATIONFILEEDITOR_H
#define INITIALIZATIONFILEEDITOR_H
#include <QDialog>
#include <QPushButton>
#include <memory>
#include "core/Cutter.h"
class PreferencesDialog;
namespace Ui {
class InitializationFileEditor;
}
class InitializationFileEditor : public QDialog
{
Q_OBJECT
public:
explicit InitializationFileEditor(PreferencesDialog *dialog);
~InitializationFileEditor();
void saveCutterRC();
void executeCutterRC();
private:
std::unique_ptr<Ui::InitializationFileEditor> ui;
};
#endif // INITIALIZATIONFILEEDITOR_H
| 561
|
C++
|
.h
| 22
| 23.136364
| 65
| 0.812383
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,685
|
ColorThemeEditDialog.h
|
rizinorg_cutter/src/dialogs/preferences/ColorThemeEditDialog.h
|
#ifndef COLORTHEMEEDITDIALOG_H
#define COLORTHEMEEDITDIALOG_H
#include <QDialog>
class DisassemblyWidget;
namespace Ui {
class ColorThemeEditDialog;
}
class ColorThemeEditDialog : public QDialog
{
Q_OBJECT
public:
explicit ColorThemeEditDialog(QWidget *parent = nullptr);
~ColorThemeEditDialog() override;
public slots:
void accept() override;
void reject() override;
protected slots:
void keyPressEvent(QKeyEvent *event) override;
private slots:
/**
* @brief Sets @a newColor color for current option.
* @param newColor
* New color for current color option.
*/
void colorOptionChanged(const QColor &newColor);
/**
* @brief Changes current theme to edit.
* @param newTheme
* Name of new theme.
*/
void editThemeChanged(const QString &newTheme);
private:
bool themeWasEdited(const QString &theme) const;
private:
QList<QString> showAlphaOptions;
Ui::ColorThemeEditDialog *ui;
QSignalBlocker configSignalBlocker;
DisassemblyWidget *previewDisasmWidget;
QString colorTheme;
};
#endif // COLORTHEMEEDITDIALOG_H
| 1,123
|
C++
|
.h
| 41
| 23.560976
| 61
| 0.749533
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,686
|
AsmOptionsWidget.h
|
rizinorg_cutter/src/dialogs/preferences/AsmOptionsWidget.h
|
#ifndef ASMOPTIONSWIDGET_H
#define ASMOPTIONSWIDGET_H
#include <QDialog>
#include <QPushButton>
#include <memory>
#include "core/Cutter.h"
class PreferencesDialog;
namespace Ui {
class AsmOptionsWidget;
}
class AsmOptionsWidget : public QDialog
{
Q_OBJECT
public:
explicit AsmOptionsWidget(PreferencesDialog *dialog);
~AsmOptionsWidget();
private:
std::unique_ptr<Ui::AsmOptionsWidget> ui;
struct ConfigCheckbox
{
QCheckBox *checkBox;
QString config;
};
QList<ConfigCheckbox> checkboxes;
void triggerAsmOptionsChanged();
private slots:
void resetToDefault();
void updateAsmOptionsFromVars();
void on_cmtcolSpinBox_valueChanged(int value);
void on_syntaxComboBox_currentIndexChanged(int index);
void on_caseComboBox_currentIndexChanged(int index);
void on_asmTabsSpinBox_valueChanged(int value);
void on_asmTabsOffSpinBox_valueChanged(int value);
void on_nbytesSpinBox_valueChanged(int value);
void on_bytesCheckBox_toggled(bool checked);
void on_varsubCheckBox_toggled(bool checked);
void on_previewCheckBox_toggled(bool checked);
void on_buttonBox_clicked(QAbstractButton *button);
void commentsComboBoxChanged(int index);
void asmComboBoxChanged(int index);
void offsetCheckBoxToggled(bool checked);
void relOffCheckBoxToggled(bool checked);
void checkboxEnabler(QCheckBox *checkbox, QString config);
};
#endif // ASMOPTIONSWIDGET_H
| 1,472
|
C++
|
.h
| 45
| 28.666667
| 62
| 0.776596
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,687
|
DebugOptionsWidget.h
|
rizinorg_cutter/src/dialogs/preferences/DebugOptionsWidget.h
|
#pragma once
#include <memory>
#include "core/Cutter.h"
class PreferencesDialog;
namespace Ui {
class DebugOptionsWidget;
}
class DebugOptionsWidget : public QDialog
{
Q_OBJECT
public:
explicit DebugOptionsWidget(PreferencesDialog *dialog);
~DebugOptionsWidget();
private:
std::unique_ptr<Ui::DebugOptionsWidget> ui;
private slots:
void updateDebugPlugin();
void updateStackAddr();
void updateStackSize();
void onDebugPluginChanged(const QString &index);
};
| 499
|
C++
|
.h
| 21
| 20.809524
| 59
| 0.780384
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,688
|
PreferenceCategory.h
|
rizinorg_cutter/src/dialogs/preferences/PreferenceCategory.h
|
#ifndef PREFERENCECATEGORY_H
#define PREFERENCECATEGORY_H
#include <QString>
#include <QTreeWidget>
#include <QStackedWidget>
class PreferenceCategory
{
public:
PreferenceCategory(const QString &name, const QIcon &icon);
PreferenceCategory(const QString &name, QWidget *widget, const QIcon &icon);
PreferenceCategory(const QString &name, QWidget *widget, const QIcon &icon,
const QList<PreferenceCategory> &children);
PreferenceCategory(const QString &name, const QIcon &icon,
const QList<PreferenceCategory> &children);
void addItem(QTreeWidget &tree, QStackedWidget &panel);
void addItem(QTreeWidgetItem &tree, QStackedWidget &panel);
private:
QString name;
QIcon icon;
QWidget *widget;
QList<PreferenceCategory> children;
};
#endif // PREFERENCECATEGORY_H
| 850
|
C++
|
.h
| 23
| 32
| 80
| 0.743309
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,689
|
AppearanceOptionsWidget.h
|
rizinorg_cutter/src/dialogs/preferences/AppearanceOptionsWidget.h
|
#ifndef AppearanceOptionsWidget_H
#define AppearanceOptionsWidget_H
#include <QDialog>
#include <QPushButton>
#include <memory>
#include "core/Cutter.h"
class PreferencesDialog;
namespace Ui {
class AppearanceOptionsWidget;
}
class AppearanceOptionsWidget : public QDialog
{
Q_OBJECT
public:
explicit AppearanceOptionsWidget(PreferencesDialog *dialog);
~AppearanceOptionsWidget();
private:
std::unique_ptr<Ui::AppearanceOptionsWidget> ui;
private slots:
void updateFontFromConfig();
void updateThemeFromConfig(bool interfaceThemeChanged = true);
void on_fontSelectionButton_clicked();
void onFontZoomBoxValueChanged(int zoom);
void on_themeComboBox_currentIndexChanged(int index);
void on_copyButton_clicked();
void on_deleteButton_clicked();
/**
* @brief Imports theme file specified by user to custom themes
* directory.
*/
void on_importButton_clicked();
/**
* @brief Exports current color theme to file
* specified by user.
*/
void on_exportButton_clicked();
/**
* @brief Shows dialog to rename current color theme.
*/
void on_renameButton_clicked();
void on_editButton_clicked();
void onLanguageComboBoxCurrentIndexChanged(int index);
private:
void updateModificationButtons(const QString &theme);
void updateFromConfig();
/**
* @brief Changes all @a before colors in given @a fileName svg file to @a after
* and returns result icon. If @a before is not specified, changes all colors.
* @param fileName
* Path to svg file.
* @param after
* What color should be inserted instead of old one.
* @param before
* Color that should be repalced.
*/
QIcon getIconFromSvg(const QString &fileName, const QColor &after,
const QColor &before = QColor());
};
#endif // ASMOPTIONSDIALOG_H
| 1,898
|
C++
|
.h
| 59
| 27.474576
| 84
| 0.720241
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,690
|
AnalysisOptionsWidget.h
|
rizinorg_cutter/src/dialogs/preferences/AnalysisOptionsWidget.h
|
#ifndef ANALOPTIONSWIDGET_H
#define ANALOPTIONSWIDGET_H
#include <QDialog>
#include <memory>
#include "core/Cutter.h"
class PreferencesDialog;
namespace Ui {
class AnalysisOptionsWidget;
}
class AnalysisOptionsWidget : public QDialog
{
Q_OBJECT
public:
explicit AnalysisOptionsWidget(PreferencesDialog *dialog);
~AnalysisOptionsWidget();
private:
std::unique_ptr<Ui::AnalysisOptionsWidget> ui;
struct ConfigCheckbox
{
QCheckBox *checkBox;
QString config;
};
QList<ConfigCheckbox> checkboxes;
/**
* @brief This function creates the list with the different options shown in the selector for
* analysis.in
*/
void createAnalysisInOptionsList();
private slots:
/**
* @brief A slot to display the options in the dialog according to the current analysis.*
* configuration
*/
void updateAnalysisOptionsFromVars();
/**
* @brief A generic slot to handle the simple cases where a checkbox is toggled
* while it's only responsible for a single independent boolean configuration eval.
* @param checkBox - The checkbox which is responsible for the signal
* @param config - the configuration string to be toggled
*/
static void checkboxEnabler(QCheckBox *checkbox, const QString &config);
/**
* @brief A slot to update the value of analysis.in when a different option is selected
* @param index - The index of the selected option for analysis.in
*/
void updateAnalysisIn(int index);
/**
* @brief A slot to update the value of analysis.ptrdepth when a new value is selected
* @param value - The new value for analysis.ptrdepth
*/
static void updateAnalysisPtrDepth(int value);
/**
* @brief slot to update the value of analysis.prelude when a new value is introduced in the
* corresponding textbox
* @param prelude - The new value for analysis.prelude
*/
static void updateAnalysisPrelude(const QString &prelude);
};
#endif // ANALOPTIONSWIDGET_H
| 2,046
|
C++
|
.h
| 59
| 30.033898
| 97
| 0.724785
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,691
|
PluginsOptionsWidget.h
|
rizinorg_cutter/src/dialogs/preferences/PluginsOptionsWidget.h
|
#ifndef PLUGINSOPTIONSWIDGET_H
#define PLUGINSOPTIONSWIDGET_H
#include <QDialog>
class PreferencesDialog;
class PluginsOptionsWidget : public QDialog
{
Q_OBJECT
public:
explicit PluginsOptionsWidget(PreferencesDialog *dialog);
~PluginsOptionsWidget();
};
#endif // CUTTER_PLUGINSOPTIONSWIDGET_H
| 313
|
C++
|
.h
| 12
| 23.583333
| 61
| 0.827119
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,692
|
PluginManager.h
|
rizinorg_cutter/src/plugins/PluginManager.h
|
#ifndef PLUGINMANAGER_H
#define PLUGINMANAGER_H
#include <QObject>
#include <QDir>
#include <memory>
#include <vector>
#include "plugins/CutterPlugin.h"
class PluginManager : public QObject
{
Q_OBJECT
public:
static PluginManager *getInstance();
class PluginTerminator
{
public:
void operator()(CutterPlugin *) const;
};
using PluginPtr = std::unique_ptr<CutterPlugin, PluginTerminator>;
PluginManager();
~PluginManager();
/**
* @brief Load all plugins, should be called once on application start
* @param enablePlugins set to false if plugin code shouldn't be started
*/
void loadPlugins(bool enablePlugins = true);
/**
* @brief Destroy all loaded plugins, should be called once on application shutdown
*/
void destroyPlugins();
const std::vector<PluginPtr> &getPlugins() { return plugins; }
QVector<QDir> getPluginDirectories() const;
QString getUserPluginsDirectory() const;
private:
std::vector<PluginPtr> plugins;
void loadNativePlugins(const QDir &directory);
void loadPluginsFromDir(const QDir &pluginsDir, bool writable = false);
#ifdef CUTTER_ENABLE_PYTHON_BINDINGS
void loadPythonPlugins(const QDir &directory);
CutterPlugin *loadPythonPlugin(const char *moduleName);
#endif
};
#define Plugins() (PluginManager::getInstance())
#endif // PLUGINMANAGER_H
| 1,396
|
C++
|
.h
| 43
| 28.372093
| 87
| 0.736724
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,693
|
CutterPlugin.h
|
rizinorg_cutter/src/plugins/CutterPlugin.h
|
#ifndef CUTTERPLUGIN_H
#define CUTTERPLUGIN_H
class MainWindow;
#include "widgets/CutterDockWidget.h"
class CUTTER_EXPORT CutterPlugin
{
public:
virtual ~CutterPlugin() = default;
/**
* @brief Initialize the Plugin
*
* called right when the plugin is loaded initially
*/
virtual void setupPlugin() = 0;
/**
* @brief Setup any UI components for the Plugin
* @param main the MainWindow to add any UI to
*
* called after Cutter's core UI has been initialized
*/
virtual void setupInterface(MainWindow *main) = 0;
/**
* @brief Register any decompiler implemented by the Plugin
*
* called during initialization of Cutter, after setupPlugin()
*/
virtual void registerDecompilers() {}
/**
* @brief Shutdown the Plugin
*
* called just before the Plugin is deleted.
* This method is usually only relevant for Python Plugins where there is no
* direct equivalent of the destructor.
*/
virtual void terminate() {};
virtual QString getName() const = 0;
virtual QString getAuthor() const = 0;
virtual QString getDescription() const = 0;
virtual QString getVersion() const = 0;
};
#define CutterPlugin_iid "re.rizin.cutter.plugins.CutterPlugin"
Q_DECLARE_INTERFACE(CutterPlugin, CutterPlugin_iid)
#endif // CUTTERPLUGIN_H
| 1,366
|
C++
|
.h
| 43
| 27.093023
| 80
| 0.698933
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,694
|
CutterSamplePlugin.h
|
rizinorg_cutter/src/plugins/sample-cpp/CutterSamplePlugin.h
|
#ifndef CUTTERSAMPLEPLUGIN_H
#define CUTTERSAMPLEPLUGIN_H
#include <CutterPlugin.h>
#include <QLabel>
class CutterSamplePlugin : public QObject, CutterPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "re.rizin.cutter.plugins.CutterPlugin")
Q_INTERFACES(CutterPlugin)
public:
void setupPlugin() override;
void setupInterface(MainWindow *main) override;
QString getName() const override { return "SamplePlugin"; }
QString getAuthor() const override { return "xarkes"; }
QString getDescription() const override { return "Just a sample plugin."; }
QString getVersion() const override { return "1.0"; }
};
class CutterSamplePluginWidget : public CutterDockWidget
{
Q_OBJECT
public:
explicit CutterSamplePluginWidget(MainWindow *main);
private:
QLabel *text;
private slots:
void on_seekChanged(RVA addr);
void on_buttonClicked();
};
#endif // CUTTERSAMPLEPLUGIN_H
| 915
|
C++
|
.h
| 29
| 28.275862
| 79
| 0.761416
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,695
|
BaseFindDialog.h
|
rizinorg_cutter/src/tools/basefind/BaseFindDialog.h
|
#ifndef BASEFIND_DIALOG_H
#define BASEFIND_DIALOG_H
#include <QDialog>
#include <QListWidgetItem>
#include <memory>
#include <core/Cutter.h>
namespace Ui {
class BaseFindDialog;
}
class BaseFindDialog : public QDialog
{
Q_OBJECT
public:
explicit BaseFindDialog(QWidget *parent = nullptr);
~BaseFindDialog();
RzThreadNCores getNCores() const;
ut32 getPointerSize() const;
RVA getStartAddress() const;
RVA getEndAddress() const;
RVA getAlignment() const;
ut32 getMinStrLen() const;
ut32 getMinScore() const;
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
private:
std::unique_ptr<Ui::BaseFindDialog> ui;
};
#endif // BASEFIND_DIALOG_H
| 722
|
C++
|
.h
| 29
| 21.793103
| 55
| 0.747076
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,696
|
BaseFindSearchDialog.h
|
rizinorg_cutter/src/tools/basefind/BaseFindSearchDialog.h
|
#ifndef BASEFIND_SEARCH_DIALOG_H
#define BASEFIND_SEARCH_DIALOG_H
#include <QDialog>
#include <QListWidgetItem>
#include <QProgressBar>
#include <memory>
#include <core/Cutter.h>
namespace Ui {
class BaseFindSearchDialog;
}
class BaseFindSearchDialog : public QDialog
{
Q_OBJECT
public:
explicit BaseFindSearchDialog(QWidget *parent = nullptr);
~BaseFindSearchDialog();
void show(RzBaseFindOpt *opts);
public slots:
void onProgress(BasefindCoreStatusDescription status);
void onCompletion();
signals:
void cancelSearch();
private slots:
void on_buttonBox_rejected();
private:
std::vector<QProgressBar *> bars;
std::unique_ptr<Basefind> basefind;
std::unique_ptr<Ui::BaseFindSearchDialog> ui;
};
#endif // BASEFIND_SEARCH_DIALOG_H
| 785
|
C++
|
.h
| 30
| 23.333333
| 61
| 0.774194
|
rizinorg/cutter
| 15,656
| 1,143
| 512
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.