Compare commits

..

1 Commits

Author SHA1 Message Date
d33937748f Android #155 2023-12-09 00:57:26 +00:00
58 changed files with 840 additions and 2883 deletions

View File

@ -14,10 +14,8 @@ import org.yuzu.yuzu_emu.R
import org.yuzu.yuzu_emu.databinding.DialogAddFolderBinding
import org.yuzu.yuzu_emu.model.GameDir
import org.yuzu.yuzu_emu.model.GamesViewModel
import org.yuzu.yuzu_emu.model.HomeViewModel
class AddGameFolderDialogFragment : DialogFragment() {
private val homeViewModel: HomeViewModel by activityViewModels()
private val gamesViewModel: GamesViewModel by activityViewModels()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
@ -32,7 +30,6 @@ class AddGameFolderDialogFragment : DialogFragment() {
.setTitle(R.string.add_game_folder)
.setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int ->
val newGameDir = GameDir(folderUriString!!, binding.deepScanSwitch.isChecked)
homeViewModel.setGamesDirSelected(true)
gamesViewModel.addFolder(newGameDir)
}
.setNegativeButton(android.R.string.cancel, null)

View File

@ -4,7 +4,6 @@
package org.yuzu.yuzu_emu.fragments
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
@ -76,8 +75,6 @@ class SetupFragment : Fragment() {
return binding.root
}
// This is using the correct scope, lint is just acting up
@SuppressLint("UnsafeRepeatOnLifecycleDetector")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mainActivity = requireActivity() as MainActivity
@ -209,24 +206,12 @@ class SetupFragment : Fragment() {
)
}
viewLifecycleOwner.lifecycleScope.apply {
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
homeViewModel.shouldPageForward.collect {
if (it) {
pageForward()
homeViewModel.setShouldPageForward(false)
}
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
homeViewModel.gamesDirSelected.collect {
if (it) {
gamesDirCallback.onStepCompleted()
homeViewModel.setGamesDirSelected(false)
}
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
homeViewModel.shouldPageForward.collect {
if (it) {
pageForward()
homeViewModel.setShouldPageForward(false)
}
}
}
@ -354,6 +339,7 @@ class SetupFragment : Fragment() {
registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { result ->
if (result != null) {
mainActivity.processGamesDir(result)
gamesDirCallback.onStepCompleted()
}
}

View File

@ -133,7 +133,7 @@ class GamesViewModel : ViewModel() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
NativeConfig.addGameDir(gameDir)
getGameDirs(true)
getGameDirs()
}
}

View File

@ -6,7 +6,6 @@ package org.yuzu.yuzu_emu.model
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
class HomeViewModel : ViewModel() {
val navigationVisible: StateFlow<Pair<Boolean, Boolean>> get() = _navigationVisible
@ -18,9 +17,6 @@ class HomeViewModel : ViewModel() {
val shouldPageForward: StateFlow<Boolean> get() = _shouldPageForward
private val _shouldPageForward = MutableStateFlow(false)
private val _gamesDirSelected = MutableStateFlow(false)
val gamesDirSelected get() = _gamesDirSelected.asStateFlow()
var navigatedToSetup = false
fun setNavigationVisibility(visible: Boolean, animated: Boolean) {
@ -40,8 +36,4 @@ class HomeViewModel : ViewModel() {
fun setShouldPageForward(pageForward: Boolean) {
_shouldPageForward.value = pageForward
}
fun setGamesDirSelected(selected: Boolean) {
_gamesDirSelected.value = selected
}
}

View File

@ -160,16 +160,12 @@ static bool is_nce_enabled = false;
void SetNceEnabled(bool is_39bit) {
const bool is_nce_selected = values.cpu_backend.GetValue() == CpuBackend::Nce;
if (is_nce_selected && !IsFastmemEnabled()) {
LOG_WARNING(Common, "Fastmem is required to natively execute code in a performant manner, "
"falling back to Dynarmic");
}
if (is_nce_selected && !is_39bit) {
is_nce_enabled = IsFastmemEnabled() && is_nce_selected && is_39bit;
if (is_nce_selected && !is_nce_enabled) {
LOG_WARNING(
Common,
"Program does not utilize 39-bit address space, unable to natively execute code");
}
is_nce_enabled = IsFastmemEnabled() && is_nce_selected && is_39bit;
}
bool IsNceEnabled() {

View File

@ -180,20 +180,14 @@ struct Values {
&use_speed_limit};
// Cpu
SwitchableSetting<CpuBackend, true> cpu_backend{linkage,
SwitchableSetting<CpuBackend, true> cpu_backend{
linkage, CpuBackend::Dynarmic, CpuBackend::Dynarmic,
#ifdef HAS_NCE
CpuBackend::Nce,
CpuBackend::Nce,
#else
CpuBackend::Dynarmic,
#endif
CpuBackend::Dynarmic,
#ifdef HAS_NCE
CpuBackend::Nce,
#else
CpuBackend::Dynarmic,
#endif
"cpu_backend",
Category::Cpu};
"cpu_backend", Category::Cpu};
SwitchableSetting<CpuAccuracy, true> cpu_accuracy{linkage, CpuAccuracy::Auto,
CpuAccuracy::Auto, CpuAccuracy::Paranoid,
"cpu_accuracy", Category::Cpu};

View File

@ -251,16 +251,10 @@ add_library(core STATIC
hle/kernel/k_hardware_timer.h
hle/kernel/k_interrupt_manager.cpp
hle/kernel/k_interrupt_manager.h
hle/kernel/k_light_client_session.cpp
hle/kernel/k_light_client_session.h
hle/kernel/k_light_condition_variable.cpp
hle/kernel/k_light_condition_variable.h
hle/kernel/k_light_lock.cpp
hle/kernel/k_light_lock.h
hle/kernel/k_light_server_session.cpp
hle/kernel/k_light_server_session.h
hle/kernel/k_light_session.cpp
hle/kernel/k_light_session.h
hle/kernel/k_memory_block.h
hle/kernel/k_memory_block_manager.cpp
hle/kernel/k_memory_block_manager.h
@ -549,8 +543,6 @@ add_library(core STATIC
hle/service/hid/xcd.cpp
hle/service/hid/xcd.h
hle/service/hid/errors.h
hle/service/hid/controllers/applet_resource.cpp
hle/service/hid/controllers/applet_resource.h
hle/service/hid/controllers/console_six_axis.cpp
hle/service/hid/controllers/console_six_axis.h
hle/service/hid/controllers/controller_base.cpp
@ -772,12 +764,6 @@ add_library(core STATIC
hle/service/kernel_helpers.h
hle/service/mutex.cpp
hle/service/mutex.h
hle/service/ro/ro_nro_utils.cpp
hle/service/ro/ro_nro_utils.h
hle/service/ro/ro_results.h
hle/service/ro/ro_types.h
hle/service/ro/ro.cpp
hle/service/ro/ro.h
hle/service/server_manager.cpp
hle/service/server_manager.h
hle/service/service.cpp

View File

@ -282,8 +282,6 @@ Loader::AppLoader::Modules FindModules(const Kernel::KProcess* process) {
// Ignore leading directories.
char* path_pointer = module_path.path.data();
char* path_end =
path_pointer + std::min(PathLengthMax, module_path.path_length);
for (s32 i = 0; i < std::min(PathLengthMax, module_path.path_length) &&
module_path.path[i] != '\0';
@ -294,8 +292,7 @@ Loader::AppLoader::Modules FindModules(const Kernel::KProcess* process) {
}
// Insert output.
modules.emplace(svc_mem_info.base_address,
std::string_view(path_pointer, path_end));
modules.emplace(svc_mem_info.base_address, path_pointer);
}
}
}

View File

@ -12,6 +12,8 @@
namespace FileSys {
constexpr char SAVE_DATA_SIZE_FILENAME[] = ".yuzu_save_size";
namespace {
void PrintSaveDataAttributeWarnings(SaveDataAttribute meta) {
@ -195,7 +197,7 @@ SaveDataSize SaveDataFactory::ReadSaveDataSize(SaveDataType type, u64 title_id,
GetFullPath(system, dir, SaveDataSpaceId::NandUser, type, title_id, user_id, 0);
const auto relative_dir = GetOrCreateDirectoryRelative(dir, path);
const auto size_file = relative_dir->GetFile(GetSaveDataSizeFileName());
const auto size_file = relative_dir->GetFile(SAVE_DATA_SIZE_FILENAME);
if (size_file == nullptr || size_file->GetSize() < sizeof(SaveDataSize)) {
return {0, 0};
}
@ -214,7 +216,7 @@ void SaveDataFactory::WriteSaveDataSize(SaveDataType type, u64 title_id, u128 us
GetFullPath(system, dir, SaveDataSpaceId::NandUser, type, title_id, user_id, 0);
const auto relative_dir = GetOrCreateDirectoryRelative(dir, path);
const auto size_file = relative_dir->CreateFile(GetSaveDataSizeFileName());
const auto size_file = relative_dir->CreateFile(SAVE_DATA_SIZE_FILENAME);
if (size_file == nullptr) {
return;
}

View File

@ -83,10 +83,6 @@ struct SaveDataSize {
u64 journal;
};
constexpr const char* GetSaveDataSizeFileName() {
return ".yuzu_save_size";
}
/// File system interface to the SaveData archive
class SaveDataFactory {
public:

View File

@ -3,7 +3,6 @@
#include "common/scope_exit.h"
#include "core/hle/kernel/k_client_port.h"
#include "core/hle/kernel/k_light_session.h"
#include "core/hle/kernel/k_port.h"
#include "core/hle/kernel/k_scheduler.h"
#include "core/hle/kernel/k_scoped_resource_reservation.h"
@ -64,7 +63,6 @@ Result KClientPort::CreateSession(KClientSession** out) {
R_UNLESS(session_reservation.Succeeded(), ResultLimitReached);
// Allocate a session normally.
// TODO: Dynamic resource limits
session = KSession::Create(m_kernel);
// Check that we successfully created a session.
@ -121,71 +119,4 @@ Result KClientPort::CreateSession(KClientSession** out) {
R_SUCCEED();
}
Result KClientPort::CreateLightSession(KLightClientSession** out) {
// Declare the session we're going to allocate.
KLightSession* session{};
// Reserve a new session from the resource limit.
KScopedResourceReservation session_reservation(GetCurrentProcessPointer(m_kernel),
Svc::LimitableResource::SessionCountMax);
R_UNLESS(session_reservation.Succeeded(), ResultLimitReached);
// Allocate a session normally.
// TODO: Dynamic resource limits
session = KLightSession::Create(m_kernel);
// Check that we successfully created a session.
R_UNLESS(session != nullptr, ResultOutOfResource);
// Update the session counts.
{
ON_RESULT_FAILURE {
session->Close();
};
// Atomically increment the number of sessions.
s32 new_sessions;
{
const auto max = m_max_sessions;
auto cur_sessions = m_num_sessions.load(std::memory_order_acquire);
do {
R_UNLESS(cur_sessions < max, ResultOutOfSessions);
new_sessions = cur_sessions + 1;
} while (!m_num_sessions.compare_exchange_weak(cur_sessions, new_sessions,
std::memory_order_relaxed));
}
// Atomically update the peak session tracking.
{
auto peak = m_peak_sessions.load(std::memory_order_acquire);
do {
if (peak >= new_sessions) {
break;
}
} while (!m_peak_sessions.compare_exchange_weak(peak, new_sessions,
std::memory_order_relaxed));
}
}
// Initialize the session.
session->Initialize(this, m_parent->GetName());
// Commit the session reservation.
session_reservation.Commit();
// Register the session.
KLightSession::Register(m_kernel, session);
ON_RESULT_FAILURE {
session->GetClientSession().Close();
session->GetServerSession().Close();
};
// Enqueue the session with our parent.
R_TRY(m_parent->EnqueueSession(std::addressof(session->GetServerSession())));
// We succeeded, so set the output.
*out = std::addressof(session->GetClientSession());
R_SUCCEED();
}
} // namespace Kernel

View File

@ -11,7 +11,6 @@
namespace Kernel {
class KLightClientSession;
class KClientSession;
class KernelCore;
class KPort;
@ -52,7 +51,6 @@ public:
bool IsSignaled() const override;
Result CreateSession(KClientSession** out);
Result CreateLightSession(KLightClientSession** out);
private:
std::atomic<s32> m_num_sessions{};

View File

@ -10,7 +10,9 @@
namespace Kernel {
KClientSession::KClientSession(KernelCore& kernel) : KAutoObject{kernel} {}
static constexpr u32 MessageBufferSize = 0x100;
KClientSession::KClientSession(KernelCore& kernel) : KAutoObjectWithSlabHeapAndContainer{kernel} {}
KClientSession::~KClientSession() = default;
void KClientSession::Destroy() {
@ -20,30 +22,18 @@ void KClientSession::Destroy() {
void KClientSession::OnServerClosed() {}
Result KClientSession::SendSyncRequest(uintptr_t address, size_t size) {
Result KClientSession::SendSyncRequest() {
// Create a session request.
KSessionRequest* request = KSessionRequest::Create(m_kernel);
R_UNLESS(request != nullptr, ResultOutOfResource);
SCOPE_EXIT({ request->Close(); });
// Initialize the request.
request->Initialize(nullptr, address, size);
request->Initialize(nullptr, GetInteger(GetCurrentThread(m_kernel).GetTlsAddress()),
MessageBufferSize);
// Send the request.
R_RETURN(m_parent->OnRequest(request));
}
Result KClientSession::SendAsyncRequest(KEvent* event, uintptr_t address, size_t size) {
// Create a session request.
KSessionRequest* request = KSessionRequest::Create(m_kernel);
R_UNLESS(request != nullptr, ResultOutOfResource);
SCOPE_EXIT({ request->Close(); });
// Initialize the request.
request->Initialize(event, address, size);
// Send the request.
R_RETURN(m_parent->OnRequest(request));
R_RETURN(m_parent->GetServerSession().OnRequest(request));
}
} // namespace Kernel

View File

@ -9,12 +9,24 @@
#include "core/hle/kernel/slab_helpers.h"
#include "core/hle/result.h"
union Result;
namespace Core::Memory {
class Memory;
}
namespace Core::Timing {
class CoreTiming;
}
namespace Kernel {
class KernelCore;
class KSession;
class KThread;
class KClientSession final : public KAutoObject {
class KClientSession final
: public KAutoObjectWithSlabHeapAndContainer<KClientSession, KAutoObjectWithList> {
KERNEL_AUTOOBJECT_TRAITS(KClientSession, KAutoObject);
public:
@ -27,13 +39,13 @@ public:
}
void Destroy() override;
static void PostDestroy(uintptr_t arg) {}
KSession* GetParent() const {
return m_parent;
}
Result SendSyncRequest(uintptr_t address, size_t size);
Result SendAsyncRequest(KEvent* event, uintptr_t address, size_t size);
Result SendSyncRequest();
void OnServerClosed();

View File

@ -1,31 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/kernel/k_light_client_session.h"
#include "core/hle/kernel/k_light_session.h"
#include "core/hle/kernel/k_thread.h"
namespace Kernel {
KLightClientSession::KLightClientSession(KernelCore& kernel) : KAutoObject(kernel) {}
KLightClientSession::~KLightClientSession() = default;
void KLightClientSession::Destroy() {
m_parent->OnClientClosed();
}
void KLightClientSession::OnServerClosed() {}
Result KLightClientSession::SendSyncRequest(u32* data) {
// Get the request thread.
KThread* cur_thread = GetCurrentThreadPointer(m_kernel);
// Set the light data.
cur_thread->SetLightSessionData(data);
// Send the request.
R_RETURN(m_parent->OnRequest(cur_thread));
}
} // namespace Kernel

View File

@ -1,39 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "core/hle/kernel/k_auto_object.h"
#include "core/hle/result.h"
namespace Kernel {
class KLightSession;
class KLightClientSession final : public KAutoObject {
KERNEL_AUTOOBJECT_TRAITS(KLightClientSession, KAutoObject);
public:
explicit KLightClientSession(KernelCore& kernel);
~KLightClientSession();
void Initialize(KLightSession* parent) {
// Set member variables.
m_parent = parent;
}
virtual void Destroy() override;
const KLightSession* GetParent() const {
return m_parent;
}
Result SendSyncRequest(u32* data);
void OnServerClosed();
private:
KLightSession* m_parent;
};
} // namespace Kernel

View File

@ -1,247 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/kernel/k_light_server_session.h"
#include "core/hle/kernel/k_light_session.h"
#include "core/hle/kernel/k_thread.h"
#include "core/hle/kernel/k_thread_queue.h"
#include "core/hle/kernel/svc_results.h"
namespace Kernel {
namespace {
constexpr u64 InvalidThreadId = std::numeric_limits<u64>::max();
class ThreadQueueImplForKLightServerSessionRequest final : public KThreadQueue {
private:
KThread::WaiterList* m_wait_list;
public:
ThreadQueueImplForKLightServerSessionRequest(KernelCore& kernel, KThread::WaiterList* wl)
: KThreadQueue(kernel), m_wait_list(wl) {}
virtual void EndWait(KThread* waiting_thread, Result wait_result) override {
// Remove the thread from our wait list.
m_wait_list->erase(m_wait_list->iterator_to(*waiting_thread));
// Invoke the base end wait handler.
KThreadQueue::EndWait(waiting_thread, wait_result);
}
virtual void CancelWait(KThread* waiting_thread, Result wait_result,
bool cancel_timer_task) override {
// Remove the thread from our wait list.
m_wait_list->erase(m_wait_list->iterator_to(*waiting_thread));
// Invoke the base cancel wait handler.
KThreadQueue::CancelWait(waiting_thread, wait_result, cancel_timer_task);
}
};
class ThreadQueueImplForKLightServerSessionReceive final : public KThreadQueue {
private:
KThread** m_server_thread;
public:
ThreadQueueImplForKLightServerSessionReceive(KernelCore& kernel, KThread** st)
: KThreadQueue(kernel), m_server_thread(st) {}
virtual void EndWait(KThread* waiting_thread, Result wait_result) override {
// Clear the server thread.
*m_server_thread = nullptr;
// Set the waiting thread as not cancelable.
waiting_thread->ClearCancellable();
// Invoke the base end wait handler.
KThreadQueue::EndWait(waiting_thread, wait_result);
}
virtual void CancelWait(KThread* waiting_thread, Result wait_result,
bool cancel_timer_task) override {
// Clear the server thread.
*m_server_thread = nullptr;
// Set the waiting thread as not cancelable.
waiting_thread->ClearCancellable();
// Invoke the base cancel wait handler.
KThreadQueue::CancelWait(waiting_thread, wait_result, cancel_timer_task);
}
};
} // namespace
KLightServerSession::KLightServerSession(KernelCore& kernel) : KAutoObject(kernel) {}
KLightServerSession::~KLightServerSession() = default;
void KLightServerSession::Destroy() {
this->CleanupRequests();
m_parent->OnServerClosed();
}
void KLightServerSession::OnClientClosed() {
this->CleanupRequests();
}
Result KLightServerSession::OnRequest(KThread* request_thread) {
ThreadQueueImplForKLightServerSessionRequest wait_queue(m_kernel,
std::addressof(m_request_list));
// Send the request.
{
// Lock the scheduler.
KScopedSchedulerLock sl(m_kernel);
// Check that the server isn't closed.
R_UNLESS(!m_parent->IsServerClosed(), ResultSessionClosed);
// Check that the request thread isn't terminating.
R_UNLESS(!request_thread->IsTerminationRequested(), ResultTerminationRequested);
// Add the request thread to our list.
m_request_list.push_back(*request_thread);
// Begin waiting on the request.
request_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::IPC);
request_thread->BeginWait(std::addressof(wait_queue));
// If we have a server thread, end its wait.
if (m_server_thread != nullptr) {
m_server_thread->EndWait(ResultSuccess);
}
}
// NOTE: Nintendo returns GetCurrentThread().GetWaitResult() here.
// This is technically incorrect, although it doesn't cause problems in practice
// because this is only ever called with request_thread = GetCurrentThreadPointer().
R_RETURN(request_thread->GetWaitResult());
}
Result KLightServerSession::ReplyAndReceive(u32* data) {
// Set the server context.
GetCurrentThread(m_kernel).SetLightSessionData(data);
// Reply, if we need to.
if (data[0] & KLightSession::ReplyFlag) {
KScopedSchedulerLock sl(m_kernel);
// Check that we're open.
R_UNLESS(!m_parent->IsClientClosed(), ResultSessionClosed);
R_UNLESS(!m_parent->IsServerClosed(), ResultSessionClosed);
// Check that we have a request to reply to.
R_UNLESS(m_current_request != nullptr, ResultInvalidState);
// Check that the server thread id is correct.
R_UNLESS(m_server_thread_id == GetCurrentThread(m_kernel).GetId(), ResultInvalidState);
// If we can reply, do so.
if (!m_current_request->IsTerminationRequested()) {
std::memcpy(m_current_request->GetLightSessionData(),
GetCurrentThread(m_kernel).GetLightSessionData(), KLightSession::DataSize);
m_current_request->EndWait(ResultSuccess);
}
// Close our current request.
m_current_request->Close();
// Clear our current request.
m_current_request = nullptr;
m_server_thread_id = InvalidThreadId;
}
// Create the wait queue for our receive.
ThreadQueueImplForKLightServerSessionReceive wait_queue(m_kernel,
std::addressof(m_server_thread));
// Receive.
while (true) {
// Try to receive a request.
{
KScopedSchedulerLock sl(m_kernel);
// Check that we aren't already receiving.
R_UNLESS(m_server_thread == nullptr, ResultInvalidState);
R_UNLESS(m_server_thread_id == InvalidThreadId, ResultInvalidState);
// Check that we're open.
R_UNLESS(!m_parent->IsClientClosed(), ResultSessionClosed);
R_UNLESS(!m_parent->IsServerClosed(), ResultSessionClosed);
// Check that we're not terminating.
R_UNLESS(!GetCurrentThread(m_kernel).IsTerminationRequested(),
ResultTerminationRequested);
// If we have a request available, use it.
if (auto head = m_request_list.begin(); head != m_request_list.end()) {
// Set our current request.
m_current_request = std::addressof(*head);
m_current_request->Open();
// Set our server thread id.
m_server_thread_id = GetCurrentThread(m_kernel).GetId();
// Copy the client request data.
std::memcpy(GetCurrentThread(m_kernel).GetLightSessionData(),
m_current_request->GetLightSessionData(), KLightSession::DataSize);
// We successfully received.
R_SUCCEED();
}
// We need to wait for a request to come in.
// Check if we were cancelled.
if (GetCurrentThread(m_kernel).IsWaitCancelled()) {
GetCurrentThread(m_kernel).ClearWaitCancelled();
R_THROW(ResultCancelled);
}
// Mark ourselves as cancellable.
GetCurrentThread(m_kernel).SetCancellable();
// Wait for a request to come in.
m_server_thread = GetCurrentThreadPointer(m_kernel);
GetCurrentThread(m_kernel).SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::IPC);
GetCurrentThread(m_kernel).BeginWait(std::addressof(wait_queue));
}
// We waited to receive a request; if our wait failed, return the failing result.
R_TRY(GetCurrentThread(m_kernel).GetWaitResult());
}
}
void KLightServerSession::CleanupRequests() {
// Cleanup all pending requests.
{
KScopedSchedulerLock sl(m_kernel);
// Handle the current request.
if (m_current_request != nullptr) {
// Reply to the current request.
if (!m_current_request->IsTerminationRequested()) {
m_current_request->EndWait(ResultSessionClosed);
}
// Clear our current request.
m_current_request->Close();
m_current_request = nullptr;
m_server_thread_id = InvalidThreadId;
}
// Reply to all other requests.
for (auto& thread : m_request_list) {
thread.EndWait(ResultSessionClosed);
}
// Wait up our server thread, if we have one.
if (m_server_thread != nullptr) {
m_server_thread->EndWait(ResultSessionClosed);
}
}
}
} // namespace Kernel

View File

@ -1,49 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "core/hle/kernel/k_auto_object.h"
#include "core/hle/kernel/k_thread.h"
#include "core/hle/result.h"
namespace Kernel {
class KLightSession;
class KLightServerSession final : public KAutoObject,
public Common::IntrusiveListBaseNode<KLightServerSession> {
KERNEL_AUTOOBJECT_TRAITS(KLightServerSession, KAutoObject);
private:
KLightSession* m_parent{};
KThread::WaiterList m_request_list{};
KThread* m_current_request{};
u64 m_server_thread_id{std::numeric_limits<u64>::max()};
KThread* m_server_thread{};
public:
explicit KLightServerSession(KernelCore& kernel);
~KLightServerSession();
void Initialize(KLightSession* parent) {
// Set member variables. */
m_parent = parent;
}
virtual void Destroy() override;
constexpr const KLightSession* GetParent() const {
return m_parent;
}
Result OnRequest(KThread* request_thread);
Result ReplyAndReceive(u32* data);
void OnClientClosed();
private:
void CleanupRequests();
};
} // namespace Kernel

View File

@ -1,81 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/kernel/k_client_port.h"
#include "core/hle/kernel/k_light_client_session.h"
#include "core/hle/kernel/k_light_server_session.h"
#include "core/hle/kernel/k_light_session.h"
#include "core/hle/kernel/k_process.h"
namespace Kernel {
KLightSession::KLightSession(KernelCore& kernel)
: KAutoObjectWithSlabHeapAndContainer(kernel), m_server(kernel), m_client(kernel) {}
KLightSession::~KLightSession() = default;
void KLightSession::Initialize(KClientPort* client_port, uintptr_t name) {
// Increment reference count.
// Because reference count is one on creation, this will result
// in a reference count of two. Thus, when both server and client are closed
// this object will be destroyed.
this->Open();
// Create our sub sessions.
KAutoObject::Create(std::addressof(m_server));
KAutoObject::Create(std::addressof(m_client));
// Initialize our sub sessions.
m_server.Initialize(this);
m_client.Initialize(this);
// Set state and name.
m_state = State::Normal;
m_name = name;
// Set our owner process.
m_process = GetCurrentProcessPointer(m_kernel);
m_process->Open();
// Set our port.
m_port = client_port;
if (m_port != nullptr) {
m_port->Open();
}
// Mark initialized.
m_initialized = true;
}
void KLightSession::Finalize() {
if (m_port != nullptr) {
m_port->OnSessionFinalized();
m_port->Close();
}
}
void KLightSession::OnServerClosed() {
if (m_state == State::Normal) {
m_state = State::ServerClosed;
m_client.OnServerClosed();
}
this->Close();
}
void KLightSession::OnClientClosed() {
if (m_state == State::Normal) {
m_state = State::ClientClosed;
m_server.OnClientClosed();
}
this->Close();
}
void KLightSession::PostDestroy(uintptr_t arg) {
// Release the session count resource the owner process holds.
KProcess* owner = reinterpret_cast<KProcess*>(arg);
owner->ReleaseResource(Svc::LimitableResource::SessionCountMax, 1);
owner->Close();
}
} // namespace Kernel

View File

@ -1,86 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "core/hle/kernel/k_light_client_session.h"
#include "core/hle/kernel/k_light_server_session.h"
#include "core/hle/kernel/slab_helpers.h"
#include "core/hle/result.h"
namespace Kernel {
class KClientPort;
class KProcess;
// TODO: SupportDynamicExpansion for SlabHeap
class KLightSession final
: public KAutoObjectWithSlabHeapAndContainer<KLightSession, KAutoObjectWithList> {
KERNEL_AUTOOBJECT_TRAITS(KLightSession, KAutoObject);
private:
enum class State : u8 {
Invalid = 0,
Normal = 1,
ClientClosed = 2,
ServerClosed = 3,
};
public:
static constexpr size_t DataSize = sizeof(u32) * 7;
static constexpr u32 ReplyFlag = (1U << 31);
private:
KLightServerSession m_server;
KLightClientSession m_client;
State m_state{State::Invalid};
KClientPort* m_port{};
uintptr_t m_name{};
KProcess* m_process{};
bool m_initialized{};
public:
explicit KLightSession(KernelCore& kernel);
~KLightSession();
void Initialize(KClientPort* client_port, uintptr_t name);
void Finalize() override;
bool IsInitialized() const override {
return m_initialized;
}
uintptr_t GetPostDestroyArgument() const override {
return reinterpret_cast<uintptr_t>(m_process);
}
static void PostDestroy(uintptr_t arg);
void OnServerClosed();
void OnClientClosed();
bool IsServerClosed() const {
return m_state != State::Normal;
}
bool IsClientClosed() const {
return m_state != State::Normal;
}
Result OnRequest(KThread* request_thread) {
R_RETURN(m_server.OnRequest(request_thread));
}
KLightClientSession& GetClientSession() {
return m_client;
}
KLightServerSession& GetServerSession() {
return m_server;
}
const KLightClientSession& GetClientSession() const {
return m_client;
}
const KLightServerSession& GetServerSession() const {
return m_server;
}
};
} // namespace Kernel

View File

@ -58,13 +58,4 @@ Result KPort::EnqueueSession(KServerSession* session) {
R_SUCCEED();
}
Result KPort::EnqueueSession(KLightServerSession* session) {
KScopedSchedulerLock sl{m_kernel};
R_UNLESS(m_state == State::Normal, ResultPortClosed);
m_server.EnqueueSession(session);
R_SUCCEED();
}
} // namespace Kernel

View File

@ -13,7 +13,6 @@
namespace Kernel {
class KLightServerSession;
class KServerSession;
class KPort final : public KAutoObjectWithSlabHeapAndContainer<KPort, KAutoObjectWithList> {
@ -39,7 +38,6 @@ public:
bool IsServerClosed() const;
Result EnqueueSession(KServerSession* session);
Result EnqueueSession(KLightServerSession* session);
KClientPort& GetClientPort() {
return m_client;

View File

@ -27,14 +27,12 @@ bool KServerPort::IsLight() const {
void KServerPort::CleanupSessions() {
// Ensure our preconditions are met.
if (this->IsLight()) {
ASSERT(m_session_list.empty());
} else {
ASSERT(m_light_session_list.empty());
UNIMPLEMENTED();
}
// Cleanup the session list.
while (true) {
// Get the last session in the list.
// Get the last session in the list
KServerSession* session = nullptr;
{
KScopedSchedulerLock sl{m_kernel};
@ -51,26 +49,6 @@ void KServerPort::CleanupSessions() {
break;
}
}
// Cleanup the light session list.
while (true) {
// Get the last session in the list.
KLightServerSession* session = nullptr;
{
KScopedSchedulerLock sl{m_kernel};
if (!m_light_session_list.empty()) {
session = std::addressof(m_light_session_list.front());
m_light_session_list.pop_front();
}
}
// Close the session.
if (session != nullptr) {
session->Close();
} else {
break;
}
}
}
void KServerPort::Destroy() {
@ -86,7 +64,8 @@ void KServerPort::Destroy() {
bool KServerPort::IsSignaled() const {
if (this->IsLight()) {
return !m_light_session_list.empty();
UNIMPLEMENTED();
return false;
} else {
return !m_session_list.empty();
}
@ -104,18 +83,6 @@ void KServerPort::EnqueueSession(KServerSession* session) {
}
}
void KServerPort::EnqueueSession(KLightServerSession* session) {
ASSERT(this->IsLight());
KScopedSchedulerLock sl{m_kernel};
// Add the session to our queue.
m_light_session_list.push_back(*session);
if (m_light_session_list.size() == 1) {
this->NotifyAvailable();
}
}
KServerSession* KServerPort::AcceptSession() {
ASSERT(!this->IsLight());
@ -131,19 +98,4 @@ KServerSession* KServerPort::AcceptSession() {
return session;
}
KLightServerSession* KServerPort::AcceptLightSession() {
ASSERT(this->IsLight());
KScopedSchedulerLock sl{m_kernel};
// Return the first session in the list.
if (m_light_session_list.empty()) {
return nullptr;
}
KLightServerSession* session = std::addressof(m_light_session_list.front());
m_light_session_list.pop_front();
return session;
}
} // namespace Kernel

View File

@ -9,7 +9,6 @@
#include "common/intrusive_list.h"
#include "core/hle/kernel/k_light_server_session.h"
#include "core/hle/kernel/k_server_session.h"
#include "core/hle/kernel/k_synchronization_object.h"
@ -29,10 +28,8 @@ public:
void Initialize(KPort* parent);
void EnqueueSession(KServerSession* session);
void EnqueueSession(KLightServerSession* session);
KServerSession* AcceptSession();
KLightServerSession* AcceptLightSession();
const KPort* GetParent() const {
return m_parent;
@ -46,12 +43,10 @@ public:
private:
using SessionList = Common::IntrusiveListBaseTraits<KServerSession>::ListType;
using LightSessionList = Common::IntrusiveListBaseTraits<KLightServerSession>::ListType;
void CleanupSessions();
SessionList m_session_list{};
LightSessionList m_light_session_list{};
KPort* m_parent{};
};

View File

@ -453,11 +453,6 @@ Result KServerSession::ReceiveRequest(std::shared_ptr<Service::HLERequestContext
size_t client_buffer_size = request->GetSize();
// bool recv_list_broken = false;
if (!client_message) {
client_message = GetInteger(client_thread->GetTlsAddress());
client_buffer_size = MessageBufferSize;
}
// Receive the message.
Core::Memory::Memory& memory{client_thread->GetOwnerProcess()->GetMemory()};
if (out_context != nullptr) {
@ -467,7 +462,8 @@ Result KServerSession::ReceiveRequest(std::shared_ptr<Service::HLERequestContext
std::make_shared<Service::HLERequestContext>(m_kernel, memory, this, client_thread);
(*out_context)->SetSessionRequestManager(manager);
(*out_context)
->PopulateFromIncomingCommandBuffer(*client_thread->GetOwnerProcess(), cmd_buf);
->PopulateFromIncomingCommandBuffer(client_thread->GetOwnerProcess()->GetHandleTable(),
cmd_buf);
} else {
KThread* server_thread = GetCurrentThreadPointer(m_kernel);
KProcess& src_process = *client_thread->GetOwnerProcess();

View File

@ -46,10 +46,6 @@ public:
return this->GetState() != State::Normal;
}
Result OnRequest(KSessionRequest* request) {
R_RETURN(m_server.OnRequest(request));
}
KClientSession& GetClientSession() {
return m_client;
}

View File

@ -385,13 +385,6 @@ public:
m_cancellable = false;
}
u32* GetLightSessionData() const {
return m_light_ipc_data;
}
void SetLightSessionData(u32* data) {
m_light_ipc_data = data;
}
bool IsTerminationRequested() const {
return m_termination_requested || GetRawState() == ThreadState::Terminated;
}

View File

@ -1340,7 +1340,6 @@ struct KernelCore::SlabHeapContainer {
KSlabHeap<KProcess> process;
KSlabHeap<KResourceLimit> resource_limit;
KSlabHeap<KSession> session;
KSlabHeap<KLightSession> light_session;
KSlabHeap<KSharedMemory> shared_memory;
KSlabHeap<KSharedMemoryInfo> shared_memory_info;
KSlabHeap<KThread> thread;
@ -1371,8 +1370,6 @@ KSlabHeap<T>& KernelCore::SlabHeap() {
return slab_heap_container->resource_limit;
} else if constexpr (std::is_same_v<T, KSession>) {
return slab_heap_container->session;
} else if constexpr (std::is_same_v<T, KLightSession>) {
return slab_heap_container->light_session;
} else if constexpr (std::is_same_v<T, KSharedMemory>) {
return slab_heap_container->shared_memory;
} else if constexpr (std::is_same_v<T, KSharedMemoryInfo>) {
@ -1410,7 +1407,6 @@ template KSlabHeap<KPort>& KernelCore::SlabHeap();
template KSlabHeap<KProcess>& KernelCore::SlabHeap();
template KSlabHeap<KResourceLimit>& KernelCore::SlabHeap();
template KSlabHeap<KSession>& KernelCore::SlabHeap();
template KSlabHeap<KLightSession>& KernelCore::SlabHeap();
template KSlabHeap<KSharedMemory>& KernelCore::SlabHeap();
template KSlabHeap<KSharedMemoryInfo>& KernelCore::SlabHeap();
template KSlabHeap<KThread>& KernelCore::SlabHeap();

View File

@ -139,7 +139,7 @@ void PhysicalCore::RunThread(Kernel::KThread* thread) {
}
// Handle external interrupt sources.
if (interrupt || m_is_single_core) {
if (interrupt || !m_is_single_core) {
return;
}
}

View File

@ -7,127 +7,59 @@
#include "core/hle/kernel/k_client_session.h"
#include "core/hle/kernel/k_hardware_timer.h"
#include "core/hle/kernel/k_process.h"
#include "core/hle/kernel/k_scoped_resource_reservation.h"
#include "core/hle/kernel/k_server_session.h"
#include "core/hle/kernel/k_session.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/kernel/svc_results.h"
namespace Kernel::Svc {
namespace {
Result SendSyncRequestImpl(KernelCore& kernel, uintptr_t message, size_t buffer_size,
Handle session_handle) {
// Get the client session.
/// Makes a blocking IPC call to a service.
Result SendSyncRequest(Core::System& system, Handle handle) {
// Get the client session from its handle.
KScopedAutoObject session =
GetCurrentProcess(kernel).GetHandleTable().GetObject<KClientSession>(session_handle);
GetCurrentProcess(system.Kernel()).GetHandleTable().GetObject<KClientSession>(handle);
R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
// Get the parent, and persist a reference to it until we're done.
KScopedAutoObject parent = session->GetParent();
ASSERT(parent.IsNotNull());
LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}", handle);
// Send the request.
R_RETURN(session->SendSyncRequest(message, buffer_size));
R_RETURN(session->SendSyncRequest());
}
Result ReplyAndReceiveImpl(KernelCore& kernel, int32_t* out_index, uintptr_t message,
size_t buffer_size, KPhysicalAddress message_paddr,
KSynchronizationObject** objs, int32_t num_objects, Handle reply_target,
int64_t timeout_ns) {
// Reply to the target, if one is specified.
if (reply_target != InvalidHandle) {
KScopedAutoObject session =
GetCurrentProcess(kernel).GetHandleTable().GetObject<KServerSession>(reply_target);
R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
// If we fail to reply, we want to set the output index to -1.
ON_RESULT_FAILURE {
*out_index = -1;
};
// Send the reply.
R_TRY(session->SendReply());
// R_TRY(session->SendReply(message, buffer_size, message_paddr));
}
// Receive a message.
{
// Convert the timeout from nanoseconds to ticks.
// NOTE: Nintendo does not use this conversion logic in WaitSynchronization...
s64 timeout;
if (timeout_ns > 0) {
const s64 offset_tick(timeout_ns);
if (offset_tick > 0) {
timeout = kernel.HardwareTimer().GetTick() + offset_tick + 2;
if (timeout <= 0) {
timeout = std::numeric_limits<s64>::max();
}
} else {
timeout = std::numeric_limits<s64>::max();
}
} else {
timeout = timeout_ns;
}
// Wait for a message.
while (true) {
// Wait for an object.
s32 index;
Result result = KSynchronizationObject::Wait(kernel, std::addressof(index), objs,
num_objects, timeout);
if (ResultTimedOut == result) {
R_THROW(result);
}
// Receive the request.
if (R_SUCCEEDED(result)) {
KServerSession* session = objs[index]->DynamicCast<KServerSession*>();
if (session != nullptr) {
// result = session->ReceiveRequest(message, buffer_size, message_paddr);
result = session->ReceiveRequest();
if (ResultNotFound == result) {
continue;
}
}
}
*out_index = index;
R_RETURN(result);
}
}
Result SendSyncRequestWithUserBuffer(Core::System& system, uint64_t message_buffer,
uint64_t message_buffer_size, Handle session_handle) {
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result ReplyAndReceiveImpl(KernelCore& kernel, int32_t* out_index, uintptr_t message,
size_t buffer_size, KPhysicalAddress message_paddr,
KProcessAddress user_handles, int32_t num_handles, Handle reply_target,
int64_t timeout_ns) {
Result SendAsyncRequestWithUserBuffer(Core::System& system, Handle* out_event_handle,
uint64_t message_buffer, uint64_t message_buffer_size,
Handle session_handle) {
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result ReplyAndReceive(Core::System& system, s32* out_index, uint64_t handles_addr, s32 num_handles,
Handle reply_target, s64 timeout_ns) {
// Ensure number of handles is valid.
R_UNLESS(0 <= num_handles && num_handles <= Svc::ArgumentHandleCountMax, ResultOutOfRange);
R_UNLESS(0 <= num_handles && num_handles <= ArgumentHandleCountMax, ResultOutOfRange);
// Get the synchronization context.
auto& process = GetCurrentProcess(kernel);
auto& thread = GetCurrentThread(kernel);
auto& handle_table = process.GetHandleTable();
KSynchronizationObject** objs = thread.GetSynchronizationObjectBuffer().data();
Handle* handles = thread.GetHandleBuffer().data();
auto& kernel = system.Kernel();
auto& handle_table = GetCurrentProcess(kernel).GetHandleTable();
auto objs = GetCurrentThread(kernel).GetSynchronizationObjectBuffer();
auto handles = GetCurrentThread(kernel).GetHandleBuffer();
// Copy user handles.
if (num_handles > 0) {
// Ensure that we can try to get the handles.
R_UNLESS(process.GetPageTable().Contains(user_handles, num_handles * sizeof(Handle)),
// Get the handles.
R_UNLESS(GetCurrentMemory(kernel).ReadBlock(handles_addr, handles.data(),
sizeof(Handle) * num_handles),
ResultInvalidPointer);
// Get the handles
R_UNLESS(
GetCurrentMemory(kernel).ReadBlock(user_handles, handles, sizeof(Handle) * num_handles),
ResultInvalidPointer);
// Convert the handles to objects.
R_UNLESS(
handle_table.GetMultipleObjects<KSynchronizationObject>(objs, handles, num_handles),
ResultInvalidHandle);
R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(
objs.data(), handles.data(), num_handles),
ResultInvalidHandle);
}
// Ensure handles are closed when we're done.
@ -137,135 +69,69 @@ Result ReplyAndReceiveImpl(KernelCore& kernel, int32_t* out_index, uintptr_t mes
}
});
R_RETURN(ReplyAndReceiveImpl(kernel, out_index, message, buffer_size, message_paddr, objs,
num_handles, reply_target, timeout_ns));
}
// Reply to the target, if one is specified.
if (reply_target != InvalidHandle) {
KScopedAutoObject session = handle_table.GetObject<KServerSession>(reply_target);
R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
} // namespace
/// Makes a blocking IPC call to a service.
Result SendSyncRequest(Core::System& system, Handle session_handle) {
R_RETURN(SendSyncRequestImpl(system.Kernel(), 0, 0, session_handle));
}
Result SendSyncRequestWithUserBuffer(Core::System& system, uint64_t message, uint64_t buffer_size,
Handle session_handle) {
auto& kernel = system.Kernel();
// Validate that the message buffer is page aligned and does not overflow.
R_UNLESS(Common::IsAligned(message, PageSize), ResultInvalidAddress);
R_UNLESS(buffer_size > 0, ResultInvalidSize);
R_UNLESS(Common::IsAligned(buffer_size, PageSize), ResultInvalidSize);
R_UNLESS(message < message + buffer_size, ResultInvalidCurrentMemory);
// Get the process page table.
auto& page_table = GetCurrentProcess(kernel).GetPageTable();
// Lock the message buffer.
R_TRY(page_table.LockForIpcUserBuffer(nullptr, message, buffer_size));
{
// If we fail to send the message, unlock the message buffer.
// If we fail to reply, we want to set the output index to -1.
ON_RESULT_FAILURE {
page_table.UnlockForIpcUserBuffer(message, buffer_size);
*out_index = -1;
};
// Send the request.
ASSERT(message != 0);
R_TRY(SendSyncRequestImpl(kernel, message, buffer_size, session_handle));
// Send the reply.
R_TRY(session->SendReply());
}
// We successfully processed, so try to unlock the message buffer.
R_RETURN(page_table.UnlockForIpcUserBuffer(message, buffer_size));
}
Result SendAsyncRequestWithUserBuffer(Core::System& system, Handle* out_event_handle,
uint64_t message, uint64_t buffer_size,
Handle session_handle) {
// Get the process and handle table.
auto& process = GetCurrentProcess(system.Kernel());
auto& handle_table = process.GetHandleTable();
// Reserve a new event from the process resource limit.
KScopedResourceReservation event_reservation(std::addressof(process),
Svc::LimitableResource::EventCountMax);
R_UNLESS(event_reservation.Succeeded(), ResultLimitReached);
// Get the client session.
KScopedAutoObject session = process.GetHandleTable().GetObject<KClientSession>(session_handle);
R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
// Get the parent, and persist a reference to it until we're done.
KScopedAutoObject parent = session->GetParent();
ASSERT(parent.IsNotNull());
// Create a new event.
KEvent* event = KEvent::Create(system.Kernel());
R_UNLESS(event != nullptr, ResultOutOfResource);
// Initialize the event.
event->Initialize(std::addressof(process));
// Commit our reservation.
event_reservation.Commit();
// At end of scope, kill the standing references to the sub events.
SCOPE_EXIT({
event->GetReadableEvent().Close();
event->Close();
});
// Register the event.
KEvent::Register(system.Kernel(), event);
// Add the readable event to the handle table.
R_TRY(handle_table.Add(out_event_handle, std::addressof(event->GetReadableEvent())));
// Ensure that if we fail to send the request, we close the readable handle.
ON_RESULT_FAILURE {
handle_table.Remove(*out_event_handle);
};
// Send the async request.
R_RETURN(session->SendAsyncRequest(event, message, buffer_size));
}
Result ReplyAndReceive(Core::System& system, s32* out_index, uint64_t handles, s32 num_handles,
Handle reply_target, s64 timeout_ns) {
R_RETURN(ReplyAndReceiveImpl(system.Kernel(), out_index, 0, 0, 0, handles, num_handles,
reply_target, timeout_ns));
}
Result ReplyAndReceiveWithUserBuffer(Core::System& system, int32_t* out_index, uint64_t message,
uint64_t buffer_size, uint64_t handles, int32_t num_handles,
Handle reply_target, int64_t timeout_ns) {
// Validate that the message buffer is page aligned and does not overflow.
R_UNLESS(Common::IsAligned(message, PageSize), ResultInvalidAddress);
R_UNLESS(buffer_size > 0, ResultInvalidSize);
R_UNLESS(Common::IsAligned(buffer_size, PageSize), ResultInvalidSize);
R_UNLESS(message < message + buffer_size, ResultInvalidCurrentMemory);
// Get the process page table.
auto& page_table = GetCurrentProcess(system.Kernel()).GetPageTable();
// Lock the message buffer, getting its physical address.
KPhysicalAddress message_paddr;
R_TRY(page_table.LockForIpcUserBuffer(std::addressof(message_paddr), message, buffer_size));
{
// If we fail to send the message, unlock the message buffer.
ON_RESULT_FAILURE {
page_table.UnlockForIpcUserBuffer(message, buffer_size);
};
// Reply/Receive the request.
ASSERT(message != 0);
R_TRY(ReplyAndReceiveImpl(system.Kernel(), out_index, message, buffer_size, message_paddr,
handles, num_handles, reply_target, timeout_ns));
// Convert the timeout from nanoseconds to ticks.
// NOTE: Nintendo does not use this conversion logic in WaitSynchronization...
s64 timeout;
if (timeout_ns > 0) {
const s64 offset_tick(timeout_ns);
if (offset_tick > 0) {
timeout = kernel.HardwareTimer().GetTick() + offset_tick + 2;
if (timeout <= 0) {
timeout = std::numeric_limits<s64>::max();
}
} else {
timeout = std::numeric_limits<s64>::max();
}
} else {
timeout = timeout_ns;
}
// We successfully processed, so try to unlock the message buffer.
R_RETURN(page_table.UnlockForIpcUserBuffer(message, buffer_size));
// Wait for a message.
while (true) {
// Wait for an object.
s32 index;
Result result = KSynchronizationObject::Wait(kernel, std::addressof(index), objs.data(),
num_handles, timeout);
if (result == ResultTimedOut) {
R_RETURN(result);
}
// Receive the request.
if (R_SUCCEEDED(result)) {
KServerSession* session = objs[index]->DynamicCast<KServerSession*>();
if (session != nullptr) {
result = session->ReceiveRequest();
if (result == ResultNotFound) {
continue;
}
}
}
*out_index = index;
R_RETURN(result);
}
}
Result ReplyAndReceiveWithUserBuffer(Core::System& system, int32_t* out_index,
uint64_t message_buffer, uint64_t message_buffer_size,
uint64_t handles, int32_t num_handles, Handle reply_target,
int64_t timeout_ns) {
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result SendSyncRequest64(Core::System& system, Handle session_handle) {

View File

@ -1,40 +1,21 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/arm/arm_interface.h"
#include "core/core.h"
#include "core/hle/kernel/k_light_client_session.h"
#include "core/hle/kernel/k_light_server_session.h"
#include "core/hle/kernel/k_process.h"
#include "core/hle/kernel/k_thread.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/kernel/svc_results.h"
namespace Kernel::Svc {
Result SendSyncRequestLight(Core::System& system, Handle session_handle, u32* args) {
// Get the light client session from its handle.
KScopedAutoObject session = GetCurrentProcess(system.Kernel())
.GetHandleTable()
.GetObject<KLightClientSession>(session_handle);
R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
// Send the request.
R_TRY(session->SendSyncRequest(args));
R_SUCCEED();
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result ReplyAndReceiveLight(Core::System& system, Handle session_handle, u32* args) {
// Get the light server session from its handle.
KScopedAutoObject session = GetCurrentProcess(system.Kernel())
.GetHandleTable()
.GetObject<KLightServerSession>(session_handle);
R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
// Handle the request.
R_TRY(session->ReplyAndReceive(args));
R_SUCCEED();
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result SendSyncRequestLight64(Core::System& system, Handle session_handle, u32* args) {

View File

@ -5,7 +5,6 @@
#include "core/core.h"
#include "core/hle/kernel/k_client_port.h"
#include "core/hle/kernel/k_client_session.h"
#include "core/hle/kernel/k_light_client_session.h"
#include "core/hle/kernel/k_object_name.h"
#include "core/hle/kernel/k_port.h"
#include "core/hle/kernel/k_process.h"
@ -52,73 +51,13 @@ Result ConnectToNamedPort(Core::System& system, Handle* out, u64 user_name) {
Result CreatePort(Core::System& system, Handle* out_server, Handle* out_client,
int32_t max_sessions, bool is_light, uint64_t name) {
auto& kernel = system.Kernel();
// Ensure max sessions is valid.
R_UNLESS(max_sessions > 0, ResultOutOfRange);
// Get the current handle table.
auto& handle_table = GetCurrentProcess(kernel).GetHandleTable();
// Create a new port.
KPort* port = KPort::Create(kernel);
R_UNLESS(port != nullptr, ResultOutOfResource);
// Initialize the port.
port->Initialize(max_sessions, is_light, name);
// Ensure that we clean up the port (and its only references are handle table) on function end.
SCOPE_EXIT({
port->GetServerPort().Close();
port->GetClientPort().Close();
});
// Register the port.
KPort::Register(kernel, port);
// Add the client to the handle table.
R_TRY(handle_table.Add(out_client, std::addressof(port->GetClientPort())));
// Ensure that we maintain a clean handle state on exit.
ON_RESULT_FAILURE {
handle_table.Remove(*out_client);
};
// Add the server to the handle table.
R_RETURN(handle_table.Add(out_server, std::addressof(port->GetServerPort())));
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result ConnectToPort(Core::System& system, Handle* out, Handle port) {
// Get the current handle table.
auto& handle_table = GetCurrentProcess(system.Kernel()).GetHandleTable();
// Get the client port.
KScopedAutoObject client_port = handle_table.GetObject<KClientPort>(port);
R_UNLESS(client_port.IsNotNull(), ResultInvalidHandle);
// Reserve a handle for the port.
// NOTE: Nintendo really does write directly to the output handle here.
R_TRY(handle_table.Reserve(out));
ON_RESULT_FAILURE {
handle_table.Unreserve(*out);
};
// Create the session.
KAutoObject* session;
if (client_port->IsLight()) {
R_TRY(client_port->CreateLightSession(
reinterpret_cast<KLightClientSession**>(std::addressof(session))));
} else {
R_TRY(client_port->CreateSession(
reinterpret_cast<KClientSession**>(std::addressof(session))));
}
// Register the session.
handle_table.Register(*out, session);
session->Close();
// We succeeded.
R_SUCCEED();
Result ConnectToPort(Core::System& system, Handle* out_handle, Handle port) {
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result ManageNamedPort(Core::System& system, Handle* out_server_handle, uint64_t user_name,

View File

@ -3,10 +3,8 @@
#include "common/scope_exit.h"
#include "core/core.h"
#include "core/hle/kernel/k_light_session.h"
#include "core/hle/kernel/k_process.h"
#include "core/hle/kernel/k_scoped_resource_reservation.h"
#include "core/hle/kernel/k_server_port.h"
#include "core/hle/kernel/k_session.h"
#include "core/hle/kernel/svc.h"
@ -22,7 +20,7 @@ Result CreateSession(Core::System& system, Handle* out_server, Handle* out_clien
T* session;
// Reserve a new session from the process resource limit.
// TODO: Dynamic resource limits
// FIXME: LimitableResource_SessionCountMax
KScopedResourceReservation session_reservation(std::addressof(process),
LimitableResource::SessionCountMax);
if (session_reservation.Succeeded()) {
@ -94,42 +92,16 @@ Result CreateSession(Core::System& system, Handle* out_server, Handle* out_clien
Result CreateSession(Core::System& system, Handle* out_server, Handle* out_client, bool is_light,
u64 name) {
if (is_light) {
R_RETURN(CreateSession<KLightSession>(system, out_server, out_client, name));
// return CreateSession<KLightSession>(system, out_server, out_client, name);
R_THROW(ResultNotImplemented);
} else {
R_RETURN(CreateSession<KSession>(system, out_server, out_client, name));
}
}
Result AcceptSession(Core::System& system, Handle* out, Handle port_handle) {
// Get the current handle table.
auto& handle_table = GetCurrentProcess(system.Kernel()).GetHandleTable();
// Get the server port.
KScopedAutoObject port = handle_table.GetObject<KServerPort>(port_handle);
R_UNLESS(port.IsNotNull(), ResultInvalidHandle);
// Reserve an entry for the new session.
R_TRY(handle_table.Reserve(out));
ON_RESULT_FAILURE {
handle_table.Unreserve(*out);
};
// Accept the session.
KAutoObject* session;
if (port->IsLight()) {
session = port->AcceptLightSession();
} else {
session = port->AcceptSession();
}
// Ensure we accepted successfully.
R_UNLESS(session != nullptr, ResultNotFound);
// Register the session.
handle_table.Register(*out, session);
session->Close();
R_SUCCEED();
Result AcceptSession(Core::System& system, Handle* out_handle, Handle port_handle) {
UNIMPLEMENTED();
R_THROW(ResultNotImplemented);
}
Result CreateSession64(Core::System& system, Handle* out_server_session_handle,

View File

@ -246,13 +246,7 @@ static void BuildEntryIndex(std::vector<FileSys::Entry>& entries, const std::vec
entries.reserve(entries.size() + new_data.size());
for (const auto& new_entry : new_data) {
auto name = new_entry->GetName();
if (type == FileSys::EntryType::File && name == FileSys::GetSaveDataSizeFileName()) {
continue;
}
entries.emplace_back(name, type,
entries.emplace_back(new_entry->GetName(), type,
type == FileSys::EntryType::Directory ? 0 : new_entry->GetSize());
}
}

View File

@ -1,199 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/core.h"
#include "core/hle/kernel/k_shared_memory.h"
#include "core/hle/service/hid/controllers/applet_resource.h"
#include "core/hle/service/hid/errors.h"
namespace Service::HID {
AppletResource::AppletResource(Core::System& system_) : system{system_} {}
AppletResource::~AppletResource() = default;
Result AppletResource::CreateAppletResource(u64 aruid) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return ResultAruidNotRegistered;
}
if (data[index].flag.is_assigned) {
return ResultAruidAlreadyRegistered;
}
// TODO: Here shared memory is created for the process we don't quite emulate this part so
// obtain this pointer from system
auto& shared_memory = system.Kernel().GetHidSharedMem();
data[index].shared_memory_handle = &shared_memory;
data[index].flag.is_assigned.Assign(true);
// TODO: InitializeSixAxisControllerConfig(false);
active_aruid = aruid;
return ResultSuccess;
}
Result AppletResource::RegisterAppletResourceUserId(u64 aruid, bool enable_input) {
const u64 index = GetIndexFromAruid(aruid);
if (index < AruidIndexMax) {
return ResultAruidAlreadyRegistered;
}
std::size_t data_index = AruidIndexMax;
for (std::size_t i = 0; i < AruidIndexMax; i++) {
if (!data[i].flag.is_initialized) {
data_index = i;
break;
}
}
if (data_index == AruidIndexMax) {
return ResultAruidNoAvailableEntries;
}
AruidData& aruid_data = data[data_index];
aruid_data.aruid = aruid;
aruid_data.flag.is_initialized.Assign(true);
if (enable_input) {
aruid_data.flag.enable_pad_input.Assign(true);
aruid_data.flag.enable_six_axis_sensor.Assign(true);
aruid_data.flag.bit_18.Assign(true);
aruid_data.flag.enable_touchscreen.Assign(true);
}
data_index = AruidIndexMax;
for (std::size_t i = 0; i < AruidIndexMax; i++) {
if (registration_list.flag[i] == RegistrationStatus::Initialized) {
if (registration_list.aruid[i] != aruid) {
continue;
}
data_index = i;
break;
}
if (registration_list.flag[i] == RegistrationStatus::None) {
data_index = i;
break;
}
}
if (data_index == AruidIndexMax) {
return ResultSuccess;
}
registration_list.flag[data_index] = RegistrationStatus::Initialized;
registration_list.aruid[data_index] = aruid;
return ResultSuccess;
}
void AppletResource::UnregisterAppletResourceUserId(u64 aruid) {
u64 index = GetIndexFromAruid(aruid);
if (index < AruidIndexMax) {
if (data[index].flag.is_assigned) {
data[index].shared_memory_handle = nullptr;
data[index].flag.is_assigned.Assign(false);
}
}
index = GetIndexFromAruid(aruid);
if (index < AruidIndexMax) {
DestroySevenSixAxisTransferMemory();
data[index].flag.raw = 0;
data[index].aruid = 0;
index = GetIndexFromAruid(aruid);
if (index < AruidIndexMax) {
registration_list.flag[index] = RegistrationStatus::PendingDelete;
}
}
}
u64 AppletResource::GetActiveAruid() {
return active_aruid;
}
Result AppletResource::GetSharedMemoryHandle(Kernel::KSharedMemory** out_handle, u64 aruid) {
u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return ResultAruidNotRegistered;
}
*out_handle = data[index].shared_memory_handle;
return ResultSuccess;
}
u64 AppletResource::GetIndexFromAruid(u64 aruid) {
for (std::size_t i = 0; i < AruidIndexMax; i++) {
if (registration_list.flag[i] == RegistrationStatus::Initialized &&
registration_list.aruid[i] == aruid) {
return i;
}
}
return AruidIndexMax;
}
Result AppletResource::DestroySevenSixAxisTransferMemory() {
// TODO
return ResultSuccess;
}
void AppletResource::EnableInput(u64 aruid, bool is_enabled) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return;
}
data[index].flag.enable_pad_input.Assign(is_enabled);
data[index].flag.enable_touchscreen.Assign(is_enabled);
}
void AppletResource::EnableSixAxisSensor(u64 aruid, bool is_enabled) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return;
}
data[index].flag.enable_six_axis_sensor.Assign(is_enabled);
}
void AppletResource::EnablePadInput(u64 aruid, bool is_enabled) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return;
}
data[index].flag.enable_pad_input.Assign(is_enabled);
}
void AppletResource::EnableTouchScreen(u64 aruid, bool is_enabled) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return;
}
data[index].flag.enable_touchscreen.Assign(is_enabled);
}
void AppletResource::SetIsPalmaConnectable(u64 aruid, bool is_connectable) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return;
}
data[index].flag.is_palma_connectable.Assign(is_connectable);
}
void AppletResource::EnablePalmaBoostMode(u64 aruid, bool is_enabled) {
const u64 index = GetIndexFromAruid(aruid);
if (index >= AruidIndexMax) {
return;
}
data[index].flag.enable_palma_boost_mode.Assign(is_enabled);
}
} // namespace Service::HID

View File

@ -1,87 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <array>
#include "common/bit_field.h"
#include "common/common_types.h"
#include "core/hle/result.h"
namespace Core {
class System;
}
namespace Kernel {
class KSharedMemory;
}
namespace Service::HID {
class AppletResource {
public:
explicit AppletResource(Core::System& system_);
~AppletResource();
Result CreateAppletResource(u64 aruid);
Result RegisterAppletResourceUserId(u64 aruid, bool enable_input);
void UnregisterAppletResourceUserId(u64 aruid);
u64 GetActiveAruid();
Result GetSharedMemoryHandle(Kernel::KSharedMemory** out_handle, u64 aruid);
u64 GetIndexFromAruid(u64 aruid);
Result DestroySevenSixAxisTransferMemory();
void EnableInput(u64 aruid, bool is_enabled);
void EnableSixAxisSensor(u64 aruid, bool is_enabled);
void EnablePadInput(u64 aruid, bool is_enabled);
void EnableTouchScreen(u64 aruid, bool is_enabled);
void SetIsPalmaConnectable(u64 aruid, bool is_connectable);
void EnablePalmaBoostMode(u64 aruid, bool is_enabled);
private:
static constexpr std::size_t AruidIndexMax = 0x20;
enum RegistrationStatus : u32 {
None,
Initialized,
PendingDelete,
};
struct DataStatusFlag {
union {
u32 raw{};
BitField<0, 1, u32> is_initialized;
BitField<1, 1, u32> is_assigned;
BitField<16, 1, u32> enable_pad_input;
BitField<17, 1, u32> enable_six_axis_sensor;
BitField<18, 1, u32> bit_18;
BitField<19, 1, u32> is_palma_connectable;
BitField<20, 1, u32> enable_palma_boost_mode;
BitField<21, 1, u32> enable_touchscreen;
};
};
struct AruidRegisterList {
std::array<RegistrationStatus, AruidIndexMax> flag{};
std::array<u64, AruidIndexMax> aruid{};
};
static_assert(sizeof(AruidRegisterList) == 0x180, "AruidRegisterList is an invalid size");
struct AruidData {
DataStatusFlag flag{};
u64 aruid{};
Kernel::KSharedMemory* shared_memory_handle{nullptr};
};
u64 active_aruid{};
AruidRegisterList registration_list{};
std::array<AruidData, AruidIndexMax> data{};
Core::System& system;
};
} // namespace Service::HID

View File

@ -19,11 +19,6 @@ constexpr Result NpadIsSameType{ErrorModule::HID, 602};
constexpr Result InvalidNpadId{ErrorModule::HID, 709};
constexpr Result NpadNotConnected{ErrorModule::HID, 710};
constexpr Result InvalidArraySize{ErrorModule::HID, 715};
constexpr Result ResultAruidNoAvailableEntries{ErrorModule::HID, 1044};
constexpr Result ResultAruidAlreadyRegistered{ErrorModule::HID, 1046};
constexpr Result ResultAruidNotRegistered{ErrorModule::HID, 1047};
constexpr Result InvalidPalmaHandle{ErrorModule::HID, 3302};
} // namespace Service::HID

View File

@ -1,8 +1,6 @@
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/kernel/k_process.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/service/hid/hid.h"
#include "core/hle/service/hid/hid_debug_server.h"
#include "core/hle/service/hid/hid_firmware_settings.h"
@ -22,12 +20,6 @@ void LoopProcess(Core::System& system) {
std::shared_ptr<HidFirmwareSettings> firmware_settings =
std::make_shared<HidFirmwareSettings>();
// TODO: Remove this hack until this service is emulated properly.
const auto process_list = system.Kernel().GetProcessList();
if (!process_list.empty()) {
resouce_manager->RegisterAppletResourceUserId(process_list[0]->GetId(), true);
}
server_manager->RegisterNamedService(
"hid", std::make_shared<IHidServer>(system, resouce_manager, firmware_settings));
server_manager->RegisterNamedService(

View File

@ -224,13 +224,8 @@ void IHidServer::CreateAppletResource(HLERequestContext& ctx) {
LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
Result result = GetResourceManager()->CreateAppletResource(applet_resource_user_id);
if (result.IsSuccess()) {
result = GetResourceManager()->GetNpad()->Activate(applet_resource_user_id);
}
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(result);
rb.Push(ResultSuccess);
rb.PushIpcInterface<IAppletResource>(system, resource_manager);
}

View File

@ -3,7 +3,6 @@
#include "core/hid/hid_core.h"
#include "core/hle/service/hid/controllers/npad.h"
#include "core/hle/service/hid/controllers/palma.h"
#include "core/hle/service/hid/controllers/touchscreen.h"
#include "core/hle/service/hid/errors.h"
#include "core/hle/service/hid/hid_system_server.h"
@ -64,13 +63,13 @@ IHidSystemServer::IHidSystemServer(Core::System& system_, std::shared_ptr<Resour
{329, nullptr, "DetachAbstractedPadAll"},
{330, nullptr, "CheckAbstractedPadConnection"},
{500, nullptr, "SetAppletResourceUserId"},
{501, &IHidSystemServer::RegisterAppletResourceUserId, "RegisterAppletResourceUserId"},
{502, &IHidSystemServer::UnregisterAppletResourceUserId, "UnregisterAppletResourceUserId"},
{503, &IHidSystemServer::EnableAppletToGetInput, "EnableAppletToGetInput"},
{501, nullptr, "RegisterAppletResourceUserId"},
{502, nullptr, "UnregisterAppletResourceUserId"},
{503, nullptr, "EnableAppletToGetInput"},
{504, nullptr, "SetAruidValidForVibration"},
{505, &IHidSystemServer::EnableAppletToGetSixAxisSensor, "EnableAppletToGetSixAxisSensor"},
{506, &IHidSystemServer::EnableAppletToGetPadInput, "EnableAppletToGetPadInput"},
{507, &IHidSystemServer::EnableAppletToGetTouchScreen, "EnableAppletToGetTouchScreen"},
{505, nullptr, "EnableAppletToGetSixAxisSensor"},
{506, nullptr, "EnableAppletToGetPadInput"},
{507, nullptr, "EnableAppletToGetTouchScreen"},
{510, nullptr, "SetVibrationMasterVolume"},
{511, nullptr, "GetVibrationMasterVolume"},
{512, nullptr, "BeginPermitVibrationSession"},
@ -421,129 +420,6 @@ void IHidSystemServer::GetIrSensorState(HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::RegisterAppletResourceUserId(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
struct Parameters {
bool enable_input;
INSERT_PADDING_WORDS_NOINIT(1);
u64 applet_resource_user_id;
};
static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
const auto parameters{rp.PopRaw<Parameters>()};
LOG_INFO(Service_HID, "called, enable_input={}, applet_resource_user_id={}",
parameters.enable_input, parameters.applet_resource_user_id);
Result result = GetResourceManager()->RegisterAppletResourceUserId(
parameters.applet_resource_user_id, parameters.enable_input);
if (result.IsSuccess()) {
// result = GetResourceManager()->GetNpad()->RegisterAppletResourceUserId(
// parameters.applet_resource_user_id);
}
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::UnregisterAppletResourceUserId(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
u64 applet_resource_user_id{rp.Pop<u64>()};
LOG_INFO(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
GetResourceManager()->UnregisterAppletResourceUserId(applet_resource_user_id);
// GetResourceManager()->GetNpad()->UnregisterAppletResourceUserId(applet_resource_user_id);
// GetResourceManager()->GetPalma()->UnregisterAppletResourceUserId(applet_resource_user_id);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::EnableAppletToGetInput(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
struct Parameters {
bool is_enabled;
INSERT_PADDING_WORDS_NOINIT(1);
u64 applet_resource_user_id;
};
static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
const auto parameters{rp.PopRaw<Parameters>()};
LOG_INFO(Service_HID, "called, is_enabled={}, applet_resource_user_id={}",
parameters.is_enabled, parameters.applet_resource_user_id);
GetResourceManager()->EnableInput(parameters.applet_resource_user_id, parameters.is_enabled);
// GetResourceManager()->GetNpad()->EnableInput(parameters.applet_resource_user_id);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::EnableAppletToGetSixAxisSensor(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
struct Parameters {
bool is_enabled;
INSERT_PADDING_WORDS_NOINIT(1);
u64 applet_resource_user_id;
};
static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
const auto parameters{rp.PopRaw<Parameters>()};
LOG_INFO(Service_HID, "called, is_enabled={}, applet_resource_user_id={}",
parameters.is_enabled, parameters.applet_resource_user_id);
GetResourceManager()->EnableTouchScreen(parameters.applet_resource_user_id,
parameters.is_enabled);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::EnableAppletToGetPadInput(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
struct Parameters {
bool is_enabled;
INSERT_PADDING_WORDS_NOINIT(1);
u64 applet_resource_user_id;
};
static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
const auto parameters{rp.PopRaw<Parameters>()};
LOG_INFO(Service_HID, "called, is_enabled={}, applet_resource_user_id={}",
parameters.is_enabled, parameters.applet_resource_user_id);
GetResourceManager()->EnablePadInput(parameters.applet_resource_user_id, parameters.is_enabled);
// GetResourceManager()->GetNpad()->EnableInput(parameters.applet_resource_user_id);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::EnableAppletToGetTouchScreen(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
struct Parameters {
bool is_enabled;
INSERT_PADDING_WORDS_NOINIT(1);
u64 applet_resource_user_id;
};
static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
const auto parameters{rp.PopRaw<Parameters>()};
LOG_INFO(Service_HID, "called, is_enabled={}, applet_resource_user_id={}",
parameters.is_enabled, parameters.applet_resource_user_id);
GetResourceManager()->EnableTouchScreen(parameters.applet_resource_user_id,
parameters.is_enabled);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void IHidSystemServer::AcquireConnectionTriggerTimeoutEvent(HLERequestContext& ctx) {
LOG_INFO(Service_AM, "(STUBBED) called");

View File

@ -38,12 +38,6 @@ private:
void HasLeftRightBattery(HLERequestContext& ctx);
void GetUniquePadsFromNpad(HLERequestContext& ctx);
void GetIrSensorState(HLERequestContext& ctx);
void RegisterAppletResourceUserId(HLERequestContext& ctx);
void UnregisterAppletResourceUserId(HLERequestContext& ctx);
void EnableAppletToGetInput(HLERequestContext& ctx);
void EnableAppletToGetSixAxisSensor(HLERequestContext& ctx);
void EnableAppletToGetPadInput(HLERequestContext& ctx);
void EnableAppletToGetTouchScreen(HLERequestContext& ctx);
void AcquireConnectionTriggerTimeoutEvent(HLERequestContext& ctx);
void AcquireDeviceRegisteredEventForControllerSupport(HLERequestContext& ctx);
void GetRegisteredDevices(HLERequestContext& ctx);

View File

@ -9,7 +9,6 @@
#include "core/hle/service/hid/resource_manager.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/hid/controllers/applet_resource.h"
#include "core/hle/service/hid/controllers/console_six_axis.h"
#include "core/hle/service/hid/controllers/debug_pad.h"
#include "core/hle/service/hid/controllers/gesture.h"
@ -34,9 +33,7 @@ constexpr auto mouse_keyboard_update_ns = std::chrono::nanoseconds{8 * 1000 * 10
constexpr auto motion_update_ns = std::chrono::nanoseconds{5 * 1000 * 1000}; // (5ms, 200Hz)
ResourceManager::ResourceManager(Core::System& system_)
: system{system_}, service_context{system_, "hid"} {
applet_resource = std::make_shared<AppletResource>(system);
}
: system{system_}, service_context{system_, "hid"} {}
ResourceManager::~ResourceManager() = default;
@ -80,11 +77,6 @@ void ResourceManager::Initialize() {
system.HIDCore().ReloadInputDevices();
is_initialized = true;
}
std::shared_ptr<AppletResource> ResourceManager::GetAppletResource() const {
return applet_resource;
}
std::shared_ptr<CaptureButton> ResourceManager::GetCaptureButton() const {
return capture_button;
}
@ -145,46 +137,6 @@ std::shared_ptr<UniquePad> ResourceManager::GetUniquePad() const {
return unique_pad;
}
Result ResourceManager::CreateAppletResource(u64 aruid) {
std::scoped_lock lock{shared_mutex};
return applet_resource->CreateAppletResource(aruid);
}
Result ResourceManager::RegisterAppletResourceUserId(u64 aruid, bool bool_value) {
std::scoped_lock lock{shared_mutex};
return applet_resource->RegisterAppletResourceUserId(aruid, bool_value);
}
void ResourceManager::UnregisterAppletResourceUserId(u64 aruid) {
std::scoped_lock lock{shared_mutex};
applet_resource->UnregisterAppletResourceUserId(aruid);
}
Result ResourceManager::GetSharedMemoryHandle(Kernel::KSharedMemory** out_handle, u64 aruid) {
std::scoped_lock lock{shared_mutex};
return applet_resource->GetSharedMemoryHandle(out_handle, aruid);
}
void ResourceManager::EnableInput(u64 aruid, bool is_enabled) {
std::scoped_lock lock{shared_mutex};
applet_resource->EnableInput(aruid, is_enabled);
}
void ResourceManager::EnableSixAxisSensor(u64 aruid, bool is_enabled) {
std::scoped_lock lock{shared_mutex};
applet_resource->EnableSixAxisSensor(aruid, is_enabled);
}
void ResourceManager::EnablePadInput(u64 aruid, bool is_enabled) {
std::scoped_lock lock{shared_mutex};
applet_resource->EnablePadInput(aruid, is_enabled);
}
void ResourceManager::EnableTouchScreen(u64 aruid, bool is_enabled) {
std::scoped_lock lock{shared_mutex};
applet_resource->EnableTouchScreen(aruid, is_enabled);
}
void ResourceManager::UpdateControllers(std::uintptr_t user_data,
std::chrono::nanoseconds ns_late) {
auto& core_timing = system.CoreTiming();
@ -220,12 +172,14 @@ void ResourceManager::UpdateMotion(std::uintptr_t user_data, std::chrono::nanose
}
IAppletResource::IAppletResource(Core::System& system_, std::shared_ptr<ResourceManager> resource)
: ServiceFramework{system_, "IAppletResource"}, resource_manager{resource} {
: ServiceFramework{system_, "IAppletResource"} {
static const FunctionInfo functions[] = {
{0, &IAppletResource::GetSharedMemoryHandle, "GetSharedMemoryHandle"},
};
RegisterHandlers(functions);
resource->Initialize();
// Register update callbacks
npad_update_event = Core::Timing::CreateEvent(
"HID::UpdatePadCallback",
@ -279,13 +233,9 @@ IAppletResource::~IAppletResource() {
void IAppletResource::GetSharedMemoryHandle(HLERequestContext& ctx) {
LOG_DEBUG(Service_HID, "called");
Kernel::KSharedMemory* handle;
const u64 applet_resource_user_id = resource_manager->GetAppletResource()->GetActiveAruid();
const auto result = resource_manager->GetSharedMemoryHandle(&handle, applet_resource_user_id);
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(result);
rb.PushCopyObjects(handle);
rb.Push(ResultSuccess);
rb.PushCopyObjects(&system.Kernel().GetHidSharedMem());
}
} // namespace Service::HID

View File

@ -6,20 +6,11 @@
#include "core/hle/service/kernel_helpers.h"
#include "core/hle/service/service.h"
namespace Core {
class System;
}
namespace Core::Timing {
struct EventType;
}
namespace Kernel {
class KSharedMemory;
}
namespace Service::HID {
class AppletResource;
class Controller_Stubbed;
class ConsoleSixAxis;
class DebugPad;
@ -47,7 +38,6 @@ public:
void Initialize();
std::shared_ptr<AppletResource> GetAppletResource() const;
std::shared_ptr<CaptureButton> GetCaptureButton() const;
std::shared_ptr<ConsoleSixAxis> GetConsoleSixAxis() const;
std::shared_ptr<DebugMouse> GetDebugMouse() const;
@ -64,18 +54,6 @@ public:
std::shared_ptr<TouchScreen> GetTouchScreen() const;
std::shared_ptr<UniquePad> GetUniquePad() const;
Result CreateAppletResource(u64 aruid);
Result RegisterAppletResourceUserId(u64 aruid, bool bool_value);
void UnregisterAppletResourceUserId(u64 aruid);
Result GetSharedMemoryHandle(Kernel::KSharedMemory** out_handle, u64 aruid);
void EnableInput(u64 aruid, bool is_enabled);
void EnableSixAxisSensor(u64 aruid, bool is_enabled);
void EnablePadInput(u64 aruid, bool is_enabled);
void EnableTouchScreen(u64 aruid, bool is_enabled);
void UpdateControllers(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
void UpdateNpad(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
void UpdateMouseKeyboard(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
@ -84,9 +62,6 @@ public:
private:
bool is_initialized{false};
mutable std::mutex shared_mutex;
std::shared_ptr<AppletResource> applet_resource = nullptr;
std::shared_ptr<CaptureButton> capture_button = nullptr;
std::shared_ptr<ConsoleSixAxis> console_six_axis = nullptr;
std::shared_ptr<DebugMouse> debug_mouse = nullptr;
@ -131,8 +106,6 @@ private:
std::shared_ptr<Core::Timing::EventType> default_update_event;
std::shared_ptr<Core::Timing::EventType> mouse_keyboard_update_event;
std::shared_ptr<Core::Timing::EventType> motion_update_event;
std::shared_ptr<ResourceManager> resource_manager;
};
} // namespace Service::HID

View File

@ -146,10 +146,8 @@ HLERequestContext::HLERequestContext(Kernel::KernelCore& kernel_, Core::Memory::
HLERequestContext::~HLERequestContext() = default;
void HLERequestContext::ParseCommandBuffer(Kernel::KProcess& process, u32_le* src_cmdbuf,
bool incoming) {
client_handle_table = &process.GetHandleTable();
void HLERequestContext::ParseCommandBuffer(const Kernel::KHandleTable& handle_table,
u32_le* src_cmdbuf, bool incoming) {
IPC::RequestParser rp(src_cmdbuf);
command_header = rp.PopRaw<IPC::CommandHeader>();
@ -162,8 +160,7 @@ void HLERequestContext::ParseCommandBuffer(Kernel::KProcess& process, u32_le* sr
if (command_header->enable_handle_descriptor) {
handle_descriptor_header = rp.PopRaw<IPC::HandleDescriptorHeader>();
if (handle_descriptor_header->send_current_pid) {
pid = process.GetProcessId();
rp.Skip(2, false);
pid = rp.Pop<u64>();
}
if (incoming) {
// Populate the object lists with the data in the IPC request.
@ -270,9 +267,9 @@ void HLERequestContext::ParseCommandBuffer(Kernel::KProcess& process, u32_le* sr
rp.Skip(1, false); // The command is actually an u64, but we don't use the high part.
}
Result HLERequestContext::PopulateFromIncomingCommandBuffer(Kernel::KProcess& process,
u32_le* src_cmdbuf) {
ParseCommandBuffer(process, src_cmdbuf, true);
Result HLERequestContext::PopulateFromIncomingCommandBuffer(
const Kernel::KHandleTable& handle_table, u32_le* src_cmdbuf) {
ParseCommandBuffer(handle_table, src_cmdbuf, true);
if (command_header->IsCloseCommand()) {
// Close does not populate the rest of the IPC header

View File

@ -38,7 +38,6 @@ namespace Kernel {
class KAutoObject;
class KernelCore;
class KHandleTable;
class KProcess;
class KServerSession;
class KThread;
} // namespace Kernel
@ -76,7 +75,6 @@ protected:
using SessionRequestHandlerWeakPtr = std::weak_ptr<SessionRequestHandler>;
using SessionRequestHandlerPtr = std::shared_ptr<SessionRequestHandler>;
using SessionRequestHandlerFactory = std::function<SessionRequestHandlerPtr()>;
/**
* Manages the underlying HLE requests for a session, and whether (or not) the session should be
@ -196,7 +194,8 @@ public:
}
/// Populates this context with data from the requesting process/thread.
Result PopulateFromIncomingCommandBuffer(Kernel::KProcess& process, u32_le* src_cmdbuf);
Result PopulateFromIncomingCommandBuffer(const Kernel::KHandleTable& handle_table,
u32_le* src_cmdbuf);
/// Writes data from this context back to the requesting process/thread.
Result WriteToOutgoingCommandBuffer(Kernel::KThread& requesting_thread);
@ -359,10 +358,6 @@ public:
return *thread;
}
Kernel::KHandleTable& GetClientHandleTable() {
return *client_handle_table;
}
[[nodiscard]] std::shared_ptr<SessionRequestManager> GetManager() const {
return manager.lock();
}
@ -378,12 +373,12 @@ public:
private:
friend class IPC::ResponseBuilder;
void ParseCommandBuffer(Kernel::KProcess& process, u32_le* src_cmdbuf, bool incoming);
void ParseCommandBuffer(const Kernel::KHandleTable& handle_table, u32_le* src_cmdbuf,
bool incoming);
std::array<u32, IPC::COMMAND_BUFFER_LENGTH> cmd_buf;
Kernel::KServerSession* server_session{};
Kernel::KHandleTable* client_handle_table{};
Kernel::KThread* thread{};
Kernel::KThread* thread;
std::vector<Handle> incoming_move_handles;
std::vector<Handle> incoming_copy_handles;

View File

@ -1,12 +1,117 @@
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <memory>
#include <fmt/format.h>
#include <mbedtls/sha256.h>
#include "common/alignment.h"
#include "common/hex_util.h"
#include "common/scope_exit.h"
#include "core/core.h"
#include "core/hle/kernel/k_page_table.h"
#include "core/hle/kernel/svc_results.h"
#include "core/hle/kernel/svc_types.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/ldr/ldr.h"
#include "core/hle/service/server_manager.h"
#include "core/hle/service/service.h"
#include "core/loader/nro.h"
#include "core/memory.h"
namespace Service::LDR {
constexpr Result ERROR_INSUFFICIENT_ADDRESS_SPACE{ErrorModule::RO, 2};
[[maybe_unused]] constexpr Result ERROR_INVALID_MEMORY_STATE{ErrorModule::Loader, 51};
constexpr Result ERROR_INVALID_NRO{ErrorModule::Loader, 52};
constexpr Result ERROR_INVALID_NRR{ErrorModule::Loader, 53};
constexpr Result ERROR_MISSING_NRR_HASH{ErrorModule::Loader, 54};
constexpr Result ERROR_MAXIMUM_NRO{ErrorModule::Loader, 55};
constexpr Result ERROR_MAXIMUM_NRR{ErrorModule::Loader, 56};
constexpr Result ERROR_ALREADY_LOADED{ErrorModule::Loader, 57};
constexpr Result ERROR_INVALID_ALIGNMENT{ErrorModule::Loader, 81};
constexpr Result ERROR_INVALID_SIZE{ErrorModule::Loader, 82};
constexpr Result ERROR_INVALID_NRO_ADDRESS{ErrorModule::Loader, 84};
[[maybe_unused]] constexpr Result ERROR_INVALID_NRR_ADDRESS{ErrorModule::Loader, 85};
constexpr Result ERROR_NOT_INITIALIZED{ErrorModule::Loader, 87};
constexpr std::size_t MAXIMUM_LOADED_RO{0x40};
constexpr std::size_t MAXIMUM_MAP_RETRIES{0x200};
constexpr std::size_t TEXT_INDEX{0};
constexpr std::size_t RO_INDEX{1};
constexpr std::size_t DATA_INDEX{2};
struct NRRCertification {
u64_le application_id_mask;
u64_le application_id_pattern;
INSERT_PADDING_BYTES(0x10);
std::array<u8, 0x100> public_key; // Also known as modulus
std::array<u8, 0x100> signature;
};
static_assert(sizeof(NRRCertification) == 0x220, "NRRCertification has invalid size.");
struct NRRHeader {
u32_le magic;
u32_le certification_signature_key_generation; // 9.0.0+
INSERT_PADDING_WORDS(2);
NRRCertification certification;
std::array<u8, 0x100> signature;
u64_le application_id;
u32_le size;
u8 nrr_kind; // 7.0.0+
INSERT_PADDING_BYTES(3);
u32_le hash_offset;
u32_le hash_count;
INSERT_PADDING_WORDS(2);
};
static_assert(sizeof(NRRHeader) == 0x350, "NRRHeader has invalid size.");
struct SegmentHeader {
u32_le memory_offset;
u32_le memory_size;
};
static_assert(sizeof(SegmentHeader) == 0x8, "SegmentHeader has invalid size.");
struct NROHeader {
// Switchbrew calls this "Start" (0x10)
INSERT_PADDING_WORDS(1);
u32_le mod_offset;
INSERT_PADDING_WORDS(2);
// Switchbrew calls this "Header" (0x70)
u32_le magic;
u32_le version;
u32_le nro_size;
u32_le flags;
// .text, .ro, .data
std::array<SegmentHeader, 3> segment_headers;
u32_le bss_size;
INSERT_PADDING_WORDS(1);
std::array<u8, 0x20> build_id;
u32_le dso_handle_offset;
INSERT_PADDING_WORDS(1);
// .apiInfo, .dynstr, .dynsym
std::array<SegmentHeader, 3> segment_headers_2;
};
static_assert(sizeof(NROHeader) == 0x80, "NROHeader has invalid size.");
using SHA256Hash = std::array<u8, 0x20>;
struct NROInfo {
SHA256Hash hash{};
VAddr nro_address{};
std::size_t nro_size{};
VAddr bss_address{};
std::size_t bss_size{};
std::size_t text_size{};
std::size_t ro_size{};
std::size_t data_size{};
VAddr src_addr{};
};
static_assert(sizeof(NROInfo) == 0x60, "NROInfo has invalid size.");
class DebugMonitor final : public ServiceFramework<DebugMonitor> {
public:
explicit DebugMonitor(Core::System& system_) : ServiceFramework{system_, "ldr:dmnt"} {
@ -53,12 +158,541 @@ public:
}
};
class RelocatableObject final : public ServiceFramework<RelocatableObject> {
public:
explicit RelocatableObject(Core::System& system_) : ServiceFramework{system_, "ldr:ro"} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &RelocatableObject::LoadModule, "LoadModule"},
{1, &RelocatableObject::UnloadModule, "UnloadModule"},
{2, &RelocatableObject::RegisterModuleInfo, "RegisterModuleInfo"},
{3, &RelocatableObject::UnregisterModuleInfo, "UnregisterModuleInfo"},
{4, &RelocatableObject::Initialize, "Initialize"},
{10, nullptr, "RegisterModuleInfo2"},
};
// clang-format on
RegisterHandlers(functions);
}
void RegisterModuleInfo(HLERequestContext& ctx) {
struct Parameters {
u64_le process_id;
u64_le nrr_address;
u64_le nrr_size;
};
IPC::RequestParser rp{ctx};
const auto [process_id, nrr_address, nrr_size] = rp.PopRaw<Parameters>();
LOG_DEBUG(Service_LDR,
"called with process_id={:016X}, nrr_address={:016X}, nrr_size={:016X}",
process_id, nrr_address, nrr_size);
if (!initialized) {
LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_NOT_INITIALIZED);
return;
}
if (nrr.size() >= MAXIMUM_LOADED_RO) {
LOG_ERROR(Service_LDR, "Loading new NRR would exceed the maximum number of loaded NRRs "
"(0x40)! Failing...");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_MAXIMUM_NRR);
return;
}
// NRR Address does not fall on 0x1000 byte boundary
if (!Common::Is4KBAligned(nrr_address)) {
LOG_ERROR(Service_LDR, "NRR Address has invalid alignment (actual {:016X})!",
nrr_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_ALIGNMENT);
return;
}
// NRR Size is zero or causes overflow
if (nrr_address + nrr_size <= nrr_address || nrr_size == 0 ||
!Common::Is4KBAligned(nrr_size)) {
LOG_ERROR(Service_LDR, "NRR Size is invalid! (nrr_address={:016X}, nrr_size={:016X})",
nrr_address, nrr_size);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_SIZE);
return;
}
// Read NRR data from memory
std::vector<u8> nrr_data(nrr_size);
system.ApplicationMemory().ReadBlock(nrr_address, nrr_data.data(), nrr_size);
NRRHeader header;
std::memcpy(&header, nrr_data.data(), sizeof(NRRHeader));
if (header.magic != Common::MakeMagic('N', 'R', 'R', '0')) {
LOG_ERROR(Service_LDR, "NRR did not have magic 'NRR0' (actual {:08X})!", header.magic);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_NRR);
return;
}
if (header.size != nrr_size) {
LOG_ERROR(Service_LDR,
"NRR header reported size did not match LoadNrr parameter size! "
"(header_size={:016X}, loadnrr_size={:016X})",
header.size, nrr_size);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_SIZE);
return;
}
if (system.GetApplicationProcessProgramID() != header.application_id) {
LOG_ERROR(Service_LDR,
"Attempting to load NRR with title ID other than current process. (actual "
"{:016X})!",
header.application_id);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_NRR);
return;
}
std::vector<SHA256Hash> hashes;
// Copy all hashes in the NRR (specified by hash count/hash offset) into vector.
for (std::size_t i = header.hash_offset;
i < (header.hash_offset + (header.hash_count * sizeof(SHA256Hash))); i += 8) {
SHA256Hash hash;
std::memcpy(hash.data(), nrr_data.data() + i, sizeof(SHA256Hash));
hashes.emplace_back(hash);
}
nrr.insert_or_assign(nrr_address, std::move(hashes));
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void UnregisterModuleInfo(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const auto pid = rp.Pop<u64>();
const auto nrr_address = rp.Pop<VAddr>();
LOG_DEBUG(Service_LDR, "called with pid={}, nrr_address={:016X}", pid, nrr_address);
nrr.erase(nrr_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
bool ValidateRegionForMap(Kernel::KProcessPageTable& page_table, VAddr start,
std::size_t size) const {
const std::size_t padding_size{page_table.GetNumGuardPages() * Kernel::PageSize};
Kernel::KMemoryInfo start_info;
Kernel::Svc::PageInfo page_info;
R_ASSERT(
page_table.QueryInfo(std::addressof(start_info), std::addressof(page_info), start - 1));
if (start_info.GetState() != Kernel::KMemoryState::Free) {
return {};
}
if (start_info.GetAddress() > (start - padding_size)) {
return {};
}
Kernel::KMemoryInfo end_info;
R_ASSERT(page_table.QueryInfo(std::addressof(end_info), std::addressof(page_info),
start + size));
if (end_info.GetState() != Kernel::KMemoryState::Free) {
return {};
}
return (start + size + padding_size) <= (end_info.GetAddress() + end_info.GetSize());
}
Result GetAvailableMapRegion(Kernel::KProcessPageTable& page_table, u64 size, VAddr& out_addr) {
size = Common::AlignUp(size, Kernel::PageSize);
size += page_table.GetNumGuardPages() * Kernel::PageSize * 4;
const auto is_region_available = [&](VAddr addr) {
const auto end_addr = addr + size;
while (addr < end_addr) {
if (system.ApplicationMemory().IsValidVirtualAddress(addr)) {
return false;
}
if (!page_table.Contains(out_addr, size)) {
return false;
}
if (page_table.IsInHeapRegion(out_addr, size)) {
return false;
}
if (page_table.IsInAliasRegion(out_addr, size)) {
return false;
}
addr += Kernel::PageSize;
}
return true;
};
bool succeeded = false;
const auto map_region_end =
GetInteger(page_table.GetAliasCodeRegionStart()) + page_table.GetAliasCodeRegionSize();
while (current_map_addr < map_region_end) {
if (is_region_available(current_map_addr)) {
succeeded = true;
break;
}
current_map_addr += 0x100000;
}
if (!succeeded) {
ASSERT_MSG(false, "Out of address space!");
return Kernel::ResultOutOfMemory;
}
out_addr = current_map_addr;
current_map_addr += size;
return ResultSuccess;
}
Result MapProcessCodeMemory(VAddr* out_map_location, Kernel::KProcess* process, VAddr base_addr,
u64 size) {
auto& page_table{process->GetPageTable()};
VAddr addr{};
for (std::size_t retry = 0; retry < MAXIMUM_MAP_RETRIES; retry++) {
R_TRY(GetAvailableMapRegion(page_table, size, addr));
const Result result{page_table.MapCodeMemory(addr, base_addr, size)};
if (result == Kernel::ResultInvalidCurrentMemory) {
continue;
}
R_TRY(result);
if (ValidateRegionForMap(page_table, addr, size)) {
*out_map_location = addr;
return ResultSuccess;
}
}
return ERROR_INSUFFICIENT_ADDRESS_SPACE;
}
Result MapNro(VAddr* out_map_location, Kernel::KProcess* process, VAddr nro_addr,
std::size_t nro_size, VAddr bss_addr, std::size_t bss_size, std::size_t size) {
for (std::size_t retry = 0; retry < MAXIMUM_MAP_RETRIES; retry++) {
auto& page_table{process->GetPageTable()};
VAddr addr{};
R_TRY(MapProcessCodeMemory(&addr, process, nro_addr, nro_size));
if (bss_size) {
auto block_guard = detail::ScopeExit([&] {
page_table.UnmapCodeMemory(addr + nro_size, bss_addr, bss_size);
page_table.UnmapCodeMemory(addr, nro_addr, nro_size);
});
const Result result{page_table.MapCodeMemory(addr + nro_size, bss_addr, bss_size)};
if (result == Kernel::ResultInvalidCurrentMemory) {
continue;
}
if (result.IsError()) {
return result;
}
block_guard.Cancel();
}
if (ValidateRegionForMap(page_table, addr, size)) {
*out_map_location = addr;
return ResultSuccess;
}
}
return ERROR_INSUFFICIENT_ADDRESS_SPACE;
}
Result LoadNro(Kernel::KProcess* process, const NROHeader& nro_header, VAddr nro_addr,
VAddr start) const {
const VAddr text_start{start + nro_header.segment_headers[TEXT_INDEX].memory_offset};
const VAddr ro_start{start + nro_header.segment_headers[RO_INDEX].memory_offset};
const VAddr data_start{start + nro_header.segment_headers[DATA_INDEX].memory_offset};
const VAddr bss_start{data_start + nro_header.segment_headers[DATA_INDEX].memory_size};
const VAddr bss_end_addr{
Common::AlignUp(bss_start + nro_header.bss_size, Kernel::PageSize)};
const auto CopyCode = [this](VAddr src_addr, VAddr dst_addr, u64 size) {
system.ApplicationMemory().CopyBlock(dst_addr, src_addr, size);
};
CopyCode(nro_addr + nro_header.segment_headers[TEXT_INDEX].memory_offset, text_start,
nro_header.segment_headers[TEXT_INDEX].memory_size);
CopyCode(nro_addr + nro_header.segment_headers[RO_INDEX].memory_offset, ro_start,
nro_header.segment_headers[RO_INDEX].memory_size);
CopyCode(nro_addr + nro_header.segment_headers[DATA_INDEX].memory_offset, data_start,
nro_header.segment_headers[DATA_INDEX].memory_size);
R_TRY(process->GetPageTable().SetProcessMemoryPermission(
text_start, ro_start - text_start, Kernel::Svc::MemoryPermission::ReadExecute));
R_TRY(process->GetPageTable().SetProcessMemoryPermission(
ro_start, data_start - ro_start, Kernel::Svc::MemoryPermission::Read));
return process->GetPageTable().SetProcessMemoryPermission(
data_start, bss_end_addr - data_start, Kernel::Svc::MemoryPermission::ReadWrite);
}
void LoadModule(HLERequestContext& ctx) {
struct Parameters {
u64_le process_id;
u64_le image_address;
u64_le image_size;
u64_le bss_address;
u64_le bss_size;
};
IPC::RequestParser rp{ctx};
const auto [process_id, nro_address, nro_size, bss_address, bss_size] =
rp.PopRaw<Parameters>();
LOG_DEBUG(Service_LDR,
"called with pid={:016X}, nro_addr={:016X}, nro_size={:016X}, bss_addr={:016X}, "
"bss_size={:016X}",
process_id, nro_address, nro_size, bss_address, bss_size);
if (!initialized) {
LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_NOT_INITIALIZED);
return;
}
if (nro.size() >= MAXIMUM_LOADED_RO) {
LOG_ERROR(Service_LDR, "Loading new NRO would exceed the maximum number of loaded NROs "
"(0x40)! Failing...");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_MAXIMUM_NRO);
return;
}
// NRO Address does not fall on 0x1000 byte boundary
if (!Common::Is4KBAligned(nro_address)) {
LOG_ERROR(Service_LDR, "NRO Address has invalid alignment (actual {:016X})!",
nro_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_ALIGNMENT);
return;
}
// NRO Size or BSS Size is zero or causes overflow
const auto nro_size_valid =
nro_size != 0 && nro_address + nro_size > nro_address && Common::Is4KBAligned(nro_size);
const auto bss_size_valid = nro_size + bss_size >= nro_size &&
(bss_size == 0 || bss_address + bss_size > bss_address);
if (!nro_size_valid || !bss_size_valid) {
LOG_ERROR(Service_LDR,
"NRO Size or BSS Size is invalid! (nro_address={:016X}, nro_size={:016X}, "
"bss_address={:016X}, bss_size={:016X})",
nro_address, nro_size, bss_address, bss_size);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_SIZE);
return;
}
// Read NRO data from memory
std::vector<u8> nro_data(nro_size);
system.ApplicationMemory().ReadBlock(nro_address, nro_data.data(), nro_size);
SHA256Hash hash{};
mbedtls_sha256_ret(nro_data.data(), nro_data.size(), hash.data(), 0);
// NRO Hash is already loaded
if (std::any_of(nro.begin(), nro.end(), [&hash](const std::pair<VAddr, NROInfo>& info) {
return info.second.hash == hash;
})) {
LOG_ERROR(Service_LDR, "NRO is already loaded!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_ALREADY_LOADED);
return;
}
// NRO Hash is not in any loaded NRR
if (!IsValidNROHash(hash)) {
LOG_ERROR(Service_LDR,
"NRO hash is not present in any currently loaded NRRs (hash={})!",
Common::HexToString(hash));
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_MISSING_NRR_HASH);
return;
}
// Load and validate the NRO header
NROHeader header{};
std::memcpy(&header, nro_data.data(), sizeof(NROHeader));
if (!IsValidNRO(header, nro_size, bss_size)) {
LOG_ERROR(Service_LDR, "NRO was invalid!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_NRO);
return;
}
// Map memory for the NRO
VAddr map_location{};
const auto map_result{MapNro(&map_location, system.ApplicationProcess(), nro_address,
nro_size, bss_address, bss_size, nro_size + bss_size)};
if (map_result != ResultSuccess) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(map_result);
}
// Load the NRO into the mapped memory
if (const auto result{
LoadNro(system.ApplicationProcess(), header, nro_address, map_location)};
result.IsError()) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
// Track the loaded NRO
nro.insert_or_assign(map_location,
NROInfo{hash, map_location, nro_size, bss_address, bss_size,
header.segment_headers[TEXT_INDEX].memory_size,
header.segment_headers[RO_INDEX].memory_size,
header.segment_headers[DATA_INDEX].memory_size, nro_address});
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(ResultSuccess);
rb.Push(map_location);
}
Result UnmapNro(const NROInfo& info) {
// Each region must be unmapped separately to validate memory state
auto& page_table{system.ApplicationProcess()->GetPageTable()};
if (info.bss_size != 0) {
R_TRY(page_table.UnmapCodeMemory(info.nro_address + info.text_size + info.ro_size +
info.data_size,
info.bss_address, info.bss_size));
}
R_TRY(page_table.UnmapCodeMemory(info.nro_address + info.text_size + info.ro_size,
info.src_addr + info.text_size + info.ro_size,
info.data_size));
R_TRY(page_table.UnmapCodeMemory(info.nro_address + info.text_size,
info.src_addr + info.text_size, info.ro_size));
R_TRY(page_table.UnmapCodeMemory(info.nro_address, info.src_addr, info.text_size));
return ResultSuccess;
}
void UnloadModule(HLERequestContext& ctx) {
if (!initialized) {
LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_NOT_INITIALIZED);
return;
}
struct Parameters {
u64_le process_id;
u64_le nro_address;
};
IPC::RequestParser rp{ctx};
const auto [process_id, nro_address] = rp.PopRaw<Parameters>();
LOG_DEBUG(Service_LDR, "called with process_id={:016X}, nro_address=0x{:016X}", process_id,
nro_address);
if (!Common::Is4KBAligned(nro_address)) {
LOG_ERROR(Service_LDR, "NRO address has invalid alignment (nro_address=0x{:016X})",
nro_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_ALIGNMENT);
return;
}
const auto iter = nro.find(nro_address);
if (iter == nro.end()) {
LOG_ERROR(Service_LDR,
"The NRO attempting to be unmapped was not mapped or has an invalid address "
"(nro_address=0x{:016X})!",
nro_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERROR_INVALID_NRO_ADDRESS);
return;
}
const auto result{UnmapNro(iter->second)};
nro.erase(iter);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
void Initialize(HLERequestContext& ctx) {
LOG_WARNING(Service_LDR, "(STUBBED) called");
initialized = true;
current_map_addr =
GetInteger(system.ApplicationProcess()->GetPageTable().GetAliasCodeRegionStart());
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
private:
bool initialized{};
std::map<VAddr, NROInfo> nro;
std::map<VAddr, std::vector<SHA256Hash>> nrr;
VAddr current_map_addr{};
bool IsValidNROHash(const SHA256Hash& hash) const {
return std::any_of(nrr.begin(), nrr.end(), [&hash](const auto& p) {
return std::find(p.second.begin(), p.second.end(), hash) != p.second.end();
});
}
static bool IsValidNRO(const NROHeader& header, u64 nro_size, u64 bss_size) {
return header.magic == Common::MakeMagic('N', 'R', 'O', '0') &&
header.nro_size == nro_size && header.bss_size == bss_size &&
header.segment_headers[RO_INDEX].memory_offset ==
header.segment_headers[TEXT_INDEX].memory_offset +
header.segment_headers[TEXT_INDEX].memory_size &&
header.segment_headers[DATA_INDEX].memory_offset ==
header.segment_headers[RO_INDEX].memory_offset +
header.segment_headers[RO_INDEX].memory_size &&
nro_size == header.segment_headers[DATA_INDEX].memory_offset +
header.segment_headers[DATA_INDEX].memory_size &&
Common::Is4KBAligned(header.segment_headers[TEXT_INDEX].memory_size) &&
Common::Is4KBAligned(header.segment_headers[RO_INDEX].memory_size) &&
Common::Is4KBAligned(header.segment_headers[DATA_INDEX].memory_size);
}
};
void LoopProcess(Core::System& system) {
auto server_manager = std::make_unique<ServerManager>(system);
server_manager->RegisterNamedService("ldr:dmnt", std::make_shared<DebugMonitor>(system));
server_manager->RegisterNamedService("ldr:pm", std::make_shared<ProcessManager>(system));
server_manager->RegisterNamedService("ldr:shel", std::make_shared<Shell>(system));
server_manager->RegisterNamedService("ldr:ro", std::make_shared<RelocatableObject>(system));
ServerManager::RunServer(std::move(server_manager));
}

View File

@ -171,7 +171,6 @@ void MakeGraphicBuffer(android::BufferQueueProducer& producer, u32 slot, u32 han
buffer->height = SharedBufferHeight;
buffer->stride = SharedBufferBlockLinearStride;
buffer->format = SharedBufferBlockLinearFormat;
buffer->external_format = SharedBufferBlockLinearFormat;
buffer->buffer_id = handle;
buffer->offset = slot * SharedBufferSlotSize;
ASSERT(producer.SetPreallocatedBuffer(slot, buffer) == android::Status::NoError);

View File

@ -1,709 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <mbedtls/sha256.h>
#include "common/scope_exit.h"
#include "core/hle/kernel/k_process.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/ro/ro.h"
#include "core/hle/service/ro/ro_nro_utils.h"
#include "core/hle/service/ro/ro_results.h"
#include "core/hle/service/ro/ro_types.h"
#include "core/hle/service/server_manager.h"
#include "core/hle/service/service.h"
namespace Service::RO {
namespace {
// Convenience definitions.
constexpr size_t MaxSessions = 0x3;
constexpr size_t MaxNrrInfos = 0x40;
constexpr size_t MaxNroInfos = 0x40;
constexpr u64 InvalidProcessId = 0xffffffffffffffffULL;
constexpr u64 InvalidContextId = 0xffffffffffffffffULL;
// Types.
using Sha256Hash = std::array<u8, 32>;
struct NroInfo {
u64 base_address;
u64 nro_heap_address;
u64 nro_heap_size;
u64 bss_heap_address;
u64 bss_heap_size;
u64 code_size;
u64 rw_size;
ModuleId module_id;
};
struct NrrInfo {
u64 nrr_heap_address;
u64 nrr_heap_size;
// Verification.
std::vector<Sha256Hash> hashes;
};
struct ProcessContext {
constexpr ProcessContext() = default;
void Initialize(Kernel::KProcess* process, u64 process_id) {
ASSERT(!m_in_use);
m_nro_in_use = {};
m_nrr_in_use = {};
m_nro_infos = {};
m_nrr_infos = {};
m_process = process;
m_process_id = process_id;
m_in_use = true;
if (m_process) {
m_process->Open();
}
}
void Finalize() {
ASSERT(m_in_use);
if (m_process) {
m_process->Close();
}
m_nro_in_use = {};
m_nrr_in_use = {};
m_nro_infos = {};
m_nrr_infos = {};
m_process = nullptr;
m_process_id = InvalidProcessId;
m_in_use = false;
}
Kernel::KProcess* GetProcess() const {
return m_process;
}
u64 GetProcessId() const {
return m_process_id;
}
bool IsFree() const {
return !m_in_use;
}
u64 GetProgramId(Kernel::KProcess* other_process) const {
// Automatically select a handle, allowing for override.
if (other_process) {
return other_process->GetProgramId();
} else if (m_process) {
return m_process->GetProgramId();
} else {
return 0;
}
}
Result GetNrrInfoByAddress(NrrInfo** out, u64 nrr_heap_address) {
for (size_t i = 0; i < MaxNrrInfos; i++) {
if (m_nrr_in_use[i] && m_nrr_infos[i].nrr_heap_address == nrr_heap_address) {
if (out != nullptr) {
*out = std::addressof(m_nrr_infos[i]);
}
R_SUCCEED();
}
}
R_THROW(RO::ResultNotRegistered);
}
Result GetFreeNrrInfo(NrrInfo** out) {
for (size_t i = 0; i < MaxNrrInfos; i++) {
if (!m_nrr_in_use[i]) {
if (out != nullptr) {
*out = std::addressof(m_nrr_infos[i]);
}
R_SUCCEED();
}
}
R_THROW(RO::ResultTooManyNrr);
}
Result GetNroInfoByAddress(NroInfo** out, u64 nro_address) {
for (size_t i = 0; i < MaxNroInfos; i++) {
if (m_nro_in_use[i] && m_nro_infos[i].base_address == nro_address) {
if (out != nullptr) {
*out = std::addressof(m_nro_infos[i]);
}
R_SUCCEED();
}
}
R_THROW(RO::ResultNotLoaded);
}
Result GetNroInfoByModuleId(NroInfo** out, const ModuleId* module_id) {
for (size_t i = 0; i < MaxNroInfos; i++) {
if (m_nro_in_use[i] && std::memcmp(std::addressof(m_nro_infos[i].module_id), module_id,
sizeof(*module_id)) == 0) {
if (out != nullptr) {
*out = std::addressof(m_nro_infos[i]);
}
R_SUCCEED();
}
}
R_THROW(RO::ResultNotLoaded);
}
Result GetFreeNroInfo(NroInfo** out) {
for (size_t i = 0; i < MaxNroInfos; i++) {
if (!m_nro_in_use[i]) {
if (out != nullptr) {
*out = std::addressof(m_nro_infos[i]);
}
R_SUCCEED();
}
}
R_THROW(RO::ResultTooManyNro);
}
Result ValidateHasNroHash(u64 base_address, const NroHeader* nro_header) const {
// Calculate hash.
Sha256Hash hash;
{
const u64 size = nro_header->GetSize();
std::vector<u8> nro_data(size);
m_process->GetMemory().ReadBlock(base_address, nro_data.data(), size);
mbedtls_sha256_ret(nro_data.data(), size, hash.data(), 0);
}
for (size_t i = 0; i < MaxNrrInfos; i++) {
// Ensure we only check NRRs that are used.
if (!m_nrr_in_use[i]) {
continue;
}
// Locate the hash within the hash list.
const auto hash_it = std::ranges::find(m_nrr_infos[i].hashes, hash);
if (hash_it == m_nrr_infos[i].hashes.end()) {
continue;
}
// The hash is valid!
R_SUCCEED();
}
R_THROW(RO::ResultNotAuthorized);
}
Result ValidateNro(ModuleId* out_module_id, u64* out_rx_size, u64* out_ro_size,
u64* out_rw_size, u64 base_address, u64 expected_nro_size,
u64 expected_bss_size) {
// Ensure we have a process to work on.
R_UNLESS(m_process != nullptr, RO::ResultInvalidProcess);
// Read the NRO header.
NroHeader header{};
m_process->GetMemory().ReadBlock(base_address, std::addressof(header), sizeof(header));
// Validate header.
R_UNLESS(header.IsMagicValid(), RO::ResultInvalidNro);
// Read sizes from header.
const u64 nro_size = header.GetSize();
const u64 text_ofs = header.GetTextOffset();
const u64 text_size = header.GetTextSize();
const u64 ro_ofs = header.GetRoOffset();
const u64 ro_size = header.GetRoSize();
const u64 rw_ofs = header.GetRwOffset();
const u64 rw_size = header.GetRwSize();
const u64 bss_size = header.GetBssSize();
// Validate sizes meet expected.
R_UNLESS(nro_size == expected_nro_size, RO::ResultInvalidNro);
R_UNLESS(bss_size == expected_bss_size, RO::ResultInvalidNro);
// Validate all sizes are aligned.
R_UNLESS(Common::IsAligned(text_size, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidNro);
R_UNLESS(Common::IsAligned(ro_size, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidNro);
R_UNLESS(Common::IsAligned(rw_size, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidNro);
R_UNLESS(Common::IsAligned(bss_size, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidNro);
// Validate sections are in order.
R_UNLESS(text_ofs <= ro_ofs, RO::ResultInvalidNro);
R_UNLESS(ro_ofs <= rw_ofs, RO::ResultInvalidNro);
// Validate sections are sequential and contiguous.
R_UNLESS(text_ofs == 0, RO::ResultInvalidNro);
R_UNLESS(text_ofs + text_size == ro_ofs, RO::ResultInvalidNro);
R_UNLESS(ro_ofs + ro_size == rw_ofs, RO::ResultInvalidNro);
R_UNLESS(rw_ofs + rw_size == nro_size, RO::ResultInvalidNro);
// Verify NRO hash.
R_TRY(this->ValidateHasNroHash(base_address, std::addressof(header)));
// Check if NRO has already been loaded.
const ModuleId* module_id = header.GetModuleId();
R_UNLESS(R_FAILED(this->GetNroInfoByModuleId(nullptr, module_id)), RO::ResultAlreadyLoaded);
// Apply patches to NRO.
// LocateAndApplyIpsPatchesToModule(module_id, static_cast<u8*>(mapped_memory), nro_size);
// Copy to output.
*out_module_id = *module_id;
*out_rx_size = text_size;
*out_ro_size = ro_size;
*out_rw_size = rw_size;
R_SUCCEED();
}
void SetNrrInfoInUse(const NrrInfo* info, bool in_use) {
ASSERT(std::addressof(m_nrr_infos[0]) <= info &&
info <= std::addressof(m_nrr_infos[MaxNrrInfos - 1]));
const size_t index = info - std::addressof(m_nrr_infos[0]);
m_nrr_in_use[index] = in_use;
}
void SetNroInfoInUse(const NroInfo* info, bool in_use) {
ASSERT(std::addressof(m_nro_infos[0]) <= info &&
info <= std::addressof(m_nro_infos[MaxNroInfos - 1]));
const size_t index = info - std::addressof(m_nro_infos[0]);
m_nro_in_use[index] = in_use;
}
private:
std::array<bool, MaxNroInfos> m_nro_in_use{};
std::array<bool, MaxNrrInfos> m_nrr_in_use{};
std::array<NroInfo, MaxNroInfos> m_nro_infos{};
std::array<NrrInfo, MaxNrrInfos> m_nrr_infos{};
Kernel::KProcess* m_process{};
u64 m_process_id{InvalidProcessId};
bool m_in_use{};
};
Result ValidateAddressAndNonZeroSize(u64 address, u64 size) {
R_UNLESS(Common::IsAligned(address, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidAddress);
R_UNLESS(size != 0, RO::ResultInvalidSize);
R_UNLESS(Common::IsAligned(size, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidSize);
R_UNLESS(address < address + size, RO::ResultInvalidSize);
R_SUCCEED();
}
Result ValidateAddressAndSize(u64 address, u64 size) {
R_UNLESS(Common::IsAligned(address, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidAddress);
R_UNLESS(Common::IsAligned(size, Core::Memory::YUZU_PAGESIZE), RO::ResultInvalidSize);
R_UNLESS(size == 0 || address < address + size, RO::ResultInvalidSize);
R_SUCCEED();
}
class RoContext {
public:
explicit RoContext() = default;
Result RegisterProcess(size_t* out_context_id, Kernel::KProcess* process, u64 process_id) {
// Validate process id.
R_UNLESS(process->GetProcessId() == process_id, RO::ResultInvalidProcess);
// Check if a process context already exists.
R_UNLESS(this->GetContextByProcessId(process_id) == nullptr, RO::ResultInvalidSession);
// Allocate a context to manage the process handle.
*out_context_id = this->AllocateContext(process, process_id);
R_SUCCEED();
}
Result ValidateProcess(size_t context_id, u64 process_id) {
const ProcessContext* ctx = this->GetContextById(context_id);
R_UNLESS(ctx != nullptr, RO::ResultInvalidProcess);
R_UNLESS(ctx->GetProcessId() == process_id, RO::ResultInvalidProcess);
R_SUCCEED();
}
void UnregisterProcess(size_t context_id) {
this->FreeContext(context_id);
}
Result RegisterModuleInfo(size_t context_id, u64 nrr_address, u64 nrr_size, NrrKind nrr_kind,
bool enforce_nrr_kind) {
// Get context.
ProcessContext* context = this->GetContextById(context_id);
ASSERT(context != nullptr);
// Validate address/size.
R_TRY(ValidateAddressAndNonZeroSize(nrr_address, nrr_size));
// Check we have space for a new NRR.
NrrInfo* nrr_info = nullptr;
R_TRY(context->GetFreeNrrInfo(std::addressof(nrr_info)));
// Ensure we have a valid process to read from.
Kernel::KProcess* process = context->GetProcess();
R_UNLESS(process != nullptr, RO::ResultInvalidProcess);
// Read NRR.
NrrHeader header{};
process->GetMemory().ReadBlock(nrr_address, std::addressof(header), sizeof(header));
// Set NRR info.
context->SetNrrInfoInUse(nrr_info, true);
nrr_info->nrr_heap_address = nrr_address;
nrr_info->nrr_heap_size = nrr_size;
// Read NRR hash list.
nrr_info->hashes.resize(header.GetNumHashes());
process->GetMemory().ReadBlock(nrr_address + header.GetHashesOffset(),
nrr_info->hashes.data(),
sizeof(Sha256Hash) * header.GetNumHashes());
R_SUCCEED();
}
Result UnregisterModuleInfo(size_t context_id, u64 nrr_address) {
// Get context.
ProcessContext* context = this->GetContextById(context_id);
ASSERT(context != nullptr);
// Validate address.
R_UNLESS(Common::IsAligned(nrr_address, Core::Memory::YUZU_PAGESIZE),
RO::ResultInvalidAddress);
// Check the NRR is loaded.
NrrInfo* nrr_info = nullptr;
R_TRY(context->GetNrrInfoByAddress(std::addressof(nrr_info), nrr_address));
// Nintendo does this unconditionally, whether or not the actual unmap succeeds.
context->SetNrrInfoInUse(nrr_info, false);
*nrr_info = {};
R_SUCCEED();
}
Result MapManualLoadModuleMemory(u64* out_address, size_t context_id, u64 nro_address,
u64 nro_size, u64 bss_address, u64 bss_size) {
// Get context.
ProcessContext* context = this->GetContextById(context_id);
ASSERT(context != nullptr);
// Validate address/size.
R_TRY(ValidateAddressAndNonZeroSize(nro_address, nro_size));
R_TRY(ValidateAddressAndSize(bss_address, bss_size));
const u64 total_size = nro_size + bss_size;
R_UNLESS(total_size >= nro_size, RO::ResultInvalidSize);
R_UNLESS(total_size >= bss_size, RO::ResultInvalidSize);
// Check we have space for a new NRO.
NroInfo* nro_info = nullptr;
R_TRY(context->GetFreeNroInfo(std::addressof(nro_info)));
nro_info->nro_heap_address = nro_address;
nro_info->nro_heap_size = nro_size;
nro_info->bss_heap_address = bss_address;
nro_info->bss_heap_size = bss_size;
// Map the NRO.
R_TRY(MapNro(std::addressof(nro_info->base_address), context->GetProcess(), nro_address,
nro_size, bss_address, bss_size, generate_random));
ON_RESULT_FAILURE {
UnmapNro(context->GetProcess(), nro_info->base_address, nro_address, nro_size,
bss_address, bss_size);
};
// Validate the NRO (parsing region extents).
u64 rx_size = 0, ro_size = 0, rw_size = 0;
R_TRY(context->ValidateNro(std::addressof(nro_info->module_id), std::addressof(rx_size),
std::addressof(ro_size), std::addressof(rw_size),
nro_info->base_address, nro_size, bss_size));
// Set NRO perms.
R_TRY(SetNroPerms(context->GetProcess(), nro_info->base_address, rx_size, ro_size,
rw_size + bss_size));
context->SetNroInfoInUse(nro_info, true);
nro_info->code_size = rx_size + ro_size;
nro_info->rw_size = rw_size;
*out_address = nro_info->base_address;
R_SUCCEED();
}
Result UnmapManualLoadModuleMemory(size_t context_id, u64 nro_address) {
// Get context.
ProcessContext* context = this->GetContextById(context_id);
ASSERT(context != nullptr);
// Validate address.
R_UNLESS(Common::IsAligned(nro_address, Core::Memory::YUZU_PAGESIZE),
RO::ResultInvalidAddress);
// Check the NRO is loaded.
NroInfo* nro_info = nullptr;
R_TRY(context->GetNroInfoByAddress(std::addressof(nro_info), nro_address));
// Unmap.
const NroInfo nro_backup = *nro_info;
{
// Nintendo does this unconditionally, whether or not the actual unmap succeeds.
context->SetNroInfoInUse(nro_info, false);
std::memset(nro_info, 0, sizeof(*nro_info));
}
R_RETURN(UnmapNro(context->GetProcess(), nro_backup.base_address,
nro_backup.nro_heap_address, nro_backup.code_size + nro_backup.rw_size,
nro_backup.bss_heap_address, nro_backup.bss_heap_size));
}
private:
std::array<ProcessContext, MaxSessions> process_contexts;
std::mt19937_64 generate_random;
// Context Helpers.
ProcessContext* GetContextById(size_t context_id) {
if (context_id == InvalidContextId) {
return nullptr;
}
ASSERT(context_id < process_contexts.size());
return std::addressof(process_contexts[context_id]);
}
ProcessContext* GetContextByProcessId(u64 process_id) {
for (size_t i = 0; i < MaxSessions; i++) {
if (process_contexts[i].GetProcessId() == process_id) {
return std::addressof(process_contexts[i]);
}
}
return nullptr;
}
size_t AllocateContext(Kernel::KProcess* process, u64 process_id) {
// Find a free process context.
for (size_t i = 0; i < MaxSessions; i++) {
ProcessContext* context = std::addressof(process_contexts[i]);
if (context->IsFree()) {
context->Initialize(process, process_id);
return i;
}
}
// Failure to find a free context is actually an abort condition.
UNREACHABLE();
}
void FreeContext(size_t context_id) {
if (ProcessContext* context = GetContextById(context_id); context != nullptr) {
context->Finalize();
}
}
};
class RoInterface {
public:
explicit RoInterface(std::shared_ptr<RoContext> ro, NrrKind nrr_kind)
: m_ro(ro), m_context_id(InvalidContextId), m_nrr_kind(nrr_kind) {}
~RoInterface() {
m_ro->UnregisterProcess(m_context_id);
}
Result MapManualLoadModuleMemory(u64* out_load_address, u64 client_pid, u64 nro_address,
u64 nro_size, u64 bss_address, u64 bss_size) {
R_TRY(m_ro->ValidateProcess(m_context_id, client_pid));
R_RETURN(m_ro->MapManualLoadModuleMemory(out_load_address, m_context_id, nro_address,
nro_size, bss_address, bss_size));
}
Result UnmapManualLoadModuleMemory(u64 client_pid, u64 nro_address) {
R_TRY(m_ro->ValidateProcess(m_context_id, client_pid));
R_RETURN(m_ro->UnmapManualLoadModuleMemory(m_context_id, nro_address));
}
Result RegisterModuleInfo(u64 client_pid, u64 nrr_address, u64 nrr_size) {
R_TRY(m_ro->ValidateProcess(m_context_id, client_pid));
R_RETURN(
m_ro->RegisterModuleInfo(m_context_id, nrr_address, nrr_size, NrrKind::User, true));
}
Result UnregisterModuleInfo(u64 client_pid, u64 nrr_address) {
R_TRY(m_ro->ValidateProcess(m_context_id, client_pid));
R_RETURN(m_ro->UnregisterModuleInfo(m_context_id, nrr_address));
}
Result RegisterProcessHandle(u64 client_pid, Kernel::KProcess* process) {
// Register the process.
R_RETURN(m_ro->RegisterProcess(std::addressof(m_context_id), process, client_pid));
}
Result RegisterProcessModuleInfo(u64 client_pid, u64 nrr_address, u64 nrr_size,
Kernel::KProcess* process) {
// Validate the process.
R_TRY(m_ro->ValidateProcess(m_context_id, client_pid));
// Register the module.
R_RETURN(m_ro->RegisterModuleInfo(m_context_id, nrr_address, nrr_size, m_nrr_kind,
m_nrr_kind == NrrKind::JitPlugin));
}
private:
std::shared_ptr<RoContext> m_ro{};
size_t m_context_id{};
NrrKind m_nrr_kind{};
};
class IRoInterface : public ServiceFramework<IRoInterface> {
public:
explicit IRoInterface(Core::System& system_, const char* name_, std::shared_ptr<RoContext> ro,
NrrKind nrr_kind)
: ServiceFramework{system_, name_}, interface {
ro, nrr_kind
} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &IRoInterface::MapManualLoadModuleMemory, "MapManualLoadModuleMemory"},
{1, &IRoInterface::UnmapManualLoadModuleMemory, "UnmapManualLoadModuleMemory"},
{2, &IRoInterface::RegisterModuleInfo, "RegisterModuleInfo"},
{3, &IRoInterface::UnregisterModuleInfo, "UnregisterModuleInfo"},
{4, &IRoInterface::RegisterProcessHandle, "RegisterProcessHandle"},
{10, &IRoInterface::RegisterProcessModuleInfo, "RegisterProcessModuleInfo"},
};
// clang-format on
RegisterHandlers(functions);
}
private:
void MapManualLoadModuleMemory(HLERequestContext& ctx) {
LOG_DEBUG(Service_LDR, "(called)");
struct InputParameters {
u64 client_pid;
u64 nro_address;
u64 nro_size;
u64 bss_address;
u64 bss_size;
};
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<InputParameters>();
u64 load_address = 0;
auto result = interface.MapManualLoadModuleMemory(&load_address, ctx.GetPID(),
params.nro_address, params.nro_size,
params.bss_address, params.bss_size);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(result);
rb.Push(load_address);
}
void UnmapManualLoadModuleMemory(HLERequestContext& ctx) {
LOG_DEBUG(Service_LDR, "(called)");
struct InputParameters {
u64 client_pid;
u64 nro_address;
};
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<InputParameters>();
auto result = interface.UnmapManualLoadModuleMemory(ctx.GetPID(), params.nro_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
void RegisterModuleInfo(HLERequestContext& ctx) {
LOG_DEBUG(Service_LDR, "(called)");
struct InputParameters {
u64 client_pid;
u64 nrr_address;
u64 nrr_size;
};
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<InputParameters>();
auto result =
interface.RegisterModuleInfo(ctx.GetPID(), params.nrr_address, params.nrr_size);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
void UnregisterModuleInfo(HLERequestContext& ctx) {
LOG_DEBUG(Service_LDR, "(called)");
struct InputParameters {
u64 client_pid;
u64 nrr_address;
};
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<InputParameters>();
auto result = interface.UnregisterModuleInfo(ctx.GetPID(), params.nrr_address);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
void RegisterProcessHandle(HLERequestContext& ctx) {
LOG_DEBUG(Service_LDR, "(called)");
auto process_h = ctx.GetClientHandleTable().GetObject(ctx.GetCopyHandle(0));
auto client_pid = ctx.GetPID();
auto result = interface.RegisterProcessHandle(client_pid,
process_h->DynamicCast<Kernel::KProcess*>());
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
void RegisterProcessModuleInfo(HLERequestContext& ctx) {
LOG_DEBUG(Service_LDR, "(called)");
struct InputParameters {
u64 client_pid;
u64 nrr_address;
u64 nrr_size;
};
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<InputParameters>();
auto process_h = ctx.GetClientHandleTable().GetObject(ctx.GetCopyHandle(0));
auto client_pid = ctx.GetPID();
auto result =
interface.RegisterProcessModuleInfo(client_pid, params.nrr_address, params.nrr_size,
process_h->DynamicCast<Kernel::KProcess*>());
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result);
}
RoInterface interface;
};
} // namespace
void LoopProcess(Core::System& system) {
auto server_manager = std::make_unique<ServerManager>(system);
auto ro = std::make_shared<RoContext>();
const auto RoInterfaceFactoryForUser = [&, ro] {
return std::make_shared<IRoInterface>(system, "ldr:ro", ro, NrrKind::User);
};
const auto RoInterfaceFactoryForJitPlugin = [&, ro] {
return std::make_shared<IRoInterface>(system, "ro:1", ro, NrrKind::JitPlugin);
};
server_manager->RegisterNamedService("ldr:ro", std::move(RoInterfaceFactoryForUser));
server_manager->RegisterNamedService("ro:1", std::move(RoInterfaceFactoryForJitPlugin));
ServerManager::RunServer(std::move(server_manager));
}
} // namespace Service::RO

View File

@ -1,14 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
namespace Core {
class System;
}
namespace Service::RO {
void LoopProcess(Core::System& system);
} // namespace Service::RO

View File

@ -1,185 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/kernel/k_process.h"
#include "core/hle/service/ro/ro_nro_utils.h"
#include "core/hle/service/ro/ro_results.h"
namespace Service::RO {
namespace {
struct ProcessMemoryRegion {
u64 address;
u64 size;
};
size_t GetTotalProcessMemoryRegionSize(const ProcessMemoryRegion* regions, size_t num_regions) {
size_t total = 0;
for (size_t i = 0; i < num_regions; ++i) {
total += regions[i].size;
}
return total;
}
size_t SetupNroProcessMemoryRegions(ProcessMemoryRegion* regions, u64 nro_heap_address,
u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size) {
// Reset region count.
size_t num_regions = 0;
// We always want a region for the nro.
regions[num_regions++] = {nro_heap_address, nro_heap_size};
// If we have bss, create a region for bss.
if (bss_heap_size > 0) {
regions[num_regions++] = {bss_heap_address, bss_heap_size};
}
return num_regions;
}
Result SetProcessMemoryPermission(Kernel::KProcess* process, u64 address, u64 size,
Kernel::Svc::MemoryPermission permission) {
auto& page_table = process->GetPageTable();
// Set permission.
R_RETURN(page_table.SetProcessMemoryPermission(address, size, permission));
}
Result UnmapProcessCodeMemory(Kernel::KProcess* process, u64 process_code_address,
const ProcessMemoryRegion* regions, size_t num_regions) {
// Get the total process memory region size.
const size_t total_size = GetTotalProcessMemoryRegionSize(regions, num_regions);
auto& page_table = process->GetPageTable();
// Unmap each region in order.
size_t cur_offset = total_size;
for (size_t i = 0; i < num_regions; ++i) {
// We want to unmap in reverse order.
const auto& cur_region = regions[num_regions - 1 - i];
// Subtract to update the current offset.
cur_offset -= cur_region.size;
// Unmap.
R_TRY(page_table.UnmapCodeMemory(process_code_address + cur_offset, cur_region.address,
cur_region.size));
}
R_SUCCEED();
}
Result EnsureGuardPages(Kernel::KProcessPageTable& page_table, u64 map_address, u64 map_size) {
Kernel::KMemoryInfo memory_info;
Kernel::Svc::PageInfo page_info;
// Ensure page before mapping is unmapped.
R_TRY(page_table.QueryInfo(std::addressof(memory_info), std::addressof(page_info),
map_address - 1));
R_UNLESS(memory_info.GetSvcState() == Kernel::Svc::MemoryState::Free,
Kernel::ResultInvalidState);
// Ensure page after mapping is unmapped.
R_TRY(page_table.QueryInfo(std::addressof(memory_info), std::addressof(page_info),
map_address + map_size));
R_UNLESS(memory_info.GetSvcState() == Kernel::Svc::MemoryState::Free,
Kernel::ResultInvalidState);
// Successfully verified guard pages.
R_SUCCEED();
}
Result MapProcessCodeMemory(u64* out, Kernel::KProcess* process, const ProcessMemoryRegion* regions,
size_t num_regions, std::mt19937_64& generate_random) {
auto& page_table = process->GetPageTable();
const u64 alias_code_start =
GetInteger(page_table.GetAliasCodeRegionStart()) / Kernel::PageSize;
const u64 alias_code_size = page_table.GetAliasCodeRegionSize() / Kernel::PageSize;
for (size_t trial = 0; trial < 64; trial++) {
// Generate a new trial address.
const u64 mapped_address =
(alias_code_start + (generate_random() % alias_code_size)) * Kernel::PageSize;
const auto MapRegions = [&] {
// Map the regions in order.
u64 mapped_size = 0;
for (size_t i = 0; i < num_regions; ++i) {
// If we fail, unmap up to where we've mapped.
ON_RESULT_FAILURE {
R_ASSERT(UnmapProcessCodeMemory(process, mapped_address, regions, i));
};
// Map the current region.
R_TRY(page_table.MapCodeMemory(mapped_address + mapped_size, regions[i].address,
regions[i].size));
mapped_size += regions[i].size;
}
// If we fail, unmap all mapped regions.
ON_RESULT_FAILURE {
R_ASSERT(UnmapProcessCodeMemory(process, mapped_address, regions, num_regions));
};
// Ensure guard pages.
R_RETURN(EnsureGuardPages(page_table, mapped_address, mapped_size));
};
if (R_SUCCEEDED(MapRegions())) {
// Set the output address.
*out = mapped_address;
R_SUCCEED();
}
}
// We failed to map anything.
R_THROW(RO::ResultOutOfAddressSpace);
}
} // namespace
Result MapNro(u64* out_base_address, Kernel::KProcess* process, u64 nro_heap_address,
u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size,
std::mt19937_64& generate_random) {
// Set up the process memory regions.
std::array<ProcessMemoryRegion, 2> regions{};
const size_t num_regions = SetupNroProcessMemoryRegions(
regions.data(), nro_heap_address, nro_heap_size, bss_heap_address, bss_heap_size);
// Re-map the nro/bss as code memory in the destination process.
R_RETURN(MapProcessCodeMemory(out_base_address, process, regions.data(), num_regions,
generate_random));
}
Result SetNroPerms(Kernel::KProcess* process, u64 base_address, u64 rx_size, u64 ro_size,
u64 rw_size) {
const u64 rx_offset = 0;
const u64 ro_offset = rx_offset + rx_size;
const u64 rw_offset = ro_offset + ro_size;
R_TRY(SetProcessMemoryPermission(process, base_address + rx_offset, rx_size,
Kernel::Svc::MemoryPermission::ReadExecute));
R_TRY(SetProcessMemoryPermission(process, base_address + ro_offset, ro_size,
Kernel::Svc::MemoryPermission::Read));
R_TRY(SetProcessMemoryPermission(process, base_address + rw_offset, rw_size,
Kernel::Svc::MemoryPermission::ReadWrite));
R_SUCCEED();
}
Result UnmapNro(Kernel::KProcess* process, u64 base_address, u64 nro_heap_address,
u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size) {
// Set up the process memory regions.
std::array<ProcessMemoryRegion, 2> regions{};
const size_t num_regions = SetupNroProcessMemoryRegions(
regions.data(), nro_heap_address, nro_heap_size, bss_heap_address, bss_heap_size);
// Unmap the nro/bss.
R_RETURN(UnmapProcessCodeMemory(process, base_address, regions.data(), num_regions));
}
} // namespace Service::RO

View File

@ -1,26 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <random>
#include "common/common_types.h"
namespace Kernel {
class KProcess;
}
union Result;
namespace Service::RO {
Result MapNro(u64* out_base_address, Kernel::KProcess* process, u64 nro_heap_address,
u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size,
std::mt19937_64& generate_random);
Result SetNroPerms(Kernel::KProcess* process, u64 base_address, u64 rx_size, u64 ro_size,
u64 rw_size);
Result UnmapNro(Kernel::KProcess* process, u64 base_address, u64 nro_heap_address,
u64 nro_heap_size, u64 bss_heap_address, u64 bss_heap_size);
} // namespace Service::RO

View File

@ -1,24 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/result.h"
namespace Service::RO {
constexpr Result ResultOutOfAddressSpace{ErrorModule::RO, 2};
constexpr Result ResultAlreadyLoaded{ErrorModule::RO, 3};
constexpr Result ResultInvalidNro{ErrorModule::RO, 4};
constexpr Result ResultInvalidNrr{ErrorModule::RO, 6};
constexpr Result ResultTooManyNro{ErrorModule::RO, 7};
constexpr Result ResultTooManyNrr{ErrorModule::RO, 8};
constexpr Result ResultNotAuthorized{ErrorModule::RO, 9};
constexpr Result ResultInvalidNrrKind{ErrorModule::RO, 10};
constexpr Result ResultInternalError{ErrorModule::RO, 1023};
constexpr Result ResultInvalidAddress{ErrorModule::RO, 1025};
constexpr Result ResultInvalidSize{ErrorModule::RO, 1026};
constexpr Result ResultNotLoaded{ErrorModule::RO, 1028};
constexpr Result ResultNotRegistered{ErrorModule::RO, 1029};
constexpr Result ResultInvalidSession{ErrorModule::RO, 1030};
constexpr Result ResultInvalidProcess{ErrorModule::RO, 1031};
} // namespace Service::RO

View File

@ -1,181 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "common/assert.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
namespace Service::RO {
enum class NrrKind : u8 {
User = 0,
JitPlugin = 1,
Count,
};
static constexpr size_t ModuleIdSize = 0x20;
struct ModuleId {
std::array<u8, ModuleIdSize> data;
};
static_assert(sizeof(ModuleId) == ModuleIdSize);
struct NrrCertification {
static constexpr size_t RsaKeySize = 0x100;
static constexpr size_t SignedSize = 0x120;
u64 program_id_mask;
u64 program_id_pattern;
std::array<u8, 0x10> reserved_10;
std::array<u8, RsaKeySize> modulus;
std::array<u8, RsaKeySize> signature;
};
static_assert(sizeof(NrrCertification) ==
NrrCertification::RsaKeySize + NrrCertification::SignedSize);
class NrrHeader {
public:
static constexpr u32 Magic = Common::MakeMagic('N', 'R', 'R', '0');
public:
bool IsMagicValid() const {
return m_magic == Magic;
}
bool IsProgramIdValid() const {
return (m_program_id & m_certification.program_id_mask) ==
m_certification.program_id_pattern;
}
NrrKind GetNrrKind() const {
const NrrKind kind = static_cast<NrrKind>(m_nrr_kind);
ASSERT(kind < NrrKind::Count);
return kind;
}
u64 GetProgramId() const {
return m_program_id;
}
u32 GetSize() const {
return m_size;
}
u32 GetNumHashes() const {
return m_num_hashes;
}
size_t GetHashesOffset() const {
return m_hashes_offset;
}
u32 GetKeyGeneration() const {
return m_key_generation;
}
const u8* GetCertificationSignature() const {
return m_certification.signature.data();
}
const u8* GetCertificationSignedArea() const {
return reinterpret_cast<const u8*>(std::addressof(m_certification));
}
const u8* GetCertificationModulus() const {
return m_certification.modulus.data();
}
const u8* GetSignature() const {
return m_signature.data();
}
size_t GetSignedAreaSize() const {
return m_size - GetSignedAreaOffset();
}
static constexpr size_t GetSignedAreaOffset() {
return offsetof(NrrHeader, m_program_id);
}
private:
u32 m_magic;
u32 m_key_generation;
INSERT_PADDING_BYTES_NOINIT(8);
NrrCertification m_certification;
std::array<u8, 0x100> m_signature;
u64 m_program_id;
u32 m_size;
u8 m_nrr_kind; // 7.0.0+
INSERT_PADDING_BYTES_NOINIT(3);
u32 m_hashes_offset;
u32 m_num_hashes;
INSERT_PADDING_BYTES_NOINIT(8);
};
static_assert(sizeof(NrrHeader) == 0x350, "NrrHeader has wrong size");
class NroHeader {
public:
static constexpr u32 Magic = Common::MakeMagic('N', 'R', 'O', '0');
public:
bool IsMagicValid() const {
return m_magic == Magic;
}
u32 GetSize() const {
return m_size;
}
u32 GetTextOffset() const {
return m_text_offset;
}
u32 GetTextSize() const {
return m_text_size;
}
u32 GetRoOffset() const {
return m_ro_offset;
}
u32 GetRoSize() const {
return m_ro_size;
}
u32 GetRwOffset() const {
return m_rw_offset;
}
u32 GetRwSize() const {
return m_rw_size;
}
u32 GetBssSize() const {
return m_bss_size;
}
const ModuleId* GetModuleId() const {
return std::addressof(m_module_id);
}
private:
u32 m_entrypoint_insn;
u32 m_mod_offset;
INSERT_PADDING_BYTES_NOINIT(0x8);
u32 m_magic;
INSERT_PADDING_BYTES_NOINIT(0x4);
u32 m_size;
INSERT_PADDING_BYTES_NOINIT(0x4);
u32 m_text_offset;
u32 m_text_size;
u32 m_ro_offset;
u32 m_ro_size;
u32 m_rw_offset;
u32 m_rw_size;
u32 m_bss_size;
INSERT_PADDING_BYTES_NOINIT(0x4);
ModuleId m_module_id;
INSERT_PADDING_BYTES_NOINIT(0x20);
};
static_assert(sizeof(NroHeader) == 0x80, "NroHeader has wrong size");
} // namespace Service::RO

View File

@ -93,13 +93,13 @@ Result ServerManager::RegisterSession(Kernel::KServerSession* session,
}
Result ServerManager::RegisterNamedService(const std::string& service_name,
SessionRequestHandlerFactory&& handler_factory,
std::shared_ptr<SessionRequestHandler>&& handler,
u32 max_sessions) {
ASSERT(m_sessions.size() + m_ports.size() < MaximumWaitObjects);
// Add the new server to sm:.
ASSERT(R_SUCCEEDED(
m_system.ServiceManager().RegisterService(service_name, max_sessions, handler_factory)));
m_system.ServiceManager().RegisterService(service_name, max_sessions, handler)));
// Get the registered port.
Kernel::KPort* port{};
@ -112,7 +112,7 @@ Result ServerManager::RegisterNamedService(const std::string& service_name,
// Begin tracking the server port.
{
std::scoped_lock ll{m_list_mutex};
m_ports.emplace(std::addressof(port->GetServerPort()), std::move(handler_factory));
m_ports.emplace(std::addressof(port->GetServerPort()), std::move(handler));
}
// Signal the wakeup event.
@ -121,18 +121,8 @@ Result ServerManager::RegisterNamedService(const std::string& service_name,
R_SUCCEED();
}
Result ServerManager::RegisterNamedService(const std::string& service_name,
std::shared_ptr<SessionRequestHandler>&& handler,
u32 max_sessions) {
// Make the factory.
const auto HandlerFactory = [handler]() { return handler; };
// Register the service with the new factory.
R_RETURN(this->RegisterNamedService(service_name, std::move(HandlerFactory), max_sessions));
}
Result ServerManager::ManageNamedPort(const std::string& service_name,
SessionRequestHandlerFactory&& handler_factory,
std::shared_ptr<SessionRequestHandler>&& handler,
u32 max_sessions) {
ASSERT(m_sessions.size() + m_ports.size() < MaximumWaitObjects);
@ -159,7 +149,7 @@ Result ServerManager::ManageNamedPort(const std::string& service_name,
// Begin tracking the server port.
{
std::scoped_lock ll{m_list_mutex};
m_ports.emplace(std::addressof(port->GetServerPort()), std::move(handler_factory));
m_ports.emplace(std::addressof(port->GetServerPort()), std::move(handler));
}
// We succeeded.
@ -279,13 +269,13 @@ Result ServerManager::WaitAndProcessImpl() {
case HandleType::Port: {
// Port signaled.
auto* port = wait_obj->DynamicCast<Kernel::KServerPort*>();
SessionRequestHandlerFactory handler_factory;
std::shared_ptr<SessionRequestHandler> handler;
// Remove from tracking.
{
std::scoped_lock ll{m_list_mutex};
ASSERT(m_ports.contains(port));
m_ports.at(port).swap(handler_factory);
m_ports.at(port).swap(handler);
m_ports.erase(port);
}
@ -293,7 +283,7 @@ Result ServerManager::WaitAndProcessImpl() {
sl.unlock();
// Finish.
R_RETURN(this->OnPortEvent(port, std::move(handler_factory)));
R_RETURN(this->OnPortEvent(port, std::move(handler)));
}
case HandleType::Session: {
// Session signaled.
@ -343,19 +333,19 @@ Result ServerManager::WaitAndProcessImpl() {
}
Result ServerManager::OnPortEvent(Kernel::KServerPort* port,
SessionRequestHandlerFactory&& handler_factory) {
std::shared_ptr<SessionRequestHandler>&& handler) {
// Accept a new server session.
Kernel::KServerSession* session = port->AcceptSession();
ASSERT(session != nullptr);
// Create the session manager and install the handler.
auto manager = std::make_shared<SessionRequestManager>(m_system.Kernel(), *this);
manager->SetSessionHandler(handler_factory());
manager->SetSessionHandler(std::shared_ptr(handler));
// Track the server session.
{
std::scoped_lock ll{m_list_mutex};
m_ports.emplace(port, std::move(handler_factory));
m_ports.emplace(port, std::move(handler));
m_sessions.emplace(session, std::move(manager));
}

View File

@ -13,7 +13,6 @@
#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "core/hle/result.h"
#include "core/hle/service/hle_ipc.h"
#include "core/hle/service/mutex.h"
namespace Core {
@ -29,6 +28,10 @@ class KSynchronizationObject;
namespace Service {
class HLERequestContext;
class SessionRequestHandler;
class SessionRequestManager;
class ServerManager {
public:
explicit ServerManager(Core::System& system);
@ -36,14 +39,11 @@ public:
Result RegisterSession(Kernel::KServerSession* session,
std::shared_ptr<SessionRequestManager> manager);
Result RegisterNamedService(const std::string& service_name,
SessionRequestHandlerFactory&& handler_factory,
u32 max_sessions = 64);
Result RegisterNamedService(const std::string& service_name,
std::shared_ptr<SessionRequestHandler>&& handler,
u32 max_sessions = 64);
Result ManageNamedPort(const std::string& service_name,
SessionRequestHandlerFactory&& handler_factory, u32 max_sessions = 64);
std::shared_ptr<SessionRequestHandler>&& handler, u32 max_sessions = 64);
Result ManageDeferral(Kernel::KEvent** out_event);
Result LoopProcess();
@ -56,7 +56,7 @@ private:
Result LoopProcessImpl();
Result WaitAndProcessImpl();
Result OnPortEvent(Kernel::KServerPort* port, SessionRequestHandlerFactory&& handler_factory);
Result OnPortEvent(Kernel::KServerPort* port, std::shared_ptr<SessionRequestHandler>&& handler);
Result OnSessionEvent(Kernel::KServerSession* session,
std::shared_ptr<SessionRequestManager>&& manager);
Result OnDeferralEvent(std::list<RequestState>&& deferrals);
@ -68,7 +68,7 @@ private:
std::mutex m_list_mutex;
// Guest state tracking
std::map<Kernel::KServerPort*, SessionRequestHandlerFactory> m_ports{};
std::map<Kernel::KServerPort*, std::shared_ptr<SessionRequestHandler>> m_ports{};
std::map<Kernel::KServerSession*, std::shared_ptr<SessionRequestManager>> m_sessions{};
Kernel::KEvent* m_event{};
Kernel::KEvent* m_deferral_event{};

View File

@ -59,7 +59,6 @@
#include "core/hle/service/prepo/prepo.h"
#include "core/hle/service/psc/psc.h"
#include "core/hle/service/ptm/ptm.h"
#include "core/hle/service/ro/ro.h"
#include "core/hle/service/service.h"
#include "core/hle/service/set/settings.h"
#include "core/hle/service/sm/sm.h"
@ -271,7 +270,6 @@ Services::Services(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system
kernel.RunOnGuestCoreProcess("ProcessManager", [&] { PM::LoopProcess(system); });
kernel.RunOnGuestCoreProcess("psc", [&] { PSC::LoopProcess(system); });
kernel.RunOnGuestCoreProcess("ptm", [&] { PTM::LoopProcess(system); });
kernel.RunOnGuestCoreProcess("ro", [&] { RO::LoopProcess(system); });
kernel.RunOnGuestCoreProcess("settings", [&] { Set::LoopProcess(system); });
kernel.RunOnGuestCoreProcess("spl", [&] { SPL::LoopProcess(system); });
kernel.RunOnGuestCoreProcess("ssl", [&] { SSL::LoopProcess(system); });

View File

@ -51,7 +51,7 @@ static Result ValidateServiceName(const std::string& name) {
}
Result ServiceManager::RegisterService(std::string name, u32 max_sessions,
SessionRequestHandlerFactory handler) {
SessionRequestHandlerPtr handler) {
R_TRY(ValidateServiceName(name));
std::scoped_lock lk{lock};
@ -121,7 +121,7 @@ void SM::Initialize(HLERequestContext& ctx) {
rb.Push(ResultSuccess);
}
void SM::GetServiceCmif(HLERequestContext& ctx) {
void SM::GetService(HLERequestContext& ctx) {
Kernel::KClientSession* client_session{};
auto result = GetServiceImpl(&client_session, ctx);
if (ctx.GetIsDeferred()) {
@ -192,32 +192,19 @@ Result SM::GetServiceImpl(Kernel::KClientSession** out_client_session, HLEReques
return result;
}
LOG_DEBUG(Service_SM, "called service={} -> session={}", name, session->GetId());
*out_client_session = session;
return ResultSuccess;
}
void SM::RegisterServiceCmif(HLERequestContext& ctx) {
void SM::RegisterService(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
std::string name(PopServiceName(rp));
const auto is_light = static_cast<bool>(rp.PopRaw<u32>());
const auto max_session_count = rp.PopRaw<u32>();
this->RegisterServiceImpl(ctx, name, max_session_count, is_light);
}
void SM::RegisterServiceTipc(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
std::string name(PopServiceName(rp));
const auto max_session_count = rp.PopRaw<u32>();
const auto is_light = static_cast<bool>(rp.PopRaw<u32>());
this->RegisterServiceImpl(ctx, name, max_session_count, is_light);
}
void SM::RegisterServiceImpl(HLERequestContext& ctx, std::string name, u32 max_session_count,
bool is_light) {
LOG_DEBUG(Service_SM, "called with name={}, max_session_count={}, is_light={}", name,
max_session_count, is_light);
@ -253,15 +240,15 @@ SM::SM(ServiceManager& service_manager_, Core::System& system_)
service_manager{service_manager_}, kernel{system_.Kernel()} {
RegisterHandlers({
{0, &SM::Initialize, "Initialize"},
{1, &SM::GetServiceCmif, "GetService"},
{2, &SM::RegisterServiceCmif, "RegisterService"},
{1, &SM::GetService, "GetService"},
{2, &SM::RegisterService, "RegisterService"},
{3, &SM::UnregisterService, "UnregisterService"},
{4, nullptr, "DetachClient"},
});
RegisterHandlersTipc({
{0, &SM::Initialize, "Initialize"},
{1, &SM::GetServiceTipc, "GetService"},
{2, &SM::RegisterServiceTipc, "RegisterService"},
{2, &SM::RegisterService, "RegisterService"},
{3, &SM::UnregisterService, "UnregisterService"},
{4, nullptr, "DetachClient"},
});
@ -277,9 +264,7 @@ void LoopProcess(Core::System& system) {
server_manager->ManageDeferral(&deferral_event);
service_manager.SetDeferralEvent(deferral_event);
auto sm_service = std::make_shared<SM>(system.ServiceManager(), system);
server_manager->ManageNamedPort("sm:", [sm_service] { return sm_service; });
server_manager->ManageNamedPort("sm:", std::make_shared<SM>(system.ServiceManager(), system));
ServerManager::RunServer(std::move(server_manager));
}

View File

@ -37,15 +37,12 @@ public:
private:
void Initialize(HLERequestContext& ctx);
void GetServiceCmif(HLERequestContext& ctx);
void GetService(HLERequestContext& ctx);
void GetServiceTipc(HLERequestContext& ctx);
void RegisterServiceCmif(HLERequestContext& ctx);
void RegisterServiceTipc(HLERequestContext& ctx);
void RegisterService(HLERequestContext& ctx);
void UnregisterService(HLERequestContext& ctx);
Result GetServiceImpl(Kernel::KClientSession** out_client_session, HLERequestContext& ctx);
void RegisterServiceImpl(HLERequestContext& ctx, std::string name, u32 max_session_count,
bool is_light);
ServiceManager& service_manager;
Kernel::KernelCore& kernel;
@ -56,8 +53,7 @@ public:
explicit ServiceManager(Kernel::KernelCore& kernel_);
~ServiceManager();
Result RegisterService(std::string name, u32 max_sessions,
SessionRequestHandlerFactory handler_factory);
Result RegisterService(std::string name, u32 max_sessions, SessionRequestHandlerPtr handler);
Result UnregisterService(const std::string& name);
Result GetServicePort(Kernel::KPort** out_port, const std::string& name);
@ -68,7 +64,7 @@ public:
LOG_DEBUG(Service, "Can't find service: {}", service_name);
return nullptr;
}
return std::static_pointer_cast<T>(service->second());
return std::static_pointer_cast<T>(service->second);
}
void InvokeControlRequest(HLERequestContext& context);
@ -83,7 +79,7 @@ private:
/// Map of registered services, retrieved using GetServicePort.
std::mutex lock;
std::unordered_map<std::string, SessionRequestHandlerFactory> registered_services;
std::unordered_map<std::string, SessionRequestHandlerPtr> registered_services;
std::unordered_map<std::string, Kernel::KPort*> service_ports;
/// Kernel context