]> git.siccegge.de Git - frida/frida.git/blob - src/gui/widgets/BasicBlockWidget.cxx
ee3b7afc0048ead4a014630349187602ea61b2a4
[frida/frida.git] / src / gui / widgets / BasicBlockWidget.cxx
1 #include "BasicBlockWidget.hxx"
2 #include "gui/Mainwindow.hxx"
3 #include "gui/dialogs/SimpleStringDialog.hxx"
4 #include "core/BasicBlock.hxx"
5 #include "core/Function.hxx"
6 #include "core/Comment.hxx"
7 #include "disassembler/Instruction.hxx"
8 #include "core/InformationManager.hxx"
9 #include "core/events/RenameFunctionEvent.hxx"
10 #include "core/events/ChangeCommentEvent.hxx"
11 #include <algorithm>
12
13 class CustomQGraphicsTextItem : public QObject, public QGraphicsTextItem {
14 public:
15 CustomQGraphicsTextItem(const QString& text, BasicBlockWidget* parent)
16 : QGraphicsTextItem(text, parent), parent(parent) {}
17 void contextMenuEvent(QGraphicsSceneContextMenuEvent*);
18
19 void adjustSize();
20 private:
21 void addComment(int row, bool global);
22
23 BasicBlockWidget* parent;
24 };
25
26 void CustomQGraphicsTextItem::addComment(int row, bool global) {
27 SimpleStringDialog dialog(global ? "Global comment" : "Local comment");
28 int result = dialog.exec();
29 uint64_t address = parent->instructions[row].getAddress();
30 if (QDialog::Accepted == result) {
31 Comment* comment;
32 if (global) {
33 comment = parent->block->getManager()->newGlobalComment(address);
34 } else {
35 /* TODO: 0x23 as we currently don't have the function here
36 * and setting it to null will make the comment appear
37 * global. Also means local comments are largely still
38 * broken.
39 */
40 comment = parent->block->getManager()->newLocalComment(address, (Function*)0x23);
41 }
42 comment->setText(dialog.result().toStdString());
43 parent->block->getManager()->finishComment(comment);
44 } else {
45 LOG4CXX_DEBUG(parent->logger, "addComment aborted");
46 }
47 }
48
49 void CustomQGraphicsTextItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) {
50 QTextCursor c = textCursor();
51 c.setPosition(document()->documentLayout()->hitTest(event->pos(), Qt::FuzzyHit));
52 c.select(QTextCursor::WordUnderCursor);
53
54 QMenu menu;
55 bool ok;
56 uint64_t address = c.selectedText().toLongLong(&ok, 16);
57 if (ok) {
58 QAction* act = menu.addAction(c.selectedText() + " is a Function");
59 QObject::connect(act, &QAction::triggered,
60 [=]() {parent->mainwindow->requestNewFunctionByAddress(address);});
61 }
62
63 QTextTable* table = c.currentTable();
64 if (NULL != table) {
65 int row = table->cellAt(c).row();
66 QAction* globalComment = menu.addAction("Add global Comment");
67 QAction* localComment = menu.addAction("Add local Comment");
68
69 QObject::connect(globalComment, &QAction::triggered,
70 [=]() { addComment(row, true); });
71 QObject::connect(localComment, &QAction::triggered,
72 [=]() { addComment(row, false); });
73 }
74
75 menu.exec(event->screenPos());
76 }
77
78 /* QGraphicsTextItem has an adjustSize() function that is supposed to
79 * resize the widget to it's "ideal" size. However it totally ignores
80 * all directives to not wrap lines and "ideal" is actually just a
81 * bunch of heuristics.
82 *
83 * We are starting with a hopefully absurdly large startingwidth and
84 * reduce it untill a line is broken (detected by a change in
85 * height). As long as the width (1000 here) is sufficiently large,
86 * this should give us a widget without any line-wrapping.
87 *
88 * One needs to call this on a Pointer of tye CustomQGraphicsTextItem
89 * as the adjustSize() function is not polymorphic (vurtual).
90 */
91 void CustomQGraphicsTextItem::adjustSize() {
92 int width = 1000;
93 setTextWidth(width);
94 int height = boundingRect().height();
95 while (width > 250 && height == boundingRect().height()) {
96 setTextWidth(width -= 10);
97 }
98 width += 10;
99 if (width < 250) width = 250;
100 setTextWidth(width);
101 }
102
103 BasicBlockWidget::BasicBlockWidget(const QString& name, BasicBlock * block,
104 Mainwindow * mainwindow)
105 : width(200), height(45), name(name)
106 , _table(NULL)
107 , block(block), mainwindow(mainwindow)
108 , logger(log4cxx::Logger::getLogger("gui.BasicBlockWidget." + name.toStdString())) {
109 next[0] = NULL; next[1] = NULL;
110
111 block->getManager()->registerRenameFunctionEvent([=](RenameFunctionEvent* event) {updateFunctionName(event);});
112
113 _widget.reset(new CustomQGraphicsTextItem("", this));
114 _widget->setPos(5, 20);
115 _widget->setTextInteractionFlags(Qt::TextSelectableByMouse|
116 Qt::LinksAccessibleByMouse);
117
118 if (width < 250) width = 250;
119
120 QObject::connect(_widget.get(), &QGraphicsTextItem::linkActivated,
121 [=](QString str) {
122 if (str.startsWith("function:")) {
123 QString address = str.remove("function:");
124 mainwindow->switchMainPlaneToAddress(address.toInt(NULL, 16));
125 }
126 });
127 instructions = block->getInstructions();
128 populateWidget();
129 block->getManager()->registerChangeCommentEvent([=](ChangeCommentEvent* e) {changeCommentHandler(e);});
130 }
131
132 void BasicBlockWidget::updateFunctionName(RenameFunctionEvent *event) {
133 QString search = QString("function:") + QString::number(event->address, 16);
134 QTextDocument *document = _widget->document();
135 QTextBlock b = document->begin();
136 while (b.isValid()) {
137 for (QTextBlock::iterator i = b.begin(); !i.atEnd(); ++i) {
138 QTextCharFormat format = i.fragment().charFormat();
139 bool isLink = format.isAnchor();
140 if (isLink)
141 {
142 if (search == format.anchorHref()) {
143 LOG4CXX_DEBUG(logger, i.fragment().text().toStdString() << " ---> "
144 << format.anchorHref().toStdString());
145
146 /* This should select the function name. It stars
147 * by selecting the whole link fragment from back
148 * to front and then moves one word to the back
149 * again deselecting whatever mnemonic is used for
150 * the call instruction.
151 */
152 QTextCursor c(b);
153 c.setPosition(i.fragment().position());
154 c.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, i.fragment().length());
155 c.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, i.fragment().length());
156 c.movePosition(QTextCursor::WordRight, QTextCursor::KeepAnchor);
157 c.insertText(event->new_name.c_str());
158
159 QGraphicsTextItem* item = _widget.get();
160 ((CustomQGraphicsTextItem*)item)->adjustSize();
161 }
162 }
163 }
164 b = b.next();
165 }
166 }
167
168 void BasicBlockWidget::changeCommentHandler(ChangeCommentEvent* event) {
169 auto inst_it = std::find_if(instructions.begin(), instructions.end(),
170 [=](Instruction& inst) {
171 return inst.getAddress() == event->address;
172 });
173 if (inst_it != instructions.end()) {
174 if (std::find(inst_it->comments().begin(),
175 inst_it->comments().begin(),
176 event->comment) == inst_it->comments().end()) {
177 LOG4CXX_DEBUG(logger, "Change Comment Event -- New Comment!");
178 inst_it->comments().push_back(event->comment);
179 }
180 int row = inst_it - instructions.begin();
181 LOG4CXX_DEBUG(logger, "Inserting comment for instruction at row " << std::hex << row);
182 QTextCursor cursor = _table->cellAt(row, 2).lastCursorPosition();
183 while (cursor != _table->cellAt(row, 2).firstCursorPosition()) {
184 cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, 1);
185 }
186 cursor.removeSelectedText();
187 cursor.insertHtml(formatComments(&*inst_it));
188 QGraphicsTextItem* item = _widget.get();
189 ((CustomQGraphicsTextItem*)item)->adjustSize();
190 }
191 }
192
193 void BasicBlockWidget::populateWidget() {
194 int row;
195 QTextTableFormat format;
196 format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
197 format.setBorder(0);
198
199 for (Instruction& inst : instructions) {
200 if (_table) {
201 row = _table->rows();
202 _table->appendRows(1);
203 } else {
204 row = 0;
205 _table = _widget->textCursor().insertTable(1, 3, format);
206 }
207 QString bytestring;
208 for (uint8_t byte : inst.getBytes()) {
209 const char * hexdigits = "0123456789ABCDEF";
210 bytestring += hexdigits[(byte >> 4) & 0xF];
211 bytestring += hexdigits[byte & 0xF];
212 bytestring += ' ';
213 }
214 _table->cellAt(row, 0).firstCursorPosition().insertHtml("<nobr>" + bytestring + "</nobr>");
215
216 QString line = inst.getText().c_str();
217 line = line.replace('\t', ' ').toHtmlEscaped();
218 if (inst.getReference() != "") {
219 QString href = inst.getReference().c_str();
220 QStringList list = href.split(":");
221 if (list[0] == "function") {
222 uint64_t address = href.split(":")[1].toLongLong(NULL, 16);
223 Function* fun = block->getManager()->getFunction(address);
224
225 if (fun) {
226 line = line.split(" ")[0] + " " + QString(fun->getName().c_str()).toHtmlEscaped();
227 LOG4CXX_DEBUG(logger, "Naming function at " << address << " " << fun->getName());
228 }
229 }
230 line = "<a href=\"" + href + "\">" + line + "</a>";
231 }
232 _table->cellAt(row, 1).firstCursorPosition().insertHtml("<nobr>" + line + "</nobr>");
233 _table->cellAt(row, 2).firstCursorPosition().insertHtml(formatComments(&inst));
234 }
235 QGraphicsTextItem* item = _widget.get();
236 ((CustomQGraphicsTextItem*)item)->adjustSize();
237 }
238
239 QString BasicBlockWidget::formatComments(Instruction* inst) {
240 QString comments;
241 for (Comment* c: inst->comments()) {
242 comments += "<br />";
243 comments += QString(c->getText().c_str()).toHtmlEscaped();
244 }
245 return (comments == "" ? "" : ";; ") + comments.trimmed();
246 }
247
248 void BasicBlockWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem*,
249 QWidget*) {
250 width = 10 + _widget->boundingRect().width();
251 height = 25 + _widget->boundingRect().height();
252 if (width < 250) width = 250;
253
254 painter->fillRect(0, 0, width, height, QColor(0xcc, 0xcc, 0xff, 0xff));
255 painter->setPen(QColor(0x00, 0x00, 0xff, 0xff));
256 painter->drawRect(0, 0, width, height);
257 painter->drawText(5, 15, name);
258 }
259
260 QRectF BasicBlockWidget::boundingRect() const {
261 qreal penWidth = 1;
262 QRectF result(- penWidth / 2, - penWidth / 2,
263 width + penWidth, height + penWidth);
264 return result;
265 }
266
267 std::array<QPointF, 3> BasicBlockWidget::getExits() const {
268 return { { mapToScene(QPointF( width/3, height)),
269 mapToScene(QPointF( width/2, height)),
270 mapToScene(QPointF(2*width/3, height)) } };
271 }
272