hle: Initial implementation of NX service framework and IPC.

This commit is contained in:
bunnei 2017-10-14 22:18:42 -04:00
parent 12c7469d81
commit 960a1416de
21 changed files with 578 additions and 863 deletions

View File

@ -32,7 +32,7 @@ namespace Log {
CLS(Kernel) \ CLS(Kernel) \
SUB(Kernel, SVC) \ SUB(Kernel, SVC) \
CLS(Service) \ CLS(Service) \
SUB(Service, SRV) \ SUB(Service, SM) \
SUB(Service, FS) \ SUB(Service, FS) \
SUB(Service, GSP) \ SUB(Service, GSP) \
SUB(Service, CFG) \ SUB(Service, CFG) \

View File

@ -49,7 +49,7 @@ enum class Class : ClassType {
Kernel_SVC, ///< Kernel system calls Kernel_SVC, ///< Kernel system calls
Service, ///< HLE implementation of system services. Each major service Service, ///< HLE implementation of system services. Each major service
/// should have its own subclass. /// should have its own subclass.
Service_SRV, ///< The SRV (Service Directory) implementation Service_SM, ///< The SRV (Service Directory) implementation
Service_FS, ///< The FS (Filesystem) service implementation Service_FS, ///< The FS (Filesystem) service implementation
Service_GSP, ///< The GSP (GPU control) service Service_GSP, ///< The GSP (GPU control) service
Service_CFG, ///< The CFG (Configuration) service Service_CFG, ///< The CFG (Configuration) service

View File

@ -51,9 +51,10 @@ set(SRCS
hle/service/dsp_dsp.cpp hle/service/dsp_dsp.cpp
hle/service/gsp_gpu.cpp hle/service/gsp_gpu.cpp
hle/service/hid/hid.cpp hle/service/hid/hid.cpp
hle/service/lm/lm.cpp
hle/service/service.cpp hle/service/service.cpp
hle/service/sm/controller.cpp
hle/service/sm/sm.cpp hle/service/sm/sm.cpp
hle/service/sm/srv.cpp
hle/shared_page.cpp hle/shared_page.cpp
hle/svc.cpp hle/svc.cpp
hw/aes/arithmetic128.cpp hw/aes/arithmetic128.cpp
@ -139,9 +140,10 @@ set(HEADERS
hle/service/dsp_dsp.h hle/service/dsp_dsp.h
hle/service/gsp_gpu.h hle/service/gsp_gpu.h
hle/service/hid/hid.h hle/service/hid/hid.h
hle/service/lm/lm.h
hle/service/service.h hle/service/service.h
hle/service/sm/controller.h
hle/service/sm/sm.h hle/service/sm/sm.h
hle/service/sm/srv.h
hle/shared_page.h hle/shared_page.h
hle/svc.h hle/svc.h
hw/aes/arithmetic128.h hw/aes/arithmetic128.h

View File

@ -5,43 +5,10 @@
#pragma once #pragma once
#include "common/common_types.h" #include "common/common_types.h"
#include "common/swap.h"
#include "core/hle/kernel/errors.h" #include "core/hle/kernel/errors.h"
#include "core/hle/kernel/thread.h"
#include "core/memory.h" #include "core/memory.h"
namespace Kernel {
/// Offset into command buffer of header
static const int kCommandHeaderOffset = 0x80;
/**
* Returns a pointer to the command buffer in the current thread's TLS
* TODO(Subv): This is not entirely correct, the command buffer should be copied from
* the thread's TLS to an intermediate buffer in kernel memory, and then copied again to
* the service handler process' memory.
* @param offset Optional offset into command buffer
* @param offset Optional offset into command buffer (in bytes)
* @return Pointer to command buffer
*/
inline u32* GetCommandBuffer(const int offset = 0) {
return (u32*)Memory::GetPointer(GetCurrentThread()->GetTLSAddress() + kCommandHeaderOffset +
offset);
}
/// Offset into static buffers, relative to command buffer header
static const int kStaticBuffersOffset = 0x100;
/**
* Returns a pointer to the static buffers area in the current thread's TLS
* TODO(Subv): cf. GetCommandBuffer
* @param offset Optional offset into static buffers area (in bytes)
* @return Pointer to static buffers area
*/
inline u32* GetStaticBuffers(const int offset = 0) {
return GetCommandBuffer(kStaticBuffersOffset + offset);
}
}
namespace IPC { namespace IPC {
/// Size of the command buffer area, in 32-bit words. /// Size of the command buffer area, in 32-bit words.
@ -53,6 +20,130 @@ constexpr size_t COMMAND_BUFFER_LENGTH = 0x100 / sizeof(u32);
using Kernel::ERR_INVALID_BUFFER_DESCRIPTOR; using Kernel::ERR_INVALID_BUFFER_DESCRIPTOR;
constexpr auto ERR_INVALID_HANDLE = Kernel::ERR_INVALID_HANDLE_OS; constexpr auto ERR_INVALID_HANDLE = Kernel::ERR_INVALID_HANDLE_OS;
enum class ControlCommand : u32 {
ConvertSessionToDomain = 0,
ConvertDomainToSession = 1,
DuplicateSession = 2,
QueryPointerBufferSize = 3,
DuplicateSessionEx = 4,
Unspecified,
};
enum class CommandType : u32 {
Close = 2,
Request = 4,
Control = 5,
Unspecified,
};
struct CommandHeader {
union {
u32_le raw_low;
BitField<0, 16, CommandType> type;
BitField<16, 4, u32_le> num_buf_x_descriptors;
BitField<20, 4, u32_le> num_buf_a_descriptors;
BitField<24, 4, u32_le> num_buf_b_descriptors;
BitField<28, 4, u32_le> num_buf_w_descriptors;
};
enum class BufferDescriptorCFlag : u32 {
Disabled = 0,
NoDescriptor = 1,
TwoDesciptors = 2,
};
union {
u32_le raw_high;
BitField<0, 10, u32_le> data_size;
BitField<10, 4, BufferDescriptorCFlag> buf_c_descriptor_flags;
BitField<31, 1, u32_le> enable_handle_descriptor;
};
};
static_assert(sizeof(CommandHeader) == 8, "CommandHeader size is incorrect");
union HandleDescriptorHeader {
u32_le raw_high;
BitField<0, 1, u32_le> send_current_pid;
BitField<1, 4, u32_le> num_handles_to_copy;
BitField<5, 4, u32_le> num_handles_to_move;
};
static_assert(sizeof(HandleDescriptorHeader) == 4, "HandleDescriptorHeader size is incorrect");
struct BufferDescriptorX {
union {
BitField<0, 6, u32_le> counter_bits_0_5;
BitField<6, 3, u32_le> address_bits_36_38;
BitField<9, 3, u32_le> counter_bits_9_11;
BitField<12, 4, u32_le> address_bits_32_35;
BitField<16, 16, u32_le> size;
};
u32_le address_bits_0_31;
u32_le Counter() const {
u32_le counter{ counter_bits_0_5 };
counter |= counter_bits_9_11 << 9;
return counter;
}
VAddr Address() const {
VAddr address{ address_bits_0_31 };
address |= static_cast<VAddr>(address_bits_32_35) << 32;
address |= static_cast<VAddr>(address_bits_36_38) << 36;
return address;
}
};
static_assert(sizeof(BufferDescriptorX) == 8, "BufferDescriptorX size is incorrect");
struct BufferDescriptorABW {
u32_le size_bits_0_31;
u32_le address_bits_0_31;
union {
BitField<0, 2, u32_le> flags;
BitField<2, 3, u32_le> address_bits_36_38;
BitField<24, 4, u32_le> size_bits_32_35;
BitField<28, 4, u32_le> address_bits_32_35;
};
VAddr Address() const {
VAddr address{ address_bits_0_31 };
address |= static_cast<VAddr>(address_bits_32_35) << 32;
address |= static_cast<VAddr>(address_bits_36_38) << 36;
return address;
}
u64 Size() const {
u64 size{ size_bits_0_31 };
size |= static_cast<u64>(size_bits_32_35) << 32;
return size;
}
};
static_assert(sizeof(BufferDescriptorABW) == 12, "BufferDescriptorABW size is incorrect");
struct BufferDescriptorC {
u32_le address_bits_0_31;
union {
BitField<0, 16, u32_le> address_bits_32_47;
BitField<16, 16, u32_le> size;
};
VAddr Address() const {
VAddr address{ address_bits_0_31 };
address |= static_cast<VAddr>(address_bits_32_47) << 32;
return address;
}
};
static_assert(sizeof(BufferDescriptorC) == 8, "BufferDescriptorC size is incorrect");
struct DataPayloadHeader {
u32_le magic;
INSERT_PADDING_WORDS(1);
};
static_assert(sizeof(DataPayloadHeader) == 8, "DataPayloadRequest size is incorrect");
enum DescriptorType : u32 { enum DescriptorType : u32 {
// Buffer related desciptors types (mask : 0x0F) // Buffer related desciptors types (mask : 0x0F)
StaticBuffer = 0x02, StaticBuffer = 0x02,
@ -65,36 +156,6 @@ enum DescriptorType : u32 {
CallingPid = 0x20, CallingPid = 0x20,
}; };
union Header {
u32 raw;
BitField<0, 6, u32> translate_params_size;
BitField<6, 6, u32> normal_params_size;
BitField<16, 16, u32> command_id;
};
/**
* @brief Creates a command header to be used for IPC
* @param command_id ID of the command to create a header for.
* @param normal_params_size Size of the normal parameters in words. Up to 63.
* @param translate_params_size Size of the translate parameters in words. Up to 63.
* @return The created IPC header.
*
* Normal parameters are sent directly to the process while the translate parameters might go
* through modifications and checks by the kernel.
* The translate parameters are described by headers generated with the IPC::*Desc functions.
*
* @note While @p normal_params_size is equivalent to the number of normal parameters,
* @p translate_params_size includes the size occupied by the translate parameters headers.
*/
inline u32 MakeHeader(u16 command_id, unsigned int normal_params_size,
unsigned int translate_params_size) {
Header header{};
header.command_id.Assign(command_id);
header.normal_params_size.Assign(normal_params_size);
header.translate_params_size.Assign(translate_params_size);
return header.raw;
}
constexpr u32 MoveHandleDesc(u32 num_handles = 1) { constexpr u32 MoveHandleDesc(u32 num_handles = 1) {
return MoveHandle | ((num_handles - 1) << 26); return MoveHandle | ((num_handles - 1) << 26);
} }

View File

@ -19,24 +19,17 @@ class RequestHelperBase {
protected: protected:
Kernel::HLERequestContext* context = nullptr; Kernel::HLERequestContext* context = nullptr;
u32* cmdbuf; u32* cmdbuf;
ptrdiff_t index = 1; ptrdiff_t index = 0;
Header header;
public: public:
RequestHelperBase(Kernel::HLERequestContext& context, Header desired_header) RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
: context(&context), cmdbuf(context.CommandBuffer()), header(desired_header) {}
RequestHelperBase(u32* command_buffer, Header command_header) RequestHelperBase(Kernel::HLERequestContext& context)
: cmdbuf(command_buffer), header(command_header) {} : context(&context), cmdbuf(context.CommandBuffer()) {}
/// Returns the total size of the request in words
size_t TotalSize() const {
return 1 /* command header */ + header.normal_params_size + header.translate_params_size;
}
void ValidateHeader() { void ValidateHeader() {
DEBUG_ASSERT_MSG(index == TotalSize(), "Operations do not match the header (cmd 0x%x)", // DEBUG_ASSERT_MSG(index == TotalSize(), "Operations do not match the header (cmd 0x%x)",
header.raw); // header.raw);
} }
void Skip(unsigned size_in_words, bool set_to_null) { void Skip(unsigned size_in_words, bool set_to_null) {
@ -46,46 +39,51 @@ public:
} }
/** /**
* @brief Retrieves the address of a static buffer, used when a buffer is needed for output * Aligns the current position forward to a 16-byte boundary, padding with zeros. Jumps forward
* @param buffer_id The index of the static buffer * by 16-bytes at a minimum.
* @param data_size If non-null, will store the size of the buffer
*/ */
VAddr PeekStaticBuffer(u8 buffer_id, size_t* data_size = nullptr) const { void AlignWithPadding() {
u32* static_buffer = cmdbuf + Kernel::kStaticBuffersOffset / sizeof(u32) + buffer_id * 2; Skip(4 - (index & 3), true);
if (data_size) }
*data_size = StaticBufferDescInfo{static_buffer[0]}.size;
return static_buffer[1]; unsigned GetCurrentOffset() const {
return static_cast<unsigned>(index);
} }
}; };
class RequestBuilder : public RequestHelperBase { class RequestBuilder : public RequestHelperBase {
public: public:
RequestBuilder(Kernel::HLERequestContext& context, Header command_header) RequestBuilder(u32* command_buffer) : RequestHelperBase(command_buffer) {}
: RequestHelperBase(context, command_header) {
// From this point we will start overwriting the existing command buffer, so it's safe to RequestBuilder(Kernel::HLERequestContext& context, unsigned normal_params_size,
// release all previous incoming Object pointers since they won't be usable anymore. u32 num_handles_to_copy = 0, u32 num_handles_to_move = 0)
: RequestHelperBase(context) {
memset(cmdbuf, 0, 64);
context.ClearIncomingObjects(); context.ClearIncomingObjects();
cmdbuf[0] = header.raw;
IPC::CommandHeader header{};
header.data_size.Assign(normal_params_size * sizeof(u32));
if (num_handles_to_copy || num_handles_to_move) {
header.enable_handle_descriptor.Assign(1);
}
PushRaw(header);
if (header.enable_handle_descriptor) {
IPC::HandleDescriptorHeader handle_descriptor_header{};
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);
Skip(num_handles_to_copy + num_handles_to_move, true);
} }
RequestBuilder(Kernel::HLERequestContext& context, u16 command_id, unsigned normal_params_size, AlignWithPadding();
unsigned translate_params_size)
: RequestBuilder(
context, Header{MakeHeader(command_id, normal_params_size, translate_params_size)}) {}
RequestBuilder(u32* command_buffer, Header command_header) IPC::DataPayloadHeader data_payload_header{};
: RequestHelperBase(command_buffer, command_header) { data_payload_header.magic = 0x4f434653;
cmdbuf[0] = header.raw; PushRaw(data_payload_header);
} }
explicit RequestBuilder(u32* command_buffer, u32 command_header)
: RequestBuilder(command_buffer, Header{command_header}) {}
RequestBuilder(u32* command_buffer, u16 command_id, unsigned normal_params_size,
unsigned translate_params_size)
: RequestBuilder(command_buffer,
MakeHeader(command_id, normal_params_size, translate_params_size)) {}
// Validate on destruction, as there shouldn't be any case where we don't want it // Validate on destruction, as there shouldn't be any case where we don't want it
~RequestBuilder() { ~RequestBuilder() {
ValidateHeader(); ValidateHeader();
@ -131,7 +129,6 @@ inline void RequestBuilder::Push(u32 value) {
template <typename T> template <typename T>
void RequestBuilder::PushRaw(const T& value) { void RequestBuilder::PushRaw(const T& value) {
static_assert(std::is_trivially_copyable<T>(), "Raw types should be trivially copyable");
std::memcpy(cmdbuf + index, &value, sizeof(T)); std::memcpy(cmdbuf + index, &value, sizeof(T));
index += (sizeof(T) + 3) / 4; // round up to word length index += (sizeof(T) + 3) / 4; // round up to word length
} }
@ -203,36 +200,20 @@ inline void RequestBuilder::PushMappedBuffer(VAddr buffer_vaddr, size_t size,
class RequestParser : public RequestHelperBase { class RequestParser : public RequestHelperBase {
public: public:
RequestParser(Kernel::HLERequestContext& context, Header desired_header) RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
: RequestHelperBase(context, desired_header) {}
RequestParser(Kernel::HLERequestContext& context, u16 command_id, unsigned normal_params_size, RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
unsigned translate_params_size) ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
: RequestParser(context, Skip(context.GetDataPayloadOffset(), false);
Header{MakeHeader(command_id, normal_params_size, translate_params_size)}) {
} }
RequestParser(u32* command_buffer, Header command_header) RequestBuilder MakeBuilder(u32 normal_params_size, u32 num_handles_to_copy,
: RequestHelperBase(command_buffer, command_header) {} u32 num_handles_to_move, bool validate_header = true) {
if (validate_header) {
explicit RequestParser(u32* command_buffer, u32 command_header)
: RequestParser(command_buffer, Header{command_header}) {}
RequestParser(u32* command_buffer, u16 command_id, unsigned normal_params_size,
unsigned translate_params_size)
: RequestParser(command_buffer,
MakeHeader(command_id, normal_params_size, translate_params_size)) {}
RequestBuilder MakeBuilder(u32 normal_params_size, u32 translate_params_size,
bool validateHeader = true) {
if (validateHeader)
ValidateHeader(); ValidateHeader();
Header builderHeader{MakeHeader(static_cast<u16>(header.command_id), normal_params_size, }
translate_params_size)};
if (context != nullptr) return {*context, normal_params_size, num_handles_to_copy, num_handles_to_move};
return {*context, builderHeader};
else
return {cmdbuf, builderHeader};
} }
template <typename T> template <typename T>
@ -342,7 +323,6 @@ inline u32 RequestParser::Pop() {
template <typename T> template <typename T>
void RequestParser::PopRaw(T& value) { void RequestParser::PopRaw(T& value) {
static_assert(std::is_trivially_copyable<T>(), "Raw types should be trivially copyable");
std::memcpy(&value, cmdbuf + index, sizeof(T)); std::memcpy(&value, cmdbuf + index, sizeof(T));
index += (sizeof(T) + 3) / 4; // round up to word length index += (sizeof(T) + 3) / 4; // round up to word length
} }

View File

@ -5,6 +5,7 @@
#include <boost/range/algorithm_ext/erase.hpp> #include <boost/range/algorithm_ext/erase.hpp>
#include "common/assert.h" #include "common/assert.h"
#include "common/common_types.h" #include "common/common_types.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/handle_table.h"
#include "core/hle/kernel/hle_ipc.h" #include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/kernel.h" #include "core/hle/kernel/kernel.h"
@ -44,83 +45,97 @@ void HLERequestContext::ClearIncomingObjects() {
request_handles.clear(); request_handles.clear();
} }
ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const u32_le* src_cmdbuf, void HLERequestContext::ParseCommandBuffer(u32_le* src_cmdbuf) {
IPC::RequestParser rp(src_cmdbuf);
command_header = std::make_unique<IPC::CommandHeader>(rp.PopRaw<IPC::CommandHeader>());
// If handle descriptor is present, add size of it
if (command_header->enable_handle_descriptor) {
handle_descriptor_header =
std::make_unique<IPC::HandleDescriptorHeader>(rp.PopRaw<IPC::HandleDescriptorHeader>());
if (handle_descriptor_header->send_current_pid) {
rp.Skip(2, false);
}
rp.Skip(handle_descriptor_header->num_handles_to_copy, false);
rp.Skip(handle_descriptor_header->num_handles_to_move, false);
}
// Padding to align to 16 bytes
rp.AlignWithPadding();
if (command_header->num_buf_x_descriptors) {
UNIMPLEMENTED();
}
if (command_header->num_buf_a_descriptors) {
UNIMPLEMENTED();
}
if (command_header->num_buf_b_descriptors) {
UNIMPLEMENTED();
}
if (command_header->num_buf_w_descriptors) {
UNIMPLEMENTED();
}
if (command_header->buf_c_descriptor_flags !=
IPC::CommandHeader::BufferDescriptorCFlag::Disabled) {
UNIMPLEMENTED();
}
data_payload_header =
std::make_unique<IPC::DataPayloadHeader>(rp.PopRaw<IPC::DataPayloadHeader>());
ASSERT(data_payload_header->magic == 0x49434653 || data_payload_header->magic == 0x4F434653);
data_payload_offset = rp.GetCurrentOffset();
command = rp.Pop<u32_le>();
}
ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(u32_le* src_cmdbuf,
Process& src_process, Process& src_process,
HandleTable& src_table) { HandleTable& src_table) {
IPC::Header header{src_cmdbuf[0]}; ParseCommandBuffer(src_cmdbuf);
size_t untranslated_size = data_payload_offset + command_header->data_size;
size_t untranslated_size = 1u + header.normal_params_size;
size_t command_size = untranslated_size + header.translate_params_size;
ASSERT(command_size <= IPC::COMMAND_BUFFER_LENGTH); // TODO(yuriks): Return error
std::copy_n(src_cmdbuf, untranslated_size, cmd_buf.begin()); std::copy_n(src_cmdbuf, untranslated_size, cmd_buf.begin());
size_t i = untranslated_size; if (command_header->enable_handle_descriptor) {
while (i < command_size) { if (handle_descriptor_header->num_handles_to_copy ||
u32 descriptor = cmd_buf[i] = src_cmdbuf[i]; handle_descriptor_header->num_handles_to_move) {
i += 1; UNIMPLEMENTED();
switch (IPC::GetDescriptorType(descriptor)) {
case IPC::DescriptorType::CopyHandle:
case IPC::DescriptorType::MoveHandle: {
u32 num_handles = IPC::HandleNumberFromDesc(descriptor);
ASSERT(i + num_handles <= command_size); // TODO(yuriks): Return error
for (u32 j = 0; j < num_handles; ++j) {
Handle handle = src_cmdbuf[i];
SharedPtr<Object> object = nullptr;
if (handle != 0) {
object = src_table.GetGeneric(handle);
ASSERT(object != nullptr); // TODO(yuriks): Return error
if (descriptor == IPC::DescriptorType::MoveHandle) {
src_table.Close(handle);
} }
} }
cmd_buf[i++] = AddOutgoingHandle(std::move(object));
}
break;
}
case IPC::DescriptorType::CallingPid: {
cmd_buf[i++] = src_process.process_id;
break;
}
default:
UNIMPLEMENTED_MSG("Unsupported handle translation: 0x%08X", descriptor);
}
}
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }
ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(u32_le* dst_cmdbuf, Process& dst_process, ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(u32_le* dst_cmdbuf, Process& dst_process,
HandleTable& dst_table) const { HandleTable& dst_table) {
IPC::Header header{cmd_buf[0]}; ParseCommandBuffer(&cmd_buf[0]);
size_t untranslated_size = data_payload_offset + command_header->data_size;
size_t untranslated_size = 1u + header.normal_params_size;
size_t command_size = untranslated_size + header.translate_params_size;
ASSERT(command_size <= IPC::COMMAND_BUFFER_LENGTH);
std::copy_n(cmd_buf.begin(), untranslated_size, dst_cmdbuf); std::copy_n(cmd_buf.begin(), untranslated_size, dst_cmdbuf);
size_t i = untranslated_size; if (command_header->enable_handle_descriptor) {
while (i < command_size) { size_t command_size = untranslated_size + handle_descriptor_header->num_handles_to_copy +
u32 descriptor = dst_cmdbuf[i] = cmd_buf[i]; handle_descriptor_header->num_handles_to_move;
i += 1; ASSERT(command_size <= IPC::COMMAND_BUFFER_LENGTH);
size_t untranslated_index = untranslated_size;
size_t handle_write_offset = 3;
while (untranslated_index < command_size) {
u32 descriptor = cmd_buf[untranslated_index];
untranslated_index += 1;
switch (IPC::GetDescriptorType(descriptor)) { switch (IPC::GetDescriptorType(descriptor)) {
case IPC::DescriptorType::CopyHandle: case IPC::DescriptorType::CopyHandle:
case IPC::DescriptorType::MoveHandle: { case IPC::DescriptorType::MoveHandle: {
// HLE services don't use handles, so we treat both CopyHandle and MoveHandle equally // HLE services don't use handles, so we treat both CopyHandle and MoveHandle
// equally
u32 num_handles = IPC::HandleNumberFromDesc(descriptor); u32 num_handles = IPC::HandleNumberFromDesc(descriptor);
ASSERT(i + num_handles <= command_size);
for (u32 j = 0; j < num_handles; ++j) { for (u32 j = 0; j < num_handles; ++j) {
SharedPtr<Object> object = GetIncomingHandle(cmd_buf[i]); SharedPtr<Object> object = GetIncomingHandle(cmd_buf[untranslated_index]);
Handle handle = 0; Handle handle = 0;
if (object != nullptr) { if (object != nullptr) {
// TODO(yuriks): Figure out the proper error handling for if this fails // TODO(yuriks): Figure out the proper error handling for if this fails
handle = dst_table.Create(object).Unwrap(); handle = dst_table.Create(object).Unwrap();
} }
dst_cmdbuf[i++] = handle; dst_cmdbuf[handle_write_offset++] = handle;
untranslated_index++;
} }
break; break;
} }
@ -128,6 +143,7 @@ ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(u32_le* dst_cmdbuf, P
UNIMPLEMENTED_MSG("Unsupported handle translation: 0x%08X", descriptor); UNIMPLEMENTED_MSG("Unsupported handle translation: 0x%08X", descriptor);
} }
} }
}
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }

View File

@ -119,18 +119,39 @@ public:
*/ */
void ClearIncomingObjects(); void ClearIncomingObjects();
void ParseCommandBuffer(u32_le* src_cmdbuf);
/// Populates this context with data from the requesting process/thread. /// Populates this context with data from the requesting process/thread.
ResultCode PopulateFromIncomingCommandBuffer(const u32_le* src_cmdbuf, Process& src_process, ResultCode PopulateFromIncomingCommandBuffer(u32_le* src_cmdbuf, Process& src_process,
HandleTable& src_table); HandleTable& src_table);
/// Writes data from this context back to the requesting process/thread. /// Writes data from this context back to the requesting process/thread.
ResultCode WriteToOutgoingCommandBuffer(u32_le* dst_cmdbuf, Process& dst_process, ResultCode WriteToOutgoingCommandBuffer(u32_le* dst_cmdbuf, Process& dst_process,
HandleTable& dst_table) const; HandleTable& dst_table);
u32_le GetCommand() const {
return command;
}
IPC::CommandType GetCommandType() const {
return command_header->type;
}
unsigned GetDataPayloadOffset() const {
return data_payload_offset;
}
private: private:
std::array<u32, IPC::COMMAND_BUFFER_LENGTH> cmd_buf; std::array<u32, IPC::COMMAND_BUFFER_LENGTH> cmd_buf;
SharedPtr<ServerSession> session; SharedPtr<ServerSession> session;
// TODO(yuriks): Check common usage of this and optimize size accordingly // TODO(yuriks): Check common usage of this and optimize size accordingly
boost::container::small_vector<SharedPtr<Object>, 8> request_handles; boost::container::small_vector<SharedPtr<Object>, 8> request_handles;
std::unique_ptr<IPC::CommandHeader> command_header;
std::unique_ptr<IPC::HandleDescriptorHeader> handle_descriptor_header;
std::unique_ptr<IPC::DataPayloadHeader> data_payload_header;
unsigned data_payload_offset{};
u32_le command{};
}; };
} // namespace Kernel } // namespace Kernel

View File

@ -0,0 +1,43 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/logging/log.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/service/lm/lm.h"
namespace Service {
namespace LM {
void InstallInterfaces(SM::ServiceManager& service_manager) {
std::make_shared<LM>()->InstallAsService(service_manager);
}
/**
* SRV::Initialize service function
* Inputs:
* 0: 0x00000000
* Outputs:
* 1: ResultCode
*/
void LM::Initialize(Kernel::HLERequestContext& ctx) {
IPC::RequestBuilder rb{ctx, 1};
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_SM, "(STUBBED) called");
}
LM::LM() : ServiceFramework("lm") {
static const FunctionInfo functions[] = {
{0x00000000, &LM::Initialize, "Initialize"},
{0x00000001, nullptr, "Unknown2"},
{0x00000002, nullptr, "Unknown3"},
{0x00000003, nullptr, "Unknown4"},
{0x00000004, nullptr, "Unknown5"},
};
RegisterHandlers(functions);
}
LM::~LM() = default;
} // namespace LM
} // namespace Service

View File

@ -0,0 +1,25 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "core/hle/service/service.h"
namespace Service {
namespace LM {
class LM final : public ServiceFramework<LM> {
public:
explicit LM();
~LM();
private:
void Initialize(Kernel::HLERequestContext& ctx);
};
/// Registers all LM services with the specified service manager.
void InstallInterfaces(SM::ServiceManager& service_manager);
} // namespace LM
} // namespace Service

View File

@ -8,17 +8,20 @@
#include "common/logging/log.h" #include "common/logging/log.h"
#include "common/string_util.h" #include "common/string_util.h"
#include "core/hle/ipc.h" #include "core/hle/ipc.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/client_port.h" #include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/process.h" #include "core/hle/kernel/process.h"
#include "core/hle/kernel/server_port.h" #include "core/hle/kernel/server_port.h"
#include "core/hle/kernel/server_session.h" #include "core/hle/kernel/server_session.h"
#include "core/hle/kernel/thread.h"
#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/handle_table.h"
#include "core/hle/service/dsp_dsp.h" #include "core/hle/service/dsp_dsp.h"
#include "core/hle/service/gsp_gpu.h" #include "core/hle/service/gsp_gpu.h"
#include "core/hle/service/hid/hid.h" #include "core/hle/service/hid/hid.h"
#include "core/hle/service/lm/lm.h"
#include "core/hle/service/service.h" #include "core/hle/service/service.h"
#include "core/hle/service/sm/controller.h"
#include "core/hle/service/sm/sm.h" #include "core/hle/service/sm/sm.h"
#include "core/hle/service/sm/srv.h"
using Kernel::ClientPort; using Kernel::ClientPort;
using Kernel::ServerPort; using Kernel::ServerPort;
@ -46,42 +49,6 @@ static std::string MakeFunctionString(const char* name, const char* port_name,
return function_string; return function_string;
} }
Interface::Interface(u32 max_sessions) : max_sessions(max_sessions) {}
Interface::~Interface() = default;
void Interface::HandleSyncRequest(SharedPtr<ServerSession> server_session) {
// TODO(Subv): Make use of the server_session in the HLE service handlers to distinguish which
// session triggered each command.
u32* cmd_buff = Kernel::GetCommandBuffer();
auto itr = m_functions.find(cmd_buff[0]);
if (itr == m_functions.end() || itr->second.func == nullptr) {
std::string function_name = (itr == m_functions.end())
? Common::StringFromFormat("0x%08X", cmd_buff[0])
: itr->second.name;
LOG_ERROR(
Service, "unknown / unimplemented %s",
MakeFunctionString(function_name.c_str(), GetPortName().c_str(), cmd_buff).c_str());
// TODO(bunnei): Hack - ignore error
cmd_buff[1] = 0;
return;
}
LOG_TRACE(Service, "%s",
MakeFunctionString(itr->second.name, GetPortName().c_str(), cmd_buff).c_str());
itr->second.func(this);
}
void Interface::Register(const FunctionInfo* functions, size_t n) {
m_functions.reserve(n);
for (size_t i = 0; i < n; ++i) {
// Usually this array is sorted by id already, so hint to instead at the end
m_functions.emplace_hint(m_functions.cend(), functions[i].id, functions[i]);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
ServiceFrameworkBase::ServiceFrameworkBase(const char* service_name, u32 max_sessions, ServiceFrameworkBase::ServiceFrameworkBase(const char* service_name, u32 max_sessions,
@ -113,33 +80,38 @@ void ServiceFrameworkBase::RegisterHandlersBase(const FunctionInfoBase* function
} }
} }
void ServiceFrameworkBase::ReportUnimplementedFunction(u32* cmd_buf, const FunctionInfoBase* info) { void ServiceFrameworkBase::ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, const FunctionInfoBase* info) {
IPC::Header header{cmd_buf[0]}; auto cmd_buf = ctx.CommandBuffer();
int num_params = header.normal_params_size + header.translate_params_size;
std::string function_name = info == nullptr ? fmt::format("{:#08x}", cmd_buf[0]) : info->name; std::string function_name = info == nullptr ? fmt::format("{:#08x}", cmd_buf[0]) : info->name;
fmt::MemoryWriter w; fmt::MemoryWriter w;
w.write("function '{}': port='{}' cmd_buf={{[0]={:#x}", function_name, service_name, w.write("function '{}': port='{}' cmd_buf={{[0]={:#x}", function_name, service_name,
cmd_buf[0]); cmd_buf[0]);
for (int i = 1; i <= num_params; ++i) { for (int i = 1; i <= 8; ++i) {
w.write(", [{}]={:#x}", i, cmd_buf[i]); w.write(", [{}]={:#x}", i, cmd_buf[i]);
} }
w << '}'; w << '}';
LOG_ERROR(Service, "unknown / unimplemented %s", w.c_str()); LOG_ERROR(Service, "unknown / unimplemented %s", w.c_str());
// TODO(bunnei): Hack - ignore error // TODO(bunnei): Hack - ignore error
cmd_buf[1] = 0; IPC::RequestBuilder rb{ ctx, 1 };
rb.Push(RESULT_SUCCESS);
}
void ServiceFrameworkBase::InvokeRequest(Kernel::HLERequestContext& ctx) {
auto itr = handlers.find(ctx.GetCommand());
const FunctionInfoBase* info = itr == handlers.end() ? nullptr : &itr->second;
if (info == nullptr || info->handler_callback == nullptr) {
return ReportUnimplementedFunction(ctx, info);
}
LOG_TRACE(Service, "%s",
MakeFunctionString(info->name, GetServiceName().c_str(), ctx.CommandBuffer()).c_str());
handler_invoker(this, info->handler_callback, ctx);
} }
void ServiceFrameworkBase::HandleSyncRequest(SharedPtr<ServerSession> server_session) { void ServiceFrameworkBase::HandleSyncRequest(SharedPtr<ServerSession> server_session) {
u32* cmd_buf = Kernel::GetCommandBuffer(); u32* cmd_buf = (u32*)Memory::GetPointer(Kernel::GetCurrentThread()->GetTLSAddress());;
u32 header_code = cmd_buf[0];
auto itr = handlers.find(header_code);
const FunctionInfoBase* info = itr == handlers.end() ? nullptr : &itr->second;
if (info == nullptr || info->handler_callback == nullptr) {
return ReportUnimplementedFunction(cmd_buf, info);
}
// TODO(yuriks): The kernel should be the one handling this as part of translation after // TODO(yuriks): The kernel should be the one handling this as part of translation after
// everything else is migrated // everything else is migrated
@ -147,9 +119,27 @@ void ServiceFrameworkBase::HandleSyncRequest(SharedPtr<ServerSession> server_ses
context.PopulateFromIncomingCommandBuffer(cmd_buf, *Kernel::g_current_process, context.PopulateFromIncomingCommandBuffer(cmd_buf, *Kernel::g_current_process,
Kernel::g_handle_table); Kernel::g_handle_table);
LOG_TRACE(Service, "%s", switch (context.GetCommandType()) {
MakeFunctionString(info->name, GetServiceName().c_str(), cmd_buf).c_str()); case IPC::CommandType::Close:
handler_invoker(this, info->handler_callback, context); {
IPC::RequestBuilder rb{context, 1};
rb.Push(RESULT_SUCCESS);
break;
}
case IPC::CommandType::Control:
{
SM::g_service_manager->InvokeControlRequest(context);
break;
}
case IPC::CommandType::Request:
{
InvokeRequest(context);
break;
}
default:
UNIMPLEMENTED_MSG("command_type=%d", context.GetCommandType());
}
context.WriteToOutgoingCommandBuffer(cmd_buf, *Kernel::g_current_process, context.WriteToOutgoingCommandBuffer(cmd_buf, *Kernel::g_current_process,
Kernel::g_handle_table); Kernel::g_handle_table);
} }
@ -162,33 +152,14 @@ void AddNamedPort(std::string name, SharedPtr<ClientPort> port) {
g_kernel_named_ports.emplace(std::move(name), std::move(port)); g_kernel_named_ports.emplace(std::move(name), std::move(port));
} }
static void AddNamedPort(Interface* interface_) {
SharedPtr<ServerPort> server_port;
SharedPtr<ClientPort> client_port;
std::tie(server_port, client_port) =
ServerPort::CreatePortPair(interface_->GetMaxSessions(), interface_->GetPortName());
server_port->SetHleHandler(std::shared_ptr<Interface>(interface_));
AddNamedPort(interface_->GetPortName(), std::move(client_port));
}
void AddService(Interface* interface_) {
auto server_port =
SM::g_service_manager
->RegisterService(interface_->GetPortName(), interface_->GetMaxSessions())
.Unwrap();
server_port->SetHleHandler(std::shared_ptr<Interface>(interface_));
}
/// Initialize ServiceManager /// Initialize ServiceManager
void Init() { void Init() {
SM::g_service_manager = std::make_shared<SM::ServiceManager>(); SM::g_service_manager = std::make_shared<SM::ServiceManager>();
SM::ServiceManager::InstallInterfaces(SM::g_service_manager); SM::ServiceManager::InstallInterfaces(SM::g_service_manager);
HID::Init(); LM::InstallInterfaces(*SM::g_service_manager);
AddService(new DSP_DSP::Interface); HID::Init();
AddService(new GSP::GSP_GPU);
LOG_DEBUG(Service, "initialized OK"); LOG_DEBUG(Service, "initialized OK");
} }

View File

@ -20,6 +20,7 @@ namespace Kernel {
class ClientPort; class ClientPort;
class ServerPort; class ServerPort;
class ServerSession; class ServerSession;
class HLERequestContext;
} }
namespace Service { namespace Service {
@ -32,83 +33,6 @@ static const int kMaxPortSize = 8; ///< Maximum size of a port name (8 character
/// Arbitrary default number of maximum connections to an HLE service. /// Arbitrary default number of maximum connections to an HLE service.
static const u32 DefaultMaxSessions = 10; static const u32 DefaultMaxSessions = 10;
/**
* Framework for implementing HLE service handlers which dispatch incoming SyncRequests based on a
* table mapping header ids to handler functions.
*
* @deprecated Use ServiceFramework for new services instead. It allows services to be stateful and
* is more extensible going forward.
*/
class Interface : public Kernel::SessionRequestHandler {
public:
/**
* Creates an HLE interface with the specified max sessions.
* @param max_sessions Maximum number of sessions that can be
* connected to this service at the same time.
*/
Interface(u32 max_sessions = DefaultMaxSessions);
virtual ~Interface();
std::string GetName() const {
return GetPortName();
}
virtual void SetVersion(u32 raw_version) {
version.raw = raw_version;
}
/**
* Gets the maximum allowed number of sessions that can be connected to this service
* at the same time.
* @returns The maximum number of connections allowed.
*/
u32 GetMaxSessions() const {
return max_sessions;
}
typedef void (*Function)(Interface*);
struct FunctionInfo {
u32 id;
Function func;
const char* name;
};
/**
* Gets the string name used by CTROS for a service
* @return Port name of service
*/
virtual std::string GetPortName() const {
return "[UNKNOWN SERVICE PORT]";
}
protected:
void HandleSyncRequest(Kernel::SharedPtr<Kernel::ServerSession> server_session) override;
/**
* Registers the functions in the service
*/
template <size_t N>
inline void Register(const FunctionInfo (&functions)[N]) {
Register(functions, N);
}
void Register(const FunctionInfo* functions, size_t n);
union {
u32 raw;
BitField<0, 8, u32> major;
BitField<8, 8, u32> minor;
BitField<16, 8, u32> build;
BitField<24, 8, u32> revision;
} version = {};
private:
u32 max_sessions; ///< Maximum number of concurrent sessions that this service can handle.
boost::container::flat_map<u32, FunctionInfo> m_functions;
};
/** /**
* This is an non-templated base of ServiceFramework to reduce code bloat and compilation times, it * This is an non-templated base of ServiceFramework to reduce code bloat and compilation times, it
* is not meant to be used directly. * is not meant to be used directly.
@ -135,6 +59,8 @@ public:
/// Creates a port pair and registers it on the kernel's global port registry. /// Creates a port pair and registers it on the kernel's global port registry.
void InstallAsNamedPort(); void InstallAsNamedPort();
void InvokeRequest(Kernel::HLERequestContext& ctx);
void HandleSyncRequest(Kernel::SharedPtr<Kernel::ServerSession> server_session) override; void HandleSyncRequest(Kernel::SharedPtr<Kernel::ServerSession> server_session) override;
protected: protected:
@ -159,7 +85,7 @@ private:
~ServiceFrameworkBase(); ~ServiceFrameworkBase();
void RegisterHandlersBase(const FunctionInfoBase* functions, size_t n); void RegisterHandlersBase(const FunctionInfoBase* functions, size_t n);
void ReportUnimplementedFunction(u32* cmd_buf, const FunctionInfoBase* info); void ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, const FunctionInfoBase* info);
/// Identifier string used to connect to the service. /// Identifier string used to connect to the service.
std::string service_name; std::string service_name;
@ -260,7 +186,5 @@ extern std::unordered_map<std::string, Kernel::SharedPtr<Kernel::ClientPort>> g_
/// Adds a port to the named port table /// Adds a port to the named port table
void AddNamedPort(std::string name, Kernel::SharedPtr<Kernel::ClientPort> port); void AddNamedPort(std::string name, Kernel::SharedPtr<Kernel::ClientPort> port);
/// Adds a service to the services table
void AddService(Interface* interface_);
} // namespace } // namespace

View File

@ -0,0 +1,42 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/logging/log.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/service/sm/controller.h"
namespace Service {
namespace SM {
/**
* Controller::QueryPointerBufferSize service function
* Inputs:
* 0: 0x00000003
* Outputs:
* 1: ResultCode
* 3: Size of memory
*/
void Controller::QueryPointerBufferSize(Kernel::HLERequestContext& ctx) {
IPC::RequestBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
rb.Push(0x0U);
rb.Push(0x500U);
LOG_WARNING(Service, "(STUBBED) called");
}
Controller::Controller() : ServiceFramework("IpcController") {
static const FunctionInfo functions[] = {
{0x00000000, nullptr, "ConvertSessionToDomain"},
{0x00000001, nullptr, "ConvertDomainToSession"},
{0x00000002, nullptr, "DuplicateSession"},
{0x00000003, &Controller::QueryPointerBufferSize, "QueryPointerBufferSize"},
{0x00000004, nullptr, "DuplicateSessionEx"},
};
RegisterHandlers(functions);
}
Controller::~Controller() = default;
} // namespace SM
} // namespace Service

View File

@ -0,0 +1,22 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "core/hle/service/service.h"
namespace Service {
namespace SM {
class Controller final : public ServiceFramework<Controller> {
public:
explicit Controller();
~Controller();
private:
void QueryPointerBufferSize(Kernel::HLERequestContext& ctx);
};
} // namespace SM
} // namespace Service

View File

@ -4,16 +4,21 @@
#include <tuple> #include <tuple>
#include "common/assert.h" #include "common/assert.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/client_port.h" #include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h" #include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/server_port.h" #include "core/hle/kernel/server_port.h"
#include "core/hle/result.h" #include "core/hle/result.h"
#include "core/hle/service/sm/controller.h"
#include "core/hle/service/sm/sm.h" #include "core/hle/service/sm/sm.h"
#include "core/hle/service/sm/srv.h"
namespace Service { namespace Service {
namespace SM { namespace SM {
void ServiceManager::InvokeControlRequest(Kernel::HLERequestContext& context) {
controller_interface->InvokeRequest(context);
}
static ResultCode ValidateServiceName(const std::string& name) { static ResultCode ValidateServiceName(const std::string& name) {
if (name.size() <= 0 || name.size() > 8) { if (name.size() <= 0 || name.size() > 8) {
return ERR_INVALID_NAME_SIZE; return ERR_INVALID_NAME_SIZE;
@ -25,11 +30,12 @@ static ResultCode ValidateServiceName(const std::string& name) {
} }
void ServiceManager::InstallInterfaces(std::shared_ptr<ServiceManager> self) { void ServiceManager::InstallInterfaces(std::shared_ptr<ServiceManager> self) {
ASSERT(self->srv_interface.expired()); ASSERT(self->sm_interface.expired());
auto srv = std::make_shared<SRV>(self); auto sm = std::make_shared<SM>(self);
srv->InstallAsNamedPort(); sm->InstallAsNamedPort();
self->srv_interface = srv; self->sm_interface = sm;
self->controller_interface = std::make_unique<Controller>();
} }
ResultVal<Kernel::SharedPtr<Kernel::ServerPort>> ServiceManager::RegisterService( ResultVal<Kernel::SharedPtr<Kernel::ServerPort>> ServiceManager::RegisterService(
@ -69,5 +75,80 @@ ResultVal<Kernel::SharedPtr<Kernel::ClientSession>> ServiceManager::ConnectToSer
std::shared_ptr<ServiceManager> g_service_manager; std::shared_ptr<ServiceManager> g_service_manager;
/**
* SM::Initialize service function
* Inputs:
* 0: 0x00000000
* Outputs:
* 1: ResultCode
*/
void SM::Initialize(Kernel::HLERequestContext& ctx) {
IPC::RequestBuilder rb{ctx, 1};
rb.Push(RESULT_SUCCESS);
LOG_DEBUG(Service_SM, "called");
}
/**
* SM::GetServiceHandle service function
* Inputs:
* 0: 0x00000001
* 1: Unknown
* 2: Unknown
* 3-4: 8-byte UTF-8 service name
* Outputs:
* 1: ResultCode
* 3: Service handle
*/
void SM::GetService(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
u32 unk1 = rp.Pop<u32>();
u32 unk2 = rp.Pop<u32>();
auto name_buf = rp.PopRaw<std::array<char, 6>>();
std::string name(name_buf.data());
// TODO(yuriks): Permission checks go here
auto client_port = service_manager->GetServicePort(name);
if (client_port.Failed()) {
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0, 0);
rb.Push(client_port.Code());
LOG_ERROR(Service_SM, "called service=%s -> error 0x%08X", name.c_str(),
client_port.Code().raw);
return;
}
auto session = client_port.Unwrap()->Connect();
if (session.Succeeded()) {
LOG_DEBUG(Service_SM, "called service=%s -> session=%u", name.c_str(),
(*session)->GetObjectId());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0, 1);
rb.Push(session.Code());
rb.PushObjects(std::move(session).Unwrap());
} else if (session.Code() == Kernel::ERR_MAX_CONNECTIONS_REACHED /*&& return_port_on_failure*/) {
LOG_WARNING(Service_SM, "called service=%s -> ERR_MAX_CONNECTIONS_REACHED, *port*=%u",
name.c_str(), (*client_port)->GetObjectId());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0, 1);
rb.Push(ERR_MAX_CONNECTIONS_REACHED);
rb.PushObjects(std::move(client_port).Unwrap());
} else {
LOG_ERROR(Service_SM, "called service=%s -> error 0x%08X", name.c_str(), session.Code());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0, 0);
rb.Push(session.Code());
}
}
SM::SM(std::shared_ptr<ServiceManager> service_manager)
: ServiceFramework("sm:", 4), service_manager(std::move(service_manager)) {
static const FunctionInfo functions[] = {
{0x00000000, &SM::Initialize, "Initialize"},
{0x00000001, &SM::GetService, "GetService"},
{0x00000002, nullptr, "RegisterService"},
{0x00000003, nullptr, "UnregisterService"},
};
RegisterHandlers(functions);
}
SM::~SM() = default;
} // namespace SM } // namespace SM
} // namespace Service } // namespace Service

View File

@ -20,7 +20,20 @@ class SessionRequestHandler;
namespace Service { namespace Service {
namespace SM { namespace SM {
class SRV; /// Interface to "sm:" service
class SM final : public ServiceFramework<SM> {
public:
explicit SM(std::shared_ptr<ServiceManager> service_manager);
~SM();
private:
void Initialize(Kernel::HLERequestContext& ctx);
void GetService(Kernel::HLERequestContext& ctx);
std::shared_ptr<ServiceManager> service_manager;
};
class Controller;
constexpr ResultCode ERR_SERVICE_NOT_REGISTERED(1, ErrorModule::SRV, ErrorSummary::WouldBlock, constexpr ResultCode ERR_SERVICE_NOT_REGISTERED(1, ErrorModule::SRV, ErrorSummary::WouldBlock,
ErrorLevel::Temporary); // 0xD0406401 ErrorLevel::Temporary); // 0xD0406401
@ -45,8 +58,11 @@ public:
ResultVal<Kernel::SharedPtr<Kernel::ClientPort>> GetServicePort(const std::string& name); ResultVal<Kernel::SharedPtr<Kernel::ClientPort>> GetServicePort(const std::string& name);
ResultVal<Kernel::SharedPtr<Kernel::ClientSession>> ConnectToService(const std::string& name); ResultVal<Kernel::SharedPtr<Kernel::ClientSession>> ConnectToService(const std::string& name);
void InvokeControlRequest(Kernel::HLERequestContext& context);
private: private:
std::weak_ptr<SRV> srv_interface; std::weak_ptr<SM> sm_interface;
std::unique_ptr<Controller> controller_interface;
/// Map of registered services, retrieved using GetServicePort or ConnectToService. /// Map of registered services, retrieved using GetServicePort or ConnectToService.
std::unordered_map<std::string, Kernel::SharedPtr<Kernel::ClientPort>> registered_services; std::unordered_map<std::string, Kernel::SharedPtr<Kernel::ClientPort>> registered_services;

View File

@ -1,235 +0,0 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <tuple>
#include "common/common_types.h"
#include "common/logging/log.h"
#include "core/hle/ipc.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/errors.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/semaphore.h"
#include "core/hle/kernel/server_port.h"
#include "core/hle/kernel/server_session.h"
#include "core/hle/service/sm/sm.h"
#include "core/hle/service/sm/srv.h"
namespace Service {
namespace SM {
constexpr int MAX_PENDING_NOTIFICATIONS = 16;
/**
* SRV::RegisterClient service function
* Inputs:
* 0: 0x00010002
* 1: ProcessId Header (must be 0x20)
* Outputs:
* 0: 0x00010040
* 1: ResultCode
*/
void SRV::RegisterClient(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0x1, 0, 2);
u32 pid_descriptor = rp.Pop<u32>();
if (pid_descriptor != IPC::CallingPidDesc()) {
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(IPC::ERR_INVALID_BUFFER_DESCRIPTOR);
return;
}
u32 caller_pid = rp.Pop<u32>();
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_SRV, "(STUBBED) called");
}
/**
* SRV::EnableNotification service function
* Inputs:
* 0: 0x00020000
* Outputs:
* 0: 0x00020042
* 1: ResultCode
* 2: Translation descriptor: 0x20
* 3: Handle to semaphore signaled on process notification
*/
void SRV::EnableNotification(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0x2, 0, 0);
notification_semaphore =
Kernel::Semaphore::Create(0, MAX_PENDING_NOTIFICATIONS, 0, "SRV:Notification").Unwrap();
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS);
rb.PushObjects(notification_semaphore);
LOG_WARNING(Service_SRV, "(STUBBED) called");
}
/**
* SRV::GetServiceHandle service function
* Inputs:
* 0: 0x00050100
* 1-2: 8-byte UTF-8 service name
* 3: Name length
* 4: Flags (bit0: if not set, return port-handle if session-handle unavailable)
* Outputs:
* 1: ResultCode
* 3: Service handle
*/
void SRV::GetServiceHandle(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0x5, 4, 0);
auto name_buf = rp.PopRaw<std::array<char, 8>>();
size_t name_len = rp.Pop<u32>();
u32 flags = rp.Pop<u32>();
bool return_port_on_failure = (flags & 1) == 0;
if (name_len > Service::kMaxPortSize) {
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(ERR_INVALID_NAME_SIZE);
LOG_ERROR(Service_SRV, "called name_len=0x%X -> ERR_INVALID_NAME_SIZE", name_len);
return;
}
std::string name(name_buf.data(), name_len);
// TODO(yuriks): Permission checks go here
auto client_port = service_manager->GetServicePort(name);
if (client_port.Failed()) {
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(client_port.Code());
LOG_ERROR(Service_SRV, "called service=%s -> error 0x%08X", name.c_str(),
client_port.Code().raw);
return;
}
auto session = client_port.Unwrap()->Connect();
if (session.Succeeded()) {
LOG_DEBUG(Service_SRV, "called service=%s -> session=%u", name.c_str(),
(*session)->GetObjectId());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(session.Code());
rb.PushObjects(std::move(session).Unwrap());
} else if (session.Code() == Kernel::ERR_MAX_CONNECTIONS_REACHED && return_port_on_failure) {
LOG_WARNING(Service_SRV, "called service=%s -> ERR_MAX_CONNECTIONS_REACHED, *port*=%u",
name.c_str(), (*client_port)->GetObjectId());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(ERR_MAX_CONNECTIONS_REACHED);
rb.PushObjects(std::move(client_port).Unwrap());
} else {
LOG_ERROR(Service_SRV, "called service=%s -> error 0x%08X", name.c_str(), session.Code());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(session.Code());
}
}
/**
* SRV::Subscribe service function
* Inputs:
* 0: 0x00090040
* 1: Notification ID
* Outputs:
* 0: 0x00090040
* 1: ResultCode
*/
void SRV::Subscribe(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0x9, 1, 0);
u32 notification_id = rp.Pop<u32>();
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_SRV, "(STUBBED) called, notification_id=0x%X", notification_id);
}
/**
* SRV::Unsubscribe service function
* Inputs:
* 0: 0x000A0040
* 1: Notification ID
* Outputs:
* 0: 0x000A0040
* 1: ResultCode
*/
void SRV::Unsubscribe(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0xA, 1, 0);
u32 notification_id = rp.Pop<u32>();
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_SRV, "(STUBBED) called, notification_id=0x%X", notification_id);
}
/**
* SRV::PublishToSubscriber service function
* Inputs:
* 0: 0x000C0080
* 1: Notification ID
* 2: Flags (bit0: only fire if not fired, bit1: report errors)
* Outputs:
* 0: 0x000C0040
* 1: ResultCode
*/
void SRV::PublishToSubscriber(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0xC, 2, 0);
u32 notification_id = rp.Pop<u32>();
u8 flags = rp.Pop<u8>();
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_SRV, "(STUBBED) called, notification_id=0x%X, flags=%u", notification_id,
flags);
}
void SRV::RegisterService(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx, 0x3, 4, 0);
auto name_buf = rp.PopRaw<std::array<char, 8>>();
size_t name_len = rp.Pop<u32>();
u32 max_sessions = rp.Pop<u32>();
std::string name(name_buf.data(), std::min(name_len, name_buf.size()));
auto port = service_manager->RegisterService(name, max_sessions);
if (port.Failed()) {
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(port.Code());
LOG_ERROR(Service_SRV, "called service=%s -> error 0x%08X", name.c_str(), port.Code().raw);
return;
}
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS);
rb.PushObjects(port.Unwrap());
}
SRV::SRV(std::shared_ptr<ServiceManager> service_manager)
: ServiceFramework("srv:", 4), service_manager(std::move(service_manager)) {
static const FunctionInfo functions[] = {
{0x00010002, &SRV::RegisterClient, "RegisterClient"},
{0x00020000, &SRV::EnableNotification, "EnableNotification"},
{0x00030100, &SRV::RegisterService, "RegisterService"},
{0x000400C0, nullptr, "UnregisterService"},
{0x00050100, &SRV::GetServiceHandle, "GetServiceHandle"},
{0x000600C2, nullptr, "RegisterPort"},
{0x000700C0, nullptr, "UnregisterPort"},
{0x00080100, nullptr, "GetPort"},
{0x00090040, &SRV::Subscribe, "Subscribe"},
{0x000A0040, &SRV::Unsubscribe, "Unsubscribe"},
{0x000B0000, nullptr, "ReceiveNotification"},
{0x000C0080, &SRV::PublishToSubscriber, "PublishToSubscriber"},
{0x000D0040, nullptr, "PublishAndGetSubscriber"},
{0x000E00C0, nullptr, "IsServiceRegistered"},
};
RegisterHandlers(functions);
}
SRV::~SRV() = default;
} // namespace SM
} // namespace Service

View File

@ -1,38 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "core/hle/kernel/kernel.h"
#include "core/hle/service/service.h"
namespace Kernel {
class HLERequestContext;
class Semaphore;
}
namespace Service {
namespace SM {
/// Interface to "srv:" service
class SRV final : public ServiceFramework<SRV> {
public:
explicit SRV(std::shared_ptr<ServiceManager> service_manager);
~SRV();
private:
void RegisterClient(Kernel::HLERequestContext& ctx);
void EnableNotification(Kernel::HLERequestContext& ctx);
void GetServiceHandle(Kernel::HLERequestContext& ctx);
void Subscribe(Kernel::HLERequestContext& ctx);
void Unsubscribe(Kernel::HLERequestContext& ctx);
void PublishToSubscriber(Kernel::HLERequestContext& ctx);
void RegisterService(Kernel::HLERequestContext& ctx);
std::shared_ptr<ServiceManager> service_manager;
Kernel::SharedPtr<Kernel::Semaphore> notification_semaphore;
};
} // namespace SM
} // namespace Service

View File

@ -10,6 +10,7 @@
#include "core/hle/kernel/client_session.h" #include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/handle_table.h"
#include "core/hle/kernel/process.h" #include "core/hle/kernel/process.h"
#include "core/hle/kernel/thread.h"
#include "core/hle/lock.h" #include "core/hle/lock.h"
#include "core/hle/result.h" #include "core/hle/result.h"
#include "core/hle/service/service.h" #include "core/hle/service/service.h"

View File

@ -3,7 +3,6 @@ set(SRCS
core/arm/arm_test_common.cpp core/arm/arm_test_common.cpp
core/arm/dyncom/arm_dyncom_vfp_tests.cpp core/arm/dyncom/arm_dyncom_vfp_tests.cpp
core/file_sys/path_parser.cpp core/file_sys/path_parser.cpp
core/hle/kernel/hle_ipc.cpp
core/memory/memory.cpp core/memory/memory.cpp
glad.cpp glad.cpp
tests.cpp tests.cpp

View File

@ -1,216 +0,0 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <catch.hpp>
#include "core/hle/ipc.h"
#include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/event.h"
#include "core/hle/kernel/handle_table.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/process.h"
#include "core/hle/kernel/server_session.h"
namespace Kernel {
static SharedPtr<Object> MakeObject() {
return Event::Create(ResetType::OneShot);
}
TEST_CASE("HLERequestContext::PopulateFromIncomingCommandBuffer", "[core][kernel]") {
auto session = std::get<SharedPtr<ServerSession>>(ServerSession::CreateSessionPair());
HLERequestContext context(std::move(session));
auto process = Process::Create("");
HandleTable handle_table;
SECTION("works with empty cmdbuf") {
const u32_le input[]{
IPC::MakeHeader(0x1234, 0, 0),
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
REQUIRE(context.CommandBuffer()[0] == 0x12340000);
}
SECTION("translates regular params") {
const u32_le input[]{
IPC::MakeHeader(0, 3, 0), 0x12345678, 0x21122112, 0xAABBCCDD,
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
auto* output = context.CommandBuffer();
REQUIRE(output[1] == 0x12345678);
REQUIRE(output[2] == 0x21122112);
REQUIRE(output[3] == 0xAABBCCDD);
}
SECTION("translates move handles") {
auto a = MakeObject();
Handle a_handle = handle_table.Create(a).Unwrap();
const u32_le input[]{
IPC::MakeHeader(0, 0, 2), IPC::MoveHandleDesc(1), a_handle,
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
auto* output = context.CommandBuffer();
REQUIRE(context.GetIncomingHandle(output[2]) == a);
REQUIRE(handle_table.GetGeneric(a_handle) == nullptr);
}
SECTION("translates copy handles") {
auto a = MakeObject();
Handle a_handle = handle_table.Create(a).Unwrap();
const u32_le input[]{
IPC::MakeHeader(0, 0, 2), IPC::CopyHandleDesc(1), a_handle,
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
auto* output = context.CommandBuffer();
REQUIRE(context.GetIncomingHandle(output[2]) == a);
REQUIRE(handle_table.GetGeneric(a_handle) == a);
}
SECTION("translates multi-handle descriptors") {
auto a = MakeObject();
auto b = MakeObject();
auto c = MakeObject();
const u32_le input[]{
IPC::MakeHeader(0, 0, 5), IPC::MoveHandleDesc(2),
handle_table.Create(a).Unwrap(), handle_table.Create(b).Unwrap(),
IPC::MoveHandleDesc(1), handle_table.Create(c).Unwrap(),
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
auto* output = context.CommandBuffer();
REQUIRE(context.GetIncomingHandle(output[2]) == a);
REQUIRE(context.GetIncomingHandle(output[3]) == b);
REQUIRE(context.GetIncomingHandle(output[5]) == c);
}
SECTION("translates null handles") {
const u32_le input[]{
IPC::MakeHeader(0, 0, 2), IPC::MoveHandleDesc(1), 0,
};
auto result = context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
REQUIRE(result == RESULT_SUCCESS);
auto* output = context.CommandBuffer();
REQUIRE(context.GetIncomingHandle(output[2]) == nullptr);
}
SECTION("translates CallingPid descriptors") {
const u32_le input[]{
IPC::MakeHeader(0, 0, 2), IPC::CallingPidDesc(), 0x98989898,
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
REQUIRE(context.CommandBuffer()[2] == process->process_id);
}
SECTION("translates mixed params") {
auto a = MakeObject();
const u32_le input[]{
IPC::MakeHeader(0, 2, 4),
0x12345678,
0xABCDEF00,
IPC::MoveHandleDesc(1),
handle_table.Create(a).Unwrap(),
IPC::CallingPidDesc(),
0,
};
context.PopulateFromIncomingCommandBuffer(input, *process, handle_table);
auto* output = context.CommandBuffer();
REQUIRE(output[1] == 0x12345678);
REQUIRE(output[2] == 0xABCDEF00);
REQUIRE(context.GetIncomingHandle(output[4]) == a);
REQUIRE(output[6] == process->process_id);
}
}
TEST_CASE("HLERequestContext::WriteToOutgoingCommandBuffer", "[core][kernel]") {
auto session = std::get<SharedPtr<ServerSession>>(ServerSession::CreateSessionPair());
HLERequestContext context(std::move(session));
auto process = Process::Create("");
HandleTable handle_table;
auto* input = context.CommandBuffer();
u32_le output[IPC::COMMAND_BUFFER_LENGTH];
SECTION("works with empty cmdbuf") {
input[0] = IPC::MakeHeader(0x1234, 0, 0);
context.WriteToOutgoingCommandBuffer(output, *process, handle_table);
REQUIRE(output[0] == 0x12340000);
}
SECTION("translates regular params") {
input[0] = IPC::MakeHeader(0, 3, 0);
input[1] = 0x12345678;
input[2] = 0x21122112;
input[3] = 0xAABBCCDD;
context.WriteToOutgoingCommandBuffer(output, *process, handle_table);
REQUIRE(output[1] == 0x12345678);
REQUIRE(output[2] == 0x21122112);
REQUIRE(output[3] == 0xAABBCCDD);
}
SECTION("translates move/copy handles") {
auto a = MakeObject();
auto b = MakeObject();
input[0] = IPC::MakeHeader(0, 0, 4);
input[1] = IPC::MoveHandleDesc(1);
input[2] = context.AddOutgoingHandle(a);
input[3] = IPC::CopyHandleDesc(1);
input[4] = context.AddOutgoingHandle(b);
context.WriteToOutgoingCommandBuffer(output, *process, handle_table);
REQUIRE(handle_table.GetGeneric(output[2]) == a);
REQUIRE(handle_table.GetGeneric(output[4]) == b);
}
SECTION("translates null handles") {
input[0] = IPC::MakeHeader(0, 0, 2);
input[1] = IPC::MoveHandleDesc(1);
input[2] = context.AddOutgoingHandle(nullptr);
auto result = context.WriteToOutgoingCommandBuffer(output, *process, handle_table);
REQUIRE(result == RESULT_SUCCESS);
REQUIRE(output[2] == 0);
}
SECTION("translates multi-handle descriptors") {
auto a = MakeObject();
auto b = MakeObject();
auto c = MakeObject();
input[0] = IPC::MakeHeader(0, 0, 5);
input[1] = IPC::MoveHandleDesc(2);
input[2] = context.AddOutgoingHandle(a);
input[3] = context.AddOutgoingHandle(b);
input[4] = IPC::CopyHandleDesc(1);
input[5] = context.AddOutgoingHandle(c);
context.WriteToOutgoingCommandBuffer(output, *process, handle_table);
REQUIRE(handle_table.GetGeneric(output[2]) == a);
REQUIRE(handle_table.GetGeneric(output[3]) == b);
REQUIRE(handle_table.GetGeneric(output[5]) == c);
}
}
} // namespace Kernel

View File

@ -366,7 +366,7 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) {
switch (id) { switch (id) {
// Trigger IRQ // Trigger IRQ
case PICA_REG_INDEX(trigger_irq): case PICA_REG_INDEX(trigger_irq):
Service::GSP::SignalInterrupt(Service::GSP::InterruptId::P3D); //Service::GSP::SignalInterrupt(Service::GSP::InterruptId::P3D);
break; break;
case PICA_REG_INDEX(pipeline.triangle_topology): case PICA_REG_INDEX(pipeline.triangle_topology):