VERY experimental Nintendo Switch 2 emulator
C++
Merge remote-tracking branch 'upstream/master' into nx
bunnei775cf60729e5
diff --cc externals/CMakeLists.txtindex b809d76d85,4a4ba11012..8f42f4fdcc--- a/externals/CMakeLists.txt+++ b/externals/CMakeLists.txt@@@ -46,6 -44,6 +49,10 @@@ add_subdirectory(soundtouch# The SoundTouch target doesn't export the necessary include paths as properties by defaulttarget_include_directories(SoundTouch INTERFACE ./soundtouch/include)++# Unicorn++add_library(unicorn-headers INTERFACE)++target_include_directories(unicorn-headers INTERFACE ./unicorn/include)++# Xbyakif (ARCHITECTURE_x86_64)# Defined before "dynarmic" abovediff --cc externals/dynarmicindex 8f15e3f70c,8f15e3f70c..69eccf826d--- a/externals/dynarmic+++ b/externals/dynarmic@@@ -1,1 -1,1 +1,1 @@@--Subproject commit 8f15e3f70cb96e56705e5de6ba97b5d09423a56b++Subproject commit 69eccf826d657a6cfb1d731b00629939d230ec5fdiff --cc externals/enetindex a84c120eff,a84c120eff..9d9ba122d4--- a/externals/enet+++ b/externals/enet@@@ -1,1 -1,1 +1,1 @@@--Subproject commit a84c120eff13d2fa3eadb41ef7afe0f7819f4d6c++Subproject commit 9d9ba122d4818f7ae1aef2197933ac696edb2331diff --cc src/common/common_types.hindex e8f7ac6be1,ee18eac815..844d349659--- a/src/common/common_types.h+++ b/src/common/common_types.h@@@ -24,6 -24,6 +24,7 @@@#pragma once++#include <array>#include <cstdint>#ifdef _MSC_VER@@@ -47,9 -47,9 +48,12 @@@ typedef double f64; ///< 64-bit floatin// TODO: It would be nice to eventually replace these with strong types that prevent accidental// conversion between each other.-typedef u32 VAddr; ///< Represents a pointer in the userspace virtual address space.-typedef u32 PAddr; ///< Represents a pointer in the ARM11 physical address space.+typedef u64 VAddr; ///< Represents a pointer in the userspace virtual address space.+typedef u64 PAddr; ///< Represents a pointer in the ARM11 physical address space.+++using u128 = std::array<std::uint64_t, 2>;++static_assert(sizeof(u128) == 16, "u128 must be 128 bits wide");+// An inheritable class to disallow the copy constructor and operator= functionsclass NonCopyable {protected:diff --cc src/core/CMakeLists.txtindex 33ce8dc81c,2618da18c4..8b25eaf0a4--- a/src/core/CMakeLists.txt+++ b/src/core/CMakeLists.txt@@@ -6,6 -6,6 +6,8 @@@ set(SRCarm/dyncom/arm_dyncom_interpreter.cpparm/dyncom/arm_dyncom_thumb.cpparm/dyncom/arm_dyncom_trans.cpp++ arm/unicorn/arm_unicorn.cpp++ arm/unicorn/unicorn_dynload.carm/skyeye_common/armstate.cpparm/skyeye_common/armsupp.cpparm/skyeye_common/vfp/vfp.cpp@@@ -198,6 -199,6 +204,8 @@@ set(HEADERarm/dyncom/arm_dyncom_run.harm/dyncom/arm_dyncom_thumb.harm/dyncom/arm_dyncom_trans.h++ arm/unicorn/arm_unicorn.h++ arm/unicorn/unicorn_dynload.harm/skyeye_common/arm_regformat.harm/skyeye_common/armstate.harm/skyeye_common/armsupp.h@@@ -394,8 -394,8 +404,8 @@@create_directory_groups(${SRCS} ${HEADERS})add_library(core STATIC ${SRCS} ${HEADERS})- target_link_libraries(core PUBLIC common PRIVATE audio_core video_core)+ target_link_libraries(core PUBLIC common PRIVATE audio_core network video_core)-target_link_libraries(core PUBLIC Boost::boost PRIVATE cryptopp dynarmic fmt)+target_link_libraries(core PUBLIC Boost::boost PRIVATE cryptopp dynarmic fmt lz4_static)if (ENABLE_WEB_SERVICE)target_link_libraries(core PUBLIC json-headers web_service)endif()diff --cc src/core/arm/arm_interface.hindex f613556dd3,ba528403c4..0b30963479--- a/src/core/arm/arm_interface.h+++ b/src/core/arm/arm_interface.h@@@ -5,6 -5,6 +5,7 @@@#pragma once#include "common/common_types.h"++#include "core/hle/kernel/vm_manager.h"#include "core/arm/skyeye_common/arm_regformat.h"#include "core/arm/skyeye_common/vfp/asm_vfp.h"@@@ -14,17 -14,14 +15,18 @@@ publicvirtual ~ARM_Interface() {}struct ThreadContext {- u32 cpu_registers[13];- u32 sp;- u32 lr;- u32 pc;- u32 cpsr;- u32 fpu_registers[64];- u32 fpscr;- u32 fpexc;+ u64 cpu_registers[30];+ u64 lr;+ u64 sp;+ u64 pc;+ u64 cpsr;- u64 fpu_registers[64];++ u128 fpu_registers[32];+ u64 fpscr;+ u64 fpexc;++++ // TODO(bunnei): Fix once we have proper support for tpidrro_el0, etc. in the JIT+ VAddr tls_address;};/**@@@ -41,6 -38,6 +43,8 @@@Run(1);}++ virtual void MapBackingMemory(VAddr address, size_t size, u8* memory, Kernel::VMAPermission perms) {}++/// Clear all instruction cachevirtual void ClearInstructionCache() = 0;@@@ -65,11 -65,11 +72,15 @@@/*** Set an ARM register- * @param index Register index (0-15)+ * @param index Register index* @param value Value to set register to*/- virtual void SetReg(int index, u32 value) = 0;+ virtual void SetReg(int index, u64 value) = 0;+++ virtual const u128& GetExtReg(int index) const = 0;++++ virtual void SetExtReg(int index, u128& value) = 0;+/*** Gets the value of a VFP register* @param index Register index (0-31)@@@ -124,16 -124,6 +135,10 @@@*/virtual void SetCP15Register(CP15Register reg, u32 value) = 0;+ virtual VAddr GetTlsAddress() const = 0;++ virtual void SetTlsAddress(VAddr address) = 0;+- /**- * Advance the CPU core by the specified number of ticks (e.g. to simulate CPU execution time)- * @param ticks Number of ticks to advance the CPU core- */- virtual void AddTicks(u64 ticks) = 0;-/*** Saves the current CPU context* @param ctx Thread context to savediff --cc src/core/arm/dynarmic/arm_dynarmic.cppindex 0ea1d76e4a,2cb56d12fc..6dcab5babe--- a/src/core/arm/dynarmic/arm_dynarmic.cpp+++ b/src/core/arm/dynarmic/arm_dynarmic.cpp@@@ -14,131 -14,98 +14,108 @@@#include "core/hle/svc.h"#include "core/memory.h"-static void InterpreterFallback(u32 pc, Dynarmic::Jit* jit, void* user_arg) {- ARMul_State* state = static_cast<ARMul_State*>(user_arg);+static void InterpreterFallback(u64 pc, Dynarmic::Jit* jit, void* user_arg) {+ UNIMPLEMENTED_MSG("InterpreterFallback for ARM64 JIT does not exist!");- //ARMul_State* state = static_cast<ARMul_State*>(user_arg);-- //state->Reg = jit->Regs();- //state->Cpsr = jit->Cpsr();- //state->Reg[15] = static_cast<u32>(pc);- //state->ExtReg = jit->ExtRegs();- //state->VFP[VFP_FPSCR] = jit->Fpscr();- //state->NumInstrsToExecute = 1;-- //InterpreterMainLoop(state);-- //bool is_thumb = (state->Cpsr & (1 << 5)) != 0;- //state->Reg[15] &= (is_thumb ? 0xFFFFFFFE : 0xFFFFFFFC);-- //jit->Regs() = state->Reg;- //jit->Cpsr() = state->Cpsr;- //jit->ExtRegs() = state->ExtReg;- //jit->SetFpscr(state->VFP[VFP_FPSCR]);+}- state->Reg = jit->Regs();- state->Cpsr = jit->Cpsr();- state->Reg[15] = pc;- state->ExtReg = jit->ExtRegs();- state->VFP[VFP_FPSCR] = jit->Fpscr();- state->NumInstrsToExecute = 1;+static bool IsReadOnlyMemory(u64 vaddr) {+ // TODO(bunnei): ImplementMe+ return false;+}- InterpreterMainLoop(state);+u8 MemoryRead8(const u64 addr) {+ return Memory::Read8(static_cast<VAddr>(addr));+}- bool is_thumb = (state->Cpsr & (1 << 5)) != 0;- state->Reg[15] &= (is_thumb ? 0xFFFFFFFE : 0xFFFFFFFC);+u16 MemoryRead16(const u64 addr) {+ return Memory::Read16(static_cast<VAddr>(addr));+}- jit->Regs() = state->Reg;- jit->Cpsr() = state->Cpsr;- jit->ExtRegs() = state->ExtReg;- jit->SetFpscr(state->VFP[VFP_FPSCR]);+u32 MemoryRead32(const u64 addr) {+ return Memory::Read32(static_cast<VAddr>(addr));}-static bool IsReadOnlyMemory(u32 vaddr) {- // TODO(bunnei): ImplementMe- return false;+u64 MemoryRead64(const u64 addr) {+ return Memory::Read64(static_cast<VAddr>(addr));+}++void MemoryWrite8(const u64 addr, const u8 data) {+ Memory::Write8(static_cast<VAddr>(addr), data);+}++void MemoryWrite16(const u64 addr, const u16 data) {+ Memory::Write16(static_cast<VAddr>(addr), data);+}++void MemoryWrite32(const u64 addr, const u32 data) {+ Memory::Write32(static_cast<VAddr>(addr), data);+}++void MemoryWrite64(const u64 addr, const u64 data) {+ Memory::Write64(static_cast<VAddr>(addr), data);}--static Dynarmic::UserCallbacks GetUserCallbacks(- const std::shared_ptr<ARMul_State>& interpeter_state) {- const std::shared_ptr<ARMul_State>& interpeter_state, Memory::PageTable* current_page_table) {++static Dynarmic::UserCallbacks GetUserCallbacks(ARM_Dynarmic* this_) {Dynarmic::UserCallbacks user_callbacks{};- //user_callbacks.InterpreterFallback = &InterpreterFallback;- //user_callbacks.user_arg = static_cast<void*>(interpeter_state.get());+ user_callbacks.InterpreterFallback = &InterpreterFallback;- user_callbacks.user_arg = static_cast<void*>(interpeter_state.get());++ user_callbacks.user_arg = static_cast<void*>(this_);user_callbacks.CallSVC = &SVC::CallSVC;user_callbacks.memory.IsReadOnlyMemory = &IsReadOnlyMemory;- user_callbacks.memory.ReadCode = &Memory::Read32;- user_callbacks.memory.Read8 = &Memory::Read8;- user_callbacks.memory.Read16 = &Memory::Read16;- user_callbacks.memory.Read32 = &Memory::Read32;- user_callbacks.memory.Read64 = &Memory::Read64;- user_callbacks.memory.Write8 = &Memory::Write8;- user_callbacks.memory.Write16 = &Memory::Write16;- user_callbacks.memory.Write32 = &Memory::Write32;- user_callbacks.memory.Write64 = &Memory::Write64;- user_callbacks.page_table = ¤t_page_table->pointers;- user_callbacks.coprocessors[15] = std::make_shared<DynarmicCP15>(interpeter_state);+ user_callbacks.memory.ReadCode = &MemoryRead32;+ user_callbacks.memory.Read8 = &MemoryRead8;+ user_callbacks.memory.Read16 = &MemoryRead16;+ user_callbacks.memory.Read32 = &MemoryRead32;+ user_callbacks.memory.Read64 = &MemoryRead64;+ user_callbacks.memory.Write8 = &MemoryWrite8;+ user_callbacks.memory.Write16 = &MemoryWrite16;+ user_callbacks.memory.Write32 = &MemoryWrite32;+ user_callbacks.memory.Write64 = &MemoryWrite64;+ //user_callbacks.page_table = Memory::GetCurrentPageTablePointers();- user_callbacks.coprocessors[15] = std::make_shared<DynarmicCP15>(interpeter_state);return user_callbacks;}ARM_Dynarmic::ARM_Dynarmic(PrivilegeMode initial_mode) {-- interpreter_state = std::make_shared<ARMul_State>(initial_mode);- jit = std::make_unique<Dynarmic::Jit>(GetUserCallbacks(interpreter_state), Dynarmic::Arch::ARM64);- PageTableChanged();+ }+-void ARM_Dynarmic::SetPC(u32 pc) {- jit->Regs()[15] = pc;++void ARM_Dynarmic::MapBackingMemory(VAddr address, size_t size, u8* memory, Kernel::VMAPermission perms) {+}++void ARM_Dynarmic::SetPC(u64 pc) {+ jit->Regs64()[32] = pc;+}++u64 ARM_Dynarmic::GetPC() const {+ return jit->Regs64()[32];+}++u64 ARM_Dynarmic::GetReg(int index) const {+ return jit->Regs64()[index];}-u32 ARM_Dynarmic::GetPC() const {- return jit->Regs()[15];+void ARM_Dynarmic::SetReg(int index, u64 value) {+ jit->Regs64()[index] = value;}-u32 ARM_Dynarmic::GetReg(int index) const {- return jit->Regs()[index];++const u128& ARM_Dynarmic::GetExtReg(int index) const {++ return jit->ExtRegs64()[index];+ }+-void ARM_Dynarmic::SetReg(int index, u32 value) {- jit->Regs()[index] = value;++void ARM_Dynarmic::SetExtReg(int index, u128& value) {++ jit->ExtRegs64()[index] = value;+ }+u32 ARM_Dynarmic::GetVFPReg(int index) const {-- return jit->ExtRegs()[index];++ return {};}void ARM_Dynarmic::SetVFPReg(int index, u32 value) {-- jit->ExtRegs()[index] = value;}u32 ARM_Dynarmic::GetVFPSystemReg(VFPSystemRegister reg) const {-- if (reg == VFP_FPSCR) {-- return jit->Fpscr();-- }---- // Dynarmic does not implement and/or expose other VFP registers, fallback to interpreter state-- return interpreter_state->VFP[reg];++ return {};}void ARM_Dynarmic::SetVFPSystemReg(VFPSystemRegister reg, u32 value) {-- if (reg == VFP_FPSCR) {-- jit->SetFpscr(value);-- }---- // Dynarmic does not implement and/or expose other VFP registers, fallback to interpreter state-- interpreter_state->VFP[reg] = value;}u32 ARM_Dynarmic::GetCPSR() const {@@@ -150,28 -117,13 +127,20 @@@ void ARM_Dynarmic::SetCPSR(u32 cpsr)}u32 ARM_Dynarmic::GetCP15Register(CP15Register reg) {-- return interpreter_state->CP15[reg];++ return {};}void ARM_Dynarmic::SetCP15Register(CP15Register reg, u32 value) {-- interpreter_state->CP15[reg] = value;+}++VAddr ARM_Dynarmic::GetTlsAddress() const {+ return jit->TlsAddr();+}++void ARM_Dynarmic::SetTlsAddress(VAddr address) {+ jit->TlsAddr() = address;}- void ARM_Dynarmic::AddTicks(u64 ticks) {- down_count -= ticks;- if (down_count < 0) {- CoreTiming::Advance();- }- }-MICROPROFILE_DEFINE(ARM_Jit, "ARM JIT", "ARM JIT", MP_RGB(255, 64, 64));void ARM_Dynarmic::ExecuteInstructions(int num_instructions) {@@@ -183,35 -136,29 +153,29 @@@}void ARM_Dynarmic::SaveContext(ARM_Interface::ThreadContext& ctx) {- memcpy(ctx.cpu_registers, jit->Regs().data(), sizeof(ctx.cpu_registers));- memcpy(ctx.fpu_registers, jit->ExtRegs().data(), sizeof(ctx.fpu_registers));+ memcpy(ctx.cpu_registers, jit->Regs64().data(), sizeof(ctx.cpu_registers));- //memcpy(ctx.fpu_registers, jit->ExtRegs().data(), sizeof(ctx.fpu_registers));++ memcpy(ctx.fpu_registers, jit->ExtRegs64().data(), sizeof(ctx.fpu_registers));- ctx.sp = jit->Regs()[13];- ctx.lr = jit->Regs()[14];- ctx.pc = jit->Regs()[15];+ ctx.lr = jit->Regs64()[30];+ ctx.sp = jit->Regs64()[31];+ ctx.pc = jit->Regs64()[32];ctx.cpsr = jit->Cpsr();-- ctx.fpscr = jit->Fpscr();-- ctx.fpexc = interpreter_state->VFP[VFP_FPEXC];-+ // TODO(bunnei): Fix once we have proper support for tpidrro_el0, etc. in the JIT+ ctx.tls_address = jit->TlsAddr();}void ARM_Dynarmic::LoadContext(const ARM_Interface::ThreadContext& ctx) {- memcpy(jit->Regs().data(), ctx.cpu_registers, sizeof(ctx.cpu_registers));- memcpy(jit->ExtRegs().data(), ctx.fpu_registers, sizeof(ctx.fpu_registers));+ memcpy(jit->Regs64().data(), ctx.cpu_registers, sizeof(ctx.cpu_registers));- //memcpy(jit->ExtRegs().data(), ctx.fpu_registers, sizeof(ctx.fpu_registers));++ memcpy(jit->ExtRegs64().data(), ctx.fpu_registers, sizeof(ctx.fpu_registers));- jit->Regs()[13] = ctx.sp;- jit->Regs()[14] = ctx.lr;- jit->Regs()[15] = ctx.pc;+ jit->Regs64()[30] = ctx.lr;+ jit->Regs64()[31] = ctx.sp;+ jit->Regs64()[32] = ctx.pc;jit->Cpsr() = ctx.cpsr;-- jit->SetFpscr(ctx.fpscr);-- interpreter_state->VFP[VFP_FPEXC] = ctx.fpexc;-+ // TODO(bunnei): Fix once we have proper support for tpidrro_el0, etc. in the JIT+ jit->TlsAddr() = ctx.tls_address;}void ARM_Dynarmic::PrepareReschedule() {@@@ -223,3 -170,16 +187,16 @@@void ARM_Dynarmic::ClearInstructionCache() {jit->ClearCache();}++ void ARM_Dynarmic::PageTableChanged() {+ current_page_table = Memory::GetCurrentPageTable();++ auto iter = jits.find(current_page_table);+ if (iter != jits.end()) {+ jit = iter->second.get();+ return;+ }+- jit = new Dynarmic::Jit(GetUserCallbacks(interpreter_state, current_page_table));++ jit = new Dynarmic::Jit(GetUserCallbacks(this), Dynarmic::Arch::ARM64);+ jits.emplace(current_page_table, std::unique_ptr<Dynarmic::Jit>(jit));+ }diff --cc src/core/arm/dynarmic/arm_dynarmic.hindex fcdc1c0e02,0b00158a52..6567359b01--- a/src/core/arm/dynarmic/arm_dynarmic.h+++ b/src/core/arm/dynarmic/arm_dynarmic.h@@@ -14,10 -19,10 +19,14 @@@ class ARM_Dynarmic final : public ARM_Ipublic:ARM_Dynarmic(PrivilegeMode initial_mode);- void SetPC(u32 pc) override;- u32 GetPC() const override;- u32 GetReg(int index) const override;- void SetReg(int index, u32 value) override;++ void MapBackingMemory(VAddr address, size_t size, u8* memory, Kernel::VMAPermission perms) override;+++ void SetPC(u64 pc) override;+ u64 GetPC() const override;+ u64 GetReg(int index) const override;+ void SetReg(int index, u64 value) override;++ const u128& GetExtReg(int index) const override;++ void SetExtReg(int index, u128& value) override;u32 GetVFPReg(int index) const override;void SetVFPReg(int index, u32 value) override;u32 GetVFPSystemReg(VFPSystemRegister reg) const override;@@@ -26,11 -31,7 +35,9 @@@void SetCPSR(u32 cpsr) override;u32 GetCP15Register(CP15Register reg) override;void SetCP15Register(CP15Register reg, u32 value) override;+ VAddr GetTlsAddress() const override;+ void SetTlsAddress(VAddr address) override;- void AddTicks(u64 ticks) override;-void SaveContext(ThreadContext& ctx) override;void LoadContext(const ThreadContext& ctx) override;@@@ -38,8 -39,11 +45,10 @@@void ExecuteInstructions(int num_instructions) override;void ClearInstructionCache() override;+ void PageTableChanged() override;private:- std::unique_ptr<Dynarmic::Jit> jit;- std::shared_ptr<ARMul_State> interpreter_state;+ Dynarmic::Jit* jit = nullptr;+ Memory::PageTable* current_page_table = nullptr;+ std::map<Memory::PageTable*, std::unique_ptr<Dynarmic::Jit>> jits;- std::shared_ptr<ARMul_State> interpreter_state;};diff --cc src/core/arm/dyncom/arm_dyncom.cppindex 99758fc2a3,4d72aef775..5ebf7a2f16--- a/src/core/arm/dyncom/arm_dyncom.cpp+++ b/src/core/arm/dyncom/arm_dyncom.cpp@@@ -25,11 -25,15 +25,15 @@@ void ARM_DynCom::ClearInstructionCache(trans_cache_buf_top = 0;}-void ARM_DynCom::PageTableChanged() {- ClearInstructionCache();+void ARM_DynCom::SetPC(u64 pc) {+ state->Reg[15] = pc;}-void ARM_DynCom::SetPC(u32 pc) {- state->Reg[15] = pc;++void ARM_DynCom::PageTableChanged() {++ ClearInstructionCache();+ }+-u32 ARM_DynCom::GetPC() const {+u64 ARM_DynCom::GetPC() const {return state->Reg[15];}@@@ -41,6 -45,6 +45,13 @@@ void ARM_DynCom::SetReg(int index, u64state->Reg[index] = value;}++const u128& ARM_DynCom::GetExtReg(int index) const {++ return {};++}++++void ARM_DynCom::SetExtReg(int index, u128& value) {++}++u32 ARM_DynCom::GetVFPReg(int index) const {return state->ExtReg[index];}@@@ -73,19 -77,6 +84,13 @@@ void ARM_DynCom::SetCP15Register(CP15Restate->CP15[reg] = value;}+VAddr ARM_DynCom::GetTlsAddress() const {+ return {};+}++void ARM_DynCom::SetTlsAddress(VAddr /*address*/) {+}+- void ARM_DynCom::AddTicks(u64 ticks) {- down_count -= ticks;- if (down_count < 0)- CoreTiming::Advance();- }-void ARM_DynCom::ExecuteInstructions(int num_instructions) {state->NumInstrsToExecute = num_instructions;diff --cc src/core/arm/dyncom/arm_dyncom.hindex 44e674ae2c,fc1ffed6aa..cc3c0f3daf--- a/src/core/arm/dyncom/arm_dyncom.h+++ b/src/core/arm/dyncom/arm_dyncom.h@@@ -16,11 -16,12 +16,14 @@@ public~ARM_DynCom();void ClearInstructionCache() override;+ void PageTableChanged() override;- void SetPC(u32 pc) override;- u32 GetPC() const override;- u32 GetReg(int index) const override;- void SetReg(int index, u32 value) override;+ void SetPC(u64 pc) override;+ u64 GetPC() const override;+ u64 GetReg(int index) const override;+ void SetReg(int index, u64 value) override;++ const u128& GetExtReg(int index) const override;++ void SetExtReg(int index, u128& value) override;u32 GetVFPReg(int index) const override;void SetVFPReg(int index, u32 value) override;u32 GetVFPSystemReg(VFPSystemRegister reg) const override;@@@ -29,11 -30,7 +32,9 @@@void SetCPSR(u32 cpsr) override;u32 GetCP15Register(CP15Register reg) override;void SetCP15Register(CP15Register reg, u32 value) override;+ VAddr GetTlsAddress() const override;+ void SetTlsAddress(VAddr address) override;- void AddTicks(u64 ticks) override;-void SaveContext(ThreadContext& ctx) override;void LoadContext(const ThreadContext& ctx) override;diff --cc src/core/core.cppindex d08f18623f,0c7a729871..c5448630f6--- a/src/core/core.cpp+++ b/src/core/core.cpp@@@ -9,6 -9,6 +9,7 @@@#include "core/arm/arm_interface.h"#include "core/arm/dynarmic/arm_dynarmic.h"#include "core/arm/dyncom/arm_dyncom.h"++#include "core/arm/unicorn/arm_unicorn.h"#include "core/core.h"#include "core/core_timing.h"#include "core/gdbstub/gdbstub.h"diff --cc src/core/file_sys/archive_selfncch.cppindex 298a37a448,a16941c70e..3222000cf3--- a/src/core/file_sys/archive_selfncch.cpp+++ b/src/core/file_sys/archive_selfncch.cpp@@@ -240,8 -278,9 +278,10 @@@ void ArchiveFactory_SelfNCCH::Register(}ResultVal<std::unique_ptr<ArchiveBackend>> ArchiveFactory_SelfNCCH::Open(const Path& path) {- auto archive = std::make_unique<SelfNCCHArchive>(ncch_data);- auto archive = std::make_unique<SelfNCCHArchive>(- ncch_data[Kernel::g_current_process->codeset->program_id]);-- return MakeResult<std::unique_ptr<ArchiveBackend>>(std::move(archive));++ //auto archive = std::make_unique<SelfNCCHArchive>(++ // ncch_data[Kernel::g_current_process->codeset->program_id]);++ //return MakeResult<std::unique_ptr<ArchiveBackend>>(std::move(archive));++ return {};}ResultCode ArchiveFactory_SelfNCCH::Format(const Path&, const FileSys::ArchiveFormatInfo&) {diff --cc src/core/hle/function_wrappers.hindex bc81c06b4c,f93439f21f..31fda6db32--- a/src/core/hle/function_wrappers.h+++ b/src/core/hle/function_wrappers.h@@@ -24,19 -24,19 +24,37 @@@ static inline void FuncReturn(u64 res)Core::CPU().SetReg(0, res);}--/**-- * HLE a function return (64-bit) from the current ARM11 userland process-- * @param res Result to return (64-bit)-- * @todo Verify that this function is correct-- */--static inline void FuncReturn64(u64 res) {-- Core::CPU().SetReg(0, (u32)(res & 0xFFFFFFFF));-- Core::CPU().SetReg(1, (u32)((res >> 32) & 0xFFFFFFFF));--}--////////////////////////////////////////////////////////////////////////////////////////////////////// Function wrappers that return type ResultCode++template <ResultCode func(u64)>++void Wrap() {++ FuncReturn(func(PARAM(0)).raw);++}++++template <ResultCode func(u32, u64, u32)>++void Wrap() {++ FuncReturn(func(PARAM(0), PARAM(1), PARAM(2)).raw);++}++++template <ResultCode func(u64, u32)>++void Wrap() {++ FuncReturn(func(PARAM(0), PARAM(1)).raw);++}++++template <ResultCode func(u64, u64, u64)>++void Wrap() {++ FuncReturn(func(PARAM(0), PARAM(1), PARAM(2)).raw);++}++++template <ResultCode func(u64*, u64, u64, u64)>++void Wrap() {++ u64 param_1 = 0;++ u32 retval = func(¶m_1, PARAM(1), PARAM(2), PARAM(3)).raw;++ Core::CPU().SetReg(1, param_1);++ FuncReturn(retval);++}++template <ResultCode func(u32, u32, u32, u32)>void Wrap() {FuncReturn(func(PARAM(0), PARAM(1), PARAM(2), PARAM(3)).raw);@@@ -85,6 -84,6 +102,14 @@@ void Wrap()func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), (((s64)PARAM(5) << 32) | PARAM(4))).raw);}++template <ResultCode func(u32, u64*)>++void Wrap() {++ u64 param_1 = 0;++ u32 retval = func(PARAM(0), ¶m_1).raw;++ Core::CPU().SetReg(1, param_1);++ FuncReturn(retval);++}++template <ResultCode func(u32*)>void Wrap() {u32 param_1 = 0;@@@ -100,16 -99,16 +125,17 @@@ void Wrap()FuncReturn(retval);}--template <ResultCode func(MemoryInfo*, PageInfo*, u32)>++template <ResultCode func(MemoryInfo*, PageInfo*, u64)>void Wrap() {MemoryInfo memory_info = {};PageInfo page_info = {};u32 retval = func(&memory_info, &page_info, PARAM(2)).raw;-- Core::CPU().SetReg(1, memory_info.base_address);-- Core::CPU().SetReg(2, memory_info.size);-- Core::CPU().SetReg(3, memory_info.permission);-- Core::CPU().SetReg(4, memory_info.state);-- Core::CPU().SetReg(5, page_info.flags);++++ Memory::Write64(PARAM(0), memory_info.base_address);++ Memory::Write64(PARAM(0) + 8, memory_info.size);++ Memory::Write64(PARAM(0) + 16, memory_info.permission);++ Memory::Write64(PARAM(0) + 24, memory_info.state);++FuncReturn(retval);}@@@ -139,7 -138,7 +165,7 @@@ void Wrap()FuncReturn(func(PARAM(0), (s32)PARAM(1)).raw);}--template <ResultCode func(u32*, u32)>++template <ResultCode func(u32*, u64)>void Wrap() {u32 param_1 = 0;u32 retval = func(¶m_1, PARAM(1)).raw;@@@ -244,6 -226,6 +253,11 @@@ void Wrap()FuncReturn(retval);}++template <ResultCode func(u32, u32, u32)>++void Wrap() {++ FuncReturn(func(PARAM(0), PARAM(1), PARAM(2)).raw);++}++////////////////////////////////////////////////////////////////////////////////////////////////////// Function wrappers that return type u32@@@ -268,14 -250,14 +282,14 @@@ void Wrap()func(((s64)PARAM(1) << 32) | PARAM(0));}- template <void func(const char*, int len)>+ template <void func(VAddr, int len)>void Wrap() {- func((char*)Memory::GetPointer(PARAM(0)), PARAM(1));+ func(PARAM(0), PARAM(1));}--template <void func(u8)>++template <void func(u64, u64, u64)>void Wrap() {-- func((u8)PARAM(0));++ func(PARAM(0), PARAM(1), PARAM(2));}#undef PARAMdiff --cc src/core/hle/kernel/mutex.cppindex cef9612899,2cbca5e5be..30dade552f--- a/src/core/hle/kernel/mutex.cpp+++ b/src/core/hle/kernel/mutex.cpp@@@ -25,10 -25,10 +25,11 @@@ void ReleaseThreadMutexes(Thread* threaMutex::Mutex() {}Mutex::~Mutex() {}--SharedPtr<Mutex> Mutex::Create(bool initial_locked, std::string name) {++SharedPtr<Mutex> Mutex::Create(bool initial_locked, VAddr addr, std::string name) {SharedPtr<Mutex> mutex(new Mutex);mutex->lock_count = 0;++ mutex->addr = addr;mutex->name = std::move(name);mutex->holding_thread = nullptr;diff --cc src/core/hle/kernel/mutex.hindex bacacd6902,bacacd6902..503d3ee750--- a/src/core/hle/kernel/mutex.h+++ b/src/core/hle/kernel/mutex.h@@@ -21,7 -21,7 +21,7 @@@ public* @param name Optional name of mutex* @return Pointer to new Mutex object*/-- static SharedPtr<Mutex> Create(bool initial_locked, std::string name = "Unknown");++ static SharedPtr<Mutex> Create(bool initial_locked, VAddr addr, std::string name = "Unknown");std::string GetTypeName() const override {return "Mutex";@@@ -39,6 -39,6 +39,7 @@@u32 priority; ///< The priority of the mutex, used for priority inheritance.std::string name; ///< Name of mutex (optional)SharedPtr<Thread> holding_thread; ///< Thread that has acquired the mutex++ VAddr addr;/*** Elevate the mutex priority to the best prioritydiff --cc src/core/hle/kernel/process.cppindex 84ebdbc582,cf3163e0fe..9e145866f9--- a/src/core/hle/kernel/process.cpp+++ b/src/core/hle/kernel/process.cpp@@@ -129,27 -147,7 +129,28 @@@ void Process::Run(VAddr entry_point, s3}vm_manager.LogLayout(Log::Level::Debug);- Kernel::SetupMainThread(entry_point, main_thread_priority);- Kernel::SetupMainThread(codeset->entrypoint, main_thread_priority, this);++++ Kernel::SetupMainThread(entry_point, main_thread_priority, this);+}++void Process::LoadModule(SharedPtr<CodeSet> module_, VAddr base_addr) {+ memory_region = GetMemoryRegion(flags.memory_region);++ auto MapSegment = [&](CodeSet::Segment& segment, VMAPermission permissions,+ MemoryState memory_state) {+ auto vma = vm_manager+ .MapMemoryBlock(segment.addr + base_addr, module_->memory, segment.offset, segment.size,+ memory_state)+ .Unwrap();+ vm_manager.Reprotect(vma, permissions);+ misc_memory_used += segment.size;+ memory_region->used += segment.size;+ };++ // Map CodeSet segments+ MapSegment(module_->code, VMAPermission::ReadWrite, MemoryState::Private);+ MapSegment(module_->rodata, VMAPermission::Read, MemoryState::Static);+ MapSegment(module_->data, VMAPermission::ReadWrite, MemoryState::Static);}VAddr Process::GetLinearHeapAreaAddress() const {diff --cc src/core/hle/kernel/semaphore.cppindex fcf5867288,fcf5867288..2605b25953--- a/src/core/hle/kernel/semaphore.cpp+++ b/src/core/hle/kernel/semaphore.cpp@@@ -13,7 -13,7 +13,7 @@@ namespace KernelSemaphore::Semaphore() {}Semaphore::~Semaphore() {}--ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count,++ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count, VAddr address,std::string name) {if (initial_count > max_count)@@@ -25,6 -25,6 +25,7 @@@// and the rest is reserved for the caller threadsemaphore->max_count = max_count;semaphore->available_count = initial_count;++ semaphore->address = address;semaphore->name = std::move(name);return MakeResult<SharedPtr<Semaphore>>(std::move(semaphore));diff --cc src/core/hle/kernel/semaphore.hindex 7b0cacf2ef,7b0cacf2ef..77c491a246--- a/src/core/hle/kernel/semaphore.h+++ b/src/core/hle/kernel/semaphore.h@@@ -22,7 -22,7 +22,7 @@@ public* @param name Optional name of semaphore* @return The created semaphore*/-- static ResultVal<SharedPtr<Semaphore>> Create(s32 initial_count, s32 max_count,++ static ResultVal<SharedPtr<Semaphore>> Create(s32 initial_count, s32 max_count, VAddr address,std::string name = "Unknown");std::string GetTypeName() const override {@@@ -39,6 -39,6 +39,7 @@@s32 max_count; ///< Maximum number of simultaneous holders the semaphore can haves32 available_count; ///< Number of free slots left in the semaphore++ VAddr address;std::string name; ///< Name of semaphore (optional)bool ShouldWait(Thread* thread) const override;diff --cc src/core/hle/kernel/thread.cppindex c01d08ebb8,0f7970ebee..75df49ac2a--- a/src/core/hle/kernel/thread.cpp+++ b/src/core/hle/kernel/thread.cpp@@@ -477,12 -494,10 +494,13 @@@ void Thread::BoostPriority(u32 prioritycurrent_priority = priority;}- SharedPtr<Thread> SetupMainThread(VAddr entry_point, s32 priority) {- DEBUG_ASSERT(!GetCurrentThread());+ SharedPtr<Thread> SetupMainThread(u32 entry_point, u32 priority, SharedPtr<Process> owner_process) {++ // Setup page table so we can write to memory++ SetCurrentPageTable(&Kernel::g_current_process->vm_manager.page_table);+// Initialize new "main" threadauto thread_res = Thread::Create("main", entry_point, priority, 0, THREADPROCESSORID_0,- Memory::HEAP_VADDR_END);+ Memory::HEAP_VADDR_END, owner_process);SharedPtr<Thread> thread = std::move(thread_res).Unwrap();diff --cc src/core/hle/kernel/thread.hindex 2cadb91dbf,314fba81f4..fafcab156a--- a/src/core/hle/kernel/thread.h+++ b/src/core/hle/kernel/thread.h@@@ -171,11 -184,11 +184,11 @@@ publicu32 thread_id;u32 status;- u32 entry_point;- u32 stack_top;+ VAddr entry_point;+ VAddr stack_top;- s32 nominal_priority; ///< Nominal thread priority, as set by the emulated application- s32 current_priority; ///< Current thread priority, can be temporarily changed+ u32 nominal_priority; ///< Nominal thread priority, as set by the emulated application+ u32 current_priority; ///< Current thread priority, can be temporarily changedu64 last_running_ticks; ///< CPU tick when thread was last runningdiff --cc src/core/hle/kernel/vm_manager.cppindex f70c325015,7a007c0656..9762ef535c--- a/src/core/hle/kernel/vm_manager.cpp+++ b/src/core/hle/kernel/vm_manager.cpp@@@ -4,8 -4,8 +4,10 @@@#include <iterator>#include "common/assert.h"++#include "core/arm/arm_interface.h"#include "core/hle/kernel/errors.h"#include "core/hle/kernel/vm_manager.h"++#include "core/core.h"#include "core/memory.h"#include "core/memory_setup.h"#include "core/mmio.h"@@@ -56,7 -56,11 +58,11 @@@ void VMManager::Reset()initial_vma.size = MAX_ADDRESS;vma_map.emplace(initial_vma.base, initial_vma);+ page_table.pointers.fill(nullptr);+ page_table.attributes.fill(Memory::PageType::Unmapped);+ page_table.cached_res_count.fill(0);+- UpdatePageTableForVMA(initial_vma);+ //UpdatePageTableForVMA(initial_vma);}VMManager::VMAHandle VMManager::FindVMA(VAddr target) const {@@@ -79,6 -83,6 +85,8 @@@ ResultVal<VMManager::VMAHandle> VMManagVirtualMemoryArea& final_vma = vma_handle->second;ASSERT(final_vma.size == size);++ Core::CPU().MapBackingMemory(target, size, block->data() + offset, VMAPermission::ReadWriteExecute);++final_vma.type = VMAType::AllocatedMemoryBlock;final_vma.permissions = VMAPermission::ReadWrite;final_vma.meminfo_state = state;@@@ -98,6 -102,6 +106,8 @@@ ResultVal<VMManager::VMAHandle> VMManagVirtualMemoryArea& final_vma = vma_handle->second;ASSERT(final_vma.size == size);++ Core::CPU().MapBackingMemory(target, size, memory, VMAPermission::ReadWriteExecute);++final_vma.type = VMAType::BackingMemory;final_vma.permissions = VMAPermission::ReadWrite;final_vma.meminfo_state = state;diff --cc src/core/hle/service/apt/apt.cppindex 5c44b43bb5,59ea9823df..912ab550de--- a/src/core/hle/service/apt/apt.cpp+++ b/src/core/hle/service/apt/apt.cpp@@@ -779,17 -1073,7 +1073,17 @@@ void Init()MemoryPermission::ReadWrite, MemoryPermission::Read, 0,Kernel::MemoryRegion::SYSTEM, "APT:SharedFont");- lock = Kernel::Mutex::Create(false, "APT_U:Lock");+ if (LoadSharedFont()) {+ shared_font_loaded = true;+ } else if (LoadLegacySharedFont()) {+ LOG_WARNING(Service_APT, "Loaded shared font by legacy method");+ shared_font_loaded = true;+ } else {+ LOG_WARNING(Service_APT, "Unable to load shared font");+ shared_font_loaded = false;+ }+- lock = Kernel::Mutex::Create(false, "APT_U:Lock");++ lock = Kernel::Mutex::Create(false, 0, "APT_U:Lock");cpu_percent = 0;unknown_ns_state_field = 0;diff --cc src/core/hle/service/csnd_snd.cppindex 9471ec1efe,9471ec1efe..aac903ccbd--- a/src/core/hle/service/csnd_snd.cpp+++ b/src/core/hle/service/csnd_snd.cpp@@@ -47,7 -47,7 +47,7 @@@ static void Initialize(Interface* selfMemoryPermission::ReadWrite, 0,Kernel::MemoryRegion::BASE, "CSND:SharedMemory");-- mutex = Kernel::Mutex::Create(false, "CSND:mutex");++ mutex = Kernel::Mutex::Create(false, 0, "CSND:mutex");cmd_buff[1] = RESULT_SUCCESS.raw;cmd_buff[2] = IPC::CopyHandleDesc(2);diff --cc src/core/hle/service/sm/srv.cppindex 352941e697,5c955cf541..fb873981cc--- a/src/core/hle/service/sm/srv.cpp+++ b/src/core/hle/service/sm/srv.cpp@@@ -61,7 -62,7 +62,7 @@@ void SRV::EnableNotification(Kernel::HLIPC::RequestParser rp(ctx, 0x2, 0, 0);notification_semaphore =-- Kernel::Semaphore::Create(0, MAX_PENDING_NOTIFICATIONS, "SRV:Notification").Unwrap();++ Kernel::Semaphore::Create(0, MAX_PENDING_NOTIFICATIONS, 0, "SRV:Notification").Unwrap();IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);rb.Push(RESULT_SUCCESS);diff --cc src/core/hw/gpu.cppindex 6838e449ca,83ad9d898a..d1bfe51e67--- a/src/core/hw/gpu.cpp+++ b/src/core/hw/gpu.cpp@@@ -515,15 -515,15 +515,15 @@@ template void Write<u8>(u32 addr, cons/// Update hardwarestatic void VBlankCallback(u64 userdata, int cycles_late) {-- VideoCore::g_renderer->SwapBuffers();---- // Signal to GSP that GPU interrupt has occurred-- // TODO(yuriks): hwtest to determine if PDC0 is for the Top screen and PDC1 for the Sub-- // screen, or if both use the same interrupts and these two instead determine the-- // beginning and end of the VBlank period. If needed, split the interrupt firing into-- // two different intervals.-- Service::GSP::SignalInterrupt(Service::GSP::InterruptId::PDC0);-- Service::GSP::SignalInterrupt(Service::GSP::InterruptId::PDC1);++ //VideoCore::g_renderer->SwapBuffers();++++ //// Signal to GSP that GPU interrupt has occurred++ //// TODO(yuriks): hwtest to determine if PDC0 is for the Top screen and PDC1 for the Sub++ //// screen, or if both use the same interrupts and these two instead determine the++ //// beginning and end of the VBlank period. If needed, split the interrupt firing into++ //// two different intervals.++ //Service::GSP::SignalInterrupt(Service::GSP::InterruptId::PDC0);++ //Service::GSP::SignalInterrupt(Service::GSP::InterruptId::PDC1);// Reschedule recurrent eventCoreTiming::ScheduleEvent(frame_ticks - cycles_late, vblank_event);diff --cc src/core/loader/3dsx.cppindex 209328347f,918038f1e3..7b0342cc95--- a/src/core/loader/3dsx.cpp+++ b/src/core/loader/3dsx.cpp@@@ -267,19 -267,17 +267,17 @@@ ResultStatus AppLoader_THREEDSX::Load(Kreturn ResultStatus::Error;codeset->name = filename;- Kernel::g_current_process = Kernel::Process::Create("main");- Kernel::g_current_process->LoadModule(codeset, codeset->entrypoint);- Kernel::g_current_process->svc_access_mask.set();- Kernel::g_current_process->address_mappings = default_address_mappings;- process = Kernel::Process::Create(std::move(codeset));++ process = Kernel::Process::Create("main");++ process->LoadModule(codeset, codeset->entrypoint);+ process->svc_access_mask.set();+ process->address_mappings = default_address_mappings;// Attach the default resource limit (APPLICATION) to the process- Kernel::g_current_process->resource_limit =+ process->resource_limit =Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);-- process->Run(48, Kernel::DEFAULT_STACK_SIZE);++ process->Run(codeset->entrypoint, 48, Kernel::DEFAULT_STACK_SIZE);- Kernel::g_current_process->Run(codeset->entrypoint, 48, Kernel::DEFAULT_STACK_SIZE);-- Service::FS::RegisterArchiveType(std::make_unique<FileSys::ArchiveFactory_SelfNCCH>(*this),- Service::FS::ArchiveIdCode::SelfNCCH);+ Service::FS::RegisterSelfNCCH(*this);is_loaded = true;return ResultStatus::Success;diff --cc src/core/loader/elf.cppindex 2efc67ff87,e36e421200..9969a8c397--- a/src/core/loader/elf.cpp+++ b/src/core/loader/elf.cpp@@@ -401,16 -394,15 +401,16 @@@ ResultStatus AppLoader_ELF::Load(KernelSharedPtr<CodeSet> codeset = elf_reader.LoadInto(Memory::PROCESS_IMAGE_VADDR);codeset->name = filename;- Kernel::g_current_process = Kernel::Process::Create("main");- Kernel::g_current_process->LoadModule(codeset, codeset->entrypoint);- Kernel::g_current_process->svc_access_mask.set();- Kernel::g_current_process->address_mappings = default_address_mappings;- process = Kernel::Process::Create(std::move(codeset));++ process = Kernel::Process::Create("main");++ process->LoadModule(codeset, codeset->entrypoint);+ process->svc_access_mask.set();+ process->address_mappings = default_address_mappings;// Attach the default resource limit (APPLICATION) to the process- Kernel::g_current_process->resource_limit =+ process->resource_limit =Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);- Kernel::g_current_process->Run(codeset->entrypoint, 48, Kernel::DEFAULT_STACK_SIZE);- process->Run(48, Kernel::DEFAULT_STACK_SIZE);++ process->Run(codeset->entrypoint, 48, Kernel::DEFAULT_STACK_SIZE);is_loaded = true;return ResultStatus::Success;diff --cc src/core/loader/ncch.cppindex 728886ea89,52686e3641..e33a37b2e6--- a/src/core/loader/ncch.cpp+++ b/src/core/loader/ncch.cpp@@@ -168,27 -118,27 +118,28 @@@ ResultStatus AppLoader_NCCH::LoadExec(Kcodeset->entrypoint = codeset->code.addr;codeset->memory = std::make_shared<std::vector<u8>>(std::move(code));- Kernel::g_current_process = Kernel::Process::Create("main");- Kernel::g_current_process->LoadModule(codeset, codeset->entrypoint);- process = Kernel::Process::Create(std::move(codeset));++ process = Kernel::Process::Create("main");++ process->LoadModule(codeset, codeset->entrypoint);// Attach a resource limit to the process based on the resource limit category- Kernel::g_current_process->resource_limit =+ process->resource_limit =Kernel::ResourceLimit::GetForCategory(static_cast<Kernel::ResourceLimitCategory>(- exheader_header.arm11_system_local_caps.resource_limit_category));+ overlay_ncch->exheader_header.arm11_system_local_caps.resource_limit_category));// Set the default CPU core for this process- Kernel::g_current_process->ideal_processor =- exheader_header.arm11_system_local_caps.ideal_processor;+ process->ideal_processor =+ overlay_ncch->exheader_header.arm11_system_local_caps.ideal_processor;// Copy data while converting endianness- std::array<u32, ARRAY_SIZE(exheader_header.arm11_kernel_caps.descriptors)> kernel_caps;- std::copy_n(exheader_header.arm11_kernel_caps.descriptors, kernel_caps.size(),+ std::array<u32, ARRAY_SIZE(overlay_ncch->exheader_header.arm11_kernel_caps.descriptors)>+ kernel_caps;+ std::copy_n(overlay_ncch->exheader_header.arm11_kernel_caps.descriptors, kernel_caps.size(),begin(kernel_caps));- Kernel::g_current_process->ParseKernelCaps(kernel_caps.data(), kernel_caps.size());+ process->ParseKernelCaps(kernel_caps.data(), kernel_caps.size());- s32 priority = exheader_header.arm11_system_local_caps.priority;- u32 stack_size = exheader_header.codeset_info.stack_size;- Kernel::g_current_process->Run(codeset->entrypoint, priority, stack_size);+ s32 priority = overlay_ncch->exheader_header.arm11_system_local_caps.priority;+ u32 stack_size = overlay_ncch->exheader_header.codeset_info.stack_size;- process->Run(priority, stack_size);++ process->Run(codeset->entrypoint, priority, stack_size);return ResultStatus::Success;}return ResultStatus::Error;diff --cc src/core/loader/nro.cppindex 753e7e08b6,0000000000..24c2c55a97mode 100644,000000..100644--- a/src/core/loader/nro.cpp+++ b/src/core/loader/nro.cpp@@@ -1,162 -1,0 +1,162 @@@+// Copyright 2017 Citra Emulator Project+// Licensed under GPLv2 or any later version+// Refer to the license.txt file included.++#include <vector>++#include "common/logging/log.h"+#include "common/swap.h"+#include "core/hle/kernel/process.h"+#include "core/hle/kernel/resource_limit.h"+#include "core/loader/nro.h"+#include "core/memory.h"++namespace Loader {++struct NroSegmentHeader {+ u32_le offset;+ u32_le size;+};+static_assert(sizeof(NroSegmentHeader) == 0x8, "NroSegmentHeader has incorrect size.");++struct NroHeader {+ INSERT_PADDING_BYTES(0x4);+ u32_le module_header_offset;+ INSERT_PADDING_BYTES(0x8);+ u32_le magic;+ INSERT_PADDING_BYTES(0x4);+ u32_le file_size;+ INSERT_PADDING_BYTES(0x4);+ std::array<NroSegmentHeader, 3> segments; // Text, RoData, Data (in that order)+ u32_le bss_size;+ INSERT_PADDING_BYTES(0x44);+};+static_assert(sizeof(NroHeader) == 0x80, "NroHeader has incorrect size.");++struct ModHeader {+ u32_le magic;+ u32_le dynamic_offset;+ u32_le bss_start_offset;+ u32_le bss_end_offset;+ u32_le unwind_start_offset;+ u32_le unwind_end_offset;+ u32_le module_offset; // Offset to runtime-generated module object. typically equal to .bss base+};+static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size.");++FileType AppLoader_NRO::IdentifyType(FileUtil::IOFile& file) {+ // Read NSO header+ NroHeader nro_header{};+ file.Seek(0, SEEK_SET);+ if (sizeof(NroHeader) != file.ReadBytes(&nro_header, sizeof(NroHeader))) {+ return FileType::Error;+ }+ if (nro_header.magic == MakeMagic('N', 'R', 'O', '0')) {+ return FileType::NRO;+ }+ return FileType::Error;+}++static constexpr u32 PageAlignSize(u32 size) {+ return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;+}++static std::vector<u8> ReadSegment(FileUtil::IOFile& file, const NroSegmentHeader& header) {+ std::vector<u8> data;+ data.resize(header.size);++ file.Seek(header.offset + sizeof(NroHeader), SEEK_SET);+ size_t bytes_read{file.ReadBytes(data.data(), header.size)};+ if (header.size != PageAlignSize(static_cast<u32>(bytes_read))) {+ LOG_CRITICAL(Loader, "Failed to read NRO segment bytes", header.size);+ return {};+ }++ return data;+}++bool AppLoader_NRO::LoadNro(const std::string& path, VAddr load_base) {+ FileUtil::IOFile file(path, "rb");+ if (!file.IsOpen()) {+ return {};+ }++ // Read NSO header+ NroHeader nro_header{};+ file.Seek(0, SEEK_SET);+ if (sizeof(NroHeader) != file.ReadBytes(&nro_header, sizeof(NroHeader))) {+ return {};+ }+ if (nro_header.magic != MakeMagic('N', 'R', 'O', '0')) {+ return {};+ }++ // Build program image+ Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create("", 0);+ std::vector<u8> program_image;+ program_image.resize(PageAlignSize(nro_header.file_size + nro_header.bss_size));+ file.Seek(0, SEEK_SET);+ file.ReadBytes(program_image.data(), nro_header.file_size);++ for (int i = 0; i < nro_header.segments.size(); ++i) {+ codeset->segments[i].addr = nro_header.segments[i].offset;+ codeset->segments[i].offset = nro_header.segments[i].offset;+ codeset->segments[i].size = PageAlignSize(nro_header.segments[i].size);+ }++ // Read MOD header+ ModHeader mod_header{};+ u32 bss_size{Memory::PAGE_SIZE}; // Default .bss to page size if MOD0 section doesn't exist+ std::memcpy(&mod_header, program_image.data() + nro_header.module_header_offset,+ sizeof(ModHeader));+ const bool has_mod_header{mod_header.magic == MakeMagic('M', 'O', 'D', '0')};+ if (has_mod_header) {+ // Resize program image to include .bss section and page align each section+ bss_size = PageAlignSize(mod_header.bss_end_offset - mod_header.bss_start_offset);+ codeset->data.size += bss_size;+ }+ program_image.resize(PageAlignSize(static_cast<u32>(program_image.size()) + bss_size));++ // Relocate symbols if there was a proper MOD header - This must happen after the image has been+ // loaded into memory+ if (has_mod_header) {+ Relocate(program_image, nro_header.module_header_offset + mod_header.dynamic_offset,+ load_base);+ }++ // Load codeset for current process+ codeset->name = path;+ codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image));+ Kernel::g_current_process->LoadModule(codeset, load_base);++ return true;+}+- ResultStatus AppLoader_NRO::Load() {++ResultStatus AppLoader_NRO::Load(Kernel::SharedPtr<Kernel::Process>& process) {+ if (is_loaded) {+ return ResultStatus::ErrorAlreadyLoaded;+ }+ if (!file.IsOpen()) {+ return ResultStatus::Error;+ }++ // Load and relocate "main" and "sdk" NSO+ static constexpr VAddr base_addr{Memory::PROCESS_IMAGE_VADDR};- Kernel::g_current_process = Kernel::Process::Create("main");++ process = Kernel::Process::Create("main");+ if (!LoadNro(filepath, base_addr)) {+ return ResultStatus::ErrorInvalidFormat;+ }+- Kernel::g_current_process->svc_access_mask.set();- Kernel::g_current_process->address_mappings = default_address_mappings;- Kernel::g_current_process->resource_limit =++ process->svc_access_mask.set();++ process->address_mappings = default_address_mappings;++ process->resource_limit =+ Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);- Kernel::g_current_process->Run(base_addr, 48, Kernel::DEFAULT_STACK_SIZE);++ process->Run(base_addr, 48, Kernel::DEFAULT_STACK_SIZE);++ ResolveImports();++ is_loaded = true;+ return ResultStatus::Success;+}++} // namespace Loaderdiff --cc src/core/loader/nro.hindex c3c7622fd8,0000000000..c85768c5b2mode 100644,000000..100644--- a/src/core/loader/nro.h+++ b/src/core/loader/nro.h@@@ -1,42 -1,0 +1,42 @@@+// Copyright 2017 Citra Emulator Project+// Licensed under GPLv2 or any later version+// Refer to the license.txt file included.++#pragma once++#include <map>+#include <string>+#include "common/common_types.h"+#include "common/file_util.h"+#include "core/hle/kernel/kernel.h"+#include "core/loader/linker.h"+#include "core/loader/loader.h"++namespace Loader {++/// Loads an NRO file+class AppLoader_NRO final : public AppLoader, Linker {+public:+ AppLoader_NRO(FileUtil::IOFile&& file, std::string filepath)+ : AppLoader(std::move(file)), filepath(std::move(filepath)) {}++ /**+ * Returns the type of the file+ * @param file FileUtil::IOFile open file+ * @return FileType found, or FileType::Error if this loader doesn't know it+ */+ static FileType IdentifyType(FileUtil::IOFile& file);++ FileType GetFileType() override {+ return IdentifyType(file);+ }+- ResultStatus Load() override;++ ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;++private:+ bool LoadNro(const std::string& path, VAddr load_base);++ std::string filepath;+};++} // namespace Loaderdiff --cc src/core/loader/nso.cppindex ac8d12ecc3,0000000000..b1b57d0c0amode 100644,000000..100644--- a/src/core/loader/nso.cpp+++ b/src/core/loader/nso.cpp@@@ -1,185 -1,0 +1,185 @@@+// Copyright 2017 Citra Emulator Project+// Licensed under GPLv2 or any later version+// Refer to the license.txt file included.++#include <vector>+#include <lz4.h>++#include "common/logging/log.h"+#include "common/swap.h"+#include "core/hle/kernel/process.h"+#include "core/hle/kernel/resource_limit.h"+#include "core/loader/nso.h"+#include "core/memory.h"++namespace Loader {++struct NsoSegmentHeader {+ u32_le offset;+ u32_le location;+ u32_le size;+ u32_le alignment;+};+static_assert(sizeof(NsoSegmentHeader) == 0x10, "NsoSegmentHeader has incorrect size.");++struct NsoHeader {+ u32_le magic;+ INSERT_PADDING_BYTES(0xc);+ std::array<NsoSegmentHeader, 3> segments; // Text, RoData, Data (in that order)+ u32_le bss_size;+ INSERT_PADDING_BYTES(0x1c);+ std::array<u32_le, 3> segments_compressed_size;+};+static_assert(sizeof(NsoHeader) == 0x6c, "NsoHeader has incorrect size.");++struct ModHeader {+ u32_le magic;+ u32_le dynamic_offset;+ u32_le bss_start_offset;+ u32_le bss_end_offset;+ u32_le eh_frame_hdr_start_offset;+ u32_le eh_frame_hdr_end_offset;+ u32_le module_offset; // Offset to runtime-generated module object. typically equal to .bss base+};+static_assert(sizeof(ModHeader) == 0x1c, "ModHeader has incorrect size.");++FileType AppLoader_NSO::IdentifyType(FileUtil::IOFile& file) {+ u32 magic = 0;+ file.Seek(0, SEEK_SET);+ if (1 != file.ReadArray<u32>(&magic, 1)) {+ return FileType::Error;+ }++ if (MakeMagic('N', 'S', 'O', '0') == magic) {+ return FileType::NSO;+ }++ return FileType::Error;+}++static std::vector<u8> ReadSegment(FileUtil::IOFile& file, const NsoSegmentHeader& header,+ int compressed_size) {+ std::vector<u8> compressed_data;+ compressed_data.resize(compressed_size);++ file.Seek(header.offset, SEEK_SET);+ if (compressed_size != file.ReadBytes(compressed_data.data(), compressed_size)) {+ LOG_CRITICAL(Loader, "Failed to read %d NSO LZ4 compressed bytes", compressed_size);+ return {};+ }++ std::vector<u8> uncompressed_data;+ uncompressed_data.resize(header.size);+ const int bytes_uncompressed = LZ4_decompress_safe(+ reinterpret_cast<const char*>(compressed_data.data()),+ reinterpret_cast<char*>(uncompressed_data.data()), compressed_size, header.size);++ ASSERT_MSG(bytes_uncompressed == header.size && bytes_uncompressed == uncompressed_data.size(),+ "%d != %d != %d", bytes_uncompressed, header.size, uncompressed_data.size());++ return uncompressed_data;+}++static constexpr u32 PageAlignSize(u32 size) {+ return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;+}++VAddr AppLoader_NSO::LoadNso(const std::string& path, VAddr load_base, bool relocate) {+ FileUtil::IOFile file(path, "rb");+ if (!file.IsOpen()) {+ return {};+ }++ // Read NSO header+ NsoHeader nso_header{};+ file.Seek(0, SEEK_SET);+ if (sizeof(NsoHeader) != file.ReadBytes(&nso_header, sizeof(NsoHeader))) {+ return {};+ }+ if (nso_header.magic != MakeMagic('N', 'S', 'O', '0')) {+ return {};+ }++ // Build program image+ Kernel::SharedPtr<Kernel::CodeSet> codeset = Kernel::CodeSet::Create("", 0);+ std::vector<u8> program_image;+ for (int i = 0; i < nso_header.segments.size(); ++i) {+ std::vector<u8> data =+ ReadSegment(file, nso_header.segments[i], nso_header.segments_compressed_size[i]);+ program_image.resize(nso_header.segments[i].location);+ program_image.insert(program_image.end(), data.begin(), data.end());+ codeset->segments[i].addr = nso_header.segments[i].location;+ codeset->segments[i].offset = nso_header.segments[i].location;+ codeset->segments[i].size = PageAlignSize(static_cast<u32>(data.size()));+ }++ // MOD header pointer is at .text offset + 4+ u32 module_offset;+ std::memcpy(&module_offset, program_image.data() + 4, sizeof(u32));++ // Read MOD header+ ModHeader mod_header{};+ u32 bss_size{Memory::PAGE_SIZE}; // Default .bss to page size if MOD0 section doesn't exist+ std::memcpy(&mod_header, program_image.data() + module_offset, sizeof(ModHeader));+ const bool has_mod_header{mod_header.magic == MakeMagic('M', 'O', 'D', '0')};+ if (has_mod_header) {+ // Resize program image to include .bss section and page align each section+ bss_size = PageAlignSize(mod_header.bss_end_offset - mod_header.bss_start_offset);+ codeset->data.size += bss_size;+ }+ const u32 image_size{PageAlignSize(static_cast<u32>(program_image.size()) + bss_size)};+ program_image.resize(image_size);++ // Relocate symbols if there was a proper MOD header - This must happen after the image has been+ // loaded into memory+ if (has_mod_header && relocate) {+ Relocate(program_image, module_offset + mod_header.dynamic_offset, load_base);+ }++ // Load codeset for current process+ codeset->name = path;+ codeset->memory = std::make_shared<std::vector<u8>>(std::move(program_image));+ Kernel::g_current_process->LoadModule(codeset, load_base);++ return load_base + image_size;+}+- ResultStatus AppLoader_NSO::Load() {++ResultStatus AppLoader_NSO::Load(Kernel::SharedPtr<Kernel::Process>& process) {+ if (is_loaded) {+ return ResultStatus::ErrorAlreadyLoaded;+ }+ if (!file.IsOpen()) {+ return ResultStatus::Error;+ }++ // Load and relocate "rtld" NSO+ static constexpr VAddr base_addr{Memory::PROCESS_IMAGE_VADDR};- Kernel::g_current_process = Kernel::Process::Create("main");++ process = Kernel::Process::Create("main");+ VAddr next_base_addr{LoadNso(filepath, base_addr)};+ if (!next_base_addr) {+ return ResultStatus::ErrorInvalidFormat;+ }++ // Load and relocate remaining submodules+ for (const auto& module_name : {"main", "sdk", "subsdk0", "subsdk1"}) {+ const std::string module_path =+ filepath.substr(0, filepath.find_last_of("/\\")) + "/" + module_name;+ next_base_addr = LoadNso(module_path, next_base_addr);+ if (!next_base_addr) {+ LOG_WARNING(Loader, "failed to find load module: %s", module_name);+ }+ }+- Kernel::g_current_process->svc_access_mask.set();- Kernel::g_current_process->address_mappings = default_address_mappings;- Kernel::g_current_process->resource_limit =++ process->svc_access_mask.set();++ process->address_mappings = default_address_mappings;++ process->resource_limit =+ Kernel::ResourceLimit::GetForCategory(Kernel::ResourceLimitCategory::APPLICATION);- Kernel::g_current_process->Run(base_addr, 48, Kernel::DEFAULT_STACK_SIZE);++ process->Run(base_addr, 48, Kernel::DEFAULT_STACK_SIZE);++ ResolveImports();++ is_loaded = true;+ return ResultStatus::Success;+}++} // namespace Loaderdiff --cc src/core/loader/nso.hindex c29803d812,0000000000..b6b86c209bmode 100644,000000..100644--- a/src/core/loader/nso.h+++ b/src/core/loader/nso.h@@@ -1,43 -1,0 +1,43 @@@+// Copyright 2017 Citra Emulator Project+// Licensed under GPLv2 or any later version+// Refer to the license.txt file included.++#pragma once++#include <map>+#include <string>+#include "common/common_types.h"+#include "common/file_util.h"+#include "core/hle/kernel/kernel.h"+#include "core/loader/linker.h"+#include "core/loader/loader.h"++namespace Loader {++/// Loads an NSO file+class AppLoader_NSO final : public AppLoader, Linker {+public:+ AppLoader_NSO(FileUtil::IOFile&& file, std::string filepath)+ : AppLoader(std::move(file)), filepath(std::move(filepath)) {+ }++ /**+ * Returns the type of the file+ * @param file FileUtil::IOFile open file+ * @return FileType found, or FileType::Error if this loader doesn't know it+ */+ static FileType IdentifyType(FileUtil::IOFile& file);++ FileType GetFileType() override {+ return IdentifyType(file);+ }+- ResultStatus Load() override;++ ResultStatus Load(Kernel::SharedPtr<Kernel::Process>& process) override;++private:+ VAddr LoadNso(const std::string& path, VAddr load_base, bool relocate = false);++ std::string filepath;+};++} // namespace Loaderdiff --cc src/core/memory.cppindex ebe16b0309,7f58be6de8..462d68386b--- a/src/core/memory.cpp+++ b/src/core/memory.cpp@@@ -17,76 -21,30 +21,30 @@@namespace Memory {- enum class PageType {- /// Page is unmapped and should cause an access error.- Unmapped,- /// Page is mapped to regular memory. This is the only type you can get pointers to.- Memory,- /// Page is mapped to regular memory, but also needs to check for rasterizer cache flushing and- /// invalidation- RasterizerCachedMemory,- /// Page is mapped to a I/O region. Writing and reading to this page is handled by functions.- Special,- /// Page is mapped to a I/O region, but also needs to check for rasterizer cache flushing and- /// invalidation- RasterizerCachedSpecial,- };-- struct SpecialRegion {- VAddr base;- u64 size;- MMIORegionPointer handler;- };+ static std::array<u8, Memory::VRAM_SIZE> vram;+ static std::array<u8, Memory::N3DS_EXTRA_RAM_SIZE> n3ds_extra_ram;- /**- * A (reasonably) fast way of allowing switchable and remappable process address spaces. It loosely- * mimics the way a real CPU page table works, but instead is optimized for minimal decoding and- * fetching requirements when accessing. In the usual case of an access to regular memory, it only- * requires an indexed fetch and a check for NULL.- */- struct PageTable {- /**- * Array of memory pointers backing each page. An entry can only be non-null if the- * corresponding entry in the `attributes` array is of type `Memory`.- */- std::map<u64, u8*> pointers;-- /**- * Contains MMIO handlers that back memory regions whose entries in the `attribute` array is of- * type `Special`.- */- std::vector<SpecialRegion> special_regions;-- /**- * Array of fine grained page attributes. If it is set to any value other than `Memory`, then- * the corresponding entry in `pointers` MUST be set to null.- */- std::map<u64, PageType> attributes;-- /**- * Indicates the number of externally cached resources touching a page that should be- * flushed before the memory is accessed- */- std::map<u64, u8> cached_res_count;- };-- /// Singular page table used for the singleton process- static PageTable main_page_table;- /// Currently active page table- static PageTable* current_page_table = &main_page_table;-- //std::array<u8*, PAGE_TABLE_NUM_ENTRIES>* GetCurrentPageTablePointers() {- // return ¤t_page_table->pointers;- //}-- static void MapPages(u64 base, u64 size, u8* memory, PageType type) {+ static PageTable* current_page_table = nullptr;++ void SetCurrentPageTable(PageTable* page_table) {+ current_page_table = page_table;+ if (Core::System::GetInstance().IsPoweredOn()) {+ Core::CPU().PageTableChanged();+ }+ }++ PageTable* GetCurrentPageTable() {+ return current_page_table;+ }+-static void MapPages(PageTable& page_table, u32 base, u32 size, u8* memory, PageType type) {++static void MapPages(PageTable& page_table, VAddr base, u32 size, u8* memory, PageType type) {LOG_DEBUG(HW_Memory, "Mapping %p onto %08X-%08X", memory, base * PAGE_SIZE,(base + size) * PAGE_SIZE);RasterizerFlushVirtualRegion(base << PAGE_BITS, size * PAGE_SIZE,FlushMode::FlushAndInvalidate);- u64 end = base + size;- u32 end = base + size;++ VAddr end = base + size;while (base != end) {ASSERT_MSG(base < PAGE_TABLE_NUM_ENTRIES, "out of range mapping at %08X", base);@@@ -299,12 -275,66 +275,66 @@@ std::string ReadCString(VAddr vaddr, st}u8* GetPhysicalPointer(PAddr address) {- // TODO(Subv): This call should not go through the application's memory mapping.- boost::optional<VAddr> vaddr = PhysicalToVirtualAddress(address);- return vaddr ? GetPointer(*vaddr) : nullptr;+ struct MemoryArea {+ PAddr paddr_base;+ u32 size;+ };++ static constexpr MemoryArea memory_areas[] = {+ {VRAM_PADDR, VRAM_SIZE},+ {IO_AREA_PADDR, IO_AREA_SIZE},+ {DSP_RAM_PADDR, DSP_RAM_SIZE},+ {FCRAM_PADDR, FCRAM_N3DS_SIZE},+ {N3DS_EXTRA_RAM_PADDR, N3DS_EXTRA_RAM_SIZE},+ };++ const auto area =+ std::find_if(std::begin(memory_areas), std::end(memory_areas), [&](const auto& area) {+ return address >= area.paddr_base && address < area.paddr_base + area.size;+ });++ if (area == std::end(memory_areas)) {+ LOG_ERROR(HW_Memory, "unknown GetPhysicalPointer @ 0x%08X", address);+ return nullptr;+ }++ if (area->paddr_base == IO_AREA_PADDR) {+ LOG_ERROR(HW_Memory, "MMIO mappings are not supported yet. phys_addr=0x%08X", address);+ return nullptr;+ }+- u32 offset_into_region = address - area->paddr_base;++ u64 offset_into_region = address - area->paddr_base;++ u8* target_pointer = nullptr;+ switch (area->paddr_base) {+ case VRAM_PADDR:+ target_pointer = vram.data() + offset_into_region;+ break;+ case DSP_RAM_PADDR:+ target_pointer = AudioCore::GetDspMemory().data() + offset_into_region;+ break;+ case FCRAM_PADDR:+ for (const auto& region : Kernel::memory_regions) {+ if (offset_into_region >= region.base &&+ offset_into_region < region.base + region.size) {+ target_pointer =+ region.linear_heap_memory->data() + offset_into_region - region.base;+ break;+ }+ }+ ASSERT_MSG(target_pointer != nullptr, "Invalid FCRAM address");+ break;+ case N3DS_EXTRA_RAM_PADDR:+ target_pointer = n3ds_extra_ram.data() + offset_into_region;+ break;+ default:+ UNREACHABLE();+ }++ return target_pointer;}- void RasterizerMarkRegionCached(PAddr start, u64 size, int count_delta) {+ void RasterizerMarkRegionCached(PAddr start, u32 size, int count_delta) {if (start == 0) {return;}@@@ -398,7 -443,7 +443,7 @@@ void RasterizerFlushVirtualRegion(VAddVAddr overlap_end = std::min(end, region_end);PAddr physical_start = TryVirtualToPhysicalAddress(overlap_start).value();- u64 overlap_size = overlap_end - overlap_start;- u32 overlap_size = overlap_end - overlap_start;++ u32 overlap_size = static_cast<u32>(overlap_end - overlap_start);auto* rasterizer = VideoCore::g_renderer->Rasterizer();switch (mode) {diff --cc src/core/memory.hindex e14d686546,dd599f73ec..9a04b9a16b--- a/src/core/memory.h+++ b/src/core/memory.h@@@ -6,9 -6,15 +6,16 @@@#include <array>#include <cstddef>++#include <map>#include <string>+ #include <vector>#include <boost/optional.hpp>#include "common/common_types.h"+ #include "core/mmio.h"++ namespace Kernel {+ class Process;+ }namespace Memory {@@@ -16,10 -22,63 +23,63 @@@* Page size used by the ARM architecture. This is the smallest granularity with which memory can* be mapped.*/-const u32 PAGE_SIZE = 0x1000;-const u32 PAGE_MASK = PAGE_SIZE - 1;const int PAGE_BITS = 12;-const size_t PAGE_TABLE_NUM_ENTRIES = 1 << (32 - PAGE_BITS);+const u64 PAGE_SIZE = 1 << PAGE_BITS;+const u64 PAGE_MASK = PAGE_SIZE - 1;- const size_t PAGE_TABLE_NUM_ENTRIES = 1ULL << (64 - PAGE_BITS);++const size_t PAGE_TABLE_NUM_ENTRIES = 1ULL << (32 - PAGE_BITS);++ enum class PageType {+ /// Page is unmapped and should cause an access error.+ Unmapped,+ /// Page is mapped to regular memory. This is the only type you can get pointers to.+ Memory,+ /// Page is mapped to regular memory, but also needs to check for rasterizer cache flushing and+ /// invalidation+ RasterizerCachedMemory,+ /// Page is mapped to a I/O region. Writing and reading to this page is handled by functions.+ Special,+ /// Page is mapped to a I/O region, but also needs to check for rasterizer cache flushing and+ /// invalidation+ RasterizerCachedSpecial,+ };++ struct SpecialRegion {+ VAddr base;+ u32 size;+ MMIORegionPointer handler;+ };++ /**+ * A (reasonably) fast way of allowing switchable and remappable process address spaces. It loosely+ * mimics the way a real CPU page table works, but instead is optimized for minimal decoding and+ * fetching requirements when accessing. In the usual case of an access to regular memory, it only+ * requires an indexed fetch and a check for NULL.+ */+ struct PageTable {+ /**+ * Array of memory pointers backing each page. An entry can only be non-null if the+ * corresponding entry in the `attributes` array is of type `Memory`.+ */+ std::array<u8*, PAGE_TABLE_NUM_ENTRIES> pointers;++ /**+ * Contains MMIO handlers that back memory regions whose entries in the `attribute` array is of+ * type `Special`.+ */+ std::vector<SpecialRegion> special_regions;++ /**+ * Array of fine grained page attributes. If it is set to any value other than `Memory`, then+ * the corresponding entry in `pointers` MUST be set to null.+ */+ std::array<PageType, PAGE_TABLE_NUM_ENTRIES> attributes;++ /**+ * Indicates the number of externally cached resources touching a page that should be+ * flushed before the memory is accessed+ */+ std::array<u8, PAGE_TABLE_NUM_ENTRIES> cached_res_count;+ };/// Physical memory regions as seen from the ARM11enum : PAddr {diff --cc src/tests/core/arm/arm_test_common.cppindex 0000000000,484713a92c..2339bdfb8fmode 000000,100644..100644--- a/src/tests/core/arm/arm_test_common.cpp+++ b/src/tests/core/arm/arm_test_common.cpp@@@ -1,0 -1,137 +1,137 @@@+ // Copyright 2016 Citra Emulator Project+ // Licensed under GPLv2 or any later version+ // Refer to the license.txt file included.++ #include "core/core.h"+ #include "core/hle/kernel/process.h"+ #include "core/memory.h"+ #include "core/memory_setup.h"+ #include "tests/core/arm/arm_test_common.h"++ namespace ArmTests {++ static Memory::PageTable* page_table = nullptr;++ TestEnvironment::TestEnvironment(bool mutable_memory_)+ : mutable_memory(mutable_memory_), test_memory(std::make_shared<TestMemory>(this)) {+- Kernel::g_current_process = Kernel::Process::Create(Kernel::CodeSet::Create("", 0));++ Kernel::g_current_process = Kernel::Process::Create("");+ page_table = &Kernel::g_current_process->vm_manager.page_table;++ page_table->pointers.fill(nullptr);+ page_table->attributes.fill(Memory::PageType::Unmapped);+ page_table->cached_res_count.fill(0);++ Memory::MapIoRegion(*page_table, 0x00000000, 0x80000000, test_memory);+ Memory::MapIoRegion(*page_table, 0x80000000, 0x80000000, test_memory);++ Memory::SetCurrentPageTable(page_table);+ }++ TestEnvironment::~TestEnvironment() {+ Memory::UnmapRegion(*page_table, 0x80000000, 0x80000000);+ Memory::UnmapRegion(*page_table, 0x00000000, 0x80000000);+ }++ void TestEnvironment::SetMemory64(VAddr vaddr, u64 value) {+ SetMemory32(vaddr + 0, static_cast<u32>(value));+ SetMemory32(vaddr + 4, static_cast<u32>(value >> 32));+ }++ void TestEnvironment::SetMemory32(VAddr vaddr, u32 value) {+ SetMemory16(vaddr + 0, static_cast<u16>(value));+ SetMemory16(vaddr + 2, static_cast<u16>(value >> 16));+ }++ void TestEnvironment::SetMemory16(VAddr vaddr, u16 value) {+ SetMemory8(vaddr + 0, static_cast<u8>(value));+ SetMemory8(vaddr + 1, static_cast<u8>(value >> 8));+ }++ void TestEnvironment::SetMemory8(VAddr vaddr, u8 value) {+ test_memory->data[vaddr] = value;+ }++ std::vector<WriteRecord> TestEnvironment::GetWriteRecords() const {+ return write_records;+ }++ void TestEnvironment::ClearWriteRecords() {+ write_records.clear();+ }++ TestEnvironment::TestMemory::~TestMemory() {}++ bool TestEnvironment::TestMemory::IsValidAddress(VAddr addr) {+ return true;+ }++ u8 TestEnvironment::TestMemory::Read8(VAddr addr) {+ auto iter = data.find(addr);+ if (iter == data.end()) {+ return addr; // Some arbitrary data+ }+ return iter->second;+ }++ u16 TestEnvironment::TestMemory::Read16(VAddr addr) {+ return Read8(addr) | static_cast<u16>(Read8(addr + 1)) << 8;+ }++ u32 TestEnvironment::TestMemory::Read32(VAddr addr) {+ return Read16(addr) | static_cast<u32>(Read16(addr + 2)) << 16;+ }++ u64 TestEnvironment::TestMemory::Read64(VAddr addr) {+ return Read32(addr) | static_cast<u64>(Read32(addr + 4)) << 32;+ }++ bool TestEnvironment::TestMemory::ReadBlock(VAddr src_addr, void* dest_buffer, size_t size) {+ VAddr addr = src_addr;+ u8* data = static_cast<u8*>(dest_buffer);++ for (size_t i = 0; i < size; i++, addr++, data++) {+ *data = Read8(addr);+ }++ return true;+ }++ void TestEnvironment::TestMemory::Write8(VAddr addr, u8 data) {+ env->write_records.emplace_back(8, addr, data);+ if (env->mutable_memory)+ env->SetMemory8(addr, data);+ }++ void TestEnvironment::TestMemory::Write16(VAddr addr, u16 data) {+ env->write_records.emplace_back(16, addr, data);+ if (env->mutable_memory)+ env->SetMemory16(addr, data);+ }++ void TestEnvironment::TestMemory::Write32(VAddr addr, u32 data) {+ env->write_records.emplace_back(32, addr, data);+ if (env->mutable_memory)+ env->SetMemory32(addr, data);+ }++ void TestEnvironment::TestMemory::Write64(VAddr addr, u64 data) {+ env->write_records.emplace_back(64, addr, data);+ if (env->mutable_memory)+ env->SetMemory64(addr, data);+ }++ bool TestEnvironment::TestMemory::WriteBlock(VAddr dest_addr, const void* src_buffer, size_t size) {+ VAddr addr = dest_addr;+ const u8* data = static_cast<const u8*>(src_buffer);++ for (size_t i = 0; i < size; i++, addr++, data++) {+ env->write_records.emplace_back(8, addr, *data);+ if (env->mutable_memory)+ env->SetMemory8(addr, *data);+ }++ return true;+ }++ } // namespace ArmTestsdiff --cc src/tests/core/memory/memory.cppindex 0000000000,a01b896f70..671afb702bmode 000000,100644..100644--- a/src/tests/core/memory/memory.cpp+++ b/src/tests/core/memory/memory.cpp@@@ -1,0 -1,56 +1,56 @@@+ // Copyright 2017 Citra Emulator Project+ // Licensed under GPLv2 or any later version+ // Refer to the license.txt file included.++ #include <catch.hpp>+ #include "core/hle/kernel/memory.h"+ #include "core/hle/kernel/process.h"+ #include "core/memory.h"++ TEST_CASE("Memory::IsValidVirtualAddress", "[core][memory]") {+ SECTION("these regions should not be mapped on an empty process") {- auto process = Kernel::Process::Create(Kernel::CodeSet::Create("", 0));++ auto process = Kernel::Process::Create("");+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::PROCESS_IMAGE_VADDR) == false);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::HEAP_VADDR) == false);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::LINEAR_HEAP_VADDR) == false);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::VRAM_VADDR) == false);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::CONFIG_MEMORY_VADDR) == false);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::SHARED_PAGE_VADDR) == false);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::TLS_AREA_VADDR) == false);+ }++ SECTION("CONFIG_MEMORY_VADDR and SHARED_PAGE_VADDR should be valid after mapping them") {- auto process = Kernel::Process::Create(Kernel::CodeSet::Create("", 0));++ auto process = Kernel::Process::Create("");+ Kernel::MapSharedPages(process->vm_manager);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::CONFIG_MEMORY_VADDR) == true);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::SHARED_PAGE_VADDR) == true);+ }++ SECTION("special regions should be valid after mapping them") {- auto process = Kernel::Process::Create(Kernel::CodeSet::Create("", 0));++ auto process = Kernel::Process::Create("");+ SECTION("VRAM") {+ Kernel::HandleSpecialMapping(process->vm_manager,+ {Memory::VRAM_VADDR, Memory::VRAM_SIZE, false, false});+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::VRAM_VADDR) == true);+ }++ SECTION("IO (Not yet implemented)") {+ Kernel::HandleSpecialMapping(+ process->vm_manager, {Memory::IO_AREA_VADDR, Memory::IO_AREA_SIZE, false, false});+ CHECK_FALSE(Memory::IsValidVirtualAddress(*process, Memory::IO_AREA_VADDR) == true);+ }++ SECTION("DSP") {+ Kernel::HandleSpecialMapping(+ process->vm_manager, {Memory::DSP_RAM_VADDR, Memory::DSP_RAM_SIZE, false, false});+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::DSP_RAM_VADDR) == true);+ }+ }++ SECTION("Unmapping a VAddr should make it invalid") {- auto process = Kernel::Process::Create(Kernel::CodeSet::Create("", 0));++ auto process = Kernel::Process::Create("");+ Kernel::MapSharedPages(process->vm_manager);+ process->vm_manager.UnmapRange(Memory::CONFIG_MEMORY_VADDR, Memory::CONFIG_MEMORY_SIZE);+ CHECK(Memory::IsValidVirtualAddress(*process, Memory::CONFIG_MEMORY_VADDR) == false);+ }+ }