From 1323ab2f5f1627b39e48b6f970ad8208fa7af71e Mon Sep 17 00:00:00 2001
From: Subv <subv2112@gmail.com>
Date: Sat, 19 Nov 2016 20:40:04 -0500
Subject: [PATCH 1/2] Kernel/Loader: Grab the system mode from the NCCH
 ExHeader.

3dsx and elf files default to system mode 2 (96MB allocated to the application).

This allows Home Menu to boot without modifications.
Closes #1849
---
 src/citra/citra.cpp            | 15 +++++++++++----
 src/citra_qt/main.cpp          | 24 ++++++++++++++++--------
 src/citra_qt/main.h            |  7 ++++++-
 src/core/hle/kernel/kernel.cpp |  6 ++----
 src/core/hle/kernel/kernel.h   |  4 ++--
 src/core/loader/loader.h       | 11 +++++++++++
 src/core/loader/ncch.cpp       |  9 +++++++++
 src/core/loader/ncch.h         |  7 +++++++
 src/core/system.cpp            |  4 ++--
 src/core/system.h              |  2 +-
 10 files changed, 67 insertions(+), 22 deletions(-)

diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp
index e47375f88..c742be231 100644
--- a/src/citra/citra.cpp
+++ b/src/citra/citra.cpp
@@ -129,16 +129,23 @@ int main(int argc, char** argv) {
 
     std::unique_ptr<EmuWindow_SDL2> emu_window = std::make_unique<EmuWindow_SDL2>();
 
-    System::Init(emu_window.get());
-    SCOPE_EXIT({ System::Shutdown(); });
-
     std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(boot_filename);
     if (!loader) {
         LOG_CRITICAL(Frontend, "Failed to obtain loader for %s!", boot_filename.c_str());
         return -1;
     }
 
-    Loader::ResultStatus load_result = loader->Load();
+    u32 system_mode;
+    Loader::ResultStatus load_result = loader->LoadKernelSystemMode(system_mode);
+    if (Loader::ResultStatus::Success != load_result) {
+        LOG_CRITICAL(Frontend, "Failed to load ROM (Error %i)!", load_result);
+        return -1;
+    }
+
+    System::Init(emu_window.get(), system_mode);
+    SCOPE_EXIT({ System::Shutdown(); });
+
+    load_result = loader->Load();
     if (Loader::ResultStatus::Success != load_result) {
         LOG_CRITICAL(Frontend, "Failed to load ROM (Error %i)!", load_result);
         return -1;
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index 0bf9f48d6..9589da4ba 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -253,7 +253,7 @@ void GMainWindow::OnDisplayTitleBars(bool show) {
     }
 }
 
-bool GMainWindow::InitializeSystem() {
+bool GMainWindow::InitializeSystem(u32 system_mode) {
     // Shutdown previous session if the emu thread is still active...
     if (emu_thread != nullptr)
         ShutdownGame();
@@ -270,7 +270,7 @@ bool GMainWindow::InitializeSystem() {
     }
 
     // Initialize the core emulation
-    System::Result system_result = System::Init(render_window);
+    System::Result system_result = System::Init(render_window, system_mode);
     if (System::Result::Success != system_result) {
         switch (system_result) {
         case System::Result::ErrorInitVideoCore:
@@ -299,8 +299,21 @@ bool GMainWindow::LoadROM(const std::string& filename) {
         return false;
     }
 
+    u32 system_mode;
+    Loader::ResultStatus load_result = app_loader->LoadKernelSystemMode(system_mode);
+    if (Loader::ResultStatus::Success != load_result) {
+        LOG_CRITICAL(Frontend, "Failed to load ROM!", load_result);
+        QMessageBox::critical(this, tr("Error while loading ROM!"),
+                              tr("Could not determine the system mode."));
+        return false;
+    }
+
+    if (!InitializeSystem(system_mode))
+        return false;
+
     Loader::ResultStatus result = app_loader->Load();
     if (Loader::ResultStatus::Success != result) {
+        System::Shutdown();
         LOG_CRITICAL(Frontend, "Failed to load ROM!");
 
         switch (result) {
@@ -338,14 +351,9 @@ void GMainWindow::BootGame(const std::string& filename) {
     LOG_INFO(Frontend, "Citra starting...");
     StoreRecentFile(filename); // Put the filename on top of the list
 
-    if (!InitializeSystem())
+    if (!LoadROM(filename))
         return;
 
-    if (!LoadROM(filename)) {
-        System::Shutdown();
-        return;
-    }
-
     // Create and start the emulation thread
     emu_thread = std::make_unique<EmuThread>(render_window);
     emit EmulationStarting(emu_thread.get());
diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h
index 82eb90aae..f87178227 100644
--- a/src/citra_qt/main.h
+++ b/src/citra_qt/main.h
@@ -60,7 +60,12 @@ signals:
     void EmulationStopping();
 
 private:
-    bool InitializeSystem();
+    /**
+     * Initializes the emulation system.
+     * @param system_mode The system mode with which to intialize the kernel.
+     * @returns Whether the system was properly initialized.
+     */
+    bool InitializeSystem(u32 system_mode);
     bool LoadROM(const std::string& filename);
     void BootGame(const std::string& filename);
     void ShutdownGame();
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index 9e1795927..0c8752670 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -124,13 +124,11 @@ void HandleTable::Clear() {
 }
 
 /// Initialize the kernel
-void Init() {
+void Init(u32 system_mode) {
     ConfigMem::Init();
     SharedPage::Init();
 
-    // TODO(yuriks): The memory type parameter needs to be determined by the ExHeader field instead
-    // For now it defaults to the one with a largest allocation to the app
-    Kernel::MemoryInit(2); // Allocates 96MB to the application
+    Kernel::MemoryInit(system_mode);
 
     Kernel::ResourceLimitsInit();
     Kernel::ThreadingInit();
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index 6b8dbecff..231cf7b75 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -286,8 +286,8 @@ private:
 
 extern HandleTable g_handle_table;
 
-/// Initialize the kernel
-void Init();
+/// Initialize the kernel with the specified system mode.
+void Init(u32 system_mode);
 
 /// Shutdown the kernel
 void Shutdown();
diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h
index 9652d7ac5..e62f77b9c 100644
--- a/src/core/loader/loader.h
+++ b/src/core/loader/loader.h
@@ -95,6 +95,17 @@ public:
      */
     virtual ResultStatus Load() = 0;
 
+    /**
+     * Loads the system mode that this application needs.
+     * This function defaults to 2 (96MB allocated to the application) if it can't read the information.
+     * @param system_mode Out variable where the system mode will be stored.
+     * @returns ResultStatus result of the operation
+     */
+    virtual ResultStatus LoadKernelSystemMode(u32& system_mode) {
+        system_mode = 2; // 96MB allocated to the application.
+        return ResultStatus::Success;
+    }
+
     /**
      * Get the code (typically .code section) of the application
      * @param buffer Reference to buffer to store data
diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp
index fadd7b16b..6fbaf4036 100644
--- a/src/core/loader/ncch.cpp
+++ b/src/core/loader/ncch.cpp
@@ -117,6 +117,14 @@ FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) {
     return FileType::Error;
 }
 
+ResultStatus AppLoader_NCCH::LoadKernelSystemMode(u32& memory_type) {
+    ResultStatus result = LoadExeFS();
+    if (result != ResultStatus::Success)
+        return result;
+    memory_type = exheader_header.arm11_system_local_caps.system_mode;
+    return ResultStatus::Success;
+}
+
 ResultStatus AppLoader_NCCH::LoadExec() {
     using Kernel::SharedPtr;
     using Kernel::CodeSet;
@@ -277,6 +285,7 @@ ResultStatus AppLoader_NCCH::LoadExeFS() {
     LOG_DEBUG(Loader, "Core version:                %d", core_version);
     LOG_DEBUG(Loader, "Thread priority:             0x%X", priority);
     LOG_DEBUG(Loader, "Resource limit category:     %d", resource_limit_category);
+    LOG_DEBUG(Loader, "System Mode:                 %d", exheader_header.arm11_system_local_caps.system_mode);
 
     if (exheader_header.arm11_system_local_caps.program_id != ncch_header.program_id) {
         LOG_ERROR(Loader, "ExHeader Program ID mismatch: the ROM is probably encrypted.");
diff --git a/src/core/loader/ncch.h b/src/core/loader/ncch.h
index f8718d063..63947c28e 100644
--- a/src/core/loader/ncch.h
+++ b/src/core/loader/ncch.h
@@ -185,6 +185,13 @@ public:
      */
     ResultStatus Load() override;
 
+    /**
+     * Loads the Exheader and returns the system mode for this application.
+     * @param system_mode Out variable where the system mode will be stored.
+     * @return ResultStatus result of the operation
+     */
+    ResultStatus LoadKernelSystemMode(u32& system_mode);
+
     /**
      * Get the code (typically .code section) of the application
      * @param buffer Reference to buffer to store data
diff --git a/src/core/system.cpp b/src/core/system.cpp
index 7d54811a0..a5f763805 100644
--- a/src/core/system.cpp
+++ b/src/core/system.cpp
@@ -17,12 +17,12 @@ namespace System {
 
 static bool is_powered_on{false};
 
-Result Init(EmuWindow* emu_window) {
+Result Init(EmuWindow* emu_window, u32 system_mode) {
     Core::Init();
     CoreTiming::Init();
     Memory::Init();
     HW::Init();
-    Kernel::Init();
+    Kernel::Init(system_mode);
     HLE::Init();
     if (!VideoCore::Init(emu_window)) {
         return Result::ErrorInitVideoCore;
diff --git a/src/core/system.h b/src/core/system.h
index 6d672b1b5..b41fc088a 100644
--- a/src/core/system.h
+++ b/src/core/system.h
@@ -15,7 +15,7 @@ enum class Result {
     ErrorInitVideoCore, ///< Something went wrong during video core init
 };
 
-Result Init(EmuWindow* emu_window);
+Result Init(EmuWindow* emu_window, u32 system_mode);
 bool IsPoweredOn();
 void Shutdown();
 }

From d171409f29ce3d8bcf7ed6ce16392b4b4ec97c4b Mon Sep 17 00:00:00 2001
From: Subv <subv2112@gmail.com>
Date: Sat, 26 Nov 2016 23:13:40 -0500
Subject: [PATCH 2/2] Kernel/Loader: Grab the system mode from the NCCH
 ExHeader.

3dsx and elf files default to system mode 2 (96MB allocated to the application).

This allows Home Menu to boot without modifications.
Closes #1849
---
 src/citra/citra.cpp      | 12 ++++++------
 src/citra_qt/main.cpp    |  9 ++++-----
 src/core/loader/loader.h | 13 +++++++------
 src/core/loader/ncch.cpp | 15 ++++++++-------
 src/core/loader/ncch.h   |  5 ++---
 5 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp
index c742be231..f9387e61c 100644
--- a/src/citra/citra.cpp
+++ b/src/citra/citra.cpp
@@ -135,17 +135,17 @@ int main(int argc, char** argv) {
         return -1;
     }
 
-    u32 system_mode;
-    Loader::ResultStatus load_result = loader->LoadKernelSystemMode(system_mode);
-    if (Loader::ResultStatus::Success != load_result) {
-        LOG_CRITICAL(Frontend, "Failed to load ROM (Error %i)!", load_result);
+    boost::optional<u32> system_mode = loader->LoadKernelSystemMode();
+
+    if (!system_mode) {
+        LOG_CRITICAL(Frontend, "Failed to load ROM (Could not determine system mode)!");
         return -1;
     }
 
-    System::Init(emu_window.get(), system_mode);
+    System::Init(emu_window.get(), system_mode.get());
     SCOPE_EXIT({ System::Shutdown(); });
 
-    load_result = loader->Load();
+    Loader::ResultStatus load_result = loader->Load();
     if (Loader::ResultStatus::Success != load_result) {
         LOG_CRITICAL(Frontend, "Failed to load ROM (Error %i)!", load_result);
         return -1;
diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp
index 9589da4ba..a3887f9ab 100644
--- a/src/citra_qt/main.cpp
+++ b/src/citra_qt/main.cpp
@@ -299,16 +299,15 @@ bool GMainWindow::LoadROM(const std::string& filename) {
         return false;
     }
 
-    u32 system_mode;
-    Loader::ResultStatus load_result = app_loader->LoadKernelSystemMode(system_mode);
-    if (Loader::ResultStatus::Success != load_result) {
-        LOG_CRITICAL(Frontend, "Failed to load ROM!", load_result);
+    boost::optional<u32> system_mode = app_loader->LoadKernelSystemMode();
+    if (!system_mode) {
+        LOG_CRITICAL(Frontend, "Failed to load ROM!");
         QMessageBox::critical(this, tr("Error while loading ROM!"),
                               tr("Could not determine the system mode."));
         return false;
     }
 
-    if (!InitializeSystem(system_mode))
+    if (!InitializeSystem(system_mode.get()))
         return false;
 
     Loader::ResultStatus result = app_loader->Load();
diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h
index e62f77b9c..5e3d46638 100644
--- a/src/core/loader/loader.h
+++ b/src/core/loader/loader.h
@@ -9,6 +9,7 @@
 #include <memory>
 #include <string>
 #include <vector>
+#include <boost/optional.hpp>
 #include "common/common_types.h"
 #include "common/file_util.h"
 
@@ -97,13 +98,13 @@ public:
 
     /**
      * Loads the system mode that this application needs.
-     * This function defaults to 2 (96MB allocated to the application) if it can't read the information.
-     * @param system_mode Out variable where the system mode will be stored.
-     * @returns ResultStatus result of the operation
+     * This function defaults to 2 (96MB allocated to the application) if it can't read the
+     * information.
+     * @returns Optional with the kernel system mode
      */
-    virtual ResultStatus LoadKernelSystemMode(u32& system_mode) {
-        system_mode = 2; // 96MB allocated to the application.
-        return ResultStatus::Success;
+    virtual boost::optional<u32> LoadKernelSystemMode() {
+        // 96MB allocated to the application.
+        return 2;
     }
 
     /**
diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp
index 6fbaf4036..d4be61e0e 100644
--- a/src/core/loader/ncch.cpp
+++ b/src/core/loader/ncch.cpp
@@ -117,12 +117,12 @@ FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) {
     return FileType::Error;
 }
 
-ResultStatus AppLoader_NCCH::LoadKernelSystemMode(u32& memory_type) {
-    ResultStatus result = LoadExeFS();
-    if (result != ResultStatus::Success)
-        return result;
-    memory_type = exheader_header.arm11_system_local_caps.system_mode;
-    return ResultStatus::Success;
+boost::optional<u32> AppLoader_NCCH::LoadKernelSystemMode() {
+    if (!is_loaded) {
+        if (LoadExeFS() != ResultStatus::Success)
+            return boost::none;
+    }
+    return exheader_header.arm11_system_local_caps.system_mode.Value();
 }
 
 ResultStatus AppLoader_NCCH::LoadExec() {
@@ -285,7 +285,8 @@ ResultStatus AppLoader_NCCH::LoadExeFS() {
     LOG_DEBUG(Loader, "Core version:                %d", core_version);
     LOG_DEBUG(Loader, "Thread priority:             0x%X", priority);
     LOG_DEBUG(Loader, "Resource limit category:     %d", resource_limit_category);
-    LOG_DEBUG(Loader, "System Mode:                 %d", exheader_header.arm11_system_local_caps.system_mode);
+    LOG_DEBUG(Loader, "System Mode:                 %d",
+              exheader_header.arm11_system_local_caps.system_mode);
 
     if (exheader_header.arm11_system_local_caps.program_id != ncch_header.program_id) {
         LOG_ERROR(Loader, "ExHeader Program ID mismatch: the ROM is probably encrypted.");
diff --git a/src/core/loader/ncch.h b/src/core/loader/ncch.h
index 63947c28e..bcf3ae6e3 100644
--- a/src/core/loader/ncch.h
+++ b/src/core/loader/ncch.h
@@ -187,10 +187,9 @@ public:
 
     /**
      * Loads the Exheader and returns the system mode for this application.
-     * @param system_mode Out variable where the system mode will be stored.
-     * @return ResultStatus result of the operation
+     * @return Optional with the kernel system mode
      */
-    ResultStatus LoadKernelSystemMode(u32& system_mode);
+    boost::optional<u32> LoadKernelSystemMode();
 
     /**
      * Get the code (typically .code section) of the application