Debian Codegraph @

Source/Core/DolphinQt/Debugger/MemoryWidget.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinQt/Debugger/MemoryWidget.h"
5
6 #include <limits>
7 #include <optional>
8 #include <string>
9
10 #include <QButtonGroup>
11 #include <QCheckBox>
12 #include <QComboBox>
13 #include <QFileDialog>
14 #include <QGroupBox>
15 #include <QHBoxLayout>
16 #include <QLabel>
17 #include <QLineEdit>
18 #include <QListWidget>
19 #include <QMenuBar>
20 #include <QPushButton>
21 #include <QRegularExpression>
22 #include <QScrollArea>
23 #include <QSpacerItem>
24 #include <QSplitter>
25 #include <QTableWidget>
26 #include <QVBoxLayout>
27
28 #include "Common/FileUtil.h"
29 #include "Common/IOFile.h"
30 #include "Core/ConfigManager.h"
31 #include "Core/Core.h"
32 #include "Core/HW/AddressSpace.h"
33 #include "Core/PowerPC/PPCSymbolDB.h"
34 #include "Core/System.h"
35 #include "DolphinQt/Debugger/MemoryViewWidget.h"
36 #include "DolphinQt/Host.h"
37 #include "DolphinQt/QtUtils/ModalMessageBox.h"
38 #include "DolphinQt/Settings.h"
39
40 using Type = MemoryViewWidget::Type;
41
42 MemoryWidget::MemoryWidget(Core::System& system, QWidget* parent)
43 : QDockWidget(parent), m_system(system), m_ppc_symbol_db(system.GetPPCSymbolDB())
44 {
45 setWindowTitle(tr("Memory"));
46 setObjectName(QStringLiteral("memory"));
47
48 setHidden(!Settings::Instance().IsMemoryVisible() || !Settings::Instance().IsDebugModeEnabled());
49
50 setAllowedAreas(Qt::AllDockWidgetAreas);
51
52 CreateWidgets();
53
54 QSettings& settings = Settings::GetQSettings();
55
56 restoreGeometry(settings.value(QStringLiteral("memorywidget/geometry")).toByteArray());
57 // macOS: setHidden() needs to be evaluated before setFloating() for proper window presentation
58 // according to Settings
59 setFloating(settings.value(QStringLiteral("memorywidget/floating")).toBool());
60 m_splitter->restoreState(settings.value(QStringLiteral("memorywidget/splitter")).toByteArray());
61
62 connect(&Settings::Instance(), &Settings::MemoryVisibilityChanged, this,
63 [this](bool visible) { setHidden(!visible); });
64
65 connect(&Settings::Instance(), &Settings::DebugModeToggled, this,
66 [this](bool enabled) { setHidden(!enabled || !Settings::Instance().IsMemoryVisible()); });
67
68 connect(this, &QDockWidget::visibilityChanged, this, [this](bool visible) {
69 // Stop auto-update if MemoryView is tabbed out.
70 if (visible && m_auto_update_enabled)
71 RegisterAfterFrameEventCallback();
72 else
73 RemoveAfterFrameEventCallback();
74 });
75 LoadSettings();
76
77 ConnectWidgets();
78 OnAddressSpaceChanged();
79 OnDisplayChanged();
80 }
81
82 MemoryWidget::~MemoryWidget()
83 {
84 QSettings& settings = Settings::GetQSettings();
85
86 settings.setValue(QStringLiteral("memorywidget/geometry"), saveGeometry());
87 settings.setValue(QStringLiteral("memorywidget/floating"), isFloating());
88 settings.setValue(QStringLiteral("memorywidget/splitter"), m_splitter->saveState());
89
90 SaveSettings();
91 }
92
93 void MemoryWidget::CreateWidgets()
94 {
95 auto* layout = new QHBoxLayout;
96
97 layout->setContentsMargins(2, 2, 2, 2);
98 layout->setSpacing(0);
99
100 //// Sidebar
101
102 // Search
103 auto* m_address_splitter = new QSplitter(Qt::Horizontal);
104
105 m_search_address = new QComboBox;
106 m_search_address->setInsertPolicy(QComboBox::InsertAtTop);
107 m_search_address->setDuplicatesEnabled(false);
108 m_search_address->setEditable(true);
109 m_search_address->setMaxVisibleItems(8);
110 m_search_offset = new QLineEdit;
111
112 m_search_offset->setMaxLength(9);
113 m_search_address->setPlaceholderText(tr("Search Address"));
114 m_search_offset->setPlaceholderText(tr("Offset"));
115
116 m_address_splitter->addWidget(m_search_address);
117 m_address_splitter->addWidget(m_search_offset);
118 m_address_splitter->setHandleWidth(1);
119 m_address_splitter->setCollapsible(0, false);
120 m_address_splitter->setStretchFactor(1, 2);
121
122 auto* input_layout = new QHBoxLayout;
123 m_data_edit = new QLineEdit;
124 m_base_check = new QCheckBox(tr("Hex"));
125 m_set_value = new QPushButton(tr("Set &Value"));
126 m_data_preview = new QLabel;
127
128 m_base_check->setLayoutDirection(Qt::RightToLeft);
129 m_data_edit->setPlaceholderText(tr("Value"));
130 m_data_preview->setBackgroundRole(QPalette::AlternateBase);
131 m_data_preview->setAutoFillBackground(true);
132
133 input_layout->addWidget(m_data_edit);
134 input_layout->addWidget(m_base_check);
135
136 // Input types
137 m_input_combo = new QComboBox;
138 m_input_combo->setMaxVisibleItems(20);
139 // Order here determines combo list order.
140 m_input_combo->addItem(tr("Hex Byte String"), int(Type::HexString));
141 m_input_combo->addItem(tr("ASCII"), int(Type::ASCII));
142 m_input_combo->addItem(tr("Float"), int(Type::Float32));
143 m_input_combo->addItem(tr("Double"), int(Type::Double));
144 m_input_combo->addItem(tr("Unsigned 8"), int(Type::Unsigned8));
145 m_input_combo->addItem(tr("Unsigned 16"), int(Type::Unsigned16));
146 m_input_combo->addItem(tr("Unsigned 32"), int(Type::Unsigned32));
147 m_input_combo->addItem(tr("Signed 8"), int(Type::Signed8));
148 m_input_combo->addItem(tr("Signed 16"), int(Type::Signed16));
149 m_input_combo->addItem(tr("Signed 32"), int(Type::Signed32));
150
151 // Search Options
152 auto* search_group = new QGroupBox(tr("Search"));
153 auto* search_layout = new QVBoxLayout;
154 search_group->setLayout(search_layout);
155
156 m_find_next = new QPushButton(tr("Find &Next"));
157 m_find_previous = new QPushButton(tr("Find &Previous"));
158 m_result_label = new QLabel;
159
160 search_layout->addWidget(m_find_next);
161 search_layout->addWidget(m_find_previous);
162 search_layout->addWidget(m_result_label);
163 search_layout->setSpacing(1);
164
165 // Address Space
166 auto* address_space_group = new QGroupBox(tr("Address Space"));
167 auto* address_space_layout = new QVBoxLayout;
168 address_space_group->setLayout(address_space_layout);
169
170 // i18n: One of the options shown below "Address Space". "Effective" addresses are the addresses
171 // used directly by the CPU and may be subject to translation via the MMU to physical addresses.
172 m_address_space_effective = new QRadioButton(tr("Effective"));
173 // i18n: One of the options shown below "Address Space". "Auxiliary" is the address space of ARAM
174 // (Auxiliary RAM).
175 m_address_space_auxiliary = new QRadioButton(tr("Auxiliary"));
176 // i18n: One of the options shown below "Address Space". "Physical" is the address space that
177 // reflects how devices (e.g. RAM) is physically wired up.
178 m_address_space_physical = new QRadioButton(tr("Physical"));
179
180 address_space_layout->addWidget(m_address_space_effective);
181 address_space_layout->addWidget(m_address_space_auxiliary);
182 address_space_layout->addWidget(m_address_space_physical);
183 address_space_layout->setSpacing(1);
184
185 // Data Type
186 auto* displaytype_group = new QGroupBox(tr("Display Type"));
187 auto* displaytype_layout = new QVBoxLayout;
188 displaytype_group->setLayout(displaytype_layout);
189
190 m_display_combo = new QComboBox;
191 m_display_combo->setMaxVisibleItems(20);
192 m_display_combo->addItem(tr("Hex 8"), int(Type::Hex8));
193 m_display_combo->addItem(tr("Hex 16"), int(Type::Hex16));
194 m_display_combo->addItem(tr("Hex 32"), int(Type::Hex32));
195 m_display_combo->addItem(tr("Unsigned 8"), int(Type::Unsigned8));
196 m_display_combo->addItem(tr("Unsigned 16"), int(Type::Unsigned16));
197 m_display_combo->addItem(tr("Unsigned 32"), int(Type::Unsigned32));
198 m_display_combo->addItem(tr("Signed 8"), int(Type::Signed8));
199 m_display_combo->addItem(tr("Signed 16"), int(Type::Signed16));
200 m_display_combo->addItem(tr("Signed 32"), int(Type::Signed32));
201 m_display_combo->addItem(tr("ASCII"), int(Type::ASCII));
202 m_display_combo->addItem(tr("Float"), int(Type::Float32));
203 m_display_combo->addItem(tr("Double"), int(Type::Double));
204
205 m_align_combo = new QComboBox;
206 // i18n: "Fixed" here means that the alignment is always the same
207 m_align_combo->addItem(tr("Fixed Alignment"));
208 m_align_combo->addItem(tr("Type-based Alignment"), 0);
209 m_align_combo->addItem(tr("No Alignment"), 1);
210
211 m_row_length_combo = new QComboBox;
212 m_row_length_combo->addItem(tr("4 Bytes"), 4);
213 m_row_length_combo->addItem(tr("8 Bytes"), 8);
214 m_row_length_combo->addItem(tr("16 Bytes"), 16);
215
216 m_row_length_combo->setCurrentIndex(2);
217 m_dual_check = new QCheckBox(tr("Dual View"));
218
219 displaytype_layout->addWidget(m_display_combo);
220 displaytype_layout->addWidget(m_align_combo);
221 displaytype_layout->addWidget(m_row_length_combo);
222 displaytype_layout->addWidget(m_dual_check);
223
224 // MBP options
225 auto* bp_group = new QGroupBox(tr("Memory breakpoint options"));
226 auto* bp_layout = new QVBoxLayout;
227 bp_group->setLayout(bp_layout);
228
229 // i18n: This string is used for a radio button that represents the type of
230 // memory breakpoint that gets triggered when a read operation or write operation occurs.
231 // The string is not a command to read and write something or to allow reading and writing.
232 m_bp_read_write = new QRadioButton(tr("Read and write"));
233 // i18n: This string is used for a radio button that represents the type of
234 // memory breakpoint that gets triggered when a read operation occurs.
235 // The string does not mean "read-only" in the sense that something cannot be written to.
236 m_bp_read_only = new QRadioButton(tr("Read only"));
237 // i18n: This string is used for a radio button that represents the type of
238 // memory breakpoint that gets triggered when a write operation occurs.
239 // The string does not mean "write-only" in the sense that something cannot be read from.
240 m_bp_write_only = new QRadioButton(tr("Write only"));
241 m_bp_log_check = new QCheckBox(tr("Log"));
242
243 bp_layout->addWidget(m_bp_read_write);
244 bp_layout->addWidget(m_bp_read_only);
245 bp_layout->addWidget(m_bp_write_only);
246 bp_layout->addWidget(m_bp_log_check);
247 bp_layout->setSpacing(1);
248
249 // Notes
250 m_labels_group = new QGroupBox(tr("Labels"));
251 auto* symbols_box = new QTabWidget;
252 m_note_list = new QListWidget;
253 m_data_list = new QListWidget;
254 m_symbols_list = new QListWidget;
255 symbols_box->addTab(m_note_list, tr("Notes"));
256 symbols_box->addTab(m_data_list, tr("Data"));
257 symbols_box->addTab(m_symbols_list, tr("Symbols"));
258 m_symbols_list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
259
260 auto* labels_layout = new QVBoxLayout;
261 m_search_labels = new QLineEdit;
262 // i18n: Filter is a verb. Typing into this text box will filter the label list so that only
263 // labels containing the typed text are shown.
264 m_search_labels->setPlaceholderText(tr("Filter Label List"));
265
266 m_labels_group->setLayout(labels_layout);
267 labels_layout->addWidget(symbols_box);
268 labels_layout->addWidget(m_search_labels);
269
270 // Sidebar
271 auto* sidebar = new QWidget;
272 auto* sidebar_layout = new QVBoxLayout;
273
274 // Sidebar top menu
275 QMenuBar* menubar = new QMenuBar(sidebar);
276 menubar->setNativeMenuBar(false);
277 QMenu* menu_views = new QMenu(tr("&View"), menubar);
278 menubar->addMenu(menu_views);
279
280 QMenu* menu_import = new QMenu(tr("&Import"), menubar);
281 menu_import->addAction(tr("&Load file to current address"), this,
282 &MemoryWidget::OnSetValueFromFile);
283 menubar->addMenu(menu_import);
284
285 // View Menu
286 auto* auto_update_action =
287 menu_views->addAction(tr("&Auto update memory values"), this, [this](bool checked) {
288 m_auto_update_enabled = checked;
289 if (checked)
290 RegisterAfterFrameEventCallback();
291 else
292 RemoveAfterFrameEventCallback();
293 });
294 auto_update_action->setCheckable(true);
295 auto_update_action->setChecked(true);
296
297 auto* highlight_update_action =
298 // i18n: Highlight is a verb (this is the label of a checkbox)
299 menu_views->addAction(tr("&Highlight recently changed values"), this,
300 [this](bool checked) { m_memory_view->ToggleHighlights(checked); });
301 highlight_update_action->setCheckable(true);
302 highlight_update_action->setChecked(true);
303
304 // i18n: Highlight is a noun (clicking this lets you select a color)
305 menu_views->addAction(tr("Highlight &color"), this,
306 [this] { m_memory_view->SetHighlightColor(); });
307
308 auto* show_notes =
309 menu_views->addAction(tr("&Show symbols and notes"), this, [this](bool checked) {
310 m_labels_visible = checked;
311 m_memory_view->ShowSymbols(checked);
312 UpdateNotes();
313 });
314 show_notes->setCheckable(true);
315 show_notes->setChecked(true);
316
317 QMenu* menu_export = new QMenu(tr("&Export"), menubar);
318 menu_export->addAction(tr("Dump &MRAM"), this, &MemoryWidget::OnDumpMRAM);
319 menu_export->addAction(tr("Dump &ExRAM"), this, &MemoryWidget::OnDumpExRAM);
320 menu_export->addAction(tr("Dump &ARAM"), this, &MemoryWidget::OnDumpARAM);
321 menu_export->addAction(tr("Dump &FakeVMEM"), this, &MemoryWidget::OnDumpFakeVMEM);
322 menubar->addMenu(menu_export);
323
324 sidebar_layout->setSpacing(1);
325 sidebar->setLayout(sidebar_layout);
326 sidebar_layout->addItem(new QSpacerItem(1, 20));
327 sidebar_layout->addWidget(m_address_splitter);
328 sidebar_layout->addLayout(input_layout);
329 sidebar_layout->addWidget(m_input_combo);
330 sidebar_layout->addItem(new QSpacerItem(1, 10));
331 sidebar_layout->addWidget(m_data_preview);
332 sidebar_layout->addWidget(m_set_value);
333 sidebar_layout->addItem(new QSpacerItem(1, 10));
334 sidebar_layout->addWidget(search_group);
335 sidebar_layout->addItem(new QSpacerItem(1, 10));
336 sidebar_layout->addWidget(displaytype_group);
337 sidebar_layout->addItem(new QSpacerItem(1, 10));
338 sidebar_layout->addWidget(address_space_group);
339 sidebar_layout->addItem(new QSpacerItem(1, 10));
340 sidebar_layout->addWidget(bp_group);
341 sidebar_layout->addWidget(m_labels_group);
342 sidebar_layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding));
343
344 // Splitter
345 m_splitter = new QSplitter(Qt::Horizontal);
346
347 auto* sidebar_scroll = new QScrollArea;
348 sidebar_scroll->setWidget(sidebar);
349 sidebar_scroll->setWidgetResizable(true);
350
351 m_memory_view = new MemoryViewWidget(m_system, this);
352
353 m_splitter->addWidget(m_memory_view);
354 m_splitter->addWidget(sidebar_scroll);
355 m_splitter->setStretchFactor(0, 3);
356 m_splitter->setStretchFactor(1, 1);
357
358 layout->addWidget(m_splitter);
359
360 auto* widget = new QWidget;
361 widget->setLayout(layout);
362 setWidget(widget);
363 UpdateNotes();
364 }
365
366 void MemoryWidget::ConnectWidgets()
367 {
368 connect(m_search_address, &QComboBox::currentTextChanged, this, &MemoryWidget::OnSearchAddress);
369 connect(m_search_offset, &QLineEdit::textChanged, this, &MemoryWidget::OnSearchAddress);
370 connect(m_data_edit, &QLineEdit::textChanged, this, &MemoryWidget::ValidateAndPreviewInputValue);
371
372 connect(m_input_combo, &QComboBox::currentIndexChanged, this,
373 &MemoryWidget::ValidateAndPreviewInputValue);
374 connect(m_set_value, &QPushButton::clicked, this, &MemoryWidget::OnSetValue);
375
376 connect(m_find_next, &QPushButton::clicked, this, &MemoryWidget::OnFindNextValue);
377 connect(m_find_previous, &QPushButton::clicked, this, &MemoryWidget::OnFindPreviousValue);
378
379 for (auto* radio :
380 {m_address_space_effective, m_address_space_auxiliary, m_address_space_physical})
381 {
382 connect(radio, &QRadioButton::toggled, this, &MemoryWidget::OnAddressSpaceChanged);
383 }
384 for (auto* combo : {m_display_combo, m_align_combo, m_row_length_combo})
385 {
386 connect(combo, &QComboBox::currentIndexChanged, this, &MemoryWidget::OnDisplayChanged);
387 }
388
389 connect(m_dual_check, &QCheckBox::toggled, this, &MemoryWidget::OnDisplayChanged);
390
391 for (auto* radio : {m_bp_read_write, m_bp_read_only, m_bp_write_only})
392 connect(radio, &QRadioButton::toggled, this, &MemoryWidget::OnBPTypeChanged);
393
394 connect(m_base_check, &QCheckBox::toggled, this, &MemoryWidget::ValidateAndPreviewInputValue);
395 connect(m_bp_log_check, &QCheckBox::toggled, this, &MemoryWidget::OnBPLogChanged);
396
397 for (auto* list : {m_symbols_list, m_data_list, m_note_list})
398 connect(list, &QListWidget::itemClicked, this, &MemoryWidget::OnSelectLabel);
399
400 connect(Host::GetInstance(), &Host::PPCSymbolsChanged, this, &MemoryWidget::RefreshLabelBox);
401 connect(m_search_labels, &QLineEdit::textChanged, this, &MemoryWidget::RefreshLabelBox);
402 connect(m_memory_view, &MemoryViewWidget::ShowCode, this, &MemoryWidget::ShowCode);
403 connect(m_memory_view, &MemoryViewWidget::RequestWatch, this, &MemoryWidget::RequestWatch);
404 connect(m_memory_view, &MemoryViewWidget::ActivateSearch, this,
405 &MemoryWidget::ActivateSearchAddress);
406 }
407
408 void MemoryWidget::closeEvent(QCloseEvent*)
409 {
410 Settings::Instance().SetMemoryVisible(false);
411 RemoveAfterFrameEventCallback();
412 }
413
414 void MemoryWidget::showEvent(QShowEvent* event)
415 {
416 if (m_auto_update_enabled)
417 RegisterAfterFrameEventCallback();
418
419 Update();
420 }
421
422 void MemoryWidget::hideEvent(QHideEvent* event)
423 {
424 RemoveAfterFrameEventCallback();
425 }
426
427 void MemoryWidget::RegisterAfterFrameEventCallback()
428 {
429 m_vi_end_field_event =
430 m_system.GetVideoEvents().vi_end_field_event.Register([this] { AutoUpdateTable(); });
431 }
432
433 void MemoryWidget::RemoveAfterFrameEventCallback()
434 {
435 m_vi_end_field_event.reset();
436 }
437
438 void MemoryWidget::AutoUpdateTable()
439 {
440 m_memory_view->UpdateOnFrameEnd();
441 }
442
443 void MemoryWidget::Update()
444 {
445 if (!isVisible())
446 return;
447
448 m_memory_view->UpdateDispatcher(MemoryViewWidget::UpdateType::Addresses);
449 update();
450 }
451
452 void MemoryWidget::LoadSettings()
453 {
454 QSettings& settings = Settings::GetQSettings();
455
456 const int combo_index = settings.value(QStringLiteral("memorywidget/inputcombo"), 1).toInt();
457
458 m_input_combo->setCurrentIndex(combo_index);
459
460 const bool address_space_effective =
461 settings.value(QStringLiteral("memorywidget/addrspace_effective"), true).toBool();
462 const bool address_space_auxiliary =
463 settings.value(QStringLiteral("memorywidget/addrspace_auxiliary"), false).toBool();
464 const bool address_space_physical =
465 settings.value(QStringLiteral("memorywidget/addrspace_physical"), false).toBool();
466
467 m_address_space_effective->setChecked(address_space_effective);
468 m_address_space_auxiliary->setChecked(address_space_auxiliary);
469 m_address_space_physical->setChecked(address_space_physical);
470
471 const int display_index = settings.value(QStringLiteral("memorywidget/display_type"), 1).toInt();
472
473 m_display_combo->setCurrentIndex(display_index);
474
475 bool bp_rw = settings.value(QStringLiteral("memorywidget/bpreadwrite"), true).toBool();
476 bool bp_r = settings.value(QStringLiteral("memorywidget/bpread"), false).toBool();
477 bool bp_w = settings.value(QStringLiteral("memorywidget/bpwrite"), false).toBool();
478 bool bp_log = settings.value(QStringLiteral("memorywidget/bplog"), true).toBool();
479
480 if (bp_rw)
481 m_memory_view->SetBPType(MemoryViewWidget::BPType::ReadWrite);
482 else if (bp_r)
483 m_memory_view->SetBPType(MemoryViewWidget::BPType::ReadOnly);
484 else
485 m_memory_view->SetBPType(MemoryViewWidget::BPType::WriteOnly);
486
487 m_bp_read_write->setChecked(bp_rw);
488 m_bp_read_only->setChecked(bp_r);
489 m_bp_write_only->setChecked(bp_w);
490 m_bp_log_check->setChecked(bp_log);
491 }
492
493 void MemoryWidget::SaveSettings()
494 {
495 QSettings& settings = Settings::GetQSettings();
496
497 settings.setValue(QStringLiteral("memorywidget/inputcombo"), m_input_combo->currentIndex());
498
499 settings.setValue(QStringLiteral("memorywidget/addrspace_effective"),
500 m_address_space_effective->isChecked());
501 settings.setValue(QStringLiteral("memorywidget/addrspace_auxiliary"),
502 m_address_space_auxiliary->isChecked());
503 settings.setValue(QStringLiteral("memorywidget/addrspace_physical"),
504 m_address_space_physical->isChecked());
505
506 settings.setValue(QStringLiteral("memorywidget/display_type"), m_display_combo->currentIndex());
507
508 settings.setValue(QStringLiteral("memorywidget/bpreadwrite"), m_bp_read_write->isChecked());
509 settings.setValue(QStringLiteral("memorywidget/bpread"), m_bp_read_only->isChecked());
510 settings.setValue(QStringLiteral("memorywidget/bpwrite"), m_bp_write_only->isChecked());
511 settings.setValue(QStringLiteral("memorywidget/bplog"), m_bp_log_check->isChecked());
512 }
513
514 void MemoryWidget::OnAddressSpaceChanged()
515 {
516 AddressSpace::Type space;
517
518 if (m_address_space_effective->isChecked())
519 space = AddressSpace::Type::Effective;
520 else if (m_address_space_auxiliary->isChecked())
521 space = AddressSpace::Type::Auxiliary;
522 else
523 space = AddressSpace::Type::Physical;
524
525 m_memory_view->SetAddressSpace(space);
526
527 SaveSettings();
528 }
529
530 void MemoryWidget::OnDisplayChanged()
531 {
532 const auto type = static_cast<Type>(m_display_combo->currentData().toInt());
533 int bytes_per_row = m_row_length_combo->currentData().toInt();
534 int alignment;
535 bool dual_view = m_dual_check->isChecked();
536
537 if (type == Type::Double && bytes_per_row == 4)
538 bytes_per_row = 8;
539
540 // Alignment: First (fixed) option equals bytes per row. 'currentData' is correct for other
541 // options. Type-based must be calculated in memoryviewwidget and is left at 0. "No alignment" is
542 // equivalent to a value of 1.
543 if (m_align_combo->currentIndex() == 0)
544 alignment = bytes_per_row;
545 else
546 alignment = m_align_combo->currentData().toInt();
547
548 m_memory_view->SetDisplay(type, bytes_per_row, alignment, dual_view);
549
550 SaveSettings();
551 }
552
553 void MemoryWidget::OnBPLogChanged()
554 {
555 m_memory_view->SetBPLoggingEnabled(m_bp_log_check->isChecked());
556 SaveSettings();
557 }
558
559 void MemoryWidget::OnBPTypeChanged()
560 {
561 bool read_write = m_bp_read_write->isChecked();
562 bool read_only = m_bp_read_only->isChecked();
563
564 MemoryViewWidget::BPType type;
565
566 if (read_write)
567 type = MemoryViewWidget::BPType::ReadWrite;
568 else if (read_only)
569 type = MemoryViewWidget::BPType::ReadOnly;
570 else
571 type = MemoryViewWidget::BPType::WriteOnly;
572
573 m_memory_view->SetBPType(type);
574
575 SaveSettings();
576 }
577
578 void MemoryWidget::SetAddress(u32 address)
579 {
580 // Store current and target address in combo box
581 const QSignalBlocker blocker(m_search_address);
582 const QString current_text = m_search_address->currentText();
583 const QString target_addr = QString::number(address, 16);
584 bool good;
585 const u32 current_addr = current_text.toUInt(&good, 16);
586
587 if (good)
588 {
589 AddressSpace::Accessors* accessors =
590 AddressSpace::GetAccessors(m_memory_view->GetAddressSpace());
591
592 const Core::CPUThreadGuard guard(m_system);
593 good = accessors->IsValidAddress(guard, current_addr);
594 }
595
596 if (m_search_address->findText(current_text) == -1 && good)
597 m_search_address->insertItem(0, current_text);
598
599 if (m_search_address->findText(target_addr) == -1)
600 m_search_address->insertItem(0, target_addr);
601
602 m_search_address->setCurrentText(target_addr);
603
604 m_memory_view->SetAddress(address);
605 Settings::Instance().SetMemoryVisible(true);
606 raise();
607
608 m_memory_view->setFocus();
609 }
610
611 void MemoryWidget::ActivateSearchAddress()
612 {
613 m_search_address->setFocus();
614 m_search_address->lineEdit()->selectAll();
615 }
616
617 void MemoryWidget::OnSearchAddress()
618 {
619 const auto target_addr = GetTargetAddress();
620
621 if (target_addr.is_good_address && target_addr.is_good_offset)
622 m_memory_view->SetAddress(target_addr.address);
623
624 QFont addr_font, offset_font;
625 QPalette addr_palette, offset_palette;
626
627 if (!target_addr.is_good_address)
628 {
629 addr_font.setBold(true);
630 addr_palette.setColor(QPalette::Text, Qt::red);
631 }
632
633 if (!target_addr.is_good_offset)
634 {
635 offset_font.setBold(true);
636 offset_palette.setColor(QPalette::Text, Qt::red);
637 }
638
639 m_search_address->setFont(addr_font);
640 m_search_address->setPalette(addr_palette);
641 m_search_offset->setFont(offset_font);
642 m_search_offset->setPalette(offset_palette);
643 }
644
645 void MemoryWidget::ValidateAndPreviewInputValue()
646 {
647 m_data_preview->clear();
648 QString input_text = m_data_edit->text();
649 const auto input_type = static_cast<Type>(m_input_combo->currentData().toInt());
650
651 m_base_check->setEnabled(input_type == Type::Unsigned32 || input_type == Type::Signed32 ||
652 input_type == Type::Unsigned16 || input_type == Type::Signed16 ||
653 input_type == Type::Unsigned8 || input_type == Type::Signed8);
654
655 if (input_text.isEmpty())
656 return;
657
658 // Remove any spaces
659 if (input_type != Type::ASCII)
660 input_text.remove(QLatin1Char(' '));
661
662 if (input_type == Type::HexString)
663 {
664 // Hex strings are parsed using QByteArray::fromHex which doesn't expect a 0x prefix. If the
665 // user has inserted one, remove it.
666 if (input_text.startsWith(QStringLiteral("0x"), Qt::CaseInsensitive))
667 input_text.remove(0, 2);
668 }
669 else if (m_base_check->isChecked())
670 {
671 // Add 0x to the front of the input (after the '-', if present), but only if the user didn't
672 // already do so.
673 if (input_text.startsWith(QLatin1Char('-')))
674 {
675 if (!input_text.startsWith(QStringLiteral("-0x"), Qt::CaseInsensitive))
676 input_text.insert(1, QStringLiteral("0x"));
677 }
678 else if (!input_text.startsWith(QStringLiteral("0x"), Qt::CaseInsensitive))
679 {
680 input_text.prepend(QStringLiteral("0x"));
681 }
682 }
683
684 QFont font;
685 QPalette palette;
686 std::vector<u8> bytes = m_memory_view->ConvertTextToBytes(input_type, input_text);
687
688 if (!bytes.empty())
689 {
690 QString hex_string;
691 std::string s;
692
693 for (const u8 c : bytes)
694 s.append(fmt::format("{:02x}", c));
695
696 hex_string = QString::fromStdString(s);
697 int output_length = hex_string.length();
698
699 if (output_length > 16)
700 {
701 hex_string.truncate(16);
702 output_length = hex_string.length();
703 hex_string.append(QStringLiteral("..."));
704 }
705
706 for (int i = 2; i < output_length; i += 2)
707 hex_string.insert(output_length - i, QLatin1Char{' '});
708
709 m_data_preview->setText(hex_string);
710 }
711 else
712 {
713 font.setBold(true);
714 palette.setColor(QPalette::Text, Qt::red);
715 }
716
717 m_data_edit->setFont(font);
718 m_data_edit->setPalette(palette);
719 }
720
721 QByteArray MemoryWidget::GetInputData() const
722 {
723 // Empty or invalid input data returns an empty array.
724 if (m_data_preview->text().isEmpty())
725 return QByteArray();
726
727 const auto input_type = static_cast<Type>(m_input_combo->currentData().toInt());
728
729 // Ascii might be truncated, pull from data edit box.
730 if (input_type == Type::ASCII)
731 return QByteArray(m_data_edit->text().toUtf8());
732
733 // If we are doing a large array of hex bytes
734 if (input_type == Type::HexString)
735 return QByteArray::fromHex(m_data_edit->text().toUtf8());
736
737 // Data preview has exactly what we want to input, so pull it from there.
738 return QByteArray::fromHex(m_data_preview->text().toUtf8());
739 }
740
741 void MemoryWidget::OnSetValue()
742 {
743 if (!Core::IsRunning(m_system))
744 return;
745
746 auto target_addr = GetTargetAddress();
747
748 if (!target_addr.is_good_address)
749 {
750 ModalMessageBox::critical(this, tr("Error"), tr("Bad address provided."));
751 return;
752 }
753
754 if (!target_addr.is_good_offset)
755 {
756 ModalMessageBox::critical(this, tr("Error"), tr("Bad offset provided."));
757 return;
758 }
759
760 const QByteArray bytes = GetInputData();
761
762 // Invalid input will give an empty array.
763 if (bytes.isEmpty())
764 {
765 ModalMessageBox::critical(this, tr("Error"), tr("Bad value provided."));
766 return;
767 }
768
769 const Core::CPUThreadGuard guard(m_system);
770
771 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(m_memory_view->GetAddressSpace());
772 u32 end_address = target_addr.address + static_cast<u32>(bytes.size()) - 1;
773
774 if (!accessors->IsValidAddress(guard, target_addr.address) ||
775 !accessors->IsValidAddress(guard, end_address))
776 {
777 ModalMessageBox::critical(this, tr("Error"), tr("Target address range is invalid."));
778 return;
779 }
780
781 for (const char c : bytes)
782 accessors->WriteU8(guard, target_addr.address++, static_cast<u8>(c));
783
784 Update();
785 }
786
787 void MemoryWidget::OnSetValueFromFile()
788 {
789 if (!Core::IsRunning(m_system))
790 return;
791
792 auto target_addr = GetTargetAddress();
793
794 if (!target_addr.is_good_address)
795 {
796 ModalMessageBox::critical(this, tr("Error"), tr("Bad address provided."));
797 return;
798 }
799
800 if (!target_addr.is_good_offset)
801 {
802 ModalMessageBox::critical(this, tr("Error"), tr("Bad offset provided."));
803 return;
804 }
805
806 QString path = QFileDialog::getOpenFileName(this, tr("Select a file"), QDir::currentPath(),
807 tr("All files (*)"));
808 if (path.isNull())
809 {
810 return;
811 }
812
813 File::IOFile f(path.toStdString(), "rb");
814
815 if (!f)
816 {
817 ModalMessageBox::critical(this, tr("Error"), tr("Unable to open file."));
818 return;
819 }
820
821 const u64 file_length = f.GetSize();
822 std::vector<u8> file_contents(file_length);
823 if (!f.ReadBytes(file_contents.data(), file_length))
824 {
825 ModalMessageBox::critical(this, tr("Error"), tr("Unable to read file."));
826 return;
827 }
828
829 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(m_memory_view->GetAddressSpace());
830
831 const Core::CPUThreadGuard guard(m_system);
832
833 for (u8 b : file_contents)
834 accessors->WriteU8(guard, target_addr.address++, b);
835
836 Update();
837 }
838
839 void MemoryWidget::RefreshLabelBox()
840 {
841 if (!m_labels_visible || m_ppc_symbol_db.IsEmpty())
842 {
843 m_labels_group->hide();
844 return;
845 }
846
847 m_labels_group->show();
848
849 UpdateSymbols();
850 UpdateNotes();
851 }
852
853 void MemoryWidget::OnSelectLabel()
854 {
855 QList<QListWidgetItem*> items;
856 if (m_note_list->isVisible())
857 items = m_note_list->selectedItems();
858 else if (m_symbols_list->isVisible())
859 items = m_symbols_list->selectedItems();
860 else if (m_data_list->isVisible())
861 items = m_data_list->selectedItems();
862
863 if (items.isEmpty())
864 return;
865
866 const u32 address = items[0]->data(Qt::UserRole).toUInt();
867
868 SetAddress(address);
869 }
870
871 void MemoryWidget::UpdateSymbols()
872 {
873 const QString selection = m_symbols_list->selectedItems().isEmpty() ?
874 QString{} :
875 m_symbols_list->selectedItems()[0]->text();
876 m_symbols_list->clear();
877 m_data_list->clear();
878
879 m_ppc_symbol_db.ForEachSymbol([&](const Common::Symbol& symbol) {
880 QString name = QString::fromStdString(symbol.name);
881
882 // If the symbol has an object name, add it to the entry name.
883 if (!symbol.object_name.empty())
884 {
885 name += QString::fromStdString(fmt::format(" ({})", symbol.object_name));
886 }
887
888 auto* item = new QListWidgetItem(name);
889 if (name == selection)
890 item->setSelected(true);
891
892 item->setData(Qt::UserRole, symbol.address);
893
894 if (!name.contains(m_search_labels->text(), Qt::CaseInsensitive))
895 return;
896
897 if (symbol.type != Common::Symbol::Type::Function)
898 m_data_list->addItem(item);
899 else
900 m_symbols_list->addItem(item);
901 });
902
903 m_symbols_list->sortItems();
904 }
905
906 void MemoryWidget::UpdateNotes()
907 {
908 // Save selection to re-apply.
909 const QString selection = m_note_list->selectedItems().isEmpty() ?
910 QStringLiteral("") :
911 m_note_list->selectedItems()[0]->text();
912 m_note_list->clear();
913
914 m_ppc_symbol_db.ForEachNote([&](const Common::Note& note) {
915 const QString name = QString::fromStdString(note.name);
916
917 auto* item = new QListWidgetItem(name);
918 if (name == selection)
919 item->setSelected(true);
920
921 item->setData(Qt::UserRole, note.address);
922
923 // Filter notes based on the search text.
924 if (name.contains(m_search_labels->text(), Qt::CaseInsensitive))
925 m_note_list->addItem(item);
926 });
927
928 m_note_list->sortItems();
929 }
930
931 static void DumpArray(const std::string& filename, const u8* data, size_t length)
932 {
933 if (!data)
934 return;
935
936 File::IOFile f(filename, "wb");
937
938 if (!f)
939 {
940 ModalMessageBox::critical(
941 nullptr, QObject::tr("Error"),
942 QObject::tr("Failed to dump %1: Can't open file").arg(QString::fromStdString(filename)));
943 return;
944 }
945
946 if (!f.WriteBytes(data, length))
947 {
948 ModalMessageBox::critical(nullptr, QObject::tr("Error"),
949 QObject::tr("Failed to dump %1: Failed to write to file")
950 .arg(QString::fromStdString(filename)));
951 }
952 }
953
954 void MemoryWidget::OnDumpMRAM()
955 {
956 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(AddressSpace::Type::Mem1);
957 DumpArray(File::GetUserPath(F_MEM1DUMP_IDX), accessors->begin(),
958 std::distance(accessors->begin(), accessors->end()));
959 }
960
961 void MemoryWidget::OnDumpExRAM()
962 {
963 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(AddressSpace::Type::Mem2);
964 DumpArray(File::GetUserPath(F_MEM2DUMP_IDX), accessors->begin(),
965 std::distance(accessors->begin(), accessors->end()));
966 }
967
968 void MemoryWidget::OnDumpARAM()
969 {
970 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(AddressSpace::Type::Auxiliary);
971 DumpArray(File::GetUserPath(F_ARAMDUMP_IDX), accessors->begin(),
972 std::distance(accessors->begin(), accessors->end()));
973 }
974
975 void MemoryWidget::OnDumpFakeVMEM()
976 {
977 AddressSpace::Accessors* accessors = AddressSpace::GetAccessors(AddressSpace::Type::Fake);
978 DumpArray(File::GetUserPath(F_FAKEVMEMDUMP_IDX), accessors->begin(),
979 std::distance(accessors->begin(), accessors->end()));
980 }
981
982 MemoryWidget::TargetAddress MemoryWidget::GetTargetAddress() const
983 {
984 TargetAddress target;
985
986 // Returns 0 if conversion fails
987 const u32 addr = m_search_address->currentText().toUInt(&target.is_good_address, 16);
988 target.is_good_address |= m_search_address->currentText().isEmpty();
989 const s32 offset = m_search_offset->text().toInt(&target.is_good_offset, 16);
990 const u32 neg_offset = offset != std::numeric_limits<s32>::min() ?
991 -offset :
992 u32(std::numeric_limits<s32>::max()) + 1;
993 target.is_good_offset |= m_search_offset->text().isEmpty();
994 target.is_good_offset &= offset >= 0 || neg_offset <= addr;
995 target.is_good_offset &= offset <= 0 || (std::numeric_limits<u32>::max() - u32(offset)) >= addr;
996
997 if (!target.is_good_address || !target.is_good_offset)
998 return target;
999
1000 if (offset < 0)
1001 target.address = addr - neg_offset;
1002 else
1003 target.address = addr + u32(offset);
1004 return target;
1005 }
1006
1007 void MemoryWidget::FindValue(bool next)
1008 {
1009 auto target_addr = GetTargetAddress();
1010
1011 if (!target_addr.is_good_address)
1012 {
1013 m_result_label->setText(tr("Bad address provided."));
1014 return;
1015 }
1016
1017 if (!target_addr.is_good_offset)
1018 {
1019 m_result_label->setText(tr("Bad offset provided."));
1020 return;
1021 }
1022
1023 const QByteArray search_for = GetInputData();
1024
1025 if (search_for.isEmpty())
1026 {
1027 m_result_label->setText(tr("Bad Value Given"));
1028 return;
1029 }
1030
1031 if (!m_search_address->currentText().isEmpty())
1032 {
1033 // skip the quoted address so we don't potentially refind the last result
1034 target_addr.address += next ? 1 : -1;
1035 }
1036
1037 const std::optional<u32> found_addr = [&] {
1038 AddressSpace::Accessors* accessors =
1039 AddressSpace::GetAccessors(m_memory_view->GetAddressSpace());
1040
1041 const Core::CPUThreadGuard guard(m_system);
1042 return accessors->Search(guard, target_addr.address,
1043 reinterpret_cast<const u8*>(search_for.data()),
1044 static_cast<u32>(search_for.size()), next);
1045 }();
1046
1047 if (found_addr.has_value())
1048 {
1049 m_result_label->setText(tr("Match Found"));
1050
1051 u32 offset = *found_addr;
1052
1053 m_search_address->setCurrentText(QStringLiteral("%1").arg(offset, 8, 16, QLatin1Char('0')));
1054 m_search_offset->clear();
1055
1056 m_memory_view->SetAddress(offset);
1057
1058 return;
1059 }
1060
1061 m_result_label->setText(tr("No Match"));
1062 }
1063
1064 void MemoryWidget::OnFindNextValue()
1065 {
1066 FindValue(true);
1067 }
1068
1069 void MemoryWidget::OnFindPreviousValue()
1070 {
1071 FindValue(false);
1072 }