Debian Codegraph @

Source/Core/DolphinQt/Debugger/MemoryViewWidget.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinQt/Debugger/MemoryViewWidget.h"
5
6 #include <bit>
7 #include <cmath>
8
9 #include <QApplication>
10 #include <QClipboard>
11 #include <QColorDialog>
12 #include <QHBoxLayout>
13 #include <QHeaderView>
14 #include <QLineEdit>
15 #include <QMenu>
16 #include <QMouseEvent>
17 #include <QScrollBar>
18 #include <QStyledItemDelegate>
19 #include <QTableWidget>
20 #include <QtGlobal>
21
22 #include "Common/Align.h"
23 #include "Common/BitUtils.h"
24 #include "Common/StringUtil.h"
25 #include "Common/Swap.h"
26 #include "Core/Core.h"
27 #include "Core/HW/AddressSpace.h"
28 #include "Core/PowerPC/BreakPoints.h"
29 #include "Core/PowerPC/PPCSymbolDB.h"
30 #include "Core/PowerPC/PowerPC.h"
31 #include "Core/System.h"
32 #include "DolphinQt/Debugger/EditSymbolDialog.h"
33 #include "DolphinQt/Host.h"
34 #include "DolphinQt/Resources.h"
35 #include "DolphinQt/Settings.h"
36
37 // "Most mouse types work in steps of 15 degrees, in which case the delta value is a multiple of
38 // 120; i.e., 120 units * 1/8 = 15 degrees." (http://doc.qt.io/qt-5/qwheelevent.html#angleDelta)
39 constexpr double SCROLL_FRACTION_DEGREES = 15.;
40
41 // Number of columns that don't contain the value of a memory address.
42 constexpr int MISC_COLUMNS = 2;
43 constexpr auto USER_ROLE_IS_ROW_BREAKPOINT_CELL = Qt::UserRole;
44 constexpr auto USER_ROLE_CELL_ADDRESS = Qt::UserRole + 1;
45 constexpr auto USER_ROLE_VALUE_TYPE = Qt::UserRole + 2;
46 constexpr auto USER_ROLE_VALID_ADDRESS = Qt::UserRole + 3;
47
48 // Numbers for the scrollbar. These affect how much big the draggable part of the scrollbar is, how
49 // smooth it scrolls, and how much memory it traverses while dragging.
50 constexpr int SCROLLBAR_MINIMUM = 0;
51 constexpr int SCROLLBAR_PAGESTEP = 250;
52 constexpr int SCROLLBAR_MAXIMUM = 20000;
53 constexpr int SCROLLBAR_CENTER = SCROLLBAR_MAXIMUM / 2;
54
55 const QString INVALID_MEMORY = QStringLiteral("-");
56
57 void TableEditDelegate::setModelData(QWidget* editor, QAbstractItemModel* model,
58 const QModelIndex& index) const
59 {
60 // Triggers on placing data into a cell. Editor has the text to be input, index has the location.
61 const QString input = qobject_cast<QLineEdit*>(editor)->text();
62 emit editFinished(index.row(), index.column(), input);
63 }
64
65 class MemoryViewTable final : public QTableWidget
66 {
67 public:
68 explicit MemoryViewTable(MemoryViewWidget* parent) : QTableWidget(parent), m_view(parent)
69 {
70 horizontalHeader()->hide();
71 verticalHeader()->hide();
72 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
73 setShowGrid(false);
74 setContextMenuPolicy(Qt::CustomContextMenu);
75 // Selection will be set programmatically. User will still get an outline on clicked items.
76 setSelectionMode(NoSelection);
77 setTextElideMode(Qt::TextElideMode::ElideNone);
78
79 // Route user's direct cell inputs to an editFinished signal. Much better than an itemChanged
80 // signal and QSignalBlock juggling.
81 TableEditDelegate* table_edit_delegate = new TableEditDelegate(this);
82 setItemDelegate(table_edit_delegate);
83
84 // Prevent colors from changing based on focus.
85 QPalette palette(m_view->palette());
86 palette.setBrush(QPalette::Inactive, QPalette::Highlight, palette.brush(QPalette::Highlight));
87 palette.setBrush(QPalette::Inactive, QPalette::HighlightedText,
88 palette.brush(QPalette::HighlightedText));
89 setPalette(palette);
90
91 setRowCount(30);
92 setColumnCount(8);
93
94 connect(this, &MemoryViewTable::customContextMenuRequested, m_view,
95 &MemoryViewWidget::OnContextMenu);
96 connect(table_edit_delegate, &TableEditDelegate::editFinished, this,
97 &MemoryViewTable::OnDirectTableEdit);
98 }
99
100 void resizeEvent(QResizeEvent* event) override
101 {
102 QTableWidget::resizeEvent(event);
103 // Remakes table if vertically resized
104 const int rows = std::round((height() / static_cast<float>(rowHeight(0))) - 0.25);
105 if (rows != rowCount())
106 m_view->UpdateDispatcher(MemoryViewWidget::UpdateType::Full);
107 }
108
109 void keyPressEvent(QKeyEvent* event) override
110 {
111 switch (event->key())
112 {
113 case Qt::Key_Up:
114 m_view->m_address -= m_view->m_bytes_per_row;
115 break;
116 case Qt::Key_Down:
117 m_view->m_address += m_view->m_bytes_per_row;
118 break;
119 case Qt::Key_PageUp:
120 m_view->m_address -= this->rowCount() * m_view->m_bytes_per_row;
121 break;
122 case Qt::Key_PageDown:
123 m_view->m_address += this->rowCount() * m_view->m_bytes_per_row;
124 break;
125 case Qt::Key_G:
126 if (event->modifiers() == Qt::ControlModifier)
127 {
128 m_view->TriggerActivateSearch();
129 }
130 default:
131 QWidget::keyPressEvent(event);
132 return;
133 }
134 m_view->UpdateDispatcher(MemoryViewWidget::UpdateType::Addresses);
135 }
136
137 void wheelEvent(QWheelEvent* event) override
138 {
139 auto delta =
140 -static_cast<int>(std::round((event->angleDelta().y() / (SCROLL_FRACTION_DEGREES * 8))));
141
142 if (delta == 0)
143 return;
144
145 m_view->m_address += delta * m_view->m_bytes_per_row;
146 m_view->UpdateDispatcher(MemoryViewWidget::UpdateType::Addresses);
147 }
148
149 void mousePressEvent(QMouseEvent* event) override
150 {
151 if (event->button() != Qt::LeftButton)
152 return;
153
154 auto* item = this->itemAt(event->pos());
155 if (!item)
156 return;
157
158 if (item->data(USER_ROLE_IS_ROW_BREAKPOINT_CELL).toBool())
159 {
160 const u32 address = item->data(USER_ROLE_CELL_ADDRESS).toUInt();
161 m_view->ToggleBreakpoint(address, true);
162 }
163 else
164 {
165 QTableWidget::mousePressEvent(event);
166 }
167 }
168
169 void OnDirectTableEdit(const int row, const int column, const QString& text)
170 {
171 QTableWidgetItem* item = this->item(row, column);
172 MemoryViewWidget::Type type =
173 static_cast<MemoryViewWidget::Type>(item->data(USER_ROLE_VALUE_TYPE).toInt());
174 std::vector<u8> bytes = m_view->ConvertTextToBytes(type, text);
175
176 u32 address = item->data(USER_ROLE_CELL_ADDRESS).toUInt();
177 u32 end_address = address + static_cast<u32>(bytes.size()) - 1;
178 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(m_view->GetAddressSpace());
179 {
180 const Core::CPUThreadGuard guard(m_view->m_system);
181
182 if (!bytes.empty() && accessors->IsValidAddress(guard, address) &&
183 accessors->IsValidAddress(guard, end_address))
184 {
185 for (const u8 c : bytes)
186 accessors->WriteU8(guard, address++, c);
187 }
188 }
189
190 m_view->UpdateDispatcher(MemoryViewWidget::UpdateType::Values);
191 }
192
193 private:
194 MemoryViewWidget* m_view;
195 };
196
197 MemoryViewWidget::MemoryViewWidget(Core::System& system, QWidget* parent)
198 : QWidget(parent), m_system(system), m_ppc_symbol_db(m_system.GetPPCSymbolDB())
199 {
200 auto* layout = new QHBoxLayout();
201 layout->setContentsMargins(0, 0, 0, 0);
202
203 m_table = new MemoryViewTable(this);
204 layout->addWidget(m_table);
205
206 // Since the Memory View is infinitely long -- it wraps around -- we can't use a normal scroll
207 // bar, so this initializes a custom one that is always centered but otherwise still behaves more
208 // or less like a regular scrollbar.
209 m_scrollbar = new QScrollBar(this);
210 m_scrollbar->setRange(SCROLLBAR_MINIMUM, SCROLLBAR_MAXIMUM);
211 m_scrollbar->setPageStep(SCROLLBAR_PAGESTEP);
212 m_scrollbar->setValue(SCROLLBAR_CENTER);
213 connect(m_scrollbar, &QScrollBar::actionTriggered, this,
214 &MemoryViewWidget::ScrollbarActionTriggered);
215 connect(m_scrollbar, &QScrollBar::sliderReleased, this,
216 &MemoryViewWidget::ScrollbarSliderReleased);
217 layout->addWidget(m_scrollbar);
218
219 this->setLayout(layout);
220
221 connect(&Settings::Instance(), &Settings::DebugFontChanged, this, &MemoryViewWidget::UpdateFont);
222 connect(Host::GetInstance(), &Host::PPCSymbolsChanged, this,
223 [this] { UpdateDispatcher(UpdateType::Symbols); });
224 connect(Host::GetInstance(), &Host::PPCBreakpointsChanged, this,
225 &MemoryViewWidget::UpdateBreakpointTags);
226 connect(&Settings::Instance(), &Settings::EmulationStateChanged, this, [this] {
227 // UpdateDisasmDialog currently catches pauses, no need to signal it twice.
228 if (Core::GetState(m_system) != Core::State::Paused)
229 UpdateDispatcher(UpdateType::Values);
230 });
231 connect(Host::GetInstance(), &Host::UpdateDisasmDialog, this, [this] {
232 // Disasm spam will break updates while running. Only need it for things like steps when paused
233 // and breaks which trigger a pause.
234 if (Core::GetState(m_system) != Core::State::Running)
235 UpdateDispatcher(UpdateType::Values);
236 });
237
238 // CPU Thread to Main Thread.
239 connect(this, &MemoryViewWidget::AutoUpdate, this,
240 [this] { UpdateDispatcher(UpdateType::Auto); });
241 connect(&Settings::Instance(), &Settings::ThemeChanged, this,
242 [this] { UpdateDispatcher(UpdateType::Full); });
243
244 // Also calls create table.
245 UpdateFont(Settings::Instance().GetDebugFont());
246 }
247
248 void MemoryViewWidget::UpdateFont(const QFont& font)
249 {
250 const QFontMetrics fm(font);
251 m_font_vspace = fm.lineSpacing() + 4;
252 // BoundingRect is too unpredictable, a custom one would be needed for each view type. Different
253 // fonts have wildly different spacing between two characters and horizontalAdvance includes
254 // spacing.
255 m_font_width = fm.horizontalAdvance(QLatin1Char('0'));
256 m_table->setFont(font);
257
258 UpdateDispatcher(UpdateType::Full);
259 }
260
261 void MemoryViewWidget::TriggerActivateSearch()
262 {
263 emit ActivateSearch();
264 }
265
266 constexpr int GetTypeSize(MemoryViewWidget::Type type)
267 {
268 switch (type)
269 {
270 case MemoryViewWidget::Type::ASCII:
271 case MemoryViewWidget::Type::Hex8:
272 case MemoryViewWidget::Type::Unsigned8:
273 case MemoryViewWidget::Type::Signed8:
274 return 1;
275 case MemoryViewWidget::Type::Unsigned16:
276 case MemoryViewWidget::Type::Signed16:
277 case MemoryViewWidget::Type::Hex16:
278 return 2;
279 case MemoryViewWidget::Type::Hex32:
280 case MemoryViewWidget::Type::Unsigned32:
281 case MemoryViewWidget::Type::Signed32:
282 case MemoryViewWidget::Type::Float32:
283 return 4;
284 case MemoryViewWidget::Type::Double:
285 case MemoryViewWidget::Type::Hex64:
286 return 8;
287 default:
288 return 1;
289 }
290 }
291
292 constexpr int GetCharacterCount(MemoryViewWidget::Type type)
293 {
294 // Max number of characters +1 for spacing between columns.
295 switch (type)
296 {
297 case MemoryViewWidget::Type::ASCII: // A
298 return 2;
299 case MemoryViewWidget::Type::Hex8: // Byte = FF
300 return 3;
301 case MemoryViewWidget::Type::Unsigned8: // UCHAR_MAX = 255
302 return 4;
303 case MemoryViewWidget::Type::Hex16: // 2 Bytes = FFFF
304 case MemoryViewWidget::Type::Signed8: // CHAR_MIN = -128
305 return 5;
306 case MemoryViewWidget::Type::Unsigned16: // USHORT_MAX = 65535
307 return 6;
308 case MemoryViewWidget::Type::Signed16: // SHORT_MIN = -32768
309 return 7;
310 case MemoryViewWidget::Type::Hex32: // 4 Bytes = FFFFFFFF
311 return 9;
312 case MemoryViewWidget::Type::Float32: // Rounded and Negative FLT_MAX = -3.403e+38
313 case MemoryViewWidget::Type::Unsigned32: // UINT_MAX = 4294967295
314 return 11;
315 case MemoryViewWidget::Type::Double: // Rounded and Negative DBL_MAX = -1.798e+308
316 case MemoryViewWidget::Type::Signed32: // INT_MIN = -2147483648
317 return 12;
318 case MemoryViewWidget::Type::Hex64: // For dual_view + Double. 8 Bytes = FFFFFFFFFFFFFFFF
319 return 17;
320 default:
321 return 10;
322 }
323 }
324
325 void MemoryViewWidget::UpdateDispatcher(UpdateType type)
326 {
327 std::unique_lock lock(m_updating, std::defer_lock);
328
329 // A full update may change parameters like row count, so make sure it goes through.
330 if (type == UpdateType::Full)
331 lock.lock();
332 else if (!isVisible() || !lock.try_lock())
333 return;
334
335 // Check if table needs to be created.
336 if (m_table->item(2, 1) == nullptr)
337 type = UpdateType::Full;
338
339 switch (type)
340 {
341 case UpdateType::Full:
342 CreateTable();
343 [[fallthrough]];
344 case UpdateType::Addresses:
345 Update();
346 [[fallthrough]];
347 case UpdateType::Values:
348 if (Core::GetState(m_system) == Core::State::Paused)
349 GetValues();
350 UpdateColumns();
351 [[fallthrough]];
352 case UpdateType::Symbols:
353 UpdateSymbols();
354 break;
355 case UpdateType::Auto:
356 // Values were captured on CPU thread while doing a callback.
357 if (m_values.size() != 0)
358 UpdateColumns();
359 default:
360 break;
361 }
362 }
363
364 void MemoryViewWidget::CreateTable()
365 {
366 m_table->clearContents();
367
368 // This sets all row heights and determines horizontal ascii spacing.
369 // Could be placed in UpdateFont() but doesn't apply correctly unless called more.
370 m_table->verticalHeader()->setDefaultSectionSize(m_font_vspace);
371 m_table->verticalHeader()->setMinimumSectionSize(m_font_vspace);
372 m_table->horizontalHeader()->setMinimumSectionSize(m_font_width * 2);
373
374 // Set column and row parameters.
375 // Span is the number of unique memory values covered in one row.
376 const int data_span = m_bytes_per_row / GetTypeSize(m_type);
377 m_data_columns = m_dual_view ? data_span * 2 : data_span;
378 const int total_columns = MISC_COLUMNS + m_data_columns + (m_show_symbols ? 1 : 0);
379
380 const int rows =
381 std::round((m_table->height() / static_cast<float>(m_table->rowHeight(0))) - 0.25);
382
383 m_table->setColumnCount(total_columns);
384 m_table->setRowCount(rows);
385 m_table->setColumnWidth(0, m_table->rowHeight(0));
386
387 // Get optional dual-view type
388 std::optional<Type> left_type = std::nullopt;
389
390 if (m_dual_view)
391 {
392 if (GetTypeSize(m_type) == 1)
393 left_type = Type::Hex8;
394 else if (GetTypeSize(m_type) == 2)
395 left_type = Type::Hex16;
396 else if (GetTypeSize(m_type) == 8)
397 left_type = Type::Hex64;
398 else
399 left_type = Type::Hex32;
400 }
401
402 // Create cells and add data that won't be changing.
403 // Breakpoint buttons
404 auto bp_item = QTableWidgetItem();
405 bp_item.setFlags(Qt::ItemIsEnabled);
406 bp_item.setData(USER_ROLE_IS_ROW_BREAKPOINT_CELL, true);
407 bp_item.setData(USER_ROLE_VALUE_TYPE, static_cast<int>(Type::Null));
408
409 // Row Addresses
410 auto row_item = QTableWidgetItem(INVALID_MEMORY);
411 row_item.setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
412 row_item.setData(USER_ROLE_IS_ROW_BREAKPOINT_CELL, false);
413 row_item.setData(USER_ROLE_VALUE_TYPE, static_cast<int>(Type::Null));
414
415 // Data item
416 auto item = QTableWidgetItem(INVALID_MEMORY);
417 item.setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
418 item.setData(USER_ROLE_IS_ROW_BREAKPOINT_CELL, false);
419
420 for (int i = 0; i < rows; i++)
421 {
422 m_table->setItem(i, 0, bp_item.clone());
423 m_table->setItem(i, 1, row_item.clone());
424
425 for (int c = 0; c < m_data_columns; c++)
426 {
427 if (left_type && c < data_span)
428 {
429 item.setData(USER_ROLE_VALUE_TYPE, static_cast<int>(left_type.value()));
430 }
431 else
432 {
433 item.setData(USER_ROLE_VALUE_TYPE, static_cast<int>(m_type));
434
435 // Left type will never be these.
436 auto text_alignment = Qt::AlignLeft;
437 if (m_type == Type::Signed32 || m_type == Type::Unsigned32 || m_type == Type::Signed16 ||
438 m_type == Type::Unsigned16 || m_type == Type::Signed8 || m_type == Type::Unsigned8)
439 {
440 text_alignment = Qt::AlignRight;
441 }
442 item.setTextAlignment(text_alignment | Qt::AlignVCenter);
443 }
444
445 m_table->setItem(i, c + MISC_COLUMNS, item.clone());
446 }
447
448 if (!m_show_symbols)
449 continue;
450
451 // Symbols
452 auto* description_item = new QTableWidgetItem(QStringLiteral("-"));
453 description_item->setFlags(Qt::ItemIsEnabled);
454
455 m_table->setItem(i, m_table->columnCount() - 1, description_item);
456 }
457
458 // Update column width
459 int start_fill = MISC_COLUMNS;
460 if (left_type)
461 {
462 const int width_left = m_font_width * GetCharacterCount(left_type.value());
463
464 for (int i = 0; i < data_span - 1; i++)
465 m_table->setColumnWidth(i + start_fill, width_left);
466
467 // Extra spacing between dual views.
468 m_table->setColumnWidth(start_fill + data_span - 1, width_left + m_font_width * 2);
469
470 start_fill += data_span;
471 }
472
473 // If dual-view, updates the right-side columns only.
474 const int width = m_font_width * GetCharacterCount(m_type);
475 for (int i = start_fill; i < total_columns; i++)
476 m_table->setColumnWidth(i, width);
477 }
478
479 void MemoryViewWidget::Update()
480 {
481 m_table->clearSelection();
482
483 // Update addresses
484 const u32 address = Common::AlignDown(m_address, m_alignment);
485 u32 row_address = address - (m_table->rowCount() / 2) * m_bytes_per_row;
486 const int data_span = m_bytes_per_row / GetTypeSize(m_type);
487
488 m_address_range.first = row_address;
489 m_address_range.second = row_address + m_table->rowCount() * m_bytes_per_row;
490
491 for (int i = 0; i < m_table->rowCount(); i++, row_address += m_bytes_per_row)
492 {
493 auto* bp_item = m_table->item(i, 0);
494 bp_item->setData(USER_ROLE_CELL_ADDRESS, row_address);
495
496 auto* row_item = m_table->item(i, 1);
497 row_item->setText(QStringLiteral("%1").arg(row_address, 8, 16, QLatin1Char('0')));
498 row_item->setData(USER_ROLE_CELL_ADDRESS, row_address);
499
500 for (int c = 0; c < m_data_columns; c++)
501 {
502 auto* item = m_table->item(i, c + MISC_COLUMNS);
503
504 u32 item_address;
505 if (m_dual_view && c >= data_span)
506 item_address = row_address + (c - data_span) * GetTypeSize(m_type);
507 else
508 item_address = row_address + c * GetTypeSize(m_type);
509
510 item->setData(USER_ROLE_CELL_ADDRESS, item_address);
511
512 // Reset highlighting.
513 item->setBackground(Qt::transparent);
514 item->setData(USER_ROLE_VALID_ADDRESS, false);
515 }
516
517 if (m_show_symbols)
518 m_table->item(i, m_table->columnCount() - 1)->setData(USER_ROLE_CELL_ADDRESS, row_address);
519 }
520
521 UpdateBreakpointTags();
522 }
523
524 void MemoryViewWidget::UpdateColumns()
525 {
526 for (int i = 0; i < m_table->rowCount(); i++)
527 {
528 for (int c = 0; c < m_data_columns; c++)
529 {
530 auto* cell_item = m_table->item(i, c + MISC_COLUMNS);
531 if (!cell_item)
532 return;
533
534 const u32 cell_address = cell_item->data(USER_ROLE_CELL_ADDRESS).toUInt();
535 const Type type = static_cast<Type>(cell_item->data(USER_ROLE_VALUE_TYPE).toInt());
536 std::optional<QString> new_text;
537
538 // Dual view auto sets the type of the left-side based on m_type. Only time type and
539 // m_type differ.
540 if (type != m_type)
541 {
542 new_text = m_values_dual_view.empty() || !m_values_dual_view.contains(cell_address) ?
543 std::nullopt :
544 m_values_dual_view.at(cell_address);
545 }
546 else
547 {
548 new_text = m_values.empty() || !m_values.contains(cell_address) ? std::nullopt :
549 m_values.at(cell_address);
550 }
551
552 // Set search address to selected / colored
553 if (cell_address == m_address_highlight)
554 cell_item->setSelected(true);
555
556 // Color recently changed items.
557 QColor bcolor = cell_item->background().color();
558 const bool valid = cell_item->data(USER_ROLE_VALID_ADDRESS).toBool();
559
560 // It gets a bit complicated, because invalid addresses becoming valid should not be
561 // colored.
562 if (!new_text.has_value())
563 {
564 cell_item->setBackground(Qt::transparent);
565 cell_item->setData(USER_ROLE_VALID_ADDRESS, false);
566 cell_item->setText(INVALID_MEMORY);
567 }
568 else if (!valid)
569 {
570 // Wasn't valid on last update, is valid now.
571 cell_item->setData(USER_ROLE_VALID_ADDRESS, true);
572 cell_item->setText(new_text.value());
573 }
574 else if (bcolor.rgb() != m_highlight_color.rgb() && bcolor != Qt::transparent)
575 {
576 // Filter out colors that shouldn't change, such as breakpoints.
577 cell_item->setText(new_text.value());
578 }
579 else if (cell_item->text() != new_text.value())
580 {
581 // Cell changed, apply highlighting.
582 cell_item->setBackground(m_highlight_color);
583 cell_item->setText(new_text.value());
584 }
585 else if (bcolor.alpha() > 0)
586 {
587 // Fade out highlighting each frame.
588 bcolor.setAlpha(bcolor.alpha() - 1);
589 cell_item->setBackground(bcolor);
590 }
591 }
592 }
593 }
594
595 void MemoryViewWidget::UpdateSymbols()
596 {
597 if (!m_show_symbols)
598 return;
599
600 // Update symbols
601 for (int i = 0; i < m_table->rowCount(); i++)
602 {
603 auto* item = m_table->item(i, m_table->columnCount() - 1);
604 if (!item)
605 continue;
606
607 const u32 address = item->data(USER_ROLE_CELL_ADDRESS).toUInt();
608 const Common::Note* note = m_ppc_symbol_db.GetNoteFromAddr(address);
609
610 std::string desc;
611 if (note == nullptr)
612 desc = m_ppc_symbol_db.GetDescription(address);
613 else
614 desc = note->name;
615
616 item->setText(QString::fromStdString(" " + desc));
617 }
618
619 if (m_show_symbols)
620 m_table->resizeColumnToContents(m_table->columnCount() - 1);
621 }
622
623 // Always runs on CPU thread from a callback.
624 void MemoryViewWidget::UpdateOnFrameEnd()
625 {
626 std::unique_lock lock(m_updating, std::try_to_lock);
627 if (lock)
628 {
629 GetValues();
630 // Should not directly trigger widget updates on a cpu thread. Signal main thread to do it.
631 emit AutoUpdate();
632 }
633 }
634
635 void MemoryViewWidget::GetValues()
636 {
637 m_values.clear();
638 m_values_dual_view.clear();
639
640 // Check for dual view type
641 Type type = Type::Null;
642
643 if (m_dual_view)
644 {
645 if (GetTypeSize(m_type) == 1)
646 type = Type::Hex8;
647 else if (GetTypeSize(m_type) == 2)
648 type = Type::Hex16;
649 else if (GetTypeSize(m_type) == 8)
650 type = Type::Hex64;
651 else
652 type = Type::Hex32;
653 }
654
655 // Grab memory values as QStrings
656 Core::CPUThreadGuard guard(m_system);
657
658 const u32 type_size = static_cast<u32>(GetTypeSize(m_type));
659 const auto& [range_begin, range_end] = m_address_range;
660 const u32 address_count = (range_end - range_begin) / type_size;
661
662 for (u32 i = 0; i < address_count; ++i)
663 {
664 const u32 address = range_begin + i * type_size;
665 m_values.insert(std::pair(address, ValueToString(guard, address, m_type)));
666
667 if (m_dual_view)
668 m_values_dual_view.insert(std::pair(address, ValueToString(guard, address, type)));
669 }
670 }
671
672 // May only be called if we have taken on the role of the CPU thread
673 std::optional<QString> MemoryViewWidget::ValueToString(const Core::CPUThreadGuard& guard,
674 u32 address, Type type)
675 {
676 const AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(m_address_space);
677 if (!accessors->IsValidAddress(guard, address))
678 return std::nullopt;
679
680 switch (type)
681 {
682 case Type::Hex8:
683 {
684 const u8 value = accessors->ReadU8(guard, address);
685 return QStringLiteral("%1").arg(value, 2, 16, QLatin1Char('0'));
686 }
687 case Type::ASCII:
688 {
689 const char value = accessors->ReadU8(guard, address);
690 return Common::IsPrintableCharacter(value) ? QString{QChar::fromLatin1(value)} :
691 QString{QChar::fromLatin1('.')};
692 }
693 case Type::Hex16:
694 {
695 const u16 value = accessors->ReadU16(guard, address);
696 return QStringLiteral("%1").arg(value, 4, 16, QLatin1Char('0'));
697 }
698 case Type::Hex32:
699 {
700 const u32 value = accessors->ReadU32(guard, address);
701 return QStringLiteral("%1").arg(value, 8, 16, QLatin1Char('0'));
702 }
703 case Type::Hex64:
704 {
705 const u64 value = accessors->ReadU64(guard, address);
706 return QStringLiteral("%1").arg(value, 16, 16, QLatin1Char('0'));
707 }
708 case Type::Unsigned8:
709 return QString::number(accessors->ReadU8(guard, address));
710 case Type::Unsigned16:
711 return QString::number(accessors->ReadU16(guard, address));
712 case Type::Unsigned32:
713 return QString::number(accessors->ReadU32(guard, address));
714 case Type::Signed8:
715 return QString::number(std::bit_cast<s8>(accessors->ReadU8(guard, address)));
716 case Type::Signed16:
717 return QString::number(std::bit_cast<s16>(accessors->ReadU16(guard, address)));
718 case Type::Signed32:
719 return QString::number(std::bit_cast<s32>(accessors->ReadU32(guard, address)));
720 case Type::Float32:
721 {
722 QString string = QString::number(accessors->ReadF32(guard, address), 'g', 4);
723 // Align to first digit.
724 if (!string.startsWith(QLatin1Char('-')))
725 string.prepend(QLatin1Char(' '));
726
727 return string;
728 }
729 case Type::Double:
730 {
731 QString string =
732 QString::number(std::bit_cast<double>(accessors->ReadU64(guard, address)), 'g', 4);
733 // Align to first digit.
734 if (!string.startsWith(QLatin1Char('-')))
735 string.prepend(QLatin1Char(' '));
736
737 return string;
738 }
739 default:
740 return std::nullopt;
741 }
742 }
743
744 void MemoryViewWidget::UpdateBreakpointTags()
745 {
746 for (int i = 0; i < m_table->rowCount(); i++)
747 {
748 bool row_breakpoint = false;
749
750 for (int c = 0; c < m_data_columns; c++)
751 {
752 // Pull address from cell itself, helpful for dual column view.
753 auto cell = m_table->item(i, c + MISC_COLUMNS);
754 const u32 address = cell->data(USER_ROLE_CELL_ADDRESS).toUInt();
755
756 if (address == 0)
757 {
758 row_breakpoint = false;
759 continue;
760 }
761
762 if (m_address_space == AddressSpace::Type::Effective &&
763 m_system.GetPowerPC().GetMemChecks().GetMemCheck(address, GetTypeSize(m_type)) != nullptr)
764 {
765 row_breakpoint = true;
766 cell->setBackground(Qt::red);
767 }
768 else
769 {
770 cell->setBackground(Qt::transparent);
771 }
772 }
773
774 if (row_breakpoint)
775 {
776 m_table->item(i, 0)->setData(
777 Qt::DecorationRole,
778 Resources::GetThemeIcon("debugger_breakpoint")
779 .pixmap(QSize(m_table->rowHeight(0) - 3, m_table->rowHeight(0) - 3)));
780 }
781 else
782 {
783 m_table->item(i, 0)->setData(Qt::DecorationRole, QIcon());
784 }
785 }
786 }
787
788 void MemoryViewWidget::SetAddressSpace(AddressSpace::Type address_space)
789 {
790 if (m_address_space == address_space)
791 {
792 return;
793 }
794
795 m_address_space = address_space;
796 UpdateDispatcher(UpdateType::Addresses);
797 }
798
799 AddressSpace::Type MemoryViewWidget::GetAddressSpace() const
800 {
801 return m_address_space;
802 }
803
804 std::vector<u8> MemoryViewWidget::ConvertTextToBytes(Type type, QStringView input_text) const
805 {
806 if (type == Type::Null)
807 return {};
808
809 bool good = false;
810 int radix = 0;
811
812 switch (type)
813 {
814 case Type::ASCII:
815 {
816 const QByteArray qbytes = input_text.toUtf8();
817 std::vector<u8> bytes;
818
819 for (const char c : qbytes)
820 bytes.push_back(static_cast<u8>(c));
821
822 return bytes;
823 }
824 case Type::Float32:
825 {
826 const float float_value = input_text.toFloat(&good);
827
828 if (good)
829 {
830 const u32 value = std::bit_cast<u32>(float_value);
831 auto std_array = Common::BitCastToArray<u8>(Common::swap32(value));
832 return std::vector<u8>(std_array.begin(), std_array.end());
833 }
834 break;
835 }
836 case Type::Double:
837 {
838 const double double_value = input_text.toDouble(&good);
839
840 if (good)
841 {
842 const u64 value = std::bit_cast<u64>(double_value);
843 auto std_array = Common::BitCastToArray<u8>(Common::swap64(value));
844 return std::vector<u8>(std_array.begin(), std_array.end());
845 }
846 break;
847 }
848 case Type::Signed8:
849 {
850 const short value = input_text.toShort(&good, radix);
851 good &= std::numeric_limits<signed char>::min() <= value &&
852 value <= std::numeric_limits<signed char>::max();
853 if (good)
854 {
855 auto std_array = Common::BitCastToArray<u8>(Common::swap8(value));
856 return std::vector<u8>(std_array.begin(), std_array.end());
857 }
858 break;
859 }
860 case Type::Signed16:
861 {
862 const short value = input_text.toShort(&good, radix);
863 if (good)
864 {
865 auto std_array = Common::BitCastToArray<u8>(Common::swap16(value));
866 return std::vector<u8>(std_array.begin(), std_array.end());
867 }
868 break;
869 }
870 case Type::Signed32:
871 {
872 const int value = input_text.toInt(&good, radix);
873 if (good)
874 {
875 auto std_array = Common::BitCastToArray<u8>(Common::swap32(value));
876 return std::vector<u8>(std_array.begin(), std_array.end());
877 }
878 break;
879 }
880 case Type::Hex8:
881 radix = 16;
882 [[fallthrough]];
883 case Type::Unsigned8:
884 {
885 const unsigned short value = input_text.toUShort(&good, radix);
886 good &= (value & 0xFF00) == 0;
887 if (good)
888 {
889 auto std_array = Common::BitCastToArray<u8>(Common::swap8(value));
890 return std::vector<u8>(std_array.begin(), std_array.end());
891 }
892 break;
893 }
894 case Type::Hex16:
895 radix = 16;
896 [[fallthrough]];
897 case Type::Unsigned16:
898 {
899 const unsigned short value = input_text.toUShort(&good, radix);
900 if (good)
901 {
902 auto std_array = Common::BitCastToArray<u8>(Common::swap16(value));
903 return std::vector<u8>(std_array.begin(), std_array.end());
904 }
905 break;
906 }
907 case Type::Hex32:
908 radix = 16;
909 [[fallthrough]];
910 case Type::Unsigned32:
911 {
912 const u32 value = input_text.toUInt(&good, radix);
913 if (good)
914 {
915 auto std_array = Common::BitCastToArray<u8>(Common::swap32(value));
916 return std::vector<u8>(std_array.begin(), std_array.end());
917 }
918 break;
919 }
920 case Type::Hex64:
921 {
922 const u64 value = input_text.toULongLong(&good, 16);
923 if (good)
924 {
925 auto std_array = Common::BitCastToArray<u8>(Common::swap64(value));
926 return std::vector<u8>(std_array.begin(), std_array.end());
927 }
928 break;
929 }
930 case Type::HexString:
931 {
932 // Confirm it is only hex bytes
933 const QRegularExpression is_hex(QStringLiteral("^([0-9A-F]{2})*$"),
934 QRegularExpression::CaseInsensitiveOption);
935 #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
936 const QRegularExpressionMatch match = is_hex.matchView(input_text);
937 #else
938 const QRegularExpressionMatch match = is_hex.match(input_text);
939 #endif
940 good = match.hasMatch();
941 if (good)
942 {
943 const QByteArray qbytes = QByteArray::fromHex(input_text.toUtf8());
944 std::vector<u8> bytes;
945
946 for (const char c : qbytes)
947 bytes.push_back(static_cast<u8>(c));
948
949 return bytes;
950 }
951 break;
952 }
953 default:
954 // Do nothing
955 break;
956 }
957
958 return {};
959 }
960
961 void MemoryViewWidget::SetDisplay(Type type, int bytes_per_row, int alignment, bool dual_view)
962 {
963 m_type = type;
964 m_bytes_per_row = bytes_per_row;
965 m_dual_view = dual_view;
966 if (alignment == 0)
967 m_alignment = GetTypeSize(type);
968 else
969 m_alignment = alignment;
970
971 UpdateDispatcher(UpdateType::Full);
972 }
973
974 void MemoryViewWidget::ToggleHighlights(bool enabled)
975 {
976 // m_highlight_color should hold the current highlight color even when disabled, so it can
977 // be used if re-enabled. If modifying the enabled alpha, change in .h file as well.
978 if (enabled)
979 {
980 m_highlight_color.setAlpha(100);
981 }
982 else
983 {
984 // Treated as being interchangeable with Qt::transparent.
985 m_highlight_color.setAlpha(0);
986
987 // Immediately remove highlights when paused.
988 for (int i = 0; i < m_table->rowCount(); i++)
989 {
990 for (int c = 0; c < m_data_columns; c++)
991 m_table->item(i, c + MISC_COLUMNS)->setBackground(m_highlight_color);
992 }
993 }
994 }
995
996 void MemoryViewWidget::SetHighlightColor()
997 {
998 // Could allow custom alphas to be set, which would change fade-out rate.
999 QColor color = QColorDialog::getColor(m_highlight_color);
1000 if (!color.isValid())
1001 return;
1002
1003 const bool enabled = m_highlight_color.alpha() != 0;
1004 m_highlight_color = color;
1005 m_highlight_color.setAlpha(enabled ? 100 : 0);
1006 if (!enabled)
1007 return;
1008
1009 // Immediately update colors. Only useful for playing with colors while paused.
1010 for (int i = 0; i < m_table->rowCount(); i++)
1011 {
1012 for (int c = 0; c < m_data_columns; c++)
1013 {
1014 auto* item = m_table->item(i, c + MISC_COLUMNS);
1015 // Get current cell alpha state.
1016 color.setAlpha(item->background().color().alpha());
1017 m_table->item(i, c + MISC_COLUMNS)->setBackground(color);
1018 }
1019 }
1020 }
1021
1022 void MemoryViewWidget::SetBPType(BPType type)
1023 {
1024 m_bp_type = type;
1025 }
1026
1027 void MemoryViewWidget::SetAddress(u32 address)
1028 {
1029 m_address_highlight = address;
1030 if (m_address == address)
1031 return;
1032
1033 m_address = address;
1034
1035 UpdateDispatcher(UpdateType::Addresses);
1036 }
1037
1038 void MemoryViewWidget::SetBPLoggingEnabled(bool enabled)
1039 {
1040 m_do_log = enabled;
1041 }
1042
1043 void MemoryViewWidget::ToggleBreakpoint(u32 addr, bool row)
1044 {
1045 if (m_address_space != AddressSpace::Type::Effective)
1046 return;
1047
1048 const auto length = GetTypeSize(m_type);
1049 const int breaks = row ? (m_bytes_per_row / length) : 1;
1050 bool overlap = false;
1051
1052 auto& memchecks = m_system.GetPowerPC().GetMemChecks();
1053
1054 // Row breakpoint should either remove any breakpoint left on the row, or activate all
1055 // breakpoints.
1056 if (row && memchecks.OverlapsMemcheck(addr, m_bytes_per_row))
1057 overlap = true;
1058
1059 {
1060 const Core::CPUThreadGuard guard(m_system);
1061 DelayedMemCheckUpdate delayed_update(&memchecks);
1062
1063 for (int i = 0; i < breaks; i++)
1064 {
1065 u32 address = addr + length * i;
1066 TMemCheck* check_ptr = memchecks.GetMemCheck(address, length);
1067
1068 if (check_ptr == nullptr && !overlap)
1069 {
1070 TMemCheck check;
1071 check.start_address = address;
1072 check.end_address = check.start_address + length - 1;
1073 check.is_ranged = length > 0;
1074 check.is_break_on_read = (m_bp_type == BPType::ReadOnly || m_bp_type == BPType::ReadWrite);
1075 check.is_break_on_write =
1076 (m_bp_type == BPType::WriteOnly || m_bp_type == BPType::ReadWrite);
1077 check.log_on_hit = m_do_log;
1078 check.break_on_hit = true;
1079
1080 delayed_update |= memchecks.Add(std::move(check));
1081 }
1082 else if (check_ptr != nullptr)
1083 {
1084 // Using the pointer fixes misaligned breakpoints (0x11 breakpoint in 0x10 aligned view).
1085 delayed_update |= memchecks.Remove(check_ptr->start_address);
1086 }
1087 }
1088 }
1089
1090 emit Host::GetInstance()->PPCBreakpointsChanged();
1091 }
1092
1093 void MemoryViewWidget::OnCopyAddress(u32 addr)
1094 {
1095 QApplication::clipboard()->setText(QStringLiteral("%1").arg(addr, 8, 16, QLatin1Char('0')));
1096 }
1097
1098 void MemoryViewWidget::OnCopyHex(u32 addr)
1099 {
1100 const auto length = GetTypeSize(m_type);
1101
1102 const u64 value =
1103 AddressSpace::GetAccessors(m_address_space)->ReadU64(Core::CPUThreadGuard{m_system}, addr);
1104
1105 QApplication::clipboard()->setText(
1106 QStringLiteral("%1").arg(value, sizeof(u64) * 2, 16, QLatin1Char('0')).left(length * 2));
1107 }
1108
1109 void MemoryViewWidget::ShowSymbols(bool enable)
1110 {
1111 m_show_symbols = enable;
1112 UpdateDispatcher(UpdateType::Full);
1113 }
1114
1115 void MemoryViewWidget::OnEditSymbol(EditSymbolType type, u32 addr)
1116 {
1117 // Add Note and Add Region use these values.
1118 std::string name = "";
1119 std::string object_name = "";
1120 u32 size = GetTypeSize(m_type);
1121 u32 address = addr;
1122 EditSymbolDialog::Type dialog_type = EditSymbolDialog::Type::Note;
1123
1124 // Add and edit region are tied to the same context menu action.
1125 if (type == EditSymbolType::EditRegion)
1126 {
1127 // If symbol doesn't exist, it's safe to add a new region.
1128 const Common::Symbol* const symbol = m_ppc_symbol_db.GetSymbolFromAddr(addr);
1129 dialog_type = EditSymbolDialog::Type::Symbol;
1130
1131 if (symbol != nullptr)
1132 {
1133 // Leave the more specialized function editing to code widget.
1134 if (symbol->type != Common::Symbol::Type::Data)
1135 return;
1136
1137 // Edit data region.
1138 name = symbol->name;
1139 object_name = symbol->object_name;
1140 size = symbol->size;
1141 address = symbol->address;
1142 }
1143 }
1144 else if (type == EditSymbolType::EditNote)
1145 {
1146 const Common::Note* note = m_ppc_symbol_db.GetNoteFromAddr(addr);
1147 if (note == nullptr)
1148 return;
1149
1150 name = note->name;
1151 size = note->size;
1152 address = note->address;
1153 }
1154
1155 EditSymbolDialog dialog(this, address, &size, &name, dialog_type);
1156
1157 if (dialog.exec() != QDialog::Accepted)
1158 return;
1159
1160 if (dialog.DeleteRequested())
1161 {
1162 if (type == EditSymbolType::EditRegion)
1163 m_ppc_symbol_db.DeleteFunction(address);
1164 else
1165 m_ppc_symbol_db.DeleteNote(address);
1166 }
1167 else if (type == EditSymbolType::EditRegion)
1168 {
1169 m_ppc_symbol_db.AddKnownSymbol(Core::CPUThreadGuard{m_system}, address, size, name, object_name,
1170 Common::Symbol::Type::Data);
1171 }
1172 else
1173 {
1174 m_ppc_symbol_db.AddKnownNote(address, size, name);
1175 m_ppc_symbol_db.DetermineNoteLayers();
1176 }
1177
1178 emit Host::GetInstance()->PPCSymbolsChanged();
1179 }
1180
1181 void MemoryViewWidget::OnContextMenu(const QPoint& pos)
1182 {
1183 auto* item_selected = m_table->itemAt(pos);
1184
1185 // We don't have a meaningful context menu to show for when the user right-clicks either free
1186 // space in the table or the row breakpoint cell.
1187 if (!item_selected || item_selected->data(USER_ROLE_IS_ROW_BREAKPOINT_CELL).toBool())
1188 return;
1189
1190 const u32 addr = item_selected->data(USER_ROLE_CELL_ADDRESS).toUInt();
1191 const bool item_has_value =
1192 item_selected->data(USER_ROLE_VALUE_TYPE).toInt() != static_cast<int>(Type::Null) &&
1193 AddressSpace::GetAccessors(m_address_space)
1194 ->IsValidAddress(Core::CPUThreadGuard{m_system}, addr);
1195
1196 auto* menu = new QMenu(this);
1197 menu->setAttribute(Qt::WA_DeleteOnClose, true);
1198
1199 menu->addAction(tr("Copy Address"), this, [this, addr] { OnCopyAddress(addr); });
1200
1201 auto* copy_hex = menu->addAction(tr("Copy Hex"), this, [this, addr] { OnCopyHex(addr); });
1202 copy_hex->setEnabled(item_has_value);
1203
1204 auto* copy_value = menu->addAction(tr("Copy Value"), this, [item_selected] {
1205 QApplication::clipboard()->setText(item_selected->text());
1206 });
1207 copy_value->setEnabled(item_has_value);
1208
1209 menu->addSeparator();
1210
1211 auto* note_add_action = menu->addAction(
1212 tr("Add Note"), this, [this, addr] { OnEditSymbol(EditSymbolType::AddNote, addr); });
1213 auto* note_edit_action = menu->addAction(
1214 tr("Edit Note"), this, [this, addr] { OnEditSymbol(EditSymbolType::EditNote, addr); });
1215 menu->addAction(tr("Add or edit region label"), this,
1216 [this, addr] { OnEditSymbol(EditSymbolType::EditRegion, addr); });
1217
1218 auto* note = m_ppc_symbol_db.GetNoteFromAddr(addr);
1219 note_edit_action->setEnabled(note != nullptr);
1220 // A note cannot be added on top of the starting address of another note.
1221 if (note != nullptr && note->address == addr)
1222 note_add_action->setEnabled(false);
1223
1224 menu->addSeparator();
1225
1226 menu->addAction(tr("Show in code"), this, [this, addr] { emit ShowCode(addr); });
1227
1228 menu->addSeparator();
1229
1230 menu->addAction(tr("Add to watch"), this, [this, addr] {
1231 const QString name = QStringLiteral("mem_%1").arg(addr, 8, 16, QLatin1Char('0'));
1232 emit RequestWatch(name, addr);
1233 });
1234
1235 menu->addAction(tr("Toggle Breakpoint"), this, [this, addr] { ToggleBreakpoint(addr, false); });
1236
1237 menu->exec(QCursor::pos());
1238 }
1239
1240 void MemoryViewWidget::ScrollbarActionTriggered(int action)
1241 {
1242 const int difference = m_scrollbar->sliderPosition() - m_scrollbar->value();
1243 if (difference == 0)
1244 return;
1245
1246 if (m_scrollbar->isSliderDown())
1247 {
1248 // User is currently dragging the scrollbar.
1249 // Adjust the memory view by the exact drag difference.
1250 m_address += difference * m_bytes_per_row;
1251 UpdateDispatcher(UpdateType::Addresses);
1252 }
1253 else
1254 {
1255 if (std::abs(difference) == 1)
1256 {
1257 // User clicked the arrows at the top or bottom, go up/down one row.
1258 m_address += difference * m_bytes_per_row;
1259 }
1260 else
1261 {
1262 // User clicked the free part of the scrollbar, go up/down one page.
1263 m_address += (difference < 0 ? -1 : 1) * m_bytes_per_row * m_table->rowCount();
1264 }
1265
1266 UpdateDispatcher(UpdateType::Addresses);
1267 // Manually reset the draggable part of the bar back to the center.
1268 m_scrollbar->setSliderPosition(SCROLLBAR_CENTER);
1269 }
1270 }
1271
1272 void MemoryViewWidget::ScrollbarSliderReleased()
1273 {
1274 // Reset the draggable part of the bar back to the center.
1275 m_scrollbar->setValue(SCROLLBAR_CENTER);
1276 }
1277
1278 void MemoryViewWidget::SetFocus() const
1279 {
1280 m_table->setFocus();
1281 }