From d08bd3e062e629e34afa4e4947cfb6c28377e12f Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 8 May 2021 02:21:50 -0700 Subject: [PATCH 01/22] hle: ipc_helpers: Update IPC response generation for TIPC. --- src/core/hle/ipc_helpers.h | 48 ++++++++++++++++++++++------------- src/core/hle/kernel/hle_ipc.h | 10 ++++++-- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h index d136be452..d1eb8b075 100644 --- a/src/core/hle/ipc_helpers.h +++ b/src/core/hle/ipc_helpers.h @@ -26,7 +26,7 @@ class RequestHelperBase { protected: Kernel::HLERequestContext* context = nullptr; u32* cmdbuf; - ptrdiff_t index = 0; + u32 index = 0; public: explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {} @@ -38,7 +38,7 @@ public: if (set_to_null) { memset(cmdbuf + index, 0, size_in_words * sizeof(u32)); } - index += static_cast(size_in_words); + index += size_in_words; } /** @@ -51,11 +51,11 @@ public: } u32 GetCurrentOffset() const { - return static_cast(index); + return index; } void SetCurrentOffset(u32 offset) { - index = static_cast(offset); + index = offset; } }; @@ -84,7 +84,9 @@ public: // The entire size of the raw data section in u32 units, including the 16 bytes of mandatory // padding. - u64 raw_data_size = sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size; + u32 raw_data_size = ctx.IsTipc() + ? normal_params_size - 1 + : sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size; u32 num_handles_to_move{}; u32 num_domain_objects{}; @@ -100,6 +102,10 @@ public: raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects; } + if (ctx.IsTipc()) { + header.type.Assign(ctx.GetCommandType()); + } + header.data_size.Assign(static_cast(raw_data_size)); if (num_handles_to_copy || num_handles_to_move) { header.enable_handle_descriptor.Assign(1); @@ -111,22 +117,30 @@ public: handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy); handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move); PushRaw(handle_descriptor_header); + + ctx.handles_offset = index; + Skip(num_handles_to_copy + num_handles_to_move, true); } - AlignWithPadding(); + if (!ctx.IsTipc()) { + AlignWithPadding(); - if (ctx.Session()->IsDomain() && ctx.HasDomainMessageHeader()) { - IPC::DomainMessageHeader domain_header{}; - domain_header.num_objects = num_domain_objects; - PushRaw(domain_header); + if (ctx.Session()->IsDomain() && ctx.HasDomainMessageHeader()) { + IPC::DomainMessageHeader domain_header{}; + domain_header.num_objects = num_domain_objects; + PushRaw(domain_header); + } + + IPC::DataPayloadHeader data_payload_header{}; + data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O'); + PushRaw(data_payload_header); } - IPC::DataPayloadHeader data_payload_header{}; - data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O'); - PushRaw(data_payload_header); + data_payload_index = index; - datapayload_index = index; + ctx.data_payload_offset = index; + ctx.domain_offset = index + raw_data_size / 4; } template @@ -152,7 +166,7 @@ public: const std::size_t num_move_objects = context->NumMoveObjects(); ASSERT_MSG(!num_domain_objects || !num_move_objects, "cannot move normal handles and domain objects"); - ASSERT_MSG((index - datapayload_index) == normal_params_size, + ASSERT_MSG((index - data_payload_index) == normal_params_size, "normal_params_size value is incorrect"); ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move, "num_objects_to_move value is incorrect"); @@ -229,14 +243,14 @@ private: u32 normal_params_size{}; u32 num_handles_to_copy{}; u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent - std::ptrdiff_t datapayload_index{}; + u32 data_payload_index{}; Kernel::KernelCore& kernel; }; /// Push /// inline void ResponseBuilder::PushImpl(s32 value) { - cmdbuf[index++] = static_cast(value); + cmdbuf[index++] = value; } inline void ResponseBuilder::PushImpl(u32 value) { diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h index 21e384706..7cdde2294 100644 --- a/src/core/hle/kernel/hle_ipc.h +++ b/src/core/hle/kernel/hle_ipc.h @@ -132,6 +132,10 @@ public: return command; } + bool IsTipc() const { + return command_header->IsTipc(); + } + IPC::CommandType GetCommandType() const { return command_header->type; } @@ -291,8 +295,10 @@ private: std::vector buffer_w_desciptors; std::vector buffer_c_desciptors; - unsigned data_payload_offset{}; - unsigned buffer_c_offset{}; + u32 data_payload_offset{}; + u32 buffer_c_offset{}; + u32 handles_offset{}; + u32 domain_offset{}; u32_le command{}; std::vector> domain_request_handlers; From ed25191ee634c3cd0df11b25407809c2ba4fe422 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 8 May 2021 02:50:47 -0700 Subject: [PATCH 02/22] hle: kernel: Further cleanup and add TIPC helpers. --- src/core/hle/kernel/hle_ipc.cpp | 2 +- src/core/hle/kernel/hle_ipc.h | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/core/hle/kernel/hle_ipc.cpp b/src/core/hle/kernel/hle_ipc.cpp index 93907f75e..d6929d2c0 100644 --- a/src/core/hle/kernel/hle_ipc.cpp +++ b/src/core/hle/kernel/hle_ipc.cpp @@ -99,7 +99,7 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32 buffer_w_desciptors.push_back(rp.PopRaw()); } - buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size; + const auto buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size; // Padding to align to 16 bytes rp.AlignWithPadding(); diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h index 7cdde2294..07360629e 100644 --- a/src/core/hle/kernel/hle_ipc.h +++ b/src/core/hle/kernel/hle_ipc.h @@ -128,10 +128,19 @@ public: /// Writes data from this context back to the requesting process/thread. ResultCode WriteToOutgoingCommandBuffer(KThread& requesting_thread); - u32_le GetCommand() const { + u32_le GetHipcCommand() const { return command; } + u32_le GetTipcCommand() const { + return static_cast(command_header->type.Value()) - + static_cast(IPC::CommandType::TIPC_CommandRegion); + } + + u32_le GetCommand() const { + return command_header->IsTipc() ? GetTipcCommand() : GetHipcCommand(); + } + bool IsTipc() const { return command_header->IsTipc(); } @@ -140,7 +149,7 @@ public: return command_header->type; } - unsigned GetDataPayloadOffset() const { + u32 GetDataPayloadOffset() const { return data_payload_offset; } @@ -296,7 +305,6 @@ private: std::vector buffer_c_desciptors; u32 data_payload_offset{}; - u32 buffer_c_offset{}; u32 handles_offset{}; u32 domain_offset{}; u32_le command{}; From 7a06037c5fd2e4ee968ca89869000a0758d38da3 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 8 May 2021 02:20:15 -0700 Subject: [PATCH 03/22] hle: ipc: Add declarations for TIPC. --- src/core/hle/ipc.h | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/core/hle/ipc.h b/src/core/hle/ipc.h index 55b1716e4..602e12606 100644 --- a/src/core/hle/ipc.h +++ b/src/core/hle/ipc.h @@ -32,7 +32,8 @@ enum class CommandType : u32 { Control = 5, RequestWithContext = 6, ControlWithContext = 7, - Unspecified, + TIPC_Close = 15, + TIPC_CommandRegion = 16, // Start of TIPC commands, this is an offset. }; struct CommandHeader { @@ -57,6 +58,20 @@ struct CommandHeader { BitField<10, 4, BufferDescriptorCFlag> buf_c_descriptor_flags; BitField<31, 1, u32> enable_handle_descriptor; }; + + bool IsTipc() const { + return type.Value() >= CommandType::TIPC_CommandRegion; + } + + bool IsCloseCommand() const { + switch (type.Value()) { + case CommandType::Close: + case CommandType::TIPC_Close: + return true; + default: + return false; + } + } }; static_assert(sizeof(CommandHeader) == 8, "CommandHeader size is incorrect"); From 75f23ad494cc1576f12b27b626e3c0de6817a7de Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:41:46 -0700 Subject: [PATCH 04/22] hle: kernel: KClientPort: Cleanup comment format. --- src/core/hle/kernel/k_client_port.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/kernel/k_client_port.cpp b/src/core/hle/kernel/k_client_port.cpp index e14b915b9..4a12dee10 100644 --- a/src/core/hle/kernel/k_client_port.cpp +++ b/src/core/hle/kernel/k_client_port.cpp @@ -91,7 +91,7 @@ ResultCode KClientPort::CreateSession(KClientSession** out) { // Create a new session. KSession* session = KSession::Create(kernel); if (session == nullptr) { - /* Decrement the session count. */ + // Decrement the session count. const auto prev = num_sessions--; if (prev == max_sessions) { this->NotifyAvailable(); From 9f44a44f2f6d55ccbc75f9f630c1fc9dd0174d47 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:42:46 -0700 Subject: [PATCH 05/22] hle: ipc_helpers: Reserve session resource when we create a KSession. --- src/core/hle/ipc_helpers.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h index d1eb8b075..c76302dc9 100644 --- a/src/core/hle/ipc_helpers.h +++ b/src/core/hle/ipc_helpers.h @@ -15,6 +15,8 @@ #include "core/hle/ipc.h" #include "core/hle/kernel/hle_ipc.h" #include "core/hle/kernel/k_client_port.h" +#include "core/hle/kernel/k_process.h" +#include "core/hle/kernel/k_resource_limit.h" #include "core/hle/kernel/k_session.h" #include "core/hle/result.h" @@ -148,6 +150,9 @@ public: if (context->Session()->IsDomain()) { context->AddDomainObject(std::move(iface)); } else { + kernel.CurrentProcess()->GetResourceLimit()->Reserve( + Kernel::LimitableResource::Sessions, 1); + auto* session = Kernel::KSession::Create(kernel); session->Initialize(nullptr, iface->GetServiceName()); From cfed6936f3c0d912bcc05f640341adb990b61d90 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:43:42 -0700 Subject: [PATCH 06/22] hle: service: sm: Increase point buffer size. --- src/core/hle/service/sm/controller.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/service/sm/controller.cpp b/src/core/hle/service/sm/controller.cpp index ee026e22f..a8f5125ab 100644 --- a/src/core/hle/service/sm/controller.cpp +++ b/src/core/hle/service/sm/controller.cpp @@ -44,7 +44,7 @@ void Controller::QueryPointerBufferSize(Kernel::HLERequestContext& ctx) { IPC::ResponseBuilder rb{ctx, 3}; rb.Push(RESULT_SUCCESS); - rb.Push(0x1000); + rb.Push(0x8000); } // https://switchbrew.org/wiki/IPC_Marshalling From 44c763f9c6306a431739e69760ef3646141e2107 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:53:07 -0700 Subject: [PATCH 07/22] hle: kernel: KSession: Improve implementation of CloneCurrentObject. --- src/core/hle/service/sm/controller.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/core/hle/service/sm/controller.cpp b/src/core/hle/service/sm/controller.cpp index a8f5125ab..de530cbfb 100644 --- a/src/core/hle/service/sm/controller.cpp +++ b/src/core/hle/service/sm/controller.cpp @@ -26,15 +26,23 @@ void Controller::CloneCurrentObject(Kernel::HLERequestContext& ctx) { // TODO(bunnei): This is just creating a new handle to the same Session. I assume this is wrong // and that we probably want to actually make an entirely new Session, but we still need to // verify this on hardware. + LOG_DEBUG(Service, "called"); + auto session = ctx.Session()->GetParent(); + + // Open a reference to the session to simulate a new one being created. + session->Open(); + session->GetClientSession().Open(); + session->GetServerSession().Open(); + IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles}; rb.Push(RESULT_SUCCESS); - rb.PushMoveObjects(ctx.Session()->GetParent()->GetClientSession()); + rb.PushMoveObjects(session->GetClientSession()); } void Controller::CloneCurrentObjectEx(Kernel::HLERequestContext& ctx) { - LOG_WARNING(Service, "(STUBBED) called, using CloneCurrentObject"); + LOG_DEBUG(Service, "called"); CloneCurrentObject(ctx); } From c6de9657be71a9c659f9c991ec8d024ebf44d56e Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:57:59 -0700 Subject: [PATCH 08/22] hle: kernel: Implement named service ports using service interface factory. - This allows us to create a new interface each time ConnectToNamedPort is called, removing the assumption that these are static. --- src/core/hle/kernel/kernel.cpp | 21 +++++++++++---------- src/core/hle/kernel/kernel.h | 18 +++++++++++------- src/core/hle/service/service.cpp | 5 +++-- src/core/hle/service/service.h | 8 +++++--- 4 files changed, 30 insertions(+), 22 deletions(-) diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp index bd4e4d350..8b55df82e 100644 --- a/src/core/hle/kernel/kernel.cpp +++ b/src/core/hle/kernel/kernel.cpp @@ -44,6 +44,7 @@ #include "core/hle/kernel/time_manager.h" #include "core/hle/lock.h" #include "core/hle/result.h" +#include "core/hle/service/sm/sm.h" #include "core/memory.h" MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70)); @@ -656,6 +657,7 @@ struct KernelCore::Impl { /// Map of named ports managed by the kernel, which can be retrieved using /// the ConnectToPort SVC. + std::unordered_map service_interface_factory; NamedPortTable named_ports; std::unique_ptr exclusive_monitor; @@ -844,18 +846,17 @@ void KernelCore::PrepareReschedule(std::size_t id) { // TODO: Reimplement, this } -void KernelCore::AddNamedPort(std::string name, KClientPort* port) { - port->Open(); - impl->named_ports.emplace(std::move(name), port); +void KernelCore::RegisterNamedService(std::string name, ServiceInterfaceFactory&& factory) { + impl->service_interface_factory.emplace(std::move(name), factory); } -KernelCore::NamedPortTable::iterator KernelCore::FindNamedPort(const std::string& name) { - return impl->named_ports.find(name); -} - -KernelCore::NamedPortTable::const_iterator KernelCore::FindNamedPort( - const std::string& name) const { - return impl->named_ports.find(name); +KClientPort* KernelCore::CreateNamedServicePort(std::string name) { + auto search = impl->service_interface_factory.find(name); + if (search == impl->service_interface_factory.end()) { + UNIMPLEMENTED(); + return {}; + } + return &search->second(impl->system.ServiceManager(), impl->system); } bool KernelCore::IsValidNamedPort(NamedPortTable::const_iterator port) const { diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h index 51aaccbc7..2d01e1ae0 100644 --- a/src/core/hle/kernel/kernel.h +++ b/src/core/hle/kernel/kernel.h @@ -27,6 +27,10 @@ class CoreTiming; struct EventType; } // namespace Core::Timing +namespace Service::SM { +class ServiceManager; +} + namespace Kernel { class KClientPort; @@ -51,6 +55,9 @@ class ServiceThread; class Synchronization; class TimeManager; +using ServiceInterfaceFactory = + std::function; + namespace Init { struct KSlabResourceCounts; } @@ -172,14 +179,11 @@ public: void InvalidateCpuInstructionCacheRange(VAddr addr, std::size_t size); - /// Adds a port to the named port table - void AddNamedPort(std::string name, KClientPort* port); + /// Registers a named HLE service, passing a factory used to open a port to that service. + void RegisterNamedService(std::string name, ServiceInterfaceFactory&& factory); - /// Finds a port within the named port table with the given name. - NamedPortTable::iterator FindNamedPort(const std::string& name); - - /// Finds a port within the named port table with the given name. - NamedPortTable::const_iterator FindNamedPort(const std::string& name) const; + /// Opens a port to a service previously registered with RegisterNamedService. + KClientPort* CreateNamedServicePort(std::string name); /// Determines whether or not the given port is a valid named port. bool IsValidNamedPort(NamedPortTable::const_iterator port) const; diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index 00e683c2f..f3fd0f534 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -111,7 +111,7 @@ void ServiceFrameworkBase::InstallAsService(SM::ServiceManager& service_manager) port_installed = true; } -void ServiceFrameworkBase::InstallAsNamedPort(Kernel::KernelCore& kernel) { +Kernel::KClientPort& ServiceFrameworkBase::CreatePort(Kernel::KernelCore& kernel) { const auto guard = LockService(); ASSERT(!port_installed); @@ -119,9 +119,10 @@ void ServiceFrameworkBase::InstallAsNamedPort(Kernel::KernelCore& kernel) { auto* port = Kernel::KPort::Create(kernel); port->Initialize(max_sessions, false, service_name); port->GetServerPort().SetHleHandler(shared_from_this()); - kernel.AddNamedPort(service_name, &port->GetClientPort()); port_installed = true; + + return port->GetClientPort(); } void ServiceFrameworkBase::RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n) { diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h index 884951428..16357b156 100644 --- a/src/core/hle/service/service.h +++ b/src/core/hle/service/service.h @@ -64,10 +64,12 @@ public: /// Creates a port pair and registers this service with the given ServiceManager. void InstallAsService(SM::ServiceManager& service_manager); - /// Creates a port pair and registers it on the kernel's global port registry. - void InstallAsNamedPort(Kernel::KernelCore& kernel); - /// Invokes a service request routine. + + /// Invokes a service request routine using the HIPC protocol. void InvokeRequest(Kernel::HLERequestContext& ctx); + /// Creates a port pair and registers it on the kernel's global port registry. + Kernel::KClientPort& CreatePort(Kernel::KernelCore& kernel); + /// Handles a synchronization request for the service. ResultCode HandleSyncRequest(Kernel::HLERequestContext& context) override; From f54ea749a4a593f63f75f6d21550534eac5eec8c Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:58:33 -0700 Subject: [PATCH 09/22] hle: kernel: svc: Update ConnectToNamedPort to use new CreateNamedServicePort interface. --- src/core/hle/kernel/svc.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp index 52011be9c..6b445677e 100644 --- a/src/core/hle/kernel/svc.cpp +++ b/src/core/hle/kernel/svc.cpp @@ -284,12 +284,11 @@ static ResultCode ConnectToNamedPort(Core::System& system, Handle* out, VAddr po auto& handle_table = kernel.CurrentProcess()->GetHandleTable(); // Find the client port. - const auto it = kernel.FindNamedPort(port_name); - if (!kernel.IsValidNamedPort(it)) { - LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name); + auto port = kernel.CreateNamedServicePort(port_name); + if (!port) { + LOG_ERROR(Kernel_SVC, "tried to connect to unknown port: {}", port_name); return ResultNotFound; } - auto port = it->second; // Reserve a handle for the port. // NOTE: Nintendo really does write directly to the output handle here. From 934b2d8842f09a8df827cd4fd5130124788b4288 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 15:59:19 -0700 Subject: [PATCH 10/22] hle: service: sm: Improve Initialize implementation. --- src/core/hle/service/sm/sm.cpp | 2 ++ src/core/hle/service/sm/sm.h | 1 + 2 files changed, 3 insertions(+) diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp index 568effbc9..7bd571880 100644 --- a/src/core/hle/service/sm/sm.cpp +++ b/src/core/hle/service/sm/sm.cpp @@ -107,6 +107,8 @@ SM::~SM() = default; void SM::Initialize(Kernel::HLERequestContext& ctx) { LOG_DEBUG(Service_SM, "called"); + is_initialized = true; + IPC::ResponseBuilder rb{ctx, 2}; rb.Push(RESULT_SUCCESS); } diff --git a/src/core/hle/service/sm/sm.h b/src/core/hle/service/sm/sm.h index af5010c3b..fed65af4f 100644 --- a/src/core/hle/service/sm/sm.h +++ b/src/core/hle/service/sm/sm.h @@ -44,6 +44,7 @@ private: void UnregisterService(Kernel::HLERequestContext& ctx); std::shared_ptr service_manager; + bool is_initialized{}; Kernel::KernelCore& kernel; }; From 41928dfdda96528f2c99d6ee00989a365f1a7ab1 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 16:03:39 -0700 Subject: [PATCH 11/22] hle: service: sm: Use RegisterNamedService to register the service. --- src/core/hle/service/service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index f3fd0f534..d7e09e8f1 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -208,7 +208,7 @@ Services::Services(std::shared_ptr& sm, Core::System& system system.GetFileSystemController().CreateFactories(*system.GetFilesystem(), false); - SM::ServiceManager::InstallInterfaces(sm, system); + system.Kernel().RegisterNamedService("sm:", SM::ServiceManager::InterfaceFactory); Account::InstallInterfaces(system); AM::InstallInterfaces(*sm, *nv_flinger, system); From da25a5986666c55de1421aed978f7e92e5a87c8f Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 16:05:37 -0700 Subject: [PATCH 12/22] hle: service: Implement IPC::CommandType::Close. - This was not actually closing sessions before. --- src/core/hle/kernel/k_server_session.cpp | 4 ++-- src/core/hle/service/service.cpp | 19 +++++++++++-------- src/core/hle/service/service.h | 3 ++- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/core/hle/kernel/k_server_session.cpp b/src/core/hle/kernel/k_server_session.cpp index b28cc2499..8850d9af5 100644 --- a/src/core/hle/kernel/k_server_session.cpp +++ b/src/core/hle/kernel/k_server_session.cpp @@ -95,7 +95,7 @@ ResultCode KServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& co UNREACHABLE(); return RESULT_SUCCESS; // Ignore error if asserts are off } - return domain_request_handlers[object_id - 1]->HandleSyncRequest(context); + return domain_request_handlers[object_id - 1]->HandleSyncRequest(*this, context); case IPC::DomainMessageHeader::CommandType::CloseVirtualHandle: { LOG_DEBUG(IPC, "CloseVirtualHandle, object_id=0x{:08X}", object_id); @@ -135,7 +135,7 @@ ResultCode KServerSession::CompleteSyncRequest(HLERequestContext& context) { // If there is no domain header, the regular session handler is used } else if (hle_handler != nullptr) { // If this ServerSession has an associated HLE handler, forward the request to it. - result = hle_handler->HandleSyncRequest(context); + result = hle_handler->HandleSyncRequest(*this, context); } if (convert_to_domain) { diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index d7e09e8f1..e36c35a86 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -167,33 +167,36 @@ void ServiceFrameworkBase::InvokeRequest(Kernel::HLERequestContext& ctx) { handler_invoker(this, info->handler_callback, ctx); } -ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::HLERequestContext& context) { +ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session, + Kernel::HLERequestContext& ctx) { const auto guard = LockService(); - switch (context.GetCommandType()) { - case IPC::CommandType::Close: { - IPC::ResponseBuilder rb{context, 2}; + switch (ctx.GetCommandType()) { + case IPC::CommandType::Close: + case IPC::CommandType::TIPC_Close: { + session.Close(); + IPC::ResponseBuilder rb{ctx, 2}; rb.Push(RESULT_SUCCESS); return IPC::ERR_REMOTE_PROCESS_DEAD; } case IPC::CommandType::ControlWithContext: case IPC::CommandType::Control: { - system.ServiceManager().InvokeControlRequest(context); + system.ServiceManager().InvokeControlRequest(ctx); break; } case IPC::CommandType::RequestWithContext: case IPC::CommandType::Request: { - InvokeRequest(context); + InvokeRequest(ctx); break; } default: - UNIMPLEMENTED_MSG("command_type={}", context.GetCommandType()); + UNIMPLEMENTED_MSG("command_type={}", ctx.GetCommandType()); } // If emulation was shutdown, we are closing service threads, do not write the response back to // memory that may be shutting down as well. if (system.IsPoweredOn()) { - context.WriteToOutgoingCommandBuffer(context.GetThread()); + ctx.WriteToOutgoingCommandBuffer(ctx.GetThread()); } return RESULT_SUCCESS; diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h index 16357b156..51e22a791 100644 --- a/src/core/hle/service/service.h +++ b/src/core/hle/service/service.h @@ -71,7 +71,8 @@ public: Kernel::KClientPort& CreatePort(Kernel::KernelCore& kernel); /// Handles a synchronization request for the service. - ResultCode HandleSyncRequest(Kernel::HLERequestContext& context) override; + ResultCode HandleSyncRequest(Kernel::KServerSession& session, + Kernel::HLERequestContext& context) override; protected: /// Member-function pointer type of SyncRequest handlers. From 21671d05a362f98cd24dcc520a3da163e349fe07 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 16:08:06 -0700 Subject: [PATCH 13/22] hle: service: Add support for dispatching TIPC requests. --- src/core/hle/service/service.cpp | 29 +++++++++++++++++++++++++++++ src/core/hle/service/service.h | 24 +++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index e36c35a86..2c9b2ce6d 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -133,6 +133,16 @@ void ServiceFrameworkBase::RegisterHandlersBase(const FunctionInfoBase* function } } +void ServiceFrameworkBase::RegisterHandlersBaseTipc(const FunctionInfoBase* functions, + std::size_t n) { + handlers_tipc.reserve(handlers_tipc.size() + n); + for (std::size_t i = 0; i < n; ++i) { + // Usually this array is sorted by id already, so hint to insert at the end + handlers_tipc.emplace_hint(handlers_tipc.cend(), functions[i].expected_header, + functions[i]); + } +} + void ServiceFrameworkBase::ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, const FunctionInfoBase* info) { auto cmd_buf = ctx.CommandBuffer(); @@ -167,6 +177,20 @@ void ServiceFrameworkBase::InvokeRequest(Kernel::HLERequestContext& ctx) { handler_invoker(this, info->handler_callback, ctx); } +void ServiceFrameworkBase::InvokeRequestTipc(Kernel::HLERequestContext& ctx) { + boost::container::flat_map::iterator itr; + + itr = handlers_tipc.find(ctx.GetCommand()); + + const FunctionInfoBase* info = itr == handlers_tipc.end() ? nullptr : &itr->second; + if (info == nullptr || info->handler_callback == nullptr) { + return ReportUnimplementedFunction(ctx, info); + } + + LOG_TRACE(Service, "{}", MakeFunctionString(info->name, GetServiceName(), ctx.CommandBuffer())); + handler_invoker(this, info->handler_callback, ctx); +} + ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session, Kernel::HLERequestContext& ctx) { const auto guard = LockService(); @@ -190,6 +214,11 @@ ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& sessi break; } default: + if (ctx.IsTipc()) { + InvokeRequestTipc(ctx); + break; + } + UNIMPLEMENTED_MSG("command_type={}", ctx.GetCommandType()); } diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h index 51e22a791..3dfb0740a 100644 --- a/src/core/hle/service/service.h +++ b/src/core/hle/service/service.h @@ -21,7 +21,9 @@ class System; namespace Kernel { class HLERequestContext; -} +class KClientPort; +class KServerSession; +} // namespace Kernel namespace Service { @@ -67,6 +69,10 @@ public: /// Invokes a service request routine using the HIPC protocol. void InvokeRequest(Kernel::HLERequestContext& ctx); + + /// Invokes a service request routine using the HIPC protocol. + void InvokeRequestTipc(Kernel::HLERequestContext& ctx); + /// Creates a port pair and registers it on the kernel's global port registry. Kernel::KClientPort& CreatePort(Kernel::KernelCore& kernel); @@ -105,6 +111,7 @@ private: ~ServiceFrameworkBase() override; void RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n); + void RegisterHandlersBaseTipc(const FunctionInfoBase* functions, std::size_t n); void ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, const FunctionInfoBase* info); /// Identifier string used to connect to the service. @@ -119,6 +126,7 @@ private: /// Function used to safely up-cast pointers to the derived class before invoking a handler. InvokerFn* handler_invoker; boost::container::flat_map handlers; + boost::container::flat_map handlers_tipc; /// Used to gain exclusive access to the service members, e.g. from CoreTiming thread. Common::SpinLock lock_service; @@ -186,6 +194,20 @@ protected: RegisterHandlersBase(functions, n); } + /// Registers handlers in the service. + template + void RegisterHandlersTipc(const FunctionInfo (&functions)[N]) { + RegisterHandlersTipc(functions, N); + } + + /** + * Registers handlers in the service. Usually prefer using the other RegisterHandlers + * overload in order to avoid needing to specify the array size. + */ + void RegisterHandlersTipc(const FunctionInfo* functions, std::size_t n) { + RegisterHandlersBaseTipc(functions, n); + } + private: /** * This function is used to allow invocation of pointers to handlers stored in the base class From 49c4c329f6c873bcf8da22c8da08a704a563ba4e Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 16:12:01 -0700 Subject: [PATCH 14/22] hle: service: sm: GetService: Reserve session resource when we create a KSession. --- src/core/hle/service/sm/sm.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp index 7bd571880..726bef4c3 100644 --- a/src/core/hle/service/sm/sm.cpp +++ b/src/core/hle/service/sm/sm.cpp @@ -133,9 +133,16 @@ void SM::GetService(Kernel::HLERequestContext& ctx) { auto* port = result.Unwrap(); + Kernel::KScopedResourceReservation session_reservation( + kernel.CurrentProcess()->GetResourceLimit(), Kernel::LimitableResource::Sessions); + R_UNLESS(session_reservation.Succeeded(), Kernel::ResultLimitReached); + auto* session = Kernel::KSession::Create(kernel); session->Initialize(&port->GetClientPort(), std::move(name)); + // Commit the session reservation. + session_reservation.Commit(); + if (port->GetServerPort().GetHLEHandler()) { port->GetServerPort().GetHLEHandler()->ClientConnected(&session->GetServerSession()); } else { From 913971417e0732ef813c57c532f9e221641cee9d Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 16:16:36 -0700 Subject: [PATCH 15/22] hle: kernel: hle_ipc: Improve IPC code and add initial support for TIPC. - Fixes our move handles implementation to actually move objects. - Simplifies the traditional IPC path. --- src/core/hle/kernel/hle_ipc.cpp | 133 +++++++++++++------------------- src/core/hle/kernel/hle_ipc.h | 3 +- 2 files changed, 56 insertions(+), 80 deletions(-) diff --git a/src/core/hle/kernel/hle_ipc.cpp b/src/core/hle/kernel/hle_ipc.cpp index d6929d2c0..edb3f8d98 100644 --- a/src/core/hle/kernel/hle_ipc.cpp +++ b/src/core/hle/kernel/hle_ipc.cpp @@ -55,7 +55,7 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32 IPC::RequestParser rp(src_cmdbuf); command_header = rp.PopRaw(); - if (command_header->type == IPC::CommandType::Close) { + if (command_header->IsCloseCommand()) { // Close does not populate the rest of the IPC header return; } @@ -101,37 +101,41 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32 const auto buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size; - // Padding to align to 16 bytes - rp.AlignWithPadding(); + if (!command_header->IsTipc()) { + // Padding to align to 16 bytes + rp.AlignWithPadding(); - if (Session()->IsDomain() && ((command_header->type == IPC::CommandType::Request || - command_header->type == IPC::CommandType::RequestWithContext) || - !incoming)) { - // If this is an incoming message, only CommandType "Request" has a domain header - // All outgoing domain messages have the domain header, if only incoming has it - if (incoming || domain_message_header) { - domain_message_header = rp.PopRaw(); - } else { - if (Session()->IsDomain()) { - LOG_WARNING(IPC, "Domain request has no DomainMessageHeader!"); + if (Session()->IsDomain() && + ((command_header->type == IPC::CommandType::Request || + command_header->type == IPC::CommandType::RequestWithContext) || + !incoming)) { + // If this is an incoming message, only CommandType "Request" has a domain header + // All outgoing domain messages have the domain header, if only incoming has it + if (incoming || domain_message_header) { + domain_message_header = rp.PopRaw(); + } else { + if (Session()->IsDomain()) { + LOG_WARNING(IPC, "Domain request has no DomainMessageHeader!"); + } } } - } - data_payload_header = rp.PopRaw(); + data_payload_header = rp.PopRaw(); - data_payload_offset = rp.GetCurrentOffset(); + data_payload_offset = rp.GetCurrentOffset(); - if (domain_message_header && domain_message_header->command == - IPC::DomainMessageHeader::CommandType::CloseVirtualHandle) { - // CloseVirtualHandle command does not have SFC* or any data - return; - } + if (domain_message_header && + domain_message_header->command == + IPC::DomainMessageHeader::CommandType::CloseVirtualHandle) { + // CloseVirtualHandle command does not have SFC* or any data + return; + } - if (incoming) { - ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'I')); - } else { - ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'O')); + if (incoming) { + ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'I')); + } else { + ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'O')); + } } rp.SetCurrentOffset(buffer_c_offset); @@ -166,84 +170,55 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32 ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table, u32_le* src_cmdbuf) { ParseCommandBuffer(handle_table, src_cmdbuf, true); - if (command_header->type == IPC::CommandType::Close) { + + if (command_header->IsCloseCommand()) { // Close does not populate the rest of the IPC header return RESULT_SUCCESS; } - // The data_size already includes the payload header, the padding and the domain header. - std::size_t size = data_payload_offset + command_header->data_size - - sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4; - if (domain_message_header) - size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32); - std::copy_n(src_cmdbuf, size, cmd_buf.begin()); + std::copy_n(src_cmdbuf, IPC::COMMAND_BUFFER_LENGTH, cmd_buf.begin()); + return RESULT_SUCCESS; } ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_thread) { + auto current_offset = handles_offset; auto& owner_process = *requesting_thread.GetOwnerProcess(); auto& handle_table = owner_process.GetHandleTable(); - std::array dst_cmdbuf; - memory.ReadBlock(owner_process, requesting_thread.GetTLSAddress(), dst_cmdbuf.data(), - dst_cmdbuf.size() * sizeof(u32)); - - // The header was already built in the internal command buffer. Attempt to parse it to verify - // the integrity and then copy it over to the target command buffer. - ParseCommandBuffer(handle_table, cmd_buf.data(), false); - - // The data_size already includes the payload header, the padding and the domain header. - std::size_t size = data_payload_offset + command_header->data_size - - sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4; - if (domain_message_header) - size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32); - - std::copy_n(cmd_buf.begin(), size, dst_cmdbuf.data()); - - if (command_header->enable_handle_descriptor) { - ASSERT_MSG(!move_objects.empty() || !copy_objects.empty(), - "Handle descriptor bit set but no handles to translate"); - // We write the translated handles at a specific offset in the command buffer, this space - // was already reserved when writing the header. - std::size_t current_offset = - (sizeof(IPC::CommandHeader) + sizeof(IPC::HandleDescriptorHeader)) / sizeof(u32); - ASSERT_MSG(!handle_descriptor_header->send_current_pid, "Sending PID is not implemented"); - - ASSERT(copy_objects.size() == handle_descriptor_header->num_handles_to_copy); - ASSERT(move_objects.size() == handle_descriptor_header->num_handles_to_move); - - // We don't make a distinction between copy and move handles when translating since HLE - // services don't deal with handles directly. However, the guest applications might check - // for specific values in each of these descriptors. - for (auto& object : copy_objects) { - ASSERT(object != nullptr); - R_TRY(handle_table.Add(&dst_cmdbuf[current_offset++], object)); + for (auto& object : copy_objects) { + Handle handle{}; + if (object) { + R_TRY(handle_table.Add(&handle, object)); } + cmd_buf[current_offset++] = handle; + } + for (auto& object : move_objects) { + Handle handle{}; + if (object) { + R_TRY(handle_table.Add(&handle, object)); - for (auto& object : move_objects) { - ASSERT(object != nullptr); - R_TRY(handle_table.Add(&dst_cmdbuf[current_offset++], object)); + // Close our reference to the object, as it is being moved to the caller. + object->Close(); } + cmd_buf[current_offset++] = handle; } - // TODO(Subv): Translate the X/A/B/W buffers. - - if (Session()->IsDomain() && domain_message_header) { - ASSERT(domain_message_header->num_objects == domain_objects.size()); - // Write the domain objects to the command buffer, these go after the raw untranslated data. - // TODO(Subv): This completely ignores C buffers. - std::size_t domain_offset = size - domain_message_header->num_objects; + // Write the domain objects to the command buffer, these go after the raw untranslated data. + // TODO(Subv): This completely ignores C buffers. + if (Session()->IsDomain()) { + current_offset = domain_offset - static_cast(domain_objects.size()); for (const auto& object : domain_objects) { server_session->AppendDomainRequestHandler(object); - dst_cmdbuf[domain_offset++] = + cmd_buf[current_offset++] = static_cast(server_session->NumDomainRequestHandlers()); } } // Copy the translated command buffer back into the thread's command buffer area. - memory.WriteBlock(owner_process, requesting_thread.GetTLSAddress(), dst_cmdbuf.data(), - dst_cmdbuf.size() * sizeof(u32)); + memory.WriteBlock(owner_process, requesting_thread.GetTLSAddress(), cmd_buf.data(), + cmd_buf.size() * sizeof(u32)); return RESULT_SUCCESS; } diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h index 07360629e..3e66e5542 100644 --- a/src/core/hle/kernel/hle_ipc.h +++ b/src/core/hle/kernel/hle_ipc.h @@ -66,7 +66,8 @@ public: * this request (ServerSession, Originator thread, Translated command buffer, etc). * @returns ResultCode the result code of the translate operation. */ - virtual ResultCode HandleSyncRequest(Kernel::HLERequestContext& context) = 0; + virtual ResultCode HandleSyncRequest(Kernel::KServerSession& session, + Kernel::HLERequestContext& context) = 0; /** * Signals that a client has just connected to this HLE handler and keeps the From 2c1e119c4a57fdd26dc8249d9b5fca3111195777 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 16:18:30 -0700 Subject: [PATCH 16/22] hle: service: sm: Add TIPC support. - Fixes our error checking of names as well. --- src/core/hle/service/sm/sm.cpp | 102 ++++++++++++++++++++------------- src/core/hle/service/sm/sm.h | 9 ++- 2 files changed, 68 insertions(+), 43 deletions(-) diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp index 726bef4c3..391db48b1 100644 --- a/src/core/hle/service/sm/sm.cpp +++ b/src/core/hle/service/sm/sm.cpp @@ -9,6 +9,7 @@ #include "core/hle/kernel/k_client_port.h" #include "core/hle/kernel/k_client_session.h" #include "core/hle/kernel/k_port.h" +#include "core/hle/kernel/k_scoped_resource_reservation.h" #include "core/hle/kernel/k_server_port.h" #include "core/hle/kernel/k_server_session.h" #include "core/hle/kernel/k_session.h" @@ -18,6 +19,7 @@ namespace Service::SM { +constexpr ResultCode ERR_NOT_INITIALIZED(ErrorModule::SM, 2); constexpr ResultCode ERR_ALREADY_REGISTERED(ErrorModule::SM, 4); constexpr ResultCode ERR_INVALID_NAME(ErrorModule::SM, 6); constexpr ResultCode ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7); @@ -34,20 +36,17 @@ static ResultCode ValidateServiceName(const std::string& name) { LOG_ERROR(Service_SM, "Invalid service name! service={}", name); return ERR_INVALID_NAME; } - if (name.rfind('\0') != std::string::npos) { - LOG_ERROR(Service_SM, "A non null terminated service was passed"); - return ERR_INVALID_NAME; - } return RESULT_SUCCESS; } -void ServiceManager::InstallInterfaces(std::shared_ptr self, Core::System& system) { - ASSERT(self->sm_interface.expired()); +Kernel::KClientPort& ServiceManager::InterfaceFactory(ServiceManager& self, Core::System& system) { + ASSERT(self.sm_interface.expired()); auto sm = std::make_shared(self, system); - sm->InstallAsNamedPort(system.Kernel()); - self->sm_interface = sm; - self->controller_interface = std::make_unique(system); + self.sm_interface = sm; + self.controller_interface = std::make_unique(system); + + return sm->CreatePort(system.Kernel()); } ResultVal ServiceManager::RegisterService(std::string name, @@ -114,21 +113,47 @@ void SM::Initialize(Kernel::HLERequestContext& ctx) { } void SM::GetService(Kernel::HLERequestContext& ctx) { - IPC::RequestParser rp{ctx}; - auto name_buf = rp.PopRaw>(); - auto end = std::find(name_buf.begin(), name_buf.end(), '\0'); - - std::string name(name_buf.begin(), end); - - auto result = service_manager->GetServicePort(name); - if (result.Failed()) { + auto result = GetServiceImpl(ctx); + if (result.Succeeded()) { + IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles}; + rb.Push(result.Code()); + rb.PushMoveObjects(result.Unwrap()); + } else { IPC::ResponseBuilder rb{ctx, 2}; rb.Push(result.Code()); + } +} + +void SM::GetServiceTipc(Kernel::HLERequestContext& ctx) { + auto result = GetServiceImpl(ctx); + IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles}; + rb.Push(result.Code()); + rb.PushMoveObjects(result.Succeeded() ? result.Unwrap() : nullptr); +} + +static std::string PopServiceName(IPC::RequestParser& rp) { + auto name_buf = rp.PopRaw>(); + std::string result; + for (const auto& c : name_buf) { + if (c >= ' ' && c <= '~') { + result.push_back(c); + } + } + return result; +} + +ResultVal SM::GetServiceImpl(Kernel::HLERequestContext& ctx) { + if (!is_initialized) { + return ERR_NOT_INITIALIZED; + } + + IPC::RequestParser rp{ctx}; + std::string name(PopServiceName(rp)); + + auto result = service_manager.GetServicePort(name); + if (result.Failed()) { LOG_ERROR(Service_SM, "called service={} -> error 0x{:08X}", name, result.Code().raw); - if (name.length() == 0) - return; // LibNX Fix - UNIMPLEMENTED(); - return; + return result.Code(); } auto* port = result.Unwrap(); @@ -150,18 +175,12 @@ void SM::GetService(Kernel::HLERequestContext& ctx) { } LOG_DEBUG(Service_SM, "called service={} -> session={}", name, session->GetId()); - IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles}; - rb.Push(RESULT_SUCCESS); - rb.PushMoveObjects(session->GetClientSession()); + return MakeResult(&session->GetClientSession()); } void SM::RegisterService(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp{ctx}; - - const auto name_buf = rp.PopRaw>(); - const auto end = std::find(name_buf.begin(), name_buf.end(), '\0'); - - const std::string name(name_buf.begin(), end); + std::string name(PopServiceName(rp)); const auto is_light = static_cast(rp.PopRaw()); const auto max_session_count = rp.PopRaw(); @@ -169,7 +188,7 @@ void SM::RegisterService(Kernel::HLERequestContext& ctx) { LOG_DEBUG(Service_SM, "called with name={}, max_session_count={}, is_light={}", name, max_session_count, is_light); - auto handle = service_manager->RegisterService(name, max_session_count); + auto handle = service_manager.RegisterService(name, max_session_count); if (handle.Failed()) { LOG_ERROR(Service_SM, "failed to register service with error_code={:08X}", handle.Code().raw); @@ -187,28 +206,31 @@ void SM::RegisterService(Kernel::HLERequestContext& ctx) { void SM::UnregisterService(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp{ctx}; + std::string name(PopServiceName(rp)); - const auto name_buf = rp.PopRaw>(); - const auto end = std::find(name_buf.begin(), name_buf.end(), '\0'); - - const std::string name(name_buf.begin(), end); LOG_DEBUG(Service_SM, "called with name={}", name); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(service_manager->UnregisterService(name)); + rb.Push(service_manager.UnregisterService(name)); } -SM::SM(std::shared_ptr service_manager_, Core::System& system_) +SM::SM(ServiceManager& service_manager_, Core::System& system_) : ServiceFramework{system_, "sm:", 4}, - service_manager{std::move(service_manager_)}, kernel{system_.Kernel()} { - static const FunctionInfo functions[] = { + service_manager{service_manager_}, kernel{system_.Kernel()} { + RegisterHandlers({ {0, &SM::Initialize, "Initialize"}, {1, &SM::GetService, "GetService"}, {2, &SM::RegisterService, "RegisterService"}, {3, &SM::UnregisterService, "UnregisterService"}, {4, nullptr, "DetachClient"}, - }; - RegisterHandlers(functions); + }); + RegisterHandlersTipc({ + {0, &SM::Initialize, "Initialize"}, + {1, &SM::GetServiceTipc, "GetService"}, + {2, &SM::RegisterService, "RegisterService"}, + {3, &SM::UnregisterService, "UnregisterService"}, + {4, nullptr, "DetachClient"}, + }); } } // namespace Service::SM diff --git a/src/core/hle/service/sm/sm.h b/src/core/hle/service/sm/sm.h index fed65af4f..60f0b3f8a 100644 --- a/src/core/hle/service/sm/sm.h +++ b/src/core/hle/service/sm/sm.h @@ -34,23 +34,26 @@ class Controller; /// Interface to "sm:" service class SM final : public ServiceFramework { public: - explicit SM(std::shared_ptr service_manager_, Core::System& system_); + explicit SM(ServiceManager& service_manager_, Core::System& system_); ~SM() override; private: void Initialize(Kernel::HLERequestContext& ctx); void GetService(Kernel::HLERequestContext& ctx); + void GetServiceTipc(Kernel::HLERequestContext& ctx); void RegisterService(Kernel::HLERequestContext& ctx); void UnregisterService(Kernel::HLERequestContext& ctx); - std::shared_ptr service_manager; + ResultVal GetServiceImpl(Kernel::HLERequestContext& ctx); + + ServiceManager& service_manager; bool is_initialized{}; Kernel::KernelCore& kernel; }; class ServiceManager { public: - static void InstallInterfaces(std::shared_ptr self, Core::System& system); + static Kernel::KClientPort& InterfaceFactory(ServiceManager& self, Core::System& system); explicit ServiceManager(Kernel::KernelCore& kernel_); ~ServiceManager(); From 343d92a092769884f7feb2563bc16a2ba09a7021 Mon Sep 17 00:00:00 2001 From: bunnei Date: Mon, 10 May 2021 17:45:55 -0700 Subject: [PATCH 17/22] core: hle: ipc_helpers: Fix cast on raw_data_size calculation. --- src/core/hle/ipc_helpers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h index c76302dc9..571b4e81d 100644 --- a/src/core/hle/ipc_helpers.h +++ b/src/core/hle/ipc_helpers.h @@ -101,7 +101,7 @@ public: } if (ctx.Session()->IsDomain()) { - raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects; + raw_data_size += static_cast(sizeof(DomainMessageHeader) / 4 + num_domain_objects); } if (ctx.IsTipc()) { From b9f543b29f2d2fbb44dbf5d821cc6b5fd10af118 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 8 May 2021 03:07:10 -0700 Subject: [PATCH 18/22] audren --- src/core/hle/service/audio/audren_u.cpp | 39 +++++++++---------------- src/core/hle/service/audio/audren_u.h | 2 ++ 2 files changed, 16 insertions(+), 25 deletions(-) diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp index 513bd3730..65887011f 100644 --- a/src/core/hle/service/audio/audren_u.cpp +++ b/src/core/hle/service/audio/audren_u.cpp @@ -169,10 +169,9 @@ private: class IAudioDevice final : public ServiceFramework { public: - explicit IAudioDevice(Core::System& system_, u32_le revision_num) - : ServiceFramework{system_, "IAudioDevice"}, revision{revision_num}, - buffer_event{system.Kernel()}, audio_input_device_switch_event{system.Kernel()}, - audio_output_device_switch_event{system.Kernel()} { + explicit IAudioDevice(Core::System& system_, Kernel::KEvent& buffer_event_, u32_le revision_) + : ServiceFramework{system_, "IAudioDevice"}, buffer_event{buffer_event_}, revision{ + revision_} { static const FunctionInfo functions[] = { {0, &IAudioDevice::ListAudioDeviceName, "ListAudioDeviceName"}, {1, &IAudioDevice::SetAudioDeviceOutputVolume, "SetAudioDeviceOutputVolume"}, @@ -189,18 +188,6 @@ public: {13, nullptr, "GetAudioSystemMasterVolumeSetting"}, }; RegisterHandlers(functions); - - Kernel::KAutoObject::Create(std::addressof(buffer_event)); - buffer_event.Initialize("IAudioOutBufferReleasedEvent"); - - // Should be similar to audio_output_device_switch_event - Kernel::KAutoObject::Create(std::addressof(audio_input_device_switch_event)); - audio_input_device_switch_event.Initialize("IAudioDevice:AudioInputDeviceSwitchedEvent"); - - // Should only be signalled when an audio output device has been changed, example: speaker - // to headset - Kernel::KAutoObject::Create(std::addressof(audio_output_device_switch_event)); - audio_output_device_switch_event.Initialize("IAudioDevice:AudioOutputDeviceSwitchedEvent"); } private: @@ -310,7 +297,7 @@ private: IPC::ResponseBuilder rb{ctx, 2, 1}; rb.Push(RESULT_SUCCESS); - rb.PushCopyObjects(audio_input_device_switch_event.GetReadableEvent()); + rb.PushCopyObjects(buffer_event.GetReadableEvent()); } void QueryAudioDeviceOutputEvent(Kernel::HLERequestContext& ctx) { @@ -318,17 +305,16 @@ private: IPC::ResponseBuilder rb{ctx, 2, 1}; rb.Push(RESULT_SUCCESS); - rb.PushCopyObjects(audio_output_device_switch_event.GetReadableEvent()); + rb.PushCopyObjects(buffer_event.GetReadableEvent()); } + Kernel::KEvent& buffer_event; u32_le revision = 0; - Kernel::KEvent buffer_event; - Kernel::KEvent audio_input_device_switch_event; - Kernel::KEvent audio_output_device_switch_event; +}; -}; // namespace Audio +AudRenU::AudRenU(Core::System& system_) + : ServiceFramework{system_, "audren:u"}, buffer_event{system.Kernel()} { -AudRenU::AudRenU(Core::System& system_) : ServiceFramework{system_, "audren:u"} { // clang-format off static const FunctionInfo functions[] = { {0, &AudRenU::OpenAudioRenderer, "OpenAudioRenderer"}, @@ -340,6 +326,9 @@ AudRenU::AudRenU(Core::System& system_) : ServiceFramework{system_, "audren:u"} // clang-format on RegisterHandlers(functions); + + Kernel::KAutoObject::Create(std::addressof(buffer_event)); + buffer_event.Initialize("IAudioOutBufferReleasedEvent"); } AudRenU::~AudRenU() = default; @@ -662,7 +651,7 @@ void AudRenU::GetAudioDeviceService(Kernel::HLERequestContext& ctx) { // always assumes the initial release revision (REV1). IPC::ResponseBuilder rb{ctx, 2, 0, 1}; rb.Push(RESULT_SUCCESS); - rb.PushIpcInterface(system, Common::MakeMagic('R', 'E', 'V', '1')); + rb.PushIpcInterface(system, buffer_event, Common::MakeMagic('R', 'E', 'V', '1')); } void AudRenU::OpenAudioRendererForManualExecution(Kernel::HLERequestContext& ctx) { @@ -684,7 +673,7 @@ void AudRenU::GetAudioDeviceServiceWithRevisionInfo(Kernel::HLERequestContext& c IPC::ResponseBuilder rb{ctx, 2, 0, 1}; rb.Push(RESULT_SUCCESS); - rb.PushIpcInterface(system, revision); + rb.PushIpcInterface(system, buffer_event, revision); } void AudRenU::OpenAudioRendererImpl(Kernel::HLERequestContext& ctx) { diff --git a/src/core/hle/service/audio/audren_u.h b/src/core/hle/service/audio/audren_u.h index 37e8b4716..0ee6f9542 100644 --- a/src/core/hle/service/audio/audren_u.h +++ b/src/core/hle/service/audio/audren_u.h @@ -4,6 +4,7 @@ #pragma once +#include "core/hle/kernel/k_event.h" #include "core/hle/service/service.h" namespace Core { @@ -31,6 +32,7 @@ private: void OpenAudioRendererImpl(Kernel::HLERequestContext& ctx); std::size_t audren_instance_count = 0; + Kernel::KEvent buffer_event; }; // Describes a particular audio feature that may be supported in a particular revision. From f2c26443f85a3c3fd43137509368ba5c7ab80ee7 Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 11 May 2021 10:27:18 -0700 Subject: [PATCH 19/22] WORKAROUND: Do not use slab heap while we track down issues with resource management. --- src/core/hle/kernel/slab_helpers.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/hle/kernel/slab_helpers.h b/src/core/hle/kernel/slab_helpers.h index 0c5995db0..d0f7f084b 100644 --- a/src/core/hle/kernel/slab_helpers.h +++ b/src/core/hle/kernel/slab_helpers.h @@ -67,11 +67,11 @@ class KAutoObjectWithSlabHeapAndContainer : public Base { private: static Derived* Allocate(KernelCore& kernel) { - return kernel.SlabHeap().AllocateWithKernel(kernel); + return new Derived(kernel); } static void Free(KernelCore& kernel, Derived* obj) { - kernel.SlabHeap().Free(obj); + delete obj; } public: From fc086f93b2165b5c210cb7dcd6c18ebe17f1fd7b Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 11 May 2021 10:51:39 -0700 Subject: [PATCH 20/22] WORKAROUND: temp. disable session resource limits while we work out issues --- src/core/hle/ipc_helpers.h | 4 ++-- src/core/hle/kernel/k_client_port.cpp | 8 ++++---- src/core/hle/kernel/k_session.cpp | 2 +- src/core/hle/service/sm/sm.cpp | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h index 571b4e81d..f235153c3 100644 --- a/src/core/hle/ipc_helpers.h +++ b/src/core/hle/ipc_helpers.h @@ -150,8 +150,8 @@ public: if (context->Session()->IsDomain()) { context->AddDomainObject(std::move(iface)); } else { - kernel.CurrentProcess()->GetResourceLimit()->Reserve( - Kernel::LimitableResource::Sessions, 1); + // kernel.CurrentProcess()->GetResourceLimit()->Reserve( + // Kernel::LimitableResource::Sessions, 1); auto* session = Kernel::KSession::Create(kernel); session->Initialize(nullptr, iface->GetServiceName()); diff --git a/src/core/hle/kernel/k_client_port.cpp b/src/core/hle/kernel/k_client_port.cpp index 4a12dee10..ad01cf67e 100644 --- a/src/core/hle/kernel/k_client_port.cpp +++ b/src/core/hle/kernel/k_client_port.cpp @@ -58,9 +58,9 @@ bool KClientPort::IsSignaled() const { ResultCode KClientPort::CreateSession(KClientSession** out) { // Reserve a new session from the resource limit. - KScopedResourceReservation session_reservation(kernel.CurrentProcess()->GetResourceLimit(), - LimitableResource::Sessions); - R_UNLESS(session_reservation.Succeeded(), ResultLimitReached); + // KScopedResourceReservation session_reservation(kernel.CurrentProcess()->GetResourceLimit(), + // LimitableResource::Sessions); + // R_UNLESS(session_reservation.Succeeded(), ResultLimitReached); // Update the session counts. { @@ -104,7 +104,7 @@ ResultCode KClientPort::CreateSession(KClientSession** out) { session->Initialize(this, parent->GetName()); // Commit the session reservation. - session_reservation.Commit(); + // session_reservation.Commit(); // Register the session. KSession::Register(kernel, session); diff --git a/src/core/hle/kernel/k_session.cpp b/src/core/hle/kernel/k_session.cpp index 025b8b555..b7ce27a0b 100644 --- a/src/core/hle/kernel/k_session.cpp +++ b/src/core/hle/kernel/k_session.cpp @@ -78,7 +78,7 @@ void KSession::OnClientClosed() { void KSession::PostDestroy(uintptr_t arg) { // Release the session count resource the owner process holds. KProcess* owner = reinterpret_cast(arg); - owner->GetResourceLimit()->Release(LimitableResource::Sessions, 1); + // owner->GetResourceLimit()->Release(LimitableResource::Sessions, 1); owner->Close(); } diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp index 391db48b1..8cc9aee8a 100644 --- a/src/core/hle/service/sm/sm.cpp +++ b/src/core/hle/service/sm/sm.cpp @@ -158,15 +158,15 @@ ResultVal SM::GetServiceImpl(Kernel::HLERequestContext& auto* port = result.Unwrap(); - Kernel::KScopedResourceReservation session_reservation( - kernel.CurrentProcess()->GetResourceLimit(), Kernel::LimitableResource::Sessions); - R_UNLESS(session_reservation.Succeeded(), Kernel::ResultLimitReached); + // Kernel::KScopedResourceReservation session_reservation( + // kernel.CurrentProcess()->GetResourceLimit(), Kernel::LimitableResource::Sessions); + // R_UNLESS(session_reservation.Succeeded(), Kernel::ResultLimitReached); auto* session = Kernel::KSession::Create(kernel); session->Initialize(&port->GetClientPort(), std::move(name)); // Commit the session reservation. - session_reservation.Commit(); + // session_reservation.Commit(); if (port->GetServerPort().GetHLEHandler()) { port->GetServerPort().GetHLEHandler()->ClientConnected(&session->GetServerSession()); From 12d569e483834c74613a744abee7f277cc3d4e16 Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 11 May 2021 12:27:43 -0700 Subject: [PATCH 21/22] hle: kernel: hle_ipc: Fix outgoing IPC response size calculation. --- src/core/hle/ipc_helpers.h | 1 + src/core/hle/kernel/hle_ipc.cpp | 14 +++++++++++++- src/core/hle/kernel/hle_ipc.h | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h index f235153c3..5fed3dbf5 100644 --- a/src/core/hle/ipc_helpers.h +++ b/src/core/hle/ipc_helpers.h @@ -108,6 +108,7 @@ public: header.type.Assign(ctx.GetCommandType()); } + ctx.data_size = static_cast(raw_data_size); header.data_size.Assign(static_cast(raw_data_size)); if (num_handles_to_copy || num_handles_to_move) { header.enable_handle_descriptor.Assign(1); diff --git a/src/core/hle/kernel/hle_ipc.cpp b/src/core/hle/kernel/hle_ipc.cpp index edb3f8d98..ce3466df8 100644 --- a/src/core/hle/kernel/hle_ipc.cpp +++ b/src/core/hle/kernel/hle_ipc.cpp @@ -186,6 +186,18 @@ ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_t auto& owner_process = *requesting_thread.GetOwnerProcess(); auto& handle_table = owner_process.GetHandleTable(); + // The data_size already includes the payload header, the padding and the domain header. + std::size_t size{}; + + if (IsTipc()) { + size = cmd_buf.size(); + } else { + size = data_payload_offset + data_size - sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4; + if (Session()->IsDomain()) { + size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32); + } + } + for (auto& object : copy_objects) { Handle handle{}; if (object) { @@ -218,7 +230,7 @@ ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_t // Copy the translated command buffer back into the thread's command buffer area. memory.WriteBlock(owner_process, requesting_thread.GetTLSAddress(), cmd_buf.data(), - cmd_buf.size() * sizeof(u32)); + size * sizeof(u32)); return RESULT_SUCCESS; } diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h index 3e66e5542..4fba300dc 100644 --- a/src/core/hle/kernel/hle_ipc.h +++ b/src/core/hle/kernel/hle_ipc.h @@ -308,6 +308,7 @@ private: u32 data_payload_offset{}; u32 handles_offset{}; u32 domain_offset{}; + u32 data_size{}; u32_le command{}; std::vector> domain_request_handlers; From eee302b9b9feb325d5444eace51266d238b8e0b3 Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 11 May 2021 15:40:20 -0700 Subject: [PATCH 22/22] common: tree: Avoid a nullptr dereference. --- src/common/tree.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/tree.h b/src/common/tree.h index 3da49e422..9d2d0df4e 100644 --- a/src/common/tree.h +++ b/src/common/tree.h @@ -322,7 +322,7 @@ void RB_INSERT_COLOR(RBHead* head, Node* elm) { template void RB_REMOVE_COLOR(RBHead* head, Node* parent, Node* elm) { Node* tmp; - while ((elm == nullptr || RB_IS_BLACK(elm)) && elm != head->Root()) { + while ((elm == nullptr || RB_IS_BLACK(elm)) && elm != head->Root() && parent != nullptr) { if (RB_LEFT(parent) == elm) { tmp = RB_RIGHT(parent); if (RB_IS_RED(tmp)) {