From 762c1a9ff5406afc4c6b1a3eb74dae2dc2fb0daf Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Thu, 16 Apr 2015 18:35:09 -0400
Subject: [PATCH 01/17] Qt: Move EmuThread ownership from render window to main
 window.

---
 src/citra_qt/bootmanager.cpp           | 27 +++----------
 src/citra_qt/bootmanager.h             | 14 +++----
 src/citra_qt/debugger/disassembler.cpp | 18 +++++----
 src/citra_qt/debugger/disassembler.h   |  6 +--
 src/citra_qt/main.cpp                  | 55 +++++++++++++-------------
 src/citra_qt/main.h                    |  6 +++
 6 files changed, 57 insertions(+), 69 deletions(-)

diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index b81bd6167..50c8fed1e 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -10,6 +10,7 @@
 
 #include "common/common.h"
 #include "bootmanager.h"
+#include "main.h"
 
 #include "core/core.h"
 #include "core/settings.h"
@@ -30,6 +31,7 @@ EmuThread::EmuThread(GRenderWindow* render_window) :
     filename(""), exec_cpu_step(false), cpu_running(false),
     stop_run(false), render_window(render_window)
 {
+    connect(this, SIGNAL(started()), render_window, SLOT(moveContext()));
 }
 
 void EmuThread::SetFilename(std::string filename)
@@ -133,13 +135,9 @@ private:
     GRenderWindow* parent;
 };
 
