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