-EmuThread& GRenderWindow::GetEmuThread()
-{
-    return emu_thread;
-}
+GRenderWindow::GRenderWindow(QWidget* parent, GMainWindow& main_window) :
+    QWidget(parent), main_window(main_window), keyboard_id(0) {
 
-GRenderWindow::GRenderWindow(QWidget* parent) : QWidget(parent), emu_thread(this), keyboard_id(0)
-{
     std::string window_title = Common::StringFromFormat("Citra | %s-%s", Common::g_scm_branch, Common::g_scm_desc);
     setWindowTitle(QString::fromStdString(window_title));
 
@@ -160,7 +158,6 @@ GRenderWindow::GRenderWindow(QWidget* parent) : QWidget(parent), emu_thread(this
     layout->addWidget(child);
     layout->setMargin(0);
     setLayout(layout);
-    connect(&emu_thread, SIGNAL(started()), this, SLOT(moveContext()));
 
     OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
 
@@ -180,29 +177,17 @@ void GRenderWindow::moveContext()
     // We need to move GL context to the swapping thread in Qt5
 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
     // If the thread started running, move the GL Context to the new thread. Otherwise, move it back.
-    child->context()->moveToThread((QThread::currentThread() == qApp->thread()) ? &emu_thread : qApp->thread());
+    auto thread = QThread::currentThread() == qApp->thread() ? main_window.GetEmuThread() : qApp->thread();
+    child->context()->moveToThread(thread);
 #endif
 }
 
-GRenderWindow::~GRenderWindow()
-{
-    if (emu_thread.isRunning())
-        emu_thread.Stop();
-}
-
 void GRenderWindow::SwapBuffers()
 {
     // MakeCurrent is already called in renderer_opengl
     child->swapBuffers();
 }
 
-void GRenderWindow::closeEvent(QCloseEvent* event)
-{
-    if (emu_thread.isRunning())
-        emu_thread.Stop();
-    QWidget::closeEvent(event);
-}
-
 void GRenderWindow::MakeCurrent()
 {
     child->makeCurrent();
diff --git a/src/citra_qt/bootmanager.h b/src/citra_qt/bootmanager.h
index 288da45a1..d3eab6ec1 100644
--- a/src/citra_qt/bootmanager.h
+++ b/src/citra_qt/bootmanager.h
@@ -14,6 +14,7 @@ class QScreen;
 class QKeyEvent;
 
 class GRenderWindow;
+class GMainWindow;
 
 class EmuThread : public QThread
 {
@@ -67,7 +68,7 @@ public slots:
     void Stop();
 
 private:
-    friend class GRenderWindow;
+    friend class GMainWindow;
 
     EmuThread(GRenderWindow* render_window);
 
@@ -100,10 +101,7 @@ class GRenderWindow : public QWidget, public EmuWindow
     Q_OBJECT
 
 public:
-    GRenderWindow(QWidget* parent = NULL);
-    ~GRenderWindow();
-
-    void closeEvent(QCloseEvent*) override;
+    GRenderWindow(QWidget* parent, GMainWindow& main_window);
 
     // EmuWindow implementation
     void SwapBuffers() override;
@@ -116,8 +114,6 @@ public:
     void restoreGeometry(const QByteArray& geometry); // overridden
     QByteArray saveGeometry();  // overridden
 
-    EmuThread& GetEmuThread();
-
     void keyPressEvent(QKeyEvent* event) override;
     void keyReleaseEvent(QKeyEvent* event) override;
 
@@ -139,10 +135,10 @@ private:
 
     QGLWidget* child;
 
-    EmuThread emu_thread;
-
     QByteArray geometry;
 
+    GMainWindow& main_window;
+
     /// Device id of keyboard for use with KeyMap
     int keyboard_id;
 };
diff --git a/src/citra_qt/debugger/disassembler.cpp b/src/citra_qt/debugger/disassembler.cpp
index f620687ae..b58edafe7 100644
--- a/src/citra_qt/debugger/disassembler.cpp
+++ b/src/citra_qt/debugger/disassembler.cpp
@@ -4,6 +4,7 @@
 
 #include "disassembler.h"
 
+#include "../main.h"
 #include "../bootmanager.h"
 #include "../hotkeys.h"
 
@@ -158,8 +159,9 @@ void DisassemblerModel::SetNextInstruction(unsigned int address) {
     emit dataChanged(prev_index, prev_index);
 }
 
-DisassemblerWidget::DisassemblerWidget(QWidget* parent, EmuThread& emu_thread) : QDockWidget(parent), base_addr(0), emu_thread(emu_thread)
-{
+DisassemblerWidget::DisassemblerWidget(QWidget* parent, GMainWindow& main_window) :
+    QDockWidget(parent), main_window(main_window), base_addr(0) {
+
     disasm_ui.setupUi(this);
 
     model = new DisassemblerModel(this);
@@ -199,7 +201,7 @@ void DisassemblerWidget::Init()
 
 void DisassemblerWidget::OnContinue()
 {
-    emu_thread.SetCpuRunning(true);
+    main_window.GetEmuThread()->SetCpuRunning(true);
 }
 
 void DisassemblerWidget::OnStep()
@@ -209,13 +211,13 @@ void DisassemblerWidget::OnStep()
 
 void DisassemblerWidget::OnStepInto()
 {
-    emu_thread.SetCpuRunning(false);
-    emu_thread.ExecStep();
+    main_window.GetEmuThread()->SetCpuRunning(false);
+    main_window.GetEmuThread()->ExecStep();
 }
 
 void DisassemblerWidget::OnPause()
 {
-    emu_thread.SetCpuRunning(false);
+    main_window.GetEmuThread()->SetCpuRunning(false);
 
     // TODO: By now, the CPU might not have actually stopped...
     if (Core::g_app_core) {
@@ -225,7 +227,7 @@ void DisassemblerWidget::OnPause()
 
 void DisassemblerWidget::OnToggleStartStop()
 {
-    emu_thread.SetCpuRunning(!emu_thread.IsCpuRunning());
+    main_window.GetEmuThread()->SetCpuRunning(!main_window.GetEmuThread()->IsCpuRunning());
 }
 
 void DisassemblerWidget::OnDebugModeEntered()
@@ -233,7 +235,7 @@ void DisassemblerWidget::OnDebugModeEntered()
     ARMword next_instr = Core::g_app_core->GetPC();
 
     if (model->GetBreakPoints().IsAddressBreakPoint(next_instr))
-        emu_thread.SetCpuRunning(false);
+        main_window.GetEmuThread()->SetCpuRunning(false);
 
     model->SetNextInstruction(next_instr);
 
diff --git a/src/citra_qt/debugger/disassembler.h b/src/citra_qt/debugger/disassembler.h
index 5e19d7c51..d9e32dbdf 100644
--- a/src/citra_qt/debugger/disassembler.h
+++ b/src/citra_qt/debugger/disassembler.h
@@ -13,7 +13,7 @@
 #include "common/break_points.h"
 
 class QAction;
-class EmuThread;
+class GMainWindow;
 
 class DisassemblerModel : public QAbstractListModel
 {
@@ -51,7 +51,7 @@ class DisassemblerWidget : public QDockWidget
     Q_OBJECT
 
 public:
-    DisassemblerWidget(QWidget* parent, EmuThread& emu_thread);
+    DisassemblerWidget(QWidget* parent, GMainWindow& main_window);
 
     void Init();
 
@@ -75,5 +75,5 @@ private:
 
     u32 base_addr;
 
-    EmuThread& emu_thread;
+    GMainWindow& main_window;
 };
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index e5ca04124..0e57d9e18 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -46,7 +46,7 @@
 
 #include "version.h"
 
-GMainWindow::GMainWindow()
+GMainWindow::GMainWindow() : emu_thread(nullptr)
 {
     Pica::g_debug_context = Pica::DebugContext::Construct();
 
@@ -55,14 +55,15 @@ GMainWindow::GMainWindow()
     ui.setupUi(this);
     statusBar()->hide();
 
-    render_window = new GRenderWindow;
+    render_window = new GRenderWindow(this, *this);
     render_window->hide();
+    emu_thread = new EmuThread(render_window);
 
     profilerWidget = new ProfilerWidget(this);
     addDockWidget(Qt::BottomDockWidgetArea, profilerWidget);
     profilerWidget->hide();
 
-    disasmWidget = new DisassemblerWidget(this, render_window->GetEmuThread());
+    disasmWidget = new DisassemblerWidget(this, *this);
     addDockWidget(Qt::BottomDockWidgetArea, disasmWidget);
     disasmWidget->hide();
 
@@ -139,13 +140,13 @@ GMainWindow::GMainWindow()
     connect(ui.action_Hotkeys, SIGNAL(triggered()), this, SLOT(OnOpenHotkeysDialog()));
 
     // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views before the CPU continues
-    connect(&render_window->GetEmuThread(), SIGNAL(DebugModeEntered()), disasmWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
-    connect(&render_window->GetEmuThread(), SIGNAL(DebugModeEntered()), registersWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
-    connect(&render_window->GetEmuThread(), SIGNAL(DebugModeEntered()), callstackWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
-    
-    connect(&render_window->GetEmuThread(), SIGNAL(DebugModeLeft()), disasmWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
-    connect(&render_window->GetEmuThread(), SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
-    connect(&render_window->GetEmuThread(), SIGNAL(DebugModeLeft()), callstackWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+    connect(emu_thread, SIGNAL(DebugModeEntered()), disasmWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
+    connect(emu_thread, SIGNAL(DebugModeEntered()), registersWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
+    connect(emu_thread, SIGNAL(DebugModeEntered()), callstackWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
+
+    connect(emu_thread, SIGNAL(DebugModeLeft()), disasmWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+    connect(emu_thread, SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+    connect(emu_thread, SIGNAL(DebugModeLeft()), callstackWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
 
     // Setup hotkeys
     RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
@@ -210,8 +211,8 @@ void GMainWindow::BootGame(std::string filename)
     registersWidget->OnDebugModeEntered();
     callstackWidget->OnDebugModeEntered();
 
-    render_window->GetEmuThread().SetFilename(filename);
-    render_window->GetEmuThread().start();
+    emu_thread->SetFilename(filename);
+    emu_thread->start();
 
     render_window->show();
     OnStartGame();
@@ -232,7 +233,7 @@ void GMainWindow::OnMenuLoadSymbolMap() {
 
 void GMainWindow::OnStartGame()
 {
-    render_window->GetEmuThread().SetCpuRunning(true);
+    emu_thread->SetCpuRunning(true);
 
     ui.action_Start->setEnabled(false);
     ui.action_Pause->setEnabled(true);
@@ -241,7 +242,7 @@ void GMainWindow::OnStartGame()
 
 void GMainWindow::OnPauseGame()
 {
-    render_window->GetEmuThread().SetCpuRunning(false);
+    emu_thread->SetCpuRunning(false);
 
     ui.action_Start->setEnabled(true);
     ui.action_Pause->setEnabled(false);
@@ -250,7 +251,7 @@ void GMainWindow::OnPauseGame()
 
 void GMainWindow::OnStopGame()
 {
-    render_window->GetEmuThread().SetCpuRunning(false);
+    emu_thread->SetCpuRunning(false);
     // TODO: Shutdown core
 
     ui.action_Start->setEnabled(true);
@@ -265,24 +266,22 @@ void GMainWindow::OnOpenHotkeysDialog()
 }
 
 
-void GMainWindow::ToggleWindowMode()
-{
-    bool enable = ui.action_Single_Window_Mode->isChecked();
-    if (!enable && render_window->parent() != nullptr)
-    {
-        ui.horizontalLayout->removeWidget(render_window);
-        render_window->setParent(nullptr);
-        render_window->setVisible(true);
-        render_window->RestoreGeometry();
-        render_window->setFocusPolicy(Qt::NoFocus);
-    }
-    else if (enable && render_window->parent() == nullptr)
-    {
+void GMainWindow::ToggleWindowMode() {
+    if (ui.action_Single_Window_Mode->isChecked()) {
+        // Render in the main window...
         render_window->BackupGeometry();
         ui.horizontalLayout->addWidget(render_window);
         render_window->setVisible(true);
         render_window->setFocusPolicy(Qt::ClickFocus);
         render_window->setFocus();
+
+    } else {
+        // Render in a separate window...
+        ui.horizontalLayout->removeWidget(render_window);
+        render_window->setParent(nullptr);
+        render_window->setVisible(true);
+        render_window->RestoreGeometry();
+        render_window->setFocusPolicy(Qt::NoFocus);
     }
 }
 
diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h
index 9b57c5772..5b33ea962 100644
--- a/src/citra_qt/main.h
+++ b/src/citra_qt/main.h
@@ -11,6 +11,7 @@
 
 class GImageInfo;
 class GRenderWindow;
+class EmuThread;
 class ProfilerWidget;
 class DisassemblerWidget;
 class RegistersWidget;
@@ -34,6 +35,10 @@ public:
     GMainWindow();
     ~GMainWindow();
 
+    EmuThread* GetEmuThread() {
+        return emu_thread;
+    }
+
 private:
     void BootGame(std::string filename);
 
@@ -54,6 +59,7 @@ private:
     Ui::MainWindow ui;
 
     GRenderWindow* render_window;
+    EmuThread* emu_thread;
 
     ProfilerWidget* profilerWidget;
     DisassemblerWidget* disasmWidget;

From d5665fea89dc2684e145e82a1b07086f11a13a65 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Thu, 16 Apr 2015 19:19:05 -0400
Subject: [PATCH 02/17] EmuThread: Remove unused filename attribute.

---
 src/citra_qt/bootmanager.cpp | 10 ++--------
 src/citra_qt/bootmanager.h   |  9 ---------
 src/citra_qt/main.cpp        |  1 -
 3 files changed, 2 insertions(+), 18 deletions(-)

diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index 50c8fed1e..c2b7ba0e2 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -28,15 +28,9 @@
 #define COPYRIGHT       "Copyright (C) 2013-2014 Citra Team"
 
 EmuThread::EmuThread(GRenderWindow* render_window) :
-    filename(""), exec_cpu_step(false), cpu_running(false),
-    stop_run(false), render_window(render_window)
-{
-    connect(this, SIGNAL(started()), render_window, SLOT(moveContext()));
-}
+    exec_cpu_step(false), cpu_running(false), stop_run(false), render_window(render_window) {
 
-void EmuThread::SetFilename(std::string filename)
-{
-    this->filename = filename;
+    connect(this, SIGNAL(started()), render_window, SLOT(moveContext()));
 }
 
 void EmuThread::run()
diff --git a/src/citra_qt/bootmanager.h b/src/citra_qt/bootmanager.h
index d3eab6ec1..8083d275b 100644
--- a/src/citra_qt/bootmanager.h
+++ b/src/citra_qt/bootmanager.h
@@ -21,13 +21,6 @@ class EmuThread : public QThread
     Q_OBJECT
 
 public:
-    /**
-     * Set image filename
-     *
-     * @param filename
-     * @warning Only call when not running!
-     */
-    void SetFilename(std::string filename);
 
     /**
      * Start emulation (on new thread)
@@ -72,8 +65,6 @@ private:
 
     EmuThread(GRenderWindow* render_window);
 
-    std::string filename;
-
     bool exec_cpu_step;
     bool cpu_running;
     std::atomic<bool> stop_run;
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index 0e57d9e18..9f9ebc918 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -211,7 +211,6 @@ void GMainWindow::BootGame(std::string filename)
     registersWidget->OnDebugModeEntered();
     callstackWidget->OnDebugModeEntered();
 
-    emu_thread->SetFilename(filename);
     emu_thread->start();
 
     render_window->show();

From 28df8dbfeb17cf5a002a5504a6bd2ba5091bf07c Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Thu, 16 Apr 2015 23:31:14 -0400
Subject: [PATCH 03/17] Qt: Create emu thread on bootup, kill it on shutdown.

---
 src/citra_qt/bootmanager.cpp | 31 +++++++++++--------------------
 src/citra_qt/bootmanager.h   | 24 +++++++++++++++++++-----
 src/citra_qt/main.cpp        | 20 ++++++++++++++------
 3 files changed, 44 insertions(+), 31 deletions(-)

diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index c2b7ba0e2..fa4e976f4 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -30,21 +30,19 @@
 EmuThread::EmuThread(GRenderWindow* render_window) :
     exec_cpu_step(false), cpu_running(false), stop_run(false), render_window(render_window) {
 
+    shutdown_event.Reset();
     connect(this, SIGNAL(started()), render_window, SLOT(moveContext()));
 }
 
-void EmuThread::run()
-{
+void EmuThread::run() {
     stop_run = false;
 
     // holds whether the cpu was running during the last iteration,
     // so that the DebugModeLeft signal can be emitted before the
     // next execution step
     bool was_active = false;
-    while (!stop_run)
-    {
-        if (cpu_running)
-        {
+    while (!stop_run) {
+        if (cpu_running) {
             if (!was_active)
                 emit DebugModeLeft();
 
@@ -53,9 +51,7 @@ void EmuThread::run()
             was_active = cpu_running || exec_cpu_step;
             if (!was_active)
                 emit DebugModeEntered();
-        }
-        else if (exec_cpu_step)
-        {
+        } else if (exec_cpu_step) {
             if (!was_active)
                 emit DebugModeLeft();
 
@@ -67,15 +63,14 @@ void EmuThread::run()
             was_active = false;
         }
     }
+
     render_window->moveContext();
 
-    Core::Stop();
+    shutdown_event.Set();
 }
 
-void EmuThread::Stop()
-{
-    if (!isRunning())
-    {
+void EmuThread::Stop() {
+    if (!isRunning()) {
         LOG_WARNING(Frontend, "EmuThread::Stop called while emu thread wasn't running, returning...");
         return;
     }
@@ -88,23 +83,19 @@ void EmuThread::Stop()
 
     // TODO: Waiting here is just a bad workaround for retarded shutdown logic.
     wait(1000);
-    if (isRunning())
-    {
+    if (isRunning()) {
         LOG_WARNING(Frontend, "EmuThread still running, terminating...");
         quit();
 
         // TODO: Waiting 50 seconds can be necessary if the logging subsystem has a lot of spam
         // queued... This should be fixed.
         wait(50000);
-        if (isRunning())
-        {
+        if (isRunning()) {
             LOG_CRITICAL(Frontend, "EmuThread STILL running, something is wrong here...");
             terminate();
         }
     }
     LOG_INFO(Frontend, "EmuThread stopped");
-
-    System::Shutdown();
 }
 
 
diff --git a/src/citra_qt/bootmanager.h b/src/citra_qt/bootmanager.h
index 8083d275b..f6f09773c 100644
--- a/src/citra_qt/bootmanager.h
+++ b/src/citra_qt/bootmanager.h
@@ -9,6 +9,7 @@
 
 #include "common/common.h"
 #include "common/emu_window.h"
+#include "common/thread.h"
 
 class QScreen;
 class QKeyEvent;
@@ -37,20 +38,31 @@ public:
     void ExecStep() { exec_cpu_step = true; }
 
     /**
-     * Allow the CPU to continue processing instructions without interruption
+     * Sets whether the CPU is running 
      *
      * @note This function is thread-safe
      */
     void SetCpuRunning(bool running) { cpu_running = running; }
 
     /**
-    * Allow the CPU to continue processing instructions without interruption
-    *
-    * @note This function is thread-safe
-    */
+     * Allow the CPU to continue processing instructions without interruption
+     *
+     * @note This function is thread-safe
+     */
     bool IsCpuRunning() { return cpu_running; }
 
 
+    /**
+     * Shutdown (permantently stops) the CPU
+     */
+    void ShutdownCpu() { stop_run = true; };
+
+    /**
+     * Waits for the CPU shutdown to complete
+     */
+    void WaitForCpuShutdown() { shutdown_event.Wait(); }
+
+
 public slots:
     /**
      * Stop emulation and wait for the thread to finish.
@@ -71,6 +83,8 @@ private:
 
     GRenderWindow* render_window;
 
+    Common::Event shutdown_event;
+
 signals:
     /**
      * Emitted when the CPU has halted execution
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index 9f9ebc918..fe1dac622 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -57,7 +57,6 @@ GMainWindow::GMainWindow() : emu_thread(nullptr)
 
     render_window = new GRenderWindow(this, *this);
     render_window->hide();
-    emu_thread = new EmuThread(render_window);
 
     profilerWidget = new ProfilerWidget(this);
     addDockWidget(Qt::BottomDockWidgetArea, profilerWidget);
@@ -197,9 +196,9 @@ void GMainWindow::OnDisplayTitleBars(bool show)
     }
 }
 
-void GMainWindow::BootGame(std::string filename)
-{
+void GMainWindow::BootGame(std::string filename) {
     LOG_INFO(Frontend, "Citra starting...\n");
+
     System::Init(render_window);
 
     // Load a game or die...
@@ -211,6 +210,7 @@ void GMainWindow::BootGame(std::string filename)
     registersWidget->OnDebugModeEntered();
     callstackWidget->OnDebugModeEntered();
 
+    emu_thread = new EmuThread(render_window);
     emu_thread->start();
 
     render_window->show();
@@ -248,14 +248,22 @@ void GMainWindow::OnPauseGame()
     ui.action_Stop->setEnabled(true);
 }
 
-void GMainWindow::OnStopGame()
-{
+void GMainWindow::OnStopGame() {
     emu_thread->SetCpuRunning(false);
-    // TODO: Shutdown core
+
+    emu_thread->ShutdownCpu();
+    emu_thread->WaitForCpuShutdown();
+    emu_thread->Stop();
+
+    delete emu_thread;
+
+    System::Shutdown();
 
     ui.action_Start->setEnabled(true);
     ui.action_Pause->setEnabled(false);
     ui.action_Stop->setEnabled(false);
+
+    render_window->hide();
 }
 
 void GMainWindow::OnOpenHotkeysDialog()

From bbabed8e98e573df5a566aa44f6a05147167b2a7 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 21:59:06 -0400
Subject: [PATCH 04/17] Memory: Properly cleanup & shutdown.

---
 src/core/mem_map.cpp       | 63 +++++++++++++++++++++++++-------------
 src/core/mem_map.h         |  6 ++++
 src/core/mem_map_funcs.cpp | 21 +++++--------
 3 files changed, 56 insertions(+), 34 deletions(-)

diff --git a/src/core/mem_map.cpp b/src/core/mem_map.cpp
index a14e8303e..22e359b3e 100644
--- a/src/core/mem_map.cpp
+++ b/src/core/mem_map.cpp
@@ -11,30 +11,30 @@
 
 namespace Memory {
 
-u8* g_base                      = nullptr;   ///< The base pointer to the auto-mirrored arena.
+u8* g_base;                     ///< The base pointer to the auto-mirrored arena.
 
-static MemArena arena;                       ///< The MemArena class
+static MemArena arena;          ///< The MemArena class
 
-u8* g_exefs_code                = nullptr;   ///< ExeFS:/.code is loaded here
-u8* g_system_mem                = nullptr;   ///< System memory
-u8* g_heap                      = nullptr;   ///< Application heap (main memory)
-u8* g_heap_linear               = nullptr;   ///< Linear heap
-u8* g_vram                      = nullptr;   ///< Video memory (VRAM) pointer
-u8* g_shared_mem                = nullptr;   ///< Shared memory
-u8* g_dsp_mem                   = nullptr;   ///< DSP memory
-u8* g_kernel_mem;                              ///< Kernel memory
+u8* g_exefs_code;               ///< ExeFS:/.code is loaded here
+u8* g_system_mem;               ///< System memory
+u8* g_heap;                     ///< Application heap (main memory)
+u8* g_heap_linear;              ///< Linear heap
+u8* g_vram;                     ///< Video memory (VRAM) pointer
+u8* g_shared_mem;               ///< Shared memory
+u8* g_dsp_mem;                  ///< DSP memory
+u8* g_kernel_mem;               ///< Kernel memory
 
-static u8* physical_bootrom     = nullptr;   ///< Bootrom physical memory
-static u8* uncached_bootrom     = nullptr;
+static u8* physical_bootrom;    ///< Bootrom physical memory
+static u8* uncached_bootrom;
 
-static u8* physical_exefs_code  = nullptr;   ///< Phsical ExeFS:/.code is loaded here
-static u8* physical_system_mem  = nullptr;   ///< System physical memory
-static u8* physical_fcram       = nullptr;   ///< Main physical memory (FCRAM)
-static u8* physical_heap_gsp    = nullptr;   ///< GSP heap physical memory
-static u8* physical_vram        = nullptr;   ///< Video physical memory (VRAM)
-static u8* physical_shared_mem  = nullptr;   ///< Physical shared memory
-static u8* physical_dsp_mem     = nullptr;   ///< Physical DSP memory
-static u8* physical_kernel_mem;              ///< Kernel memory
+static u8* physical_exefs_code; ///< Phsical ExeFS:/.code is loaded here
+static u8* physical_system_mem; ///< System physical memory
+static u8* physical_fcram;      ///< Main physical memory (FCRAM)
+static u8* physical_heap_gsp;   ///< GSP heap physical memory
+static u8* physical_vram;       ///< Video physical memory (VRAM)
+static u8* physical_shared_mem; ///< Physical shared memory
+static u8* physical_dsp_mem;    ///< Physical DSP memory
+static u8* physical_kernel_mem; ///< Kernel memory
 
 // We don't declare the IO region in here since its handled by other means.
 static MemoryView g_views[] = {
@@ -73,6 +73,7 @@ void Init() {
     }
 
     g_base = MemoryMap_Setup(g_views, kNumMemViews, flags, &arena);
+    MemBlock_Init();
 
     LOG_DEBUG(HW_Memory, "initialized OK, RAM at %p (mirror at 0 @ %p)", g_heap,
         physical_fcram);
@@ -81,9 +82,29 @@ void Init() {
 void Shutdown() {
     u32 flags = 0;
     MemoryMap_Shutdown(g_views, kNumMemViews, flags, &arena);
-
     arena.ReleaseSpace();
+    MemBlock_Shutdown();
+
     g_base = nullptr;
+    g_exefs_code = nullptr;
+    g_system_mem = nullptr;
+    g_heap = nullptr;
+    g_heap_linear = nullptr;
+    g_vram = nullptr;
+    g_shared_mem = nullptr;
+    g_dsp_mem = nullptr;
+    g_kernel_mem = nullptr;
+
+    physical_bootrom = nullptr;
+    uncached_bootrom = nullptr;
+    physical_exefs_code = nullptr;
+    physical_system_mem = nullptr;
+    physical_fcram = nullptr;
+    physical_heap_gsp = nullptr;
+    physical_vram = nullptr;
+    physical_shared_mem = nullptr;
+    physical_dsp_mem = nullptr;
+    physical_kernel_mem = nullptr;
 
     LOG_DEBUG(HW_Memory, "shutdown OK");
 }
diff --git a/src/core/mem_map.h b/src/core/mem_map.h
index ff730593e..1af02973b 100644
--- a/src/core/mem_map.h
+++ b/src/core/mem_map.h
@@ -171,6 +171,12 @@ u32 MapBlock_Heap(u32 size, u32 operation, u32 permissions);
  */
 u32 MapBlock_HeapLinear(u32 size, u32 operation, u32 permissions);
 
+/// Initialize mapped memory blocks
+void MemBlock_Init();
+
+/// Shutdown mapped memory blocks
+void MemBlock_Shutdown();
+
 inline const char* GetCharPointer(const VAddr address) {
     return (const char *)GetPointer(address);
 }
diff --git a/src/core/mem_map_funcs.cpp b/src/core/mem_map_funcs.cpp
index 5878b99dc..8759ebdfb 100644
--- a/src/core/mem_map_funcs.cpp
+++ b/src/core/mem_map_funcs.cpp
@@ -15,7 +15,6 @@ namespace Memory {
 
 static std::map<u32, MemoryBlock> heap_map;
 static std::map<u32, MemoryBlock> heap_linear_map;
-static std::map<u32, MemoryBlock> shared_map;
 
 /// Convert a physical address to virtual address
 VAddr PhysicalToVirtualAddress(const PAddr addr) {
@@ -185,12 +184,6 @@ u8 *GetPointer(const VAddr vaddr) {
     }
 }
 
-/**
- * Maps a block of memory on the heap
- * @param size Size of block in bytes
- * @param operation Memory map operation type
- * @param flags Memory allocation flags
- */
 u32 MapBlock_Heap(u32 size, u32 operation, u32 permissions) {
     MemoryBlock block;
 
@@ -208,12 +201,6 @@ u32 MapBlock_Heap(u32 size, u32 operation, u32 permissions) {
     return block.GetVirtualAddress();
 }
 
-/**
- * Maps a block of memory on the linear heap
- * @param size Size of block in bytes
- * @param operation Memory map operation type
- * @param flags Memory allocation flags
- */
 u32 MapBlock_HeapLinear(u32 size, u32 operation, u32 permissions) {
     MemoryBlock block;
 
@@ -231,6 +218,14 @@ u32 MapBlock_HeapLinear(u32 size, u32 operation, u32 permissions) {
     return block.GetVirtualAddress();
 }
 
+void MemBlock_Init() {
+}
+
+void MemBlock_Shutdown() {
+    heap_map.clear();
+    heap_linear_map.clear();
+}
+
 u8 Read8(const VAddr addr) {
     u8 data = 0;
     Read<u8>(data, addr);

From e0cb85691a99fb06dbce5e802ae756a944b1a66c Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 22:01:48 -0400
Subject: [PATCH 05/17] Services: Initialize all state variables at bootup.

---
 src/core/hle/service/apt/apt.cpp | 17 +++++++++++------
 src/core/hle/service/cfg/cfg.cpp |  2 +-
 src/core/hle/service/dsp_dsp.cpp |  2 +-
 src/core/hle/service/hid/hid.cpp | 22 ++++++++++++++--------
 src/core/hle/service/ir/ir.cpp   |  6 ++++--
 src/core/hle/service/nwm_uds.cpp |  2 +-
 src/core/hle/service/ptm/ptm.cpp |  7 +++++--
 src/core/hle/service/y2r_u.cpp   |  2 +-
 8 files changed, 38 insertions(+), 22 deletions(-)

diff --git a/src/core/hle/service/apt/apt.cpp b/src/core/hle/service/apt/apt.cpp
index 190c5df7a..98ae80b3a 100644
--- a/src/core/hle/service/apt/apt.cpp
+++ b/src/core/hle/service/apt/apt.cpp
@@ -28,15 +28,15 @@ namespace APT {
 static const VAddr SHARED_FONT_VADDR = 0x18000000;
 
 /// Handle to shared memory region designated to for shared system font
-static Kernel::SharedPtr<Kernel::SharedMemory> shared_font_mem = nullptr;
+static Kernel::SharedPtr<Kernel::SharedMemory> shared_font_mem;
 
-static Kernel::SharedPtr<Kernel::Mutex> lock = nullptr;
-static Kernel::SharedPtr<Kernel::Event> notification_event = nullptr; ///< APT notification event
-static Kernel::SharedPtr<Kernel::Event> start_event = nullptr;        ///< APT start event
+static Kernel::SharedPtr<Kernel::Mutex> lock;
+static Kernel::SharedPtr<Kernel::Event> notification_event; ///< APT notification event
+static Kernel::SharedPtr<Kernel::Event> start_event; ///< APT start event
 
 static std::vector<u8> shared_font;
 
-static u32 cpu_percent = 0; ///< CPU time available to the running application
+static u32 cpu_percent; ///< CPU time available to the running application
 
 void Initialize(Service::Interface* self) {
     u32* cmd_buff = Kernel::GetCommandBuffer();
@@ -309,6 +309,7 @@ void Init() {
     }
 
     lock = Kernel::Mutex::Create(false, "APT_U:Lock");
+
     cpu_percent = 0;
 
     // TODO(bunnei): Check if these are created in Initialize or on APT process startup.
@@ -317,7 +318,11 @@ void Init() {
 }
 
 void Shutdown() {
-
+    shared_font.clear();
+    shared_font_mem = nullptr;
+    lock = nullptr;
+    notification_event = nullptr;
+    start_event = nullptr;
 }
 
 } // namespace APT
diff --git a/src/core/hle/service/cfg/cfg.cpp b/src/core/hle/service/cfg/cfg.cpp
index 6af0352ac..5eccdecf7 100644
--- a/src/core/hle/service/cfg/cfg.cpp
+++ b/src/core/hle/service/cfg/cfg.cpp
@@ -207,6 +207,7 @@ void Init() {
 
     // Initialize the Username block
     // TODO(Subv): Initialize this directly in the variable when MSVC supports char16_t string literals
+    memset(&CONSOLE_USERNAME_BLOCK, 0, sizeof(CONSOLE_USERNAME_BLOCK));
     CONSOLE_USERNAME_BLOCK.ng_word = 0;
     CONSOLE_USERNAME_BLOCK.zero = 0;
 
@@ -219,7 +220,6 @@ void Init() {
 }
 
 void Shutdown() {
-
 }
 
 } // namespace CFG
diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp
index 4d6c70f4d..2e759a3e3 100644
--- a/src/core/hle/service/dsp_dsp.cpp
+++ b/src/core/hle/service/dsp_dsp.cpp
@@ -11,7 +11,7 @@
 
 namespace DSP_DSP {
 
-static u32 read_pipe_count    = 0;
+static u32 read_pipe_count;
 static Kernel::SharedPtr<Kernel::Event> semaphore_event;
 static Kernel::SharedPtr<Kernel::Event> interrupt_event;
 
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index 9ca5d13d4..0f30f743a 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -20,17 +20,17 @@ namespace HID {
 static const int MAX_CIRCLEPAD_POS = 0x9C; ///< Max value for a circle pad position
 
 // Handle to shared memory region designated to HID_User service
-static Kernel::SharedPtr<Kernel::SharedMemory> shared_mem = nullptr;
+static Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;
 
 // Event handles
-static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_1 = nullptr;
-static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_2 = nullptr;
-static Kernel::SharedPtr<Kernel::Event> event_accelerometer = nullptr;
-static Kernel::SharedPtr<Kernel::Event> event_gyroscope = nullptr;
-static Kernel::SharedPtr<Kernel::Event> event_debug_pad = nullptr;
+static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_1;
+static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_2;
+static Kernel::SharedPtr<Kernel::Event> event_accelerometer;
+static Kernel::SharedPtr<Kernel::Event> event_gyroscope;
+static Kernel::SharedPtr<Kernel::Event> event_debug_pad;
 
-static u32 next_pad_index = 0;
-static u32 next_touch_index = 0;
+static u32 next_pad_index;
+static u32 next_touch_index;
 
 // TODO(peachum):
 // Add a method for setting analog input from joystick device for the circle Pad.
@@ -175,6 +175,12 @@ void Init() {
 }
 
 void Shutdown() {
+    shared_mem = nullptr;
+    event_pad_or_touch_1 = nullptr;
+    event_pad_or_touch_2 = nullptr;
+    event_accelerometer = nullptr;
+    event_gyroscope = nullptr;
+    event_debug_pad = nullptr;
 }
 
 } // namespace HID
diff --git a/src/core/hle/service/ir/ir.cpp b/src/core/hle/service/ir/ir.cpp
index 58dfd8e1a..15ac477ef 100644
--- a/src/core/hle/service/ir/ir.cpp
+++ b/src/core/hle/service/ir/ir.cpp
@@ -15,8 +15,8 @@
 namespace Service {
 namespace IR {
 
-static Kernel::SharedPtr<Kernel::Event> handle_event = nullptr;
-static Kernel::SharedPtr<Kernel::SharedMemory> shared_memory = nullptr;
+static Kernel::SharedPtr<Kernel::Event> handle_event;
+static Kernel::SharedPtr<Kernel::SharedMemory> shared_memory;
 
 void GetHandles(Service::Interface* self) {
     u32* cmd_buff = Kernel::GetCommandBuffer();
@@ -41,6 +41,8 @@ void Init() {
 }
 
 void Shutdown() {
+    shared_memory = nullptr;
+    handle_event = nullptr;
 }
 
 } // namespace IR
diff --git a/src/core/hle/service/nwm_uds.cpp b/src/core/hle/service/nwm_uds.cpp
index 1cee81ab2..4b06efc3a 100644
--- a/src/core/hle/service/nwm_uds.cpp
+++ b/src/core/hle/service/nwm_uds.cpp
@@ -11,7 +11,7 @@
 
 namespace NWM_UDS {
 
-static Kernel::SharedPtr<Kernel::Event> handle_event = nullptr;
+static Kernel::SharedPtr<Kernel::Event> handle_event;
 
 /**
  * NWM_UDS::Shutdown service function
diff --git a/src/core/hle/service/ptm/ptm.cpp b/src/core/hle/service/ptm/ptm.cpp
index 57a301bec..d44510c1b 100644
--- a/src/core/hle/service/ptm/ptm.cpp
+++ b/src/core/hle/service/ptm/ptm.cpp
@@ -18,9 +18,9 @@ static const GameCoin default_game_coin = { 0x4F00, 42, 0, 0, 0, 2014, 12, 29 };
 /// Id of the SharedExtData archive used by the PTM process
 static const std::vector<u8> ptm_shared_extdata_id = {0, 0, 0, 0, 0x0B, 0, 0, 0xF0, 0, 0, 0, 0};
 
-static bool shell_open = true;
+static bool shell_open;
 
-static bool battery_is_charging = true;
+static bool battery_is_charging;
 
 u32 GetAdapterState() {
     // TODO(purpasmart96): This function is only a stub,
@@ -43,6 +43,9 @@ void Init() {
     AddService(new PTM_Sysm_Interface);
     AddService(new PTM_U_Interface);
 
+    shell_open = true;
+    battery_is_charging = true;
+
     // Open the SharedExtSaveData archive 0xF000000B and create the gamecoin.dat file if it doesn't exist
     FileSys::Path archive_path(ptm_shared_extdata_id);
     auto archive_result = Service::FS::OpenArchive(Service::FS::ArchiveIdCode::SharedExtSaveData, archive_path);
diff --git a/src/core/hle/service/y2r_u.cpp b/src/core/hle/service/y2r_u.cpp
index 6607965e1..33ecf64a2 100644
--- a/src/core/hle/service/y2r_u.cpp
+++ b/src/core/hle/service/y2r_u.cpp
@@ -11,7 +11,7 @@
 
 namespace Y2R_U {
 
-static Kernel::SharedPtr<Kernel::Event> completion_event = 0;
+static Kernel::SharedPtr<Kernel::Event> completion_event;
 
 /**
  * Y2R_U::IsBusyConversion service function

From 57aaaf92dbbdb4c1d43f6b564c7e8f83ab0811e7 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 22:03:35 -0400
Subject: [PATCH 06/17] HW: Properly initialize and shutdown all modules.

---
 src/core/hw/gpu.cpp | 8 +++++---
 src/core/hw/hw.cpp  | 2 ++
 src/core/hw/lcd.cpp | 1 +
 3 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/src/core/hw/gpu.cpp b/src/core/hw/gpu.cpp
index 308ea2035..0ad7e2963 100644
--- a/src/core/hw/gpu.cpp
+++ b/src/core/hw/gpu.cpp
@@ -29,8 +29,7 @@ namespace GPU {
 Regs g_regs;
 
 /// True if the current frame was skipped
-bool g_skip_frame = false;
-
+bool g_skip_frame;
 /// 268MHz / gpu_refresh_rate frames per second
 static u64 frame_ticks;
 /// Event id for CoreTiming
@@ -38,7 +37,7 @@ static int vblank_event;
 /// Total number of frames drawn
 static u64 frame_count;
 /// True if the last frame was skipped
-static bool last_skip_frame = false;
+static bool last_skip_frame;
 
 template <typename T>
 inline void Read(T &var, const u32 raw_addr) {
@@ -320,6 +319,8 @@ static void VBlankCallback(u64 userdata, int cycles_late) {
 
 /// Initialize hardware
 void Init() {
+    memset(&g_regs, 0, sizeof(g_regs));
+
     auto& framebuffer_top = g_regs.framebuffer_config[0];
     auto& framebuffer_sub = g_regs.framebuffer_config[1];
 
@@ -349,6 +350,7 @@ void Init() {
     frame_ticks = 268123480 / Settings::values.gpu_refresh_rate;
     last_skip_frame = false;
     g_skip_frame = false;
+    frame_count = 0;
 
     vblank_event = CoreTiming::RegisterEvent("GPU::VBlankCallback", VBlankCallback);
     CoreTiming::ScheduleEvent(frame_ticks, vblank_event);
diff --git a/src/core/hw/hw.cpp b/src/core/hw/hw.cpp
index bed50af50..236958139 100644
--- a/src/core/hw/hw.cpp
+++ b/src/core/hw/hw.cpp
@@ -63,6 +63,8 @@ void Init() {
 
 /// Shutdown hardware
 void Shutdown() {
+    GPU::Shutdown();
+    LCD::Shutdown();
     LOG_DEBUG(HW, "shutdown OK");
 }
 
diff --git a/src/core/hw/lcd.cpp b/src/core/hw/lcd.cpp
index 7986f3ddb..8a09c3bc0 100644
--- a/src/core/hw/lcd.cpp
+++ b/src/core/hw/lcd.cpp
@@ -55,6 +55,7 @@ template void Write<u8>(u32 addr, const u8 data);
 
 /// Initialize hardware
 void Init() {
+    memset(&g_regs, 0, sizeof(g_regs));
     LOG_DEBUG(HW_LCD, "initialized OK");
 }
 

From c7dc799e193d1ced47b21465f2e664908ae32ebc Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 22:12:35 -0400
Subject: [PATCH 07/17] Kernel: Properly initialize and shutdown all modules.

---
 src/core/hle/kernel/kernel.cpp | 11 +++++++----
 src/core/hle/kernel/kernel.h   |  5 +++--
 src/core/hle/kernel/thread.cpp | 10 ++++++++--
 src/core/hle/kernel/timer.cpp  |  3 ++-
 4 files changed, 20 insertions(+), 9 deletions(-)

diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index 6261b82b6..fca582bbe 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -14,11 +14,10 @@
 
 namespace Kernel {
 
-unsigned int Object::next_object_id = 0;
-
-SharedPtr<Thread> g_main_thread = nullptr;
+unsigned int Object::next_object_id;
+SharedPtr<Thread> g_main_thread;
 HandleTable g_handle_table;
-u64 g_program_id = 0;
+u64 g_program_id;
 
 void WaitObject::AddWaitingThread(SharedPtr<Thread> thread) {
     auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread);
@@ -138,6 +137,10 @@ void HandleTable::Clear() {
 void Init() {
     Kernel::ThreadingInit();
     Kernel::TimersInit();
+
+    Object::next_object_id = 0;
+    g_program_id = 0;
+    g_main_thread = nullptr;
 }
 
 /// Shutdown the kernel
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index 2d295ea00..ab06fa025 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -95,12 +95,13 @@ public:
         return false;
     }
 
+public:
+    static unsigned int next_object_id;
+
 private:
     friend void intrusive_ptr_add_ref(Object*);
     friend void intrusive_ptr_release(Object*);
 
-    static unsigned int next_object_id;
-
     unsigned int ref_count = 0;
     unsigned int object_id = next_object_id++;
 };
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 33d66b986..d678f5f6f 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -23,7 +23,7 @@
 namespace Kernel {
 
 /// Event type for the thread wake up event
-static int ThreadWakeupEventType = -1;
+static int ThreadWakeupEventType;
 
 bool Thread::ShouldWait() {
     return status != THREADSTATUS_DEAD;
@@ -42,7 +42,7 @@ static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST+1> ready_queue;
 static Thread* current_thread;
 
 // The first available thread id at startup
-static u32 next_thread_id = 1;
+static u32 next_thread_id;
 
 /**
  * Creates a new thread ID
@@ -497,6 +497,12 @@ void Thread::SetWaitSynchronizationOutput(s32 output) {
 void ThreadingInit() {
     ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
 
+    current_thread = nullptr;
+    next_thread_id = 1;
+
+    thread_list.clear();
+    ready_queue.clear();
+
     // Setup the idle thread
     SetupIdleThread();
 }
diff --git a/src/core/hle/kernel/timer.cpp b/src/core/hle/kernel/timer.cpp
index 1ec2a4b10..36979248d 100644
--- a/src/core/hle/kernel/timer.cpp
+++ b/src/core/hle/kernel/timer.cpp
@@ -12,7 +12,7 @@
 namespace Kernel {
 
 /// The event type of the generic timer callback event
-static int timer_callback_event_type = -1;
+static int timer_callback_event_type;
 // TODO(yuriks): This can be removed if Timer objects are explicitly pooled in the future, allowing
 //               us to simply use a pool index or similar.
 static Kernel::HandleTable timer_callback_handle_table;
@@ -89,6 +89,7 @@ static void TimerCallback(u64 timer_handle, int cycles_late) {
 }
 
 void TimersInit() {
+    timer_callback_handle_table.Clear();
     timer_callback_event_type = CoreTiming::RegisterEvent("TimerCallback", TimerCallback);
 }
 

From bab5abaf461f8032e042bb30997a62699e4ff483 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 22:44:05 -0400
Subject: [PATCH 08/17] Dyncom: Move cream cache to ARMul_State.

---
 src/core/arm/dyncom/arm_dyncom.cpp            |  4 ++-
 .../arm/dyncom/arm_dyncom_interpreter.cpp     | 31 ++++++-------------
 src/core/arm/interpreter/arminit.cpp          |  2 --
 src/core/arm/skyeye_common/armdefs.h          |  6 ++++
 4 files changed, 18 insertions(+), 25 deletions(-)

diff --git a/src/core/arm/dyncom/arm_dyncom.cpp b/src/core/arm/dyncom/arm_dyncom.cpp
index bc1e969e4..128413262 100644
--- a/src/core/arm/dyncom/arm_dyncom.cpp
+++ b/src/core/arm/dyncom/arm_dyncom.cpp
@@ -2,6 +2,8 @@
 // Licensed under GPLv2 or any later version
 // Refer to the license.txt file included.
 
+#include "common/make_unique.h"
+
 #include "core/arm/skyeye_common/armemu.h"
 #include "core/arm/skyeye_common/vfp/vfp.h"
 
@@ -17,7 +19,7 @@ const static cpu_config_t s_arm11_cpu_info = {
 };
 
 ARM_DynCom::ARM_DynCom(PrivilegeMode initial_mode) {
-    state = std::unique_ptr<ARMul_State>(new ARMul_State);
+    state = Common::make_unique<ARMul_State>();
 
     ARMul_NewState(state.get());
     ARMul_SelectProcessor(state.get(), ARM_v6_Prop | ARM_v5_Prop | ARM_v5e_Prop);
diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp
index fde11e4ff..991da740b 100644
--- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp
+++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp
@@ -6,7 +6,6 @@
 
 #include <algorithm>
 #include <cstdio>
-#include <unordered_map>
 
 #include "common/logging/log.h"
 #include "common/profiler.h"
@@ -3533,25 +3532,6 @@ const transop_fp_t arm_instruction_trans[] = {
     INTERPRETER_TRANSLATE(blx_1_thumb)
 };
 
-typedef std::unordered_map<u32, int> bb_map;
-static bb_map CreamCache;
-
-static void insert_bb(unsigned int addr, int start) {
-    CreamCache[addr] = start;
-}
-
-static int find_bb(unsigned int addr, int& start) {
-    int ret = -1;
-    bb_map::const_iterator it = CreamCache.find(addr);
-    if (it != CreamCache.end()) {
-        start = static_cast<int>(it->second);
-        ret = 0;
-    } else {
-        ret = -1;
-    }
-    return ret;
-}
-
 enum {
     FETCH_SUCCESS,
     FETCH_FAILURE
@@ -3674,7 +3654,9 @@ translated:
         }
         ret = inst_base->br;
     };
-    insert_bb(pc_start, bb_start);
+
+    cpu->instruction_cache[pc_start] = bb_start;
+
     return KEEP_GOING;
 }
 
@@ -4001,9 +3983,14 @@ unsigned InterpreterMainLoop(ARMul_State* state) {
 
         phys_addr = cpu->Reg[15];
 
-        if (find_bb(cpu->Reg[15], ptr) == -1)
+        // Find the cached instruction cream, otherwise translate it...
+        auto itr = cpu->instruction_cache.find(cpu->Reg[15]);
+        if (itr != cpu->instruction_cache.end()) {
+            ptr = itr->second;
+        } else {
             if (InterpreterTranslate(cpu, ptr, cpu->Reg[15]) == FETCH_EXCEPTION)
                 goto END;
+        }
 
         inst_base = (arm_inst *)&inst_buf[ptr];
         GOTO_NEXT_INST;
diff --git a/src/core/arm/interpreter/arminit.cpp b/src/core/arm/interpreter/arminit.cpp
index 6ac45c396..31b2bab06 100644
--- a/src/core/arm/interpreter/arminit.cpp
+++ b/src/core/arm/interpreter/arminit.cpp
@@ -26,8 +26,6 @@
 \***************************************************************************/
 ARMul_State* ARMul_NewState(ARMul_State* state)
 {
-    memset(state, 0, sizeof(ARMul_State));
-
     state->Emulate = RUN;
     state->Mode = USER32MODE;
 
diff --git a/src/core/arm/skyeye_common/armdefs.h b/src/core/arm/skyeye_common/armdefs.h
index 08da6d9eb..85d523bc2 100644
--- a/src/core/arm/skyeye_common/armdefs.h
+++ b/src/core/arm/skyeye_common/armdefs.h
@@ -17,6 +17,8 @@
 
 #pragma once
 
+#include <unordered_map>
+
 #include "common/common_types.h"
 #include "core/arm/skyeye_common/arm_regformat.h"
 #include "core/arm/skyeye_common/skyeye_defs.h"
@@ -152,6 +154,10 @@ So, if lateabtSig=1, then it means Late Abort Model(Base Updated Abort Model)
 
     // Added by ksh in 2005-10-1
     cpu_config_t* cpu;
+
+    // TODO(bunnei): Move this cache to a better place - it should be per codeset (likely per
+    // process for our purposes), not per ARMul_State (which tracks CPU core state).
+    std::unordered_map<u32, int> instruction_cache;
 };
 
 /***************************************************************************\

From d3c2f9a4a4c48e4571cd693a0c1801b665819cdf Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 22:45:43 -0400
Subject: [PATCH 09/17] HLE: Properly initialize and shutdown remaining
 modules.

---
 src/core/hle/config_mem.cpp  | 5 +++++
 src/core/hle/config_mem.h    | 2 ++
 src/core/hle/hle.cpp         | 9 ++++++---
 src/core/hle/shared_page.cpp | 5 +++++
 src/core/hle/shared_page.h   | 2 ++
 5 files changed, 20 insertions(+), 3 deletions(-)

diff --git a/src/core/hle/config_mem.cpp b/src/core/hle/config_mem.cpp
index 30d73adac..9fcfcc285 100644
--- a/src/core/hle/config_mem.cpp
+++ b/src/core/hle/config_mem.cpp
@@ -61,6 +61,8 @@ template void Read<u16>(u16 &var, const u32 addr);
 template void Read<u8>(u8 &var, const u32 addr);
 
 void Init() {
+    memset(&config_mem, 0, sizeof(config_mem));
+
     config_mem.update_flag = 0; // No update
     config_mem.sys_core_ver = 0x2;
     config_mem.unit_info = 0x1; // Bit 0 set for Retail
@@ -76,4 +78,7 @@ void Init() {
     config_mem.firm_sys_core_ver = 0x2;
 }
 
+void Shutdown() {
+}
+
 } // namespace
diff --git a/src/core/hle/config_mem.h b/src/core/hle/config_mem.h
index 94853901a..cbb478fb3 100644
--- a/src/core/hle/config_mem.h
+++ b/src/core/hle/config_mem.h
@@ -20,4 +20,6 @@ void Read(T &var, const u32 addr);
 
 void Init();
 
+void Shutdown();
+
 } // namespace
diff --git a/src/core/hle/hle.cpp b/src/core/hle/hle.cpp
index c645d6563..191d0411e 100644
--- a/src/core/hle/hle.cpp
+++ b/src/core/hle/hle.cpp
@@ -23,7 +23,7 @@ Common::Profiling::TimingCategory profiler_svc("SVC Calls");
 
 static std::vector<ModuleDef> g_module_db;
 
-bool g_reschedule = false;  ///< If true, immediately reschedules the CPU to a new thread
+bool g_reschedule; ///< If true, immediately reschedules the CPU to a new thread
 
 static const FunctionDef* GetSVCInfo(u32 opcode) {
     u32 func_num = opcode & 0xFFFFFF; // 8 bits
@@ -73,17 +73,20 @@ static void RegisterAllModules() {
 }
 
 void Init() {
-    Service::Init();
-
     RegisterAllModules();
 
+    Service::Init();
     ConfigMem::Init();
     SharedPage::Init();
 
+    g_reschedule = false;
+
     LOG_DEBUG(Kernel, "initialized OK");
 }
 
 void Shutdown() {
+    ConfigMem::Shutdown();
+    SharedPage::Shutdown();
     Service::Shutdown();
 
     g_module_db.clear();
diff --git a/src/core/hle/shared_page.cpp b/src/core/hle/shared_page.cpp
index 568dad684..94fae2551 100644
--- a/src/core/hle/shared_page.cpp
+++ b/src/core/hle/shared_page.cpp
@@ -62,6 +62,8 @@ template void Read<u16>(u16 &var, const u32 addr);
 template void Read<u8>(u8 &var, const u32 addr);
 
 void Set3DSlider(float amount) {
+    memset(&shared_page, 0, sizeof(shared_page));
+
     shared_page.sliderstate_3d = amount;
     shared_page.ledstate_3d = (amount == 0.0f); // off when non-zero
 }
@@ -71,4 +73,7 @@ void Init() {
     Set3DSlider(0.0f);
 }
 
+void Shutdown() {
+}
+
 } // namespace
diff --git a/src/core/hle/shared_page.h b/src/core/hle/shared_page.h
index 8f93545ec..1b6e4e581 100644
--- a/src/core/hle/shared_page.h
+++ b/src/core/hle/shared_page.h
@@ -23,4 +23,6 @@ void Set3DSlider(float amount);
 
 void Init();
 
+void Shutdown();
+
 } // namespace

From 5a855bdb2f263c143c54c0f37609aaa22e61c281 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 22:46:19 -0400
Subject: [PATCH 10/17] CoreTiming: Initialize static variables at bootup.

---
 src/core/core_timing.cpp | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/src/core/core_timing.cpp b/src/core/core_timing.cpp
index 6f716b1ca..f70c84c3d 100644
--- a/src/core/core_timing.cpp
+++ b/src/core/core_timing.cpp
@@ -160,6 +160,16 @@ void Init() {
     last_global_time_us = 0;
     has_ts_events = 0;
     mhz_change_callbacks.clear();
+
+    first = nullptr;
+    ts_first = nullptr;
+    ts_last = nullptr;
+
+    event_pool = nullptr;
+    event_ts_pool = nullptr;
+    allocated_ts_events = 0;
+
+    advance_callback = nullptr;
 }
 
 void Shutdown() {

From 3dd268878570c2c48e2be4018ff4d0ea851ece60 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Mon, 27 Apr 2015 23:13:57 -0400
Subject: [PATCH 11/17] Qt: Fix loading a new game without stopping emulation.

---
 src/citra_qt/main.cpp | 39 ++++++++++++++++++++++++---------------
 src/citra_qt/main.h   |  1 +
 2 files changed, 25 insertions(+), 15 deletions(-)

diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index fe1dac622..5441c17f1 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -199,6 +199,10 @@ void GMainWindow::OnDisplayTitleBars(bool show)
 void GMainWindow::BootGame(std::string filename) {
     LOG_INFO(Frontend, "Citra starting...\n");
 
+    // Shutdown previous session if the emu thread is still active...
+    if (emu_thread != nullptr)
+        ShutdownGame();
+
     System::Init(render_window);
 
     // Load a game or die...
@@ -217,6 +221,25 @@ void GMainWindow::BootGame(std::string filename) {
     OnStartGame();
 }
 
+void GMainWindow::ShutdownGame() {
+    emu_thread->SetCpuRunning(false);
+
+    emu_thread->ShutdownCpu();
+    emu_thread->WaitForCpuShutdown();
+    emu_thread->Stop();
+
+    delete emu_thread;
+    emu_thread = nullptr;
+
+    System::Shutdown();
+
+    ui.action_Start->setEnabled(true);
+    ui.action_Pause->setEnabled(false);
+    ui.action_Stop->setEnabled(false);
+
+    render_window->hide();
+}
+
 void GMainWindow::OnMenuLoadFile()
 {
     QString filename = QFileDialog::getOpenFileName(this, tr("Load File"), QString(), tr("3DS executable (*.3ds *.3dsx *.elf *.axf *.bin *.cci *.cxi)"));
@@ -249,21 +272,7 @@ void GMainWindow::OnPauseGame()
 }
 
 void GMainWindow::OnStopGame() {
-    emu_thread->SetCpuRunning(false);
-
-    emu_thread->ShutdownCpu();
-    emu_thread->WaitForCpuShutdown();
-    emu_thread->Stop();
-
-    delete emu_thread;
-
-    System::Shutdown();
-
-    ui.action_Start->setEnabled(true);
-    ui.action_Pause->setEnabled(false);
-    ui.action_Stop->setEnabled(false);
-
-    render_window->hide();
+    ShutdownGame();
 }
 
 void GMainWindow::OnOpenHotkeysDialog()
diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h
index 5b33ea962..1821ae35f 100644
--- a/src/citra_qt/main.h
+++ b/src/citra_qt/main.h
@@ -41,6 +41,7 @@ public:
 
 private:
     void BootGame(std::string filename);
+    void ShutdownGame();
 
     void closeEvent(QCloseEvent* event) override;
 

From e4ea133717a5292339c134160da984ba186d3de8 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Tue, 28 Apr 2015 19:03:01 -0400
Subject: [PATCH 12/17] Qt: Restructured to remove unnecessary shutdown event
 and various cleanups.

---
 src/citra_qt/bootmanager.cpp           | 43 +++----------------------
 src/citra_qt/bootmanager.h             | 44 +++++++-------------------
 src/citra_qt/debugger/disassembler.cpp | 10 +++---
 src/citra_qt/main.cpp                  | 33 ++++++++++---------
 4 files changed, 40 insertions(+), 90 deletions(-)

diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index fa4e976f4..1e902a8b6 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -28,9 +28,8 @@
 #define COPYRIGHT       "Copyright (C) 2013-2014 Citra Team"
 
 EmuThread::EmuThread(GRenderWindow* render_window) :
-    exec_cpu_step(false), cpu_running(false), stop_run(false), render_window(render_window) {
+    exec_step(false), running(false), stop_run(false), render_window(render_window) {
 
-    shutdown_event.Reset();
     connect(this, SIGNAL(started()), render_window, SLOT(moveContext()));
 }
 
@@ -42,20 +41,20 @@ void EmuThread::run() {
     // next execution step
     bool was_active = false;
     while (!stop_run) {
-        if (cpu_running) {
+        if (running) {
             if (!was_active)
                 emit DebugModeLeft();
 
             Core::RunLoop();
 
-            was_active = cpu_running || exec_cpu_step;
+            was_active = running || exec_step;
             if (!was_active)
                 emit DebugModeEntered();
-        } else if (exec_cpu_step) {
+        } else if (exec_step) {
             if (!was_active)
                 emit DebugModeLeft();
 
-            exec_cpu_step = false;
+            exec_step = false;
             Core::SingleStep();
             emit DebugModeEntered();
             yieldCurrentThread();
@@ -65,40 +64,8 @@ void EmuThread::run() {
     }
 
     render_window->moveContext();
-
-    shutdown_event.Set();
 }
 
-void EmuThread::Stop() {
-    if (!isRunning()) {
-        LOG_WARNING(Frontend, "EmuThread::Stop called while emu thread wasn't running, returning...");
-        return;
-    }
-    stop_run = true;
-
-    // Release emu threads from any breakpoints, so that this doesn't hang forever.
-    Pica::g_debug_context->ClearBreakpoints();
-
-    //core::g_state = core::SYS_DIE;
-
-    // TODO: Waiting here is just a bad workaround for retarded shutdown logic.
-    wait(1000);
-    if (isRunning()) {
-        LOG_WARNING(Frontend, "EmuThread still running, terminating...");
-        quit();
-
-        // TODO: Waiting 50 seconds can be necessary if the logging subsystem has a lot of spam
-        // queued... This should be fixed.
-        wait(50000);
-        if (isRunning()) {
-            LOG_CRITICAL(Frontend, "EmuThread STILL running, something is wrong here...");
-            terminate();
-        }
-    }
-    LOG_INFO(Frontend, "EmuThread stopped");
-}
-
-
 // This class overrides paintEvent and resizeEvent to prevent the GUI thread from stealing GL context.
 // The corresponding functionality is handled in EmuThread instead
 class GGLWidgetInternal : public QGLWidget
diff --git a/src/citra_qt/bootmanager.h b/src/citra_qt/bootmanager.h
index f6f09773c..e9b3ea664 100644
--- a/src/citra_qt/bootmanager.h
+++ b/src/citra_qt/bootmanager.h
@@ -25,66 +25,46 @@ public:
 
     /**
      * Start emulation (on new thread)
-     *
      * @warning Only call when not running!
      */
     void run() override;
 
     /**
-     * Allow the CPU to process a single instruction (if cpu is not running)
-     *
+     * Steps the emulation thread by a single CPU instruction (if the CPU is not already running)
      * @note This function is thread-safe
      */
-    void ExecStep() { exec_cpu_step = true; }
+    void ExecStep() { exec_step = true; }
 
     /**
-     * Sets whether the CPU is running 
-     *
+     * Sets whether the emulation thread is running or not
+     * @param running Boolean value, set the emulation thread to running if true
      * @note This function is thread-safe
      */
-    void SetCpuRunning(bool running) { cpu_running = running; }
+    void SetRunning(bool running) { this->running = running; }
 
     /**
-     * Allow the CPU to continue processing instructions without interruption
-     *
+     * Check if the emulation thread is running or not
+     * @return True if the emulation thread is running, otherwise false
      * @note This function is thread-safe
      */
-    bool IsCpuRunning() { return cpu_running; }
-
+    bool IsRunning() { return running; }
 
     /**
-     * Shutdown (permantently stops) the CPU
+     * Shutdown (permanently stops) the emulation thread
      */
-    void ShutdownCpu() { stop_run = true; };
-
-    /**
-     * Waits for the CPU shutdown to complete
-     */
-    void WaitForCpuShutdown() { shutdown_event.Wait(); }
-
-
-public slots:
-    /**
-     * Stop emulation and wait for the thread to finish.
-     *
-     * @details: This function will wait a second for the thread to finish; if it hasn't finished until then, we'll terminate() it and wait another second, hoping that it will be terminated by then.
-     * @note: This function is thread-safe.
-     */
-    void Stop();
+    void Shutdown() { stop_run = true; };
 
 private:
     friend class GMainWindow;
 
     EmuThread(GRenderWindow* render_window);
 
-    bool exec_cpu_step;
-    bool cpu_running;
+    bool exec_step;
+    bool running;
     std::atomic<bool> stop_run;
 
     GRenderWindow* render_window;
 
-    Common::Event shutdown_event;
-
 signals:
     /**
      * Emitted when the CPU has halted execution
diff --git a/src/citra_qt/debugger/disassembler.cpp b/src/citra_qt/debugger/disassembler.cpp
index b58edafe7..f9423e1d6 100644
--- a/src/citra_qt/debugger/disassembler.cpp
+++ b/src/citra_qt/debugger/disassembler.cpp
@@ -201,7 +201,7 @@ void DisassemblerWidget::Init()
 
 void DisassemblerWidget::OnContinue()
 {
-    main_window.GetEmuThread()->SetCpuRunning(true);
+    main_window.GetEmuThread()->SetRunning(true);
 }
 
 void DisassemblerWidget::OnStep()
@@ -211,13 +211,13 @@ void DisassemblerWidget::OnStep()
 
 void DisassemblerWidget::OnStepInto()
 {
-    main_window.GetEmuThread()->SetCpuRunning(false);
+    main_window.GetEmuThread()->SetRunning(false);
     main_window.GetEmuThread()->ExecStep();
 }
 
 void DisassemblerWidget::OnPause()
 {
-    main_window.GetEmuThread()->SetCpuRunning(false);
+    main_window.GetEmuThread()->SetRunning(false);
 
     // TODO: By now, the CPU might not have actually stopped...
     if (Core::g_app_core) {
@@ -227,7 +227,7 @@ void DisassemblerWidget::OnPause()
 
 void DisassemblerWidget::OnToggleStartStop()
 {
-    main_window.GetEmuThread()->SetCpuRunning(!main_window.GetEmuThread()->IsCpuRunning());
+    main_window.GetEmuThread()->SetRunning(!main_window.GetEmuThread()->IsRunning());
 }
 
 void DisassemblerWidget::OnDebugModeEntered()
@@ -235,7 +235,7 @@ void DisassemblerWidget::OnDebugModeEntered()
     ARMword next_instr = Core::g_app_core->GetPC();
 
     if (model->GetBreakPoints().IsAddressBreakPoint(next_instr))
-        main_window.GetEmuThread()->SetCpuRunning(false);
+        main_window.GetEmuThread()->SetRunning(false);
 
     model->SetNextInstruction(next_instr);
 
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index 5441c17f1..dd180baa4 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -199,10 +199,6 @@ void GMainWindow::OnDisplayTitleBars(bool show)
 void GMainWindow::BootGame(std::string filename) {
     LOG_INFO(Frontend, "Citra starting...\n");
 
-    // Shutdown previous session if the emu thread is still active...
-    if (emu_thread != nullptr)
-        ShutdownGame();
-
     System::Init(render_window);
 
     // Load a game or die...
@@ -222,29 +218,36 @@ void GMainWindow::BootGame(std::string filename) {
 }
 
 void GMainWindow::ShutdownGame() {
-    emu_thread->SetCpuRunning(false);
-
-    emu_thread->ShutdownCpu();
-    emu_thread->WaitForCpuShutdown();
-    emu_thread->Stop();
-
+    // Shutdown the emulation thread and wait for it to complete
+    emu_thread->SetRunning(false);
+    emu_thread->Shutdown();
+    emu_thread->wait();
     delete emu_thread;
     emu_thread = nullptr;
 
+    // Release emu threads from any breakpoints
+    Pica::g_debug_context->ClearBreakpoints();
+
+    // Shutdown the core emulation
     System::Shutdown();
 
+    // Update the GUI
     ui.action_Start->setEnabled(true);
     ui.action_Pause->setEnabled(false);
     ui.action_Stop->setEnabled(false);
-
     render_window->hide();
 }
 
 void GMainWindow::OnMenuLoadFile()
 {
     QString filename = QFileDialog::getOpenFileName(this, tr("Load File"), QString(), tr("3DS executable (*.3ds *.3dsx *.elf *.axf *.bin *.cci *.cxi)"));
-    if (filename.size())
-       BootGame(filename.toLatin1().data());
+    if (filename.size()) {
+        // Shutdown previous session if the emu thread is still active...
+        if (emu_thread != nullptr)
+            ShutdownGame();
+
+        BootGame(filename.toLatin1().data());
+    }
 }
 
 void GMainWindow::OnMenuLoadSymbolMap() {
@@ -255,7 +258,7 @@ void GMainWindow::OnMenuLoadSymbolMap() {
 
 void GMainWindow::OnStartGame()
 {
-    emu_thread->SetCpuRunning(true);
+    emu_thread->SetRunning(true);
 
     ui.action_Start->setEnabled(false);
     ui.action_Pause->setEnabled(true);
@@ -264,7 +267,7 @@ void GMainWindow::OnStartGame()
 
 void GMainWindow::OnPauseGame()
 {
-    emu_thread->SetCpuRunning(false);
+    emu_thread->SetRunning(false);
 
     ui.action_Start->setEnabled(true);
     ui.action_Pause->setEnabled(false);

From 43cf42490730d8a1b980aa1fe9ebbbe1249232ef Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Wed, 29 Apr 2015 00:01:41 -0400
Subject: [PATCH 13/17] Qt: Use signals for emu_thread start/stop and fix
 disasm widget.

---
 src/citra_qt/bootmanager.cpp           | 14 ++++-
 src/citra_qt/bootmanager.h             | 21 ++++---
 src/citra_qt/debugger/disassembler.cpp | 81 ++++++++++++++------------
 src/citra_qt/debugger/disassembler.h   |  9 ++-
 src/citra_qt/main.cpp                  | 68 ++++++++++++++-------
 src/citra_qt/main.h                    | 24 ++++++--
 6 files changed, 138 insertions(+), 79 deletions(-)

diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index 1e902a8b6..4be410fe0 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -87,8 +87,8 @@ private:
     GRenderWindow* parent;
 };
 
-GRenderWindow::GRenderWindow(QWidget* parent, GMainWindow& main_window) :
-    QWidget(parent), main_window(main_window), keyboard_id(0) {
+GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread) :
+    QWidget(parent), emu_thread(emu_thread), keyboard_id(0) {
 
     std::string window_title = Common::StringFromFormat("Citra | %s-%s", Common::g_scm_branch, Common::g_scm_desc);
     setWindowTitle(QString::fromStdString(window_title));
@@ -129,7 +129,7 @@ void GRenderWindow::moveContext()
     // We need to move GL context to the swapping thread in Qt5
 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
     // If the thread started running, move the GL Context to the new thread. Otherwise, move it back.
-    auto thread = QThread::currentThread() == qApp->thread() ? main_window.GetEmuThread() : qApp->thread();
+    auto thread = (QThread::currentThread() == qApp->thread() && emu_thread != nullptr) ? emu_thread : qApp->thread();
     child->context()->moveToThread(thread);
 #endif
 }
@@ -272,3 +272,11 @@ void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height)
 void GRenderWindow::OnMinimalClientAreaChangeRequest(const std::pair<unsigned,unsigned>& minimal_size) {
     setMinimumSize(minimal_size.first, minimal_size.second);
 }
+
+void GRenderWindow::OnEmulationStarted(EmuThread* emu_thread) {
+    this->emu_thread = emu_thread;
+}
+
+void GRenderWindow::OnEmulationStopped() {
+    emu_thread = nullptr;
+}
diff --git a/src/citra_qt/bootmanager.h b/src/citra_qt/bootmanager.h
index e9b3ea664..e57522187 100644
--- a/src/citra_qt/bootmanager.h
+++ b/src/citra_qt/bootmanager.h
@@ -22,6 +22,7 @@ class EmuThread : public QThread
     Q_OBJECT
 
 public:
+    EmuThread(GRenderWindow* render_window);
 
     /**
      * Start emulation (on new thread)
@@ -50,15 +51,14 @@ public:
     bool IsRunning() { return running; }
 
     /**
-     * Shutdown (permanently stops) the emulation thread
+     * Requests for the emulation thread to stop running and shutdown emulation
      */
-    void Shutdown() { stop_run = true; };
+    void RequestShutdown() {
+        stop_run = true;
+        running = false;
+    };
 
 private:
-    friend class GMainWindow;
-
-    EmuThread(GRenderWindow* render_window);
-
     bool exec_step;
     bool running;
     std::atomic<bool> stop_run;
@@ -86,7 +86,7 @@ class GRenderWindow : public QWidget, public EmuWindow
     Q_OBJECT
 
 public:
-    GRenderWindow(QWidget* parent, GMainWindow& main_window);
+    GRenderWindow(QWidget* parent, EmuThread* emu_thread);
 
     // EmuWindow implementation
     void SwapBuffers() override;
@@ -115,6 +115,9 @@ public:
 public slots:
     void moveContext();  // overridden
 
+    void OnEmulationStarted(EmuThread* emu_thread);
+    void OnEmulationStopped();
+
 private:
     void OnMinimalClientAreaChangeRequest(const std::pair<unsigned,unsigned>& minimal_size) override;
 
@@ -122,8 +125,8 @@ private:
 
     QByteArray geometry;
 
-    GMainWindow& main_window;
-
     /// Device id of keyboard for use with KeyMap
     int keyboard_id;
+
+    EmuThread* emu_thread;
 };
diff --git a/src/citra_qt/debugger/disassembler.cpp b/src/citra_qt/debugger/disassembler.cpp
index f9423e1d6..6400bb856 100644
--- a/src/citra_qt/debugger/disassembler.cpp
+++ b/src/citra_qt/debugger/disassembler.cpp
@@ -4,7 +4,6 @@
 
 #include "disassembler.h"
 
-#include "../main.h"
 #include "../bootmanager.h"
 #include "../hotkeys.h"
 
@@ -19,8 +18,8 @@
 #include "core/arm/disassembler/arm_disasm.h"
 
 
-DisassemblerModel::DisassemblerModel(QObject* parent) : QAbstractListModel(parent), base_address(0), code_size(0), program_counter(0), selection(QModelIndex()) {
-
+DisassemblerModel::DisassemblerModel(QObject* parent) :
+    QAbstractListModel(parent), base_address(0), code_size(0), program_counter(0), selection(QModelIndex()) {
 }
 
 int DisassemblerModel::columnCount(const QModelIndex& parent) const {
@@ -159,35 +158,28 @@ void DisassemblerModel::SetNextInstruction(unsigned int address) {
     emit dataChanged(prev_index, prev_index);
 }
 
-DisassemblerWidget::DisassemblerWidget(QWidget* parent, GMainWindow& main_window) :
-    QDockWidget(parent), main_window(main_window), base_addr(0) {
+DisassemblerWidget::DisassemblerWidget(QWidget* parent, EmuThread* emu_thread) :
+    QDockWidget(parent), emu_thread(emu_thread), base_addr(0) {
 
     disasm_ui.setupUi(this);
 
-    model = new DisassemblerModel(this);
-    disasm_ui.treeView->setModel(model);
-
     RegisterHotkey("Disassembler", "Start/Stop", QKeySequence(Qt::Key_F5), Qt::ApplicationShortcut);
     RegisterHotkey("Disassembler", "Step", QKeySequence(Qt::Key_F10), Qt::ApplicationShortcut);
     RegisterHotkey("Disassembler", "Step into", QKeySequence(Qt::Key_F11), Qt::ApplicationShortcut);
     RegisterHotkey("Disassembler", "Set Breakpoint", QKeySequence(Qt::Key_F9), Qt::ApplicationShortcut);
 
-    connect(disasm_ui.button_breakpoint, SIGNAL(clicked()), model, SLOT(OnSetOrUnsetBreakpoint()));
     connect(disasm_ui.button_step, SIGNAL(clicked()), this, SLOT(OnStep()));
     connect(disasm_ui.button_pause, SIGNAL(clicked()), this, SLOT(OnPause()));
     connect(disasm_ui.button_continue, SIGNAL(clicked()), this, SLOT(OnContinue()));
 
-    connect(disasm_ui.treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)),
-            model, SLOT(OnSelectionChanged(const QModelIndex&)));
-
     connect(GetHotkey("Disassembler", "Start/Stop", this), SIGNAL(activated()), this, SLOT(OnToggleStartStop()));
     connect(GetHotkey("Disassembler", "Step", this), SIGNAL(activated()), this, SLOT(OnStep()));
     connect(GetHotkey("Disassembler", "Step into", this), SIGNAL(activated()), this, SLOT(OnStepInto()));
-    connect(GetHotkey("Disassembler", "Set Breakpoint", this), SIGNAL(activated()), model, SLOT(OnSetOrUnsetBreakpoint()));
+
+    setEnabled(false);
 }
 
-void DisassemblerWidget::Init()
-{
+void DisassemblerWidget::Init() {
     model->ParseFromAddress(Core::g_app_core->GetPC());
 
     disasm_ui.treeView->resizeColumnToContents(0);
@@ -199,25 +191,21 @@ void DisassemblerWidget::Init()
     disasm_ui.treeView->selectionModel()->setCurrentIndex(model_index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
 }
 
-void DisassemblerWidget::OnContinue()
-{
-    main_window.GetEmuThread()->SetRunning(true);
+void DisassemblerWidget::OnContinue() {
+    emu_thread->SetRunning(true);
 }
 
-void DisassemblerWidget::OnStep()
-{
+void DisassemblerWidget::OnStep() {
     OnStepInto(); // change later
 }
 
-void DisassemblerWidget::OnStepInto()
-{
-    main_window.GetEmuThread()->SetRunning(false);
-    main_window.GetEmuThread()->ExecStep();
+void DisassemblerWidget::OnStepInto() {
+    emu_thread->SetRunning(false);
+    emu_thread->ExecStep();
 }
 
-void DisassemblerWidget::OnPause()
-{
-    main_window.GetEmuThread()->SetRunning(false);
+void DisassemblerWidget::OnPause() {
+    emu_thread->SetRunning(false);
 
     // TODO: By now, the CPU might not have actually stopped...
     if (Core::g_app_core) {
@@ -225,17 +213,15 @@ void DisassemblerWidget::OnPause()
     }
 }
 
-void DisassemblerWidget::OnToggleStartStop()
-{
-    main_window.GetEmuThread()->SetRunning(!main_window.GetEmuThread()->IsRunning());
+void DisassemblerWidget::OnToggleStartStop() {
+    emu_thread->SetRunning(!emu_thread->IsRunning());
 }
 
-void DisassemblerWidget::OnDebugModeEntered()
-{
+void DisassemblerWidget::OnDebugModeEntered() {
     ARMword next_instr = Core::g_app_core->GetPC();
 
     if (model->GetBreakPoints().IsAddressBreakPoint(next_instr))
-        main_window.GetEmuThread()->SetRunning(false);
+        emu_thread->SetRunning(false);
 
     model->SetNextInstruction(next_instr);
 
@@ -244,16 +230,35 @@ void DisassemblerWidget::OnDebugModeEntered()
     disasm_ui.treeView->selectionModel()->setCurrentIndex(model_index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
 }
 
-void DisassemblerWidget::OnDebugModeLeft()
-{
-
+void DisassemblerWidget::OnDebugModeLeft() {
 }
 
-int DisassemblerWidget::SelectedRow()
-{
+int DisassemblerWidget::SelectedRow() {
     QModelIndex index = disasm_ui.treeView->selectionModel()->currentIndex();
     if (!index.isValid())
         return -1;
 
     return disasm_ui.treeView->selectionModel()->currentIndex().row();
 }
+
+void DisassemblerWidget::OnEmulationStarted(EmuThread* emu_thread) {
+    this->emu_thread = emu_thread;
+
+    model = new DisassemblerModel(this);
+    disasm_ui.treeView->setModel(model);
+
+    connect(disasm_ui.treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)),
+        model, SLOT(OnSelectionChanged(const QModelIndex&)));
+    connect(disasm_ui.button_breakpoint, SIGNAL(clicked()), model, SLOT(OnSetOrUnsetBreakpoint()));
+    connect(GetHotkey("Disassembler", "Set Breakpoint", this), SIGNAL(activated()), model, SLOT(OnSetOrUnsetBreakpoint()));
+
+    Init();
+    setEnabled(true);
+}
+
+void DisassemblerWidget::OnEmulationStopped() {
+    disasm_ui.treeView->setModel(nullptr);
+    delete model;
+    emu_thread = nullptr;
+    setEnabled(false);
+}
diff --git a/src/citra_qt/debugger/disassembler.h b/src/citra_qt/debugger/disassembler.h
index d9e32dbdf..b771e95b7 100644
--- a/src/citra_qt/debugger/disassembler.h
+++ b/src/citra_qt/debugger/disassembler.h
@@ -13,7 +13,7 @@
 #include "common/break_points.h"
 
 class QAction;
-class GMainWindow;
+class EmuThread;
 
 class DisassemblerModel : public QAbstractListModel
 {
@@ -51,7 +51,7 @@ class DisassemblerWidget : public QDockWidget
     Q_OBJECT
 
 public:
-    DisassemblerWidget(QWidget* parent, GMainWindow& main_window);
+    DisassemblerWidget(QWidget* parent, EmuThread* emu_thread);
 
     void Init();
 
@@ -65,6 +65,9 @@ public slots:
     void OnDebugModeEntered();
     void OnDebugModeLeft();
 
+    void OnEmulationStarted(EmuThread* emu_thread);
+    void OnEmulationStopped();
+
 private:
     // returns -1 if no row is selected
     int SelectedRow();
@@ -75,5 +78,5 @@ private:
 
     u32 base_addr;
 
-    GMainWindow& main_window;
+    EmuThread* emu_thread;
 };
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index dd180baa4..7de2bf8ba 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -15,6 +15,7 @@
 #include "common/logging/log.h"
 #include "common/logging/backend.h"
 #include "common/logging/filter.h"
+#include "common/make_unique.h"
 #include "common/platform.h"
 #include "common/scope_exit.h"
 
@@ -55,14 +56,14 @@ GMainWindow::GMainWindow() : emu_thread(nullptr)
     ui.setupUi(this);
     statusBar()->hide();
 
-    render_window = new GRenderWindow(this, *this);
+    render_window = new GRenderWindow(this, emu_thread.get());
     render_window->hide();
 
     profilerWidget = new ProfilerWidget(this);
     addDockWidget(Qt::BottomDockWidgetArea, profilerWidget);
     profilerWidget->hide();
 
-    disasmWidget = new DisassemblerWidget(this, *this);
+    disasmWidget = new DisassemblerWidget(this, emu_thread.get());
     addDockWidget(Qt::BottomDockWidgetArea, disasmWidget);
     disasmWidget->hide();
 
@@ -138,14 +139,10 @@ GMainWindow::GMainWindow() : emu_thread(nullptr)
     connect(ui.action_Single_Window_Mode, SIGNAL(triggered(bool)), this, SLOT(ToggleWindowMode()));
     connect(ui.action_Hotkeys, SIGNAL(triggered()), this, SLOT(OnOpenHotkeysDialog()));
 
-    // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views before the CPU continues
-    connect(emu_thread, SIGNAL(DebugModeEntered()), disasmWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
-    connect(emu_thread, SIGNAL(DebugModeEntered()), registersWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
-    connect(emu_thread, SIGNAL(DebugModeEntered()), callstackWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
-
-    connect(emu_thread, SIGNAL(DebugModeLeft()), disasmWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
-    connect(emu_thread, SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
-    connect(emu_thread, SIGNAL(DebugModeLeft()), callstackWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+    connect(this, SIGNAL(EmulationStarted(EmuThread*)), disasmWidget, SLOT(OnEmulationStarted(EmuThread*)));
+    connect(this, SIGNAL(EmulationStopped()), disasmWidget, SLOT(OnEmulationStopped()));
+    connect(this, SIGNAL(EmulationStarted(EmuThread*)), render_window, SLOT(OnEmulationStarted(EmuThread*)));
+    connect(this, SIGNAL(EmulationStopped()), render_window, SLOT(OnEmulationStopped()));
 
     // Setup hotkeys
     RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
@@ -199,35 +196,62 @@ void GMainWindow::OnDisplayTitleBars(bool show)
 void GMainWindow::BootGame(std::string filename) {
     LOG_INFO(Frontend, "Citra starting...\n");
 
+    // Initialize the core emulation
     System::Init(render_window);
 
-    // Load a game or die...
+    // Load the game
     if (Loader::ResultStatus::Success != Loader::LoadFile(filename)) {
         LOG_CRITICAL(Frontend, "Failed to load ROM!");
+        System::Shutdown();
+        return;
     }
 
-    disasmWidget->Init();
-    registersWidget->OnDebugModeEntered();
-    callstackWidget->OnDebugModeEntered();
-
-    emu_thread = new EmuThread(render_window);
+    // Create and start the emulation thread
+    emu_thread = Common::make_unique<EmuThread>(render_window);
+    emit EmulationStarted(emu_thread.get());
     emu_thread->start();
 
+    // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views before the CPU continues
+    connect(emu_thread.get(), SIGNAL(DebugModeEntered()), disasmWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
+    connect(emu_thread.get(), SIGNAL(DebugModeEntered()), registersWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
+    connect(emu_thread.get(), SIGNAL(DebugModeEntered()), callstackWidget, SLOT(OnDebugModeEntered()), Qt::BlockingQueuedConnection);
+    connect(emu_thread.get(), SIGNAL(DebugModeLeft()), disasmWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+    connect(emu_thread.get(), SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+    connect(emu_thread.get(), SIGNAL(DebugModeLeft()), callstackWidget, SLOT(OnDebugModeLeft()), Qt::BlockingQueuedConnection);
+
+    // Update the GUI
+    registersWidget->OnDebugModeEntered();
+    callstackWidget->OnDebugModeEntered();
     render_window->show();
+
     OnStartGame();
 }
 
 void GMainWindow::ShutdownGame() {
-    // Shutdown the emulation thread and wait for it to complete
-    emu_thread->SetRunning(false);
-    emu_thread->Shutdown();
-    emu_thread->wait();
-    delete emu_thread;
-    emu_thread = nullptr;
+    // Shutdown the emulation thread
+    emu_thread->RequestShutdown();
+
+    // Disconnect signals that are attached to the current emulation thread
+    disconnect(emu_thread.get(), SIGNAL(DebugModeEntered()), disasmWidget, SLOT(OnDebugModeEntered()));
+    disconnect(emu_thread.get(), SIGNAL(DebugModeEntered()), registersWidget, SLOT(OnDebugModeEntered()));
+    disconnect(emu_thread.get(), SIGNAL(DebugModeEntered()), callstackWidget, SLOT(OnDebugModeEntered()));
+    disconnect(emu_thread.get(), SIGNAL(DebugModeLeft()), disasmWidget, SLOT(OnDebugModeLeft()));
+    disconnect(emu_thread.get(), SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()));
+    disconnect(emu_thread.get(), SIGNAL(DebugModeLeft()), callstackWidget, SLOT(OnDebugModeLeft()));
 
     // Release emu threads from any breakpoints
+    // This belongs after RequestShutdown() and before wait() because if emulation stops on a GPU
+    // breakpoint after (or before) RequestShutdown() is called, the emulation would never be able
+    // to continue out to the main loop and terminate. Thus wait() would hang forever.
+    // TODO(bunnei): This function is not thread safe, but it's being used as if it were
     Pica::g_debug_context->ClearBreakpoints();
 
+    emit EmulationStopped();
+
+    // Wait for emulation thread to complete and delete it
+    emu_thread->wait();
+    emu_thread = nullptr;
+
     // Shutdown the core emulation
     System::Shutdown();
 
diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h
index 1821ae35f..3e29534fb 100644
--- a/src/citra_qt/main.h
+++ b/src/citra_qt/main.h
@@ -5,6 +5,7 @@
 #ifndef _CITRA_QT_MAIN_HXX_
 #define _CITRA_QT_MAIN_HXX_
 
+#include <memory>
 #include <QMainWindow>
 
 #include "ui_main.h"
@@ -35,9 +36,23 @@ public:
     GMainWindow();
     ~GMainWindow();
 
-    EmuThread* GetEmuThread() {
-        return emu_thread;
-    }
+signals:
+
+    /**
+     * Signal that is emitted when a new EmuThread has been created and an emulation session is
+     * about to start. At this time, the core system emulation has been initialized, and all
+     * emulation handles and memory should be valid.
+     *
+     * @param emu_thread Pointer to the newly created EmuThread (to be used by widgets that need to
+     *      access/change emulation state).
+     */
+    void EmulationStarting(EmuThread* emu_thread);
+
+    /**
+     * Signal that is emitted when emulation is about to stop. At this time, the EmuThread and core
+     * system emulation handles and memory are still valid, but are about become invalid.
+     */
+    void EmulationStopping();
 
 private:
     void BootGame(std::string filename);
@@ -60,7 +75,8 @@ private:
     Ui::MainWindow ui;
 
     GRenderWindow* render_window;
-    EmuThread* emu_thread;
+
+    std::unique_ptr<EmuThread> emu_thread;
 
     ProfilerWidget* profilerWidget;
     DisassemblerWidget* disasmWidget;

From ad4445c5298760d07039f2293466fe6e60e39006 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Wed, 29 Apr 2015 23:26:59 -0400
Subject: [PATCH 14/17] Qt: Clear registers widget on shutdown.

---
 src/citra_qt/debugger/registers.cpp | 35 +++++++++++++++++++++--------
 src/citra_qt/debugger/registers.h   |  4 ++++
 src/citra_qt/main.cpp               |  2 ++
 3 files changed, 32 insertions(+), 9 deletions(-)

diff --git a/src/citra_qt/debugger/registers.cpp b/src/citra_qt/debugger/registers.cpp
index ab3666156..2b1e8ceb8 100644
--- a/src/citra_qt/debugger/registers.cpp
+++ b/src/citra_qt/debugger/registers.cpp
@@ -7,8 +7,7 @@
 #include "core/core.h"
 #include "core/arm/arm_interface.h"
 
-RegistersWidget::RegistersWidget(QWidget* parent) : QDockWidget(parent)
-{
+RegistersWidget::RegistersWidget(QWidget* parent) : QDockWidget(parent) {
     cpu_regs_ui.setupUi(this);
 
     tree = cpu_regs_ui.treeWidget;
@@ -18,8 +17,7 @@ RegistersWidget::RegistersWidget(QWidget* parent) : QDockWidget(parent)
     registers->setExpanded(true);
     CSPR->setExpanded(true);
 
-    for (int i = 0; i < 16; ++i)
-    {
+    for (int i = 0; i < 16; ++i) {
         QTreeWidgetItem* child = new QTreeWidgetItem(QStringList(QString("R[%1]").arg(i, 2, 10, QLatin1Char('0'))));
         registers->addChild(child);
     }
@@ -39,12 +37,16 @@ RegistersWidget::RegistersWidget(QWidget* parent) : QDockWidget(parent)
     CSPR->addChild(new QTreeWidgetItem(QStringList("C")));
     CSPR->addChild(new QTreeWidgetItem(QStringList("Z")));
     CSPR->addChild(new QTreeWidgetItem(QStringList("N")));
+
+    setEnabled(false);
 }
 
-void RegistersWidget::OnDebugModeEntered()
-{
+void RegistersWidget::OnDebugModeEntered() {
     ARM_Interface* app_core = Core::g_app_core;
 
+    if (app_core == nullptr)
+        return;
+
     for (int i = 0; i < 16; ++i)
         registers->child(i)->setText(1, QString("0x%1").arg(app_core->GetReg(i), 8, 16, QLatin1Char('0')));
 
@@ -66,7 +68,22 @@ void RegistersWidget::OnDebugModeEntered()
     CSPR->child(14)->setText(1, QString("%1").arg((app_core->GetCPSR() >> 31) & 0x1));  // N - Negative/Less than
 }
 
-void RegistersWidget::OnDebugModeLeft()
-{
-
+void RegistersWidget::OnDebugModeLeft() {
+}
+
+void RegistersWidget::OnEmulationStarted(EmuThread* emu_thread) {
+    setEnabled(true);
+}
+
+void RegistersWidget::OnEmulationStopped() {
+    // Reset widget text
+    for (int i = 0; i < 16; ++i)
+        registers->child(i)->setText(1, QString(""));
+
+    for (int i = 0; i < 15; ++i)
+        CSPR->child(i)->setText(1, QString(""));
+
+    CSPR->setText(1, QString(""));
+
+    setEnabled(false);
 }
diff --git a/src/citra_qt/debugger/registers.h b/src/citra_qt/debugger/registers.h
index bf8955625..0356de290 100644
--- a/src/citra_qt/debugger/registers.h
+++ b/src/citra_qt/debugger/registers.h
@@ -8,6 +8,7 @@
 #include <QTreeWidgetItem>
 
 class QTreeWidget;
+class EmuThread;
 
 class RegistersWidget : public QDockWidget
 {
@@ -20,6 +21,9 @@ public slots:
     void OnDebugModeEntered();
     void OnDebugModeLeft();
 
+    void OnEmulationStarted(EmuThread* emu_thread);
+    void OnEmulationStopped();
+
 private:
     Ui::ARMRegisters cpu_regs_ui;
 
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index 7de2bf8ba..f21c55db6 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -141,6 +141,8 @@ GMainWindow::GMainWindow() : emu_thread(nullptr)
 
     connect(this, SIGNAL(EmulationStarted(EmuThread*)), disasmWidget, SLOT(OnEmulationStarted(EmuThread*)));
     connect(this, SIGNAL(EmulationStopped()), disasmWidget, SLOT(OnEmulationStopped()));
+    connect(this, SIGNAL(EmulationStarted(EmuThread*)), registersWidget, SLOT(OnEmulationStarted(EmuThread*)));
+    connect(this, SIGNAL(EmulationStopped()), registersWidget, SLOT(OnEmulationStopped()));
     connect(this, SIGNAL(EmulationStarted(EmuThread*)), render_window, SLOT(OnEmulationStarted(EmuThread*)));
     connect(this, SIGNAL(EmulationStopped()), render_window, SLOT(OnEmulationStopped()));
 

From bc41de2131728192e3fd4c8c83e8b2d6e5ba4530 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Thu, 30 Apr 2015 19:46:50 -0400
Subject: [PATCH 15/17] Qt: Fixed a bug in shutdown procedure, various
 cleanups.

---
 src/citra_qt/bootmanager.cpp           |  6 ++---
 src/citra_qt/bootmanager.h             |  8 +++----
 src/citra_qt/debugger/disassembler.cpp |  4 ++--
 src/citra_qt/debugger/disassembler.h   |  4 ++--
 src/citra_qt/debugger/registers.cpp    |  4 ++--
 src/citra_qt/debugger/registers.h      |  4 ++--
 src/citra_qt/main.cpp                  | 31 +++++++++-----------------
 7 files changed, 26 insertions(+), 35 deletions(-)

diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp
index 4be410fe0..66a9e6fba 100644
--- a/src/citra_qt/bootmanager.cpp
+++ b/src/citra_qt/bootmanager.cpp
@@ -48,7 +48,7 @@ void EmuThread::run() {
             Core::RunLoop();
 
             was_active = running || exec_step;
-            if (!was_active)
+            if (!was_active && !stop_run)
                 emit DebugModeEntered();
         } else if (exec_step) {
             if (!was_active)
@@ -273,10 +273,10 @@ void GRenderWindow::OnMinimalClientAreaChangeRequest(const std::pair<unsigned,un
     setMinimumSize(minimal_size.first, minimal_size.second);
 }
 
-void GRenderWindow::OnEmulationStarted(EmuThread* emu_thread) {
+void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
     this->emu_thread = emu_thread;
 }
 
-void GRenderWindow::OnEmulationStopped() {
+void GRenderWindow::OnEmulationStopping() {
     emu_thread = nullptr;
 }
diff --git a/src/citra_qt/bootmanager.h b/src/citra_qt/bootmanager.h
index e57522187..715faf2d7 100644
--- a/src/citra_qt/bootmanager.h
+++ b/src/citra_qt/bootmanager.h
@@ -51,9 +51,9 @@ public:
     bool IsRunning() { return running; }
 
     /**
-     * Requests for the emulation thread to stop running and shutdown emulation
+     * Requests for the emulation thread to stop running
      */
-    void RequestShutdown() {
+    void RequestStop() {
         stop_run = true;
         running = false;
     };
@@ -115,8 +115,8 @@ public:
 public slots:
     void moveContext();  // overridden
 
-    void OnEmulationStarted(EmuThread* emu_thread);
-    void OnEmulationStopped();
+    void OnEmulationStarting(EmuThread* emu_thread);
+    void OnEmulationStopping();
 
 private:
     void OnMinimalClientAreaChangeRequest(const std::pair<unsigned,unsigned>& minimal_size) override;
diff --git a/src/citra_qt/debugger/disassembler.cpp b/src/citra_qt/debugger/disassembler.cpp
index 6400bb856..08c6b49bd 100644
--- a/src/citra_qt/debugger/disassembler.cpp
+++ b/src/citra_qt/debugger/disassembler.cpp
@@ -241,7 +241,7 @@ int DisassemblerWidget::SelectedRow() {
     return disasm_ui.treeView->selectionModel()->currentIndex().row();
 }
 
-void DisassemblerWidget::OnEmulationStarted(EmuThread* emu_thread) {
+void DisassemblerWidget::OnEmulationStarting(EmuThread* emu_thread) {
     this->emu_thread = emu_thread;
 
     model = new DisassemblerModel(this);
@@ -256,7 +256,7 @@ void DisassemblerWidget::OnEmulationStarted(EmuThread* emu_thread) {
     setEnabled(true);
 }
 
-void DisassemblerWidget::OnEmulationStopped() {
+void DisassemblerWidget::OnEmulationStopping() {
     disasm_ui.treeView->setModel(nullptr);
     delete model;
     emu_thread = nullptr;
diff --git a/src/citra_qt/debugger/disassembler.h b/src/citra_qt/debugger/disassembler.h
index b771e95b7..45b0a7e08 100644
--- a/src/citra_qt/debugger/disassembler.h
+++ b/src/citra_qt/debugger/disassembler.h
@@ -65,8 +65,8 @@ public slots:
     void OnDebugModeEntered();
     void OnDebugModeLeft();
 
-    void OnEmulationStarted(EmuThread* emu_thread);
-    void OnEmulationStopped();
+    void OnEmulationStarting(EmuThread* emu_thread);
+    void OnEmulationStopping();
 
 private:
     // returns -1 if no row is selected
diff --git a/src/citra_qt/debugger/registers.cpp b/src/citra_qt/debugger/registers.cpp
index 2b1e8ceb8..5527a2afd 100644
--- a/src/citra_qt/debugger/registers.cpp
+++ b/src/citra_qt/debugger/registers.cpp
@@ -71,11 +71,11 @@ void RegistersWidget::OnDebugModeEntered() {
 void RegistersWidget::OnDebugModeLeft() {
 }
 
-void RegistersWidget::OnEmulationStarted(EmuThread* emu_thread) {
+void RegistersWidget::OnEmulationStarting(EmuThread* emu_thread) {
     setEnabled(true);
 }
 
-void RegistersWidget::OnEmulationStopped() {
+void RegistersWidget::OnEmulationStopping() {
     // Reset widget text
     for (int i = 0; i < 16; ++i)
         registers->child(i)->setText(1, QString(""));
diff --git a/src/citra_qt/debugger/registers.h b/src/citra_qt/debugger/registers.h
index 0356de290..68e3fb908 100644
--- a/src/citra_qt/debugger/registers.h
+++ b/src/citra_qt/debugger/registers.h
@@ -21,8 +21,8 @@ public slots:
     void OnDebugModeEntered();
     void OnDebugModeLeft();
 
-    void OnEmulationStarted(EmuThread* emu_thread);
-    void OnEmulationStopped();
+    void OnEmulationStarting(EmuThread* emu_thread);
+    void OnEmulationStopping();
 
 private:
     Ui::ARMRegisters cpu_regs_ui;
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index f21c55db6..c3e637792 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -139,12 +139,12 @@ GMainWindow::GMainWindow() : emu_thread(nullptr)
     connect(ui.action_Single_Window_Mode, SIGNAL(triggered(bool)), this, SLOT(ToggleWindowMode()));
     connect(ui.action_Hotkeys, SIGNAL(triggered()), this, SLOT(OnOpenHotkeysDialog()));
 
-    connect(this, SIGNAL(EmulationStarted(EmuThread*)), disasmWidget, SLOT(OnEmulationStarted(EmuThread*)));
-    connect(this, SIGNAL(EmulationStopped()), disasmWidget, SLOT(OnEmulationStopped()));
-    connect(this, SIGNAL(EmulationStarted(EmuThread*)), registersWidget, SLOT(OnEmulationStarted(EmuThread*)));
-    connect(this, SIGNAL(EmulationStopped()), registersWidget, SLOT(OnEmulationStopped()));
-    connect(this, SIGNAL(EmulationStarted(EmuThread*)), render_window, SLOT(OnEmulationStarted(EmuThread*)));
-    connect(this, SIGNAL(EmulationStopped()), render_window, SLOT(OnEmulationStopped()));
+    connect(this, SIGNAL(EmulationStarting(EmuThread*)), disasmWidget, SLOT(OnEmulationStarting(EmuThread*)));
+    connect(this, SIGNAL(EmulationStopping()), disasmWidget, SLOT(OnEmulationStopping()));
+    connect(this, SIGNAL(EmulationStarting(EmuThread*)), registersWidget, SLOT(OnEmulationStarting(EmuThread*)));
+    connect(this, SIGNAL(EmulationStopping()), registersWidget, SLOT(OnEmulationStopping()));
+    connect(this, SIGNAL(EmulationStarting(EmuThread*)), render_window, SLOT(OnEmulationStarting(EmuThread*)));
+    connect(this, SIGNAL(EmulationStopping()), render_window, SLOT(OnEmulationStopping()));
 
     // Setup hotkeys
     RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
@@ -210,7 +210,7 @@ void GMainWindow::BootGame(std::string filename) {
 
     // Create and start the emulation thread
     emu_thread = Common::make_unique<EmuThread>(render_window);
-    emit EmulationStarted(emu_thread.get());
+    emit EmulationStarting(emu_thread.get());
     emu_thread->start();
 
     // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views before the CPU continues
@@ -230,25 +230,16 @@ void GMainWindow::BootGame(std::string filename) {
 }
 
 void GMainWindow::ShutdownGame() {
-    // Shutdown the emulation thread
-    emu_thread->RequestShutdown();
-
-    // Disconnect signals that are attached to the current emulation thread
-    disconnect(emu_thread.get(), SIGNAL(DebugModeEntered()), disasmWidget, SLOT(OnDebugModeEntered()));
-    disconnect(emu_thread.get(), SIGNAL(DebugModeEntered()), registersWidget, SLOT(OnDebugModeEntered()));
-    disconnect(emu_thread.get(), SIGNAL(DebugModeEntered()), callstackWidget, SLOT(OnDebugModeEntered()));
-    disconnect(emu_thread.get(), SIGNAL(DebugModeLeft()), disasmWidget, SLOT(OnDebugModeLeft()));
-    disconnect(emu_thread.get(), SIGNAL(DebugModeLeft()), registersWidget, SLOT(OnDebugModeLeft()));
-    disconnect(emu_thread.get(), SIGNAL(DebugModeLeft()), callstackWidget, SLOT(OnDebugModeLeft()));
+    emu_thread->RequestStop();
 
     // Release emu threads from any breakpoints
-    // This belongs after RequestShutdown() and before wait() because if emulation stops on a GPU
-    // breakpoint after (or before) RequestShutdown() is called, the emulation would never be able
+    // This belongs after RequestStop() and before wait() because if emulation stops on a GPU
+    // breakpoint after (or before) RequestStop() is called, the emulation would never be able
     // to continue out to the main loop and terminate. Thus wait() would hang forever.
     // TODO(bunnei): This function is not thread safe, but it's being used as if it were
     Pica::g_debug_context->ClearBreakpoints();
 
-    emit EmulationStopped();
+    emit EmulationStopping();
 
     // Wait for emulation thread to complete and delete it
     emu_thread->wait();

From 85cc81d8cc51738e0a025b8fe447173323f1db13 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Thu, 30 Apr 2015 19:58:26 -0400
Subject: [PATCH 16/17] Qt: Disable "Start" unless we are paused (it otherwise
 has no meaning and causes a crash).

---
 src/citra_qt/main.cpp | 2 +-
 src/citra_qt/main.ui  | 3 +++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index c3e637792..a3e98abfe 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -249,7 +249,7 @@ void GMainWindow::ShutdownGame() {
     System::Shutdown();
 
     // Update the GUI
-    ui.action_Start->setEnabled(true);
+    ui.action_Start->setEnabled(false);
     ui.action_Pause->setEnabled(false);
     ui.action_Stop->setEnabled(false);
     render_window->hide();
diff --git a/src/citra_qt/main.ui b/src/citra_qt/main.ui
index a3752ac1e..689806465 100644
--- a/src/citra_qt/main.ui
+++ b/src/citra_qt/main.ui
@@ -90,6 +90,9 @@
    </property>
   </action>
   <action name="action_Start">
+   <property name="enabled">
+     <bool>false</bool>
+   </property>
    <property name="text">
     <string>&amp;Start</string>
    </property>

From 046dd6e3ef3f4b4da2dd2eef0bdfe0f6fb28b1d8 Mon Sep 17 00:00:00 2001
From: bunnei <bunneidev@gmail.com>
Date: Fri, 1 May 2015 16:53:16 -0400
Subject: [PATCH 17/17] Qt: Shutdown game on emulator close event.

---
 src/citra_qt/main.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index a3e98abfe..dd0e4de8f 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -338,6 +338,8 @@ void GMainWindow::closeEvent(QCloseEvent* event)
     settings.setValue("firstStart", false);
     SaveHotkeys(settings);
 
+    ShutdownGame();
+
     render_window->close();
 
     QWidget::closeEvent(event);