ams-mtc: add ams-mtc
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_htcmisc_rpc_server.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr inline size_t ReceiveThreadStackSize = os::MemoryPageSize;
|
||||
|
||||
alignas(os::ThreadStackAlignment) constinit u8 g_receive_thread_stack[ReceiveThreadStackSize];
|
||||
|
||||
}
|
||||
|
||||
HtcmiscRpcServer::HtcmiscRpcServer(driver::IDriver *driver, htclow::ChannelId channel)
|
||||
: m_allocator(nullptr),
|
||||
m_driver(driver),
|
||||
m_channel_id(channel),
|
||||
m_receive_thread_stack(g_receive_thread_stack),
|
||||
m_cancelled(false),
|
||||
m_thread_running(false)
|
||||
{
|
||||
/* ... */
|
||||
}
|
||||
|
||||
void HtcmiscRpcServer::Open() {
|
||||
R_ABORT_UNLESS(m_driver->Open(m_channel_id, m_driver_receive_buffer, sizeof(m_driver_receive_buffer), m_driver_send_buffer, sizeof(m_driver_send_buffer)));
|
||||
}
|
||||
|
||||
void HtcmiscRpcServer::Close() {
|
||||
m_driver->Close(m_channel_id);
|
||||
}
|
||||
|
||||
Result HtcmiscRpcServer::Start() {
|
||||
/* Connect. */
|
||||
R_TRY(m_driver->Connect(m_channel_id));
|
||||
|
||||
/* Create our thread. */
|
||||
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_receive_thread), ReceiveThreadEntry, this, m_receive_thread_stack, ReceiveThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcmiscReceive)));
|
||||
|
||||
/* Set thread name pointer. */
|
||||
os::SetThreadNamePointer(std::addressof(m_receive_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcmiscReceive));
|
||||
|
||||
/* Start thread. */
|
||||
os::StartThread(std::addressof(m_receive_thread));
|
||||
|
||||
/* Set initial state. */
|
||||
m_cancelled = false;
|
||||
m_thread_running = true;
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void HtcmiscRpcServer::Cancel() {
|
||||
/* Set cancelled. */
|
||||
m_cancelled = true;
|
||||
}
|
||||
|
||||
void HtcmiscRpcServer::Wait() {
|
||||
/* Wait for thread to not be running. */
|
||||
if (m_thread_running) {
|
||||
os::WaitThread(std::addressof(m_receive_thread));
|
||||
os::DestroyThread(std::addressof(m_receive_thread));
|
||||
}
|
||||
m_thread_running = false;
|
||||
}
|
||||
|
||||
int HtcmiscRpcServer::WaitAny(htclow::ChannelState state, os::EventType *event) {
|
||||
/* Check if we're already signaled. */
|
||||
if (os::TryWaitEvent(event)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Wait. */
|
||||
while (m_driver->GetChannelState(m_channel_id) != state) {
|
||||
const auto idx = os::WaitAny(m_driver->GetChannelStateEvent(m_channel_id), event);
|
||||
if (idx != 0) {
|
||||
return idx;
|
||||
}
|
||||
|
||||
/* Clear the channel state event. */
|
||||
os::ClearEvent(m_driver->GetChannelStateEvent(m_channel_id));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Result HtcmiscRpcServer::ReceiveThread() {
|
||||
/* Loop forever. */
|
||||
auto *header = reinterpret_cast<HtcmiscRpcPacket *>(m_receive_buffer);
|
||||
while (true) {
|
||||
/* Try to receive a packet header. */
|
||||
R_TRY(this->ReceiveHeader(header));
|
||||
|
||||
/* Track how much we've received. */
|
||||
size_t received = sizeof(*header);
|
||||
|
||||
/* If the packet has one, receive its body. */
|
||||
if (header->body_size > 0) {
|
||||
/* Sanity check the body size. */
|
||||
AMS_ABORT_UNLESS(util::IsIntValueRepresentable<size_t>(header->body_size));
|
||||
AMS_ABORT_UNLESS(static_cast<size_t>(header->body_size) <= sizeof(m_receive_buffer) - received);
|
||||
|
||||
/* Receive the body. */
|
||||
R_TRY(this->ReceiveBody(header->data, header->body_size));
|
||||
|
||||
/* Note that we received the body. */
|
||||
received += header->body_size;
|
||||
}
|
||||
|
||||
/* Check that the packet is a request packet. */
|
||||
R_UNLESS(header->category == HtcmiscPacketCategory::Request, htc::ResultInvalidCategory());
|
||||
|
||||
/* Handle specific requests. */
|
||||
if (header->type == HtcmiscPacketType::SetTargetName) {
|
||||
R_TRY(this->ProcessSetTargetNameRequest(header->data, header->body_size, header->task_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result HtcmiscRpcServer::ProcessSetTargetNameRequest(const char *name, size_t size, u32 task_id) {
|
||||
/* TODO: we need to use settings::fwdbg::SetSettingsItemValue here, but this will require ams support for set:fd re-enable? */
|
||||
/* Needs some thought. */
|
||||
AMS_UNUSED(name, size, task_id);
|
||||
AMS_ABORT("HtcmiscRpcServer::ProcessSetTargetNameRequest");
|
||||
}
|
||||
|
||||
Result HtcmiscRpcServer::ReceiveHeader(HtcmiscRpcPacket *header) {
|
||||
/* Receive. */
|
||||
s64 received;
|
||||
R_TRY(m_driver->Receive(std::addressof(received), reinterpret_cast<char *>(header), sizeof(*header), m_channel_id, htclow::ReceiveOption_ReceiveAllData));
|
||||
|
||||
/* Check size. */
|
||||
R_UNLESS(static_cast<size_t>(received) == sizeof(*header), htc::ResultInvalidSize());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result HtcmiscRpcServer::ReceiveBody(char *dst, size_t size) {
|
||||
/* Receive. */
|
||||
s64 received;
|
||||
R_TRY(m_driver->Receive(std::addressof(received), dst, size, m_channel_id, htclow::ReceiveOption_ReceiveAllData));
|
||||
|
||||
/* Check size. */
|
||||
R_UNLESS(static_cast<size_t>(received) == size, htc::ResultInvalidSize());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result HtcmiscRpcServer::SendRequest(const char *src, size_t size) {
|
||||
/* Sanity check our size. */
|
||||
AMS_ASSERT(util::IsIntValueRepresentable<s64>(size));
|
||||
|
||||
/* Send the data. */
|
||||
s64 sent;
|
||||
R_TRY(m_driver->Send(std::addressof(sent), src, static_cast<s64>(size), m_channel_id));
|
||||
|
||||
/* Check that we sent the right amount. */
|
||||
R_UNLESS(sent == static_cast<s64>(size), htc::ResultInvalidSize());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
#include "../driver/htc_i_driver.hpp"
|
||||
#include "htc_htcmisc_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
class HtcmiscRpcServer {
|
||||
private:
|
||||
/* TODO: where is this value coming from, again? */
|
||||
static constexpr size_t BufferSize = 1_KB;
|
||||
private:
|
||||
mem::StandardAllocator *m_allocator;
|
||||
driver::IDriver *m_driver;
|
||||
htclow::ChannelId m_channel_id;
|
||||
void *m_receive_thread_stack;
|
||||
os::ThreadType m_receive_thread;
|
||||
bool m_cancelled;
|
||||
bool m_thread_running;
|
||||
char m_receive_buffer[BufferSize];
|
||||
char m_send_buffer[BufferSize];
|
||||
u8 m_driver_receive_buffer[4_KB];
|
||||
u8 m_driver_send_buffer[4_KB];
|
||||
private:
|
||||
static void ReceiveThreadEntry(void *arg) { static_cast<HtcmiscRpcServer *>(arg)->ReceiveThread(); }
|
||||
|
||||
Result ReceiveThread();
|
||||
public:
|
||||
HtcmiscRpcServer(driver::IDriver *driver, htclow::ChannelId channel);
|
||||
public:
|
||||
void Open();
|
||||
void Close();
|
||||
|
||||
Result Start();
|
||||
void Cancel();
|
||||
void Wait();
|
||||
|
||||
int WaitAny(htclow::ChannelState state, os::EventType *event);
|
||||
private:
|
||||
Result ProcessSetTargetNameRequest(const char *name, size_t size, u32 task_id);
|
||||
|
||||
Result ReceiveHeader(HtcmiscRpcPacket *header);
|
||||
Result ReceiveBody(char *dst, size_t size);
|
||||
Result SendRequest(const char *src, size_t size);
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_htcmisc_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
Result GetEnvironmentVariableTask::SetArguments(const char *args, size_t size) {
|
||||
/* Copy to our name. */
|
||||
const size_t copied = util::Strlcpy(m_name, args, sizeof(m_name));
|
||||
m_name_size = copied;
|
||||
|
||||
/* Require that the size be correct. */
|
||||
|
||||
R_UNLESS(size == copied || size == copied + 1, htc::ResultUnknown());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void GetEnvironmentVariableTask::Complete(HtcmiscResult result, const char *data, size_t size) {
|
||||
/* Sanity check input. */
|
||||
if (size < sizeof(m_value)) {
|
||||
/* Convert the result. */
|
||||
switch (result) {
|
||||
case HtcmiscResult::Success:
|
||||
/* Copy to our value. */
|
||||
std::memcpy(m_value, data, size);
|
||||
m_value[size] = '\x00';
|
||||
m_value_size = size + 1;
|
||||
|
||||
m_result = ResultSuccess();
|
||||
break;
|
||||
case HtcmiscResult::UnknownError:
|
||||
m_result = htc::ResultUnknown();
|
||||
break;
|
||||
case HtcmiscResult::UnsupportedVersion:
|
||||
m_result = htc::ResultConnectionFailure();
|
||||
break;
|
||||
case HtcmiscResult::InvalidRequest:
|
||||
m_result = htc::ResultNotFound();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
m_result = htc::ResultUnknown();
|
||||
}
|
||||
|
||||
/* Complete the task. */
|
||||
Task::Complete();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableTask::GetResult(size_t *out, char *dst, size_t size) const {
|
||||
/* Check our task state. */
|
||||
AMS_ASSERT(this->GetTaskState() == RpcTaskState::Completed);
|
||||
|
||||
/* Check that we succeeded. */
|
||||
R_TRY(m_result);
|
||||
|
||||
/* Check that we can convert successfully. */
|
||||
R_UNLESS(util::IsIntValueRepresentable<int>(size), htc::ResultUnknown());
|
||||
|
||||
/* Copy out. */
|
||||
const auto copied = util::Strlcpy(dst, m_value, size);
|
||||
R_UNLESS(copied < static_cast<int>(size), htc::ResultNotEnoughBuffer());
|
||||
|
||||
/* Set the output size. */
|
||||
*out = m_value_size;
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
|
||||
/* Validate pre-conditions. */
|
||||
AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket));
|
||||
AMS_UNUSED(size);
|
||||
|
||||
/* Create the packet. */
|
||||
auto *packet = reinterpret_cast<HtcmiscRpcPacket *>(data);
|
||||
*packet = {
|
||||
.protocol = HtcmiscProtocol,
|
||||
.version = HtcmiscMaxVersion,
|
||||
.category = HtcmiscPacketCategory::Request,
|
||||
.type = HtcmiscPacketType::GetEnvironmentVariable,
|
||||
.body_size = this->GetNameSize(),
|
||||
.task_id = task_id,
|
||||
.params = {
|
||||
/* ... */
|
||||
},
|
||||
};
|
||||
|
||||
/* Set the packet body. */
|
||||
std::memcpy(packet->data, this->GetName(), this->GetNameSize());
|
||||
|
||||
/* Set the output size. */
|
||||
*out = sizeof(*packet) + this->GetNameSize();
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableTask::ProcessResponse(const char *data, size_t size) {
|
||||
/* Convert the input to a packet. */
|
||||
auto *packet = reinterpret_cast<const HtcmiscRpcPacket *>(data);
|
||||
|
||||
/* Process the packet. */
|
||||
this->Complete(static_cast<HtcmiscResult>(packet->params[0]), data + sizeof(*packet), size - sizeof(*packet));
|
||||
|
||||
/* Complete the task. */
|
||||
Task::Complete();
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableLengthTask::SetArguments(const char *args, size_t size) {
|
||||
/* Copy to our name. */
|
||||
const size_t copied = util::Strlcpy(m_name, args, sizeof(m_name));
|
||||
m_name_size = copied;
|
||||
|
||||
/* Require that the size be correct. */
|
||||
|
||||
R_UNLESS(size == copied || size == copied + 1, htc::ResultUnknown());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void GetEnvironmentVariableLengthTask::Complete(HtcmiscResult result, const char *data, size_t size) {
|
||||
/* Sanity check input. */
|
||||
if (size == sizeof(s64)) {
|
||||
/* Convert the result. */
|
||||
switch (result) {
|
||||
case HtcmiscResult::Success:
|
||||
/* Copy to our value. */
|
||||
s64 tmp;
|
||||
std::memcpy(std::addressof(tmp), data, sizeof(tmp));
|
||||
if (util::IsIntValueRepresentable<size_t>(tmp)) {
|
||||
m_value_size = static_cast<size_t>(tmp);
|
||||
}
|
||||
|
||||
m_result = ResultSuccess();
|
||||
break;
|
||||
case HtcmiscResult::UnknownError:
|
||||
m_result = htc::ResultUnknown();
|
||||
break;
|
||||
case HtcmiscResult::UnsupportedVersion:
|
||||
m_result = htc::ResultConnectionFailure();
|
||||
break;
|
||||
case HtcmiscResult::InvalidRequest:
|
||||
m_result = htc::ResultNotFound();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
m_result = htc::ResultUnknown();
|
||||
}
|
||||
|
||||
/* Complete the task. */
|
||||
Task::Complete();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableLengthTask::GetResult(size_t *out) const {
|
||||
/* Check our task state. */
|
||||
AMS_ASSERT(this->GetTaskState() == RpcTaskState::Completed);
|
||||
|
||||
/* Check that we succeeded. */
|
||||
R_TRY(m_result);
|
||||
|
||||
/* Set the output size. */
|
||||
*out = m_value_size;
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableLengthTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
|
||||
/* Validate pre-conditions. */
|
||||
AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket));
|
||||
AMS_UNUSED(size);
|
||||
|
||||
/* Create the packet. */
|
||||
auto *packet = reinterpret_cast<HtcmiscRpcPacket *>(data);
|
||||
*packet = {
|
||||
.protocol = HtcmiscProtocol,
|
||||
.version = HtcmiscMaxVersion,
|
||||
.category = HtcmiscPacketCategory::Request,
|
||||
.type = HtcmiscPacketType::GetEnvironmentVariableLength,
|
||||
.body_size = this->GetNameSize(),
|
||||
.task_id = task_id,
|
||||
.params = {
|
||||
/* ... */
|
||||
},
|
||||
};
|
||||
|
||||
/* Set the packet body. */
|
||||
std::memcpy(packet->data, this->GetName(), this->GetNameSize());
|
||||
|
||||
/* Set the output size. */
|
||||
*out = sizeof(*packet) + this->GetNameSize();
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result GetEnvironmentVariableLengthTask::ProcessResponse(const char *data, size_t size) {
|
||||
/* Convert the input to a packet. */
|
||||
auto *packet = reinterpret_cast<const HtcmiscRpcPacket *>(data);
|
||||
|
||||
/* Process the packet. */
|
||||
this->Complete(static_cast<HtcmiscResult>(packet->params[0]), data + sizeof(*packet), size - sizeof(*packet));
|
||||
|
||||
/* Complete the task. */
|
||||
Task::Complete();
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result RunOnHostTask::SetArguments(const char *args, size_t size) {
|
||||
/* Verify command fits in our buffer. */
|
||||
R_UNLESS(size < sizeof(m_command), htc::ResultNotEnoughBuffer());
|
||||
|
||||
/* Set our command. */
|
||||
std::memcpy(m_command, args, size);
|
||||
m_command_size = size;
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void RunOnHostTask::Complete(int host_result) {
|
||||
/* Set our host result. */
|
||||
m_host_result = host_result;
|
||||
|
||||
/* Signal. */
|
||||
m_system_event.Signal();
|
||||
|
||||
/* Complete the task. */
|
||||
Task::Complete();
|
||||
}
|
||||
|
||||
Result RunOnHostTask::GetResult(int *out) const {
|
||||
*out = m_host_result;
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void RunOnHostTask::Cancel(RpcTaskCancelReason reason) {
|
||||
/* Cancel the task. */
|
||||
Task::Cancel(reason);
|
||||
|
||||
/* Signal our event. */
|
||||
m_system_event.Signal();
|
||||
}
|
||||
|
||||
Result RunOnHostTask::CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
|
||||
/* Validate pre-conditions. */
|
||||
AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket));
|
||||
AMS_UNUSED(size);
|
||||
|
||||
/* Create the packet. */
|
||||
auto *packet = reinterpret_cast<HtcmiscRpcPacket *>(data);
|
||||
*packet = {
|
||||
.protocol = HtcmiscProtocol,
|
||||
.version = HtcmiscMaxVersion,
|
||||
.category = HtcmiscPacketCategory::Request,
|
||||
.type = HtcmiscPacketType::RunOnHost,
|
||||
.body_size = this->GetCommandSize(),
|
||||
.task_id = task_id,
|
||||
.params = {
|
||||
/* ... */
|
||||
},
|
||||
};
|
||||
|
||||
/* Set the packet body. */
|
||||
std::memcpy(packet->data, this->GetCommand(), this->GetCommandSize());
|
||||
|
||||
/* Set the output size. */
|
||||
*out = sizeof(*packet) + this->GetCommandSize();
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result RunOnHostTask::ProcessResponse(const char *data, size_t size) {
|
||||
/* Validate pre-conditions. */
|
||||
AMS_ASSERT(size >= sizeof(HtcmiscRpcPacket));
|
||||
AMS_UNUSED(size);
|
||||
|
||||
this->Complete(reinterpret_cast<const HtcmiscRpcPacket *>(data)->params[0]);
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
os::SystemEventType *RunOnHostTask::GetSystemEvent() {
|
||||
return m_system_event.GetBase();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
enum class HtcmiscTaskType {
|
||||
GetEnvironmentVariable = 0,
|
||||
GetEnvironmentVariableLength = 1,
|
||||
SetTargetStatus = 2,
|
||||
RunOnHost = 3,
|
||||
};
|
||||
|
||||
enum class HtcmiscResult {
|
||||
Success = 0,
|
||||
UnknownError = 1,
|
||||
UnsupportedVersion = 2,
|
||||
InvalidRequest = 3,
|
||||
};
|
||||
|
||||
enum class HtcmiscPacketCategory : s16 {
|
||||
Request = 0,
|
||||
Response = 1,
|
||||
};
|
||||
|
||||
enum class HtcmiscPacketType : s16 {
|
||||
GetMaxProtocolVersion = 0,
|
||||
SetProtocolVersion = 1,
|
||||
GetEnvironmentVariable = 16,
|
||||
GetEnvironmentVariableLength = 17,
|
||||
SetTargetStatus = 18,
|
||||
RunOnHost = 19,
|
||||
GetWorkingDirectory = 20,
|
||||
GetWorkingDirectorySize = 21,
|
||||
SetTargetName = 22,
|
||||
};
|
||||
|
||||
constexpr inline s16 HtcmiscProtocol = 4;
|
||||
constexpr inline s16 HtcmiscMaxVersion = 2;
|
||||
|
||||
struct HtcmiscRpcPacket {
|
||||
s16 protocol;
|
||||
s16 version;
|
||||
HtcmiscPacketCategory category;
|
||||
HtcmiscPacketType type;
|
||||
s64 body_size;
|
||||
u32 task_id{};
|
||||
u64 params[5];
|
||||
char data[];
|
||||
};
|
||||
static_assert(sizeof(HtcmiscRpcPacket) == 0x40);
|
||||
|
||||
class HtcmiscTask : public Task {
|
||||
private:
|
||||
HtcmiscTaskType m_task_type;
|
||||
public:
|
||||
HtcmiscTask(HtcmiscTaskType type) : m_task_type(type) { /* ... */ }
|
||||
|
||||
HtcmiscTaskType GetTaskType() const { return m_task_type; }
|
||||
};
|
||||
|
||||
class GetEnvironmentVariableTask : public HtcmiscTask {
|
||||
public:
|
||||
static constexpr inline HtcmiscTaskType TaskType = HtcmiscTaskType::GetEnvironmentVariable;
|
||||
private:
|
||||
char m_name[0x800];
|
||||
int m_name_size;
|
||||
Result m_result;
|
||||
size_t m_value_size;
|
||||
char m_value[0x8000];
|
||||
public:
|
||||
GetEnvironmentVariableTask() : HtcmiscTask(HtcmiscTaskType::GetEnvironmentVariable) { /* ... */ }
|
||||
|
||||
Result SetArguments(const char *args, size_t size);
|
||||
void Complete(HtcmiscResult result, const char *data, size_t size);
|
||||
Result GetResult(size_t *out, char *dst, size_t size) const;
|
||||
|
||||
const char *GetName() const { return m_name; }
|
||||
int GetNameSize() const { return m_name_size; }
|
||||
public:
|
||||
virtual Result ProcessResponse(const char *data, size_t size) override;
|
||||
virtual Result CreateRequest(size_t *out, char *data, size_t size, u32 task_id) override;
|
||||
};
|
||||
|
||||
class GetEnvironmentVariableLengthTask : public HtcmiscTask {
|
||||
public:
|
||||
static constexpr inline HtcmiscTaskType TaskType = HtcmiscTaskType::GetEnvironmentVariableLength;
|
||||
private:
|
||||
char m_name[0x800];
|
||||
int m_name_size;
|
||||
Result m_result;
|
||||
size_t m_value_size;
|
||||
public:
|
||||
GetEnvironmentVariableLengthTask() : HtcmiscTask(HtcmiscTaskType::GetEnvironmentVariableLength) { /* ... */ }
|
||||
|
||||
Result SetArguments(const char *args, size_t size);
|
||||
void Complete(HtcmiscResult result, const char *data, size_t size);
|
||||
Result GetResult(size_t *out) const;
|
||||
|
||||
const char *GetName() const { return m_name; }
|
||||
int GetNameSize() const { return m_name_size; }
|
||||
public:
|
||||
virtual Result ProcessResponse(const char *data, size_t size) override;
|
||||
virtual Result CreateRequest(size_t *out, char *data, size_t size, u32 task_id) override;
|
||||
};
|
||||
|
||||
class RunOnHostTask : public HtcmiscTask {
|
||||
public:
|
||||
static constexpr inline HtcmiscTaskType TaskType = HtcmiscTaskType::RunOnHost;
|
||||
private:
|
||||
char m_command[0x2000];
|
||||
int m_command_size;
|
||||
Result m_result;
|
||||
int m_host_result;
|
||||
os::SystemEvent m_system_event;
|
||||
public:
|
||||
RunOnHostTask() : HtcmiscTask(HtcmiscTaskType::RunOnHost), m_system_event(os::EventClearMode_ManualClear, true) { /* ... */ }
|
||||
|
||||
Result SetArguments(const char *args, size_t size);
|
||||
void Complete(int host_result);
|
||||
Result GetResult(int *out) const;
|
||||
|
||||
const char *GetCommand() const { return m_command; }
|
||||
int GetCommandSize() const { return m_command_size; }
|
||||
public:
|
||||
virtual void Cancel(RpcTaskCancelReason reason) override;
|
||||
virtual Result ProcessResponse(const char *data, size_t size) override;
|
||||
virtual Result CreateRequest(size_t *out, char *data, size_t size, u32 task_id) override;
|
||||
virtual os::SystemEventType *GetSystemEvent() override;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_rpc_client.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr inline size_t ThreadStackSize = os::MemoryPageSize;
|
||||
|
||||
alignas(os::ThreadStackAlignment) constinit u8 g_receive_thread_stack[ThreadStackSize];
|
||||
alignas(os::ThreadStackAlignment) constinit u8 g_send_thread_stack[ThreadStackSize];
|
||||
|
||||
constinit os::SdkMutex g_rpc_mutex;
|
||||
|
||||
constinit RpcTaskIdFreeList g_task_id_free_list;
|
||||
constinit RpcTaskTable g_task_table;
|
||||
|
||||
}
|
||||
|
||||
RpcClient::RpcClient(driver::IDriver *driver, htclow::ChannelId channel)
|
||||
: m_allocator(nullptr),
|
||||
m_driver(driver),
|
||||
m_channel_id(channel),
|
||||
m_receive_thread_stack(g_receive_thread_stack),
|
||||
m_send_thread_stack(g_send_thread_stack),
|
||||
m_mutex(g_rpc_mutex),
|
||||
m_task_id_free_list(g_task_id_free_list),
|
||||
m_task_table(g_task_table),
|
||||
m_task_active(),
|
||||
m_is_htcs_task(),
|
||||
m_task_queue(),
|
||||
m_cancelled(false),
|
||||
m_thread_running(false)
|
||||
{
|
||||
/* Initialize all events. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
os::InitializeEvent(std::addressof(m_receive_buffer_available_events[i]), false, os::EventClearMode_AutoClear);
|
||||
os::InitializeEvent(std::addressof(m_send_buffer_available_events[i]), false, os::EventClearMode_AutoClear);
|
||||
}
|
||||
}
|
||||
|
||||
RpcClient::RpcClient(mem::StandardAllocator *allocator, driver::IDriver *driver, htclow::ChannelId channel)
|
||||
: m_allocator(allocator),
|
||||
m_driver(driver),
|
||||
m_channel_id(channel),
|
||||
m_receive_thread_stack(m_allocator->Allocate(ThreadStackSize, os::ThreadStackAlignment)),
|
||||
m_send_thread_stack(m_allocator->Allocate(ThreadStackSize, os::ThreadStackAlignment)),
|
||||
m_mutex(g_rpc_mutex),
|
||||
m_task_id_free_list(g_task_id_free_list),
|
||||
m_task_table(g_task_table),
|
||||
m_task_active(),
|
||||
m_is_htcs_task(),
|
||||
m_task_queue(),
|
||||
m_cancelled(false),
|
||||
m_thread_running(false)
|
||||
{
|
||||
/* Initialize all events. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
os::InitializeEvent(std::addressof(m_receive_buffer_available_events[i]), false, os::EventClearMode_AutoClear);
|
||||
os::InitializeEvent(std::addressof(m_send_buffer_available_events[i]), false, os::EventClearMode_AutoClear);
|
||||
}
|
||||
}
|
||||
|
||||
RpcClient::~RpcClient() {
|
||||
/* Finalize all events. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
os::FinalizeEvent(std::addressof(m_receive_buffer_available_events[i]));
|
||||
os::FinalizeEvent(std::addressof(m_send_buffer_available_events[i]));
|
||||
}
|
||||
|
||||
/* Free the thread stacks. */
|
||||
if (m_allocator != nullptr) {
|
||||
m_allocator->Free(m_receive_thread_stack);
|
||||
m_allocator->Free(m_send_thread_stack);
|
||||
}
|
||||
m_receive_thread_stack = nullptr;
|
||||
m_send_thread_stack = nullptr;
|
||||
|
||||
/* Free all tasks. */
|
||||
for (u32 i = 0; i < MaxRpcCount; ++i) {
|
||||
if (m_task_active[i]) {
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
m_task_table.Delete(i);
|
||||
m_task_id_free_list.Free(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RpcClient::Open() {
|
||||
R_ABORT_UNLESS(m_driver->Open(m_channel_id));
|
||||
}
|
||||
|
||||
void RpcClient::Close() {
|
||||
m_driver->Close(m_channel_id);
|
||||
}
|
||||
|
||||
Result RpcClient::Start() {
|
||||
/* Connect. */
|
||||
R_TRY(m_driver->Connect(m_channel_id));
|
||||
|
||||
/* Initialize our task queue. */
|
||||
m_task_queue.Initialize();
|
||||
|
||||
/* Create our threads. */
|
||||
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_receive_thread), ReceiveThreadEntry, this, m_receive_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcmiscReceive)));
|
||||
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_send_thread), SendThreadEntry, this, m_send_thread_stack, ThreadStackSize, AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcmiscSend)));
|
||||
|
||||
/* Set thread name pointers. */
|
||||
os::SetThreadNamePointer(std::addressof(m_receive_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcmiscReceive));
|
||||
os::SetThreadNamePointer(std::addressof(m_send_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcmiscSend));
|
||||
|
||||
/* Start threads. */
|
||||
os::StartThread(std::addressof(m_receive_thread));
|
||||
os::StartThread(std::addressof(m_send_thread));
|
||||
|
||||
/* Set initial state. */
|
||||
m_cancelled = false;
|
||||
m_thread_running = true;
|
||||
|
||||
/* Clear events. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
os::ClearEvent(std::addressof(m_receive_buffer_available_events[i]));
|
||||
os::ClearEvent(std::addressof(m_send_buffer_available_events[i]));
|
||||
}
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void RpcClient::Cancel() {
|
||||
/* Set cancelled. */
|
||||
m_cancelled = true;
|
||||
|
||||
/* Signal all events. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
os::SignalEvent(std::addressof(m_receive_buffer_available_events[i]));
|
||||
os::SignalEvent(std::addressof(m_send_buffer_available_events[i]));
|
||||
}
|
||||
|
||||
/* Cancel our queue. */
|
||||
m_task_queue.Cancel();
|
||||
}
|
||||
|
||||
void RpcClient::Wait() {
|
||||
/* Wait for thread to not be running. */
|
||||
if (m_thread_running) {
|
||||
os::WaitThread(std::addressof(m_receive_thread));
|
||||
os::WaitThread(std::addressof(m_send_thread));
|
||||
os::DestroyThread(std::addressof(m_receive_thread));
|
||||
os::DestroyThread(std::addressof(m_send_thread));
|
||||
}
|
||||
m_thread_running = false;
|
||||
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Finalize the task queue. */
|
||||
m_task_queue.Finalize();
|
||||
|
||||
/* Cancel all tasks. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
if (m_task_active[i]) {
|
||||
m_task_table.Get<Task>(i)->Cancel(RpcTaskCancelReason::ClientFinalized);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int RpcClient::WaitAny(htclow::ChannelState state, os::EventType *event) {
|
||||
/* Check if we're already signaled. */
|
||||
if (os::TryWaitEvent(event)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Wait. */
|
||||
while (m_driver->GetChannelState(m_channel_id) != state) {
|
||||
const auto idx = os::WaitAny(m_driver->GetChannelStateEvent(m_channel_id), event);
|
||||
if (idx != 0) {
|
||||
return idx;
|
||||
}
|
||||
|
||||
/* Clear the channel state event. */
|
||||
os::ClearEvent(m_driver->GetChannelStateEvent(m_channel_id));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Result RpcClient::ReceiveThread() {
|
||||
/* Loop forever. */
|
||||
auto *header = reinterpret_cast<RpcPacket *>(m_receive_buffer);
|
||||
while (true) {
|
||||
/* Try to receive a packet header. */
|
||||
R_TRY(this->ReceiveHeader(header));
|
||||
|
||||
/* Track how much we've received. */
|
||||
size_t received = sizeof(*header);
|
||||
|
||||
/* If the packet has one, receive its body. */
|
||||
if (header->body_size > 0) {
|
||||
/* Sanity check the task id. */
|
||||
AMS_ABORT_UNLESS(header->task_id < static_cast<int>(MaxRpcCount));
|
||||
|
||||
/* Sanity check the body size. */
|
||||
AMS_ABORT_UNLESS(util::IsIntValueRepresentable<size_t>(header->body_size));
|
||||
AMS_ABORT_UNLESS(static_cast<size_t>(header->body_size) <= sizeof(m_receive_buffer) - received);
|
||||
|
||||
/* Receive the body. */
|
||||
R_TRY(this->ReceiveBody(header->data, header->body_size));
|
||||
|
||||
/* Note that we received the body. */
|
||||
received += header->body_size;
|
||||
}
|
||||
|
||||
/* Acquire exclusive access to the task tables. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the specified task. */
|
||||
Task *task = m_task_table.Get<Task>(header->task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* If the task is canceled, free it. */
|
||||
if (task->GetTaskState() == RpcTaskState::Cancelled) {
|
||||
m_task_active[header->task_id] = false;
|
||||
m_is_htcs_task[header->task_id] = false;
|
||||
m_task_table.Delete(header->task_id);
|
||||
m_task_id_free_list.Free(header->task_id);
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Handle the packet. */
|
||||
switch (header->category) {
|
||||
case PacketCategory::Response:
|
||||
R_TRY(task->ProcessResponse(m_receive_buffer, received));
|
||||
break;
|
||||
case PacketCategory::Notification:
|
||||
R_TRY(task->ProcessNotification(m_receive_buffer, received));
|
||||
break;
|
||||
default:
|
||||
R_THROW(htc::ResultInvalidCategory());
|
||||
}
|
||||
|
||||
/* If we used the receive buffer, signal that we're done with it. */
|
||||
if (task->IsReceiveBufferRequired()) {
|
||||
os::SignalEvent(std::addressof(m_receive_buffer_available_events[header->task_id]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result RpcClient::ReceiveHeader(RpcPacket *header) {
|
||||
/* Receive. */
|
||||
s64 received;
|
||||
R_TRY(m_driver->Receive(std::addressof(received), reinterpret_cast<char *>(header), sizeof(*header), m_channel_id, htclow::ReceiveOption_ReceiveAllData));
|
||||
|
||||
/* Check size. */
|
||||
R_UNLESS(static_cast<size_t>(received) == sizeof(*header), htc::ResultInvalidSize());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result RpcClient::ReceiveBody(char *dst, size_t size) {
|
||||
/* Receive. */
|
||||
s64 received;
|
||||
R_TRY(m_driver->Receive(std::addressof(received), dst, size, m_channel_id, htclow::ReceiveOption_ReceiveAllData));
|
||||
|
||||
/* Check size. */
|
||||
R_UNLESS(static_cast<size_t>(received) == size, htc::ResultInvalidSize());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
Result RpcClient::SendThread() {
|
||||
while (true) {
|
||||
/* Get a task. */
|
||||
Task *task;
|
||||
u32 task_id{};
|
||||
PacketCategory category{};
|
||||
do {
|
||||
/* Dequeue a task. */
|
||||
R_TRY(m_task_queue.Take(std::addressof(task_id), std::addressof(category)));
|
||||
|
||||
/* Get the task from the table. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
task = m_task_table.Get<Task>(task_id);
|
||||
} while (task == nullptr);
|
||||
|
||||
/* If required, wait for the send buffer to become available. */
|
||||
if (task->IsSendBufferRequired()) {
|
||||
os::WaitEvent(std::addressof(m_send_buffer_available_events[task_id]));
|
||||
|
||||
/* Check if we've been cancelled. */
|
||||
if (m_cancelled) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Handle the task. */
|
||||
size_t packet_size;
|
||||
switch (category) {
|
||||
case PacketCategory::Request:
|
||||
R_TRY(task->CreateRequest(std::addressof(packet_size), m_send_buffer, sizeof(m_send_buffer), task_id));
|
||||
break;
|
||||
case PacketCategory::Notification:
|
||||
R_TRY(task->CreateNotification(std::addressof(packet_size), m_send_buffer, sizeof(m_send_buffer), task_id));
|
||||
break;
|
||||
AMS_UNREACHABLE_DEFAULT_CASE();
|
||||
}
|
||||
|
||||
/* Send the request. */
|
||||
R_TRY(this->SendRequest(m_send_buffer, packet_size));
|
||||
}
|
||||
|
||||
R_THROW(htc::ResultCancelled());
|
||||
}
|
||||
|
||||
Result RpcClient::SendRequest(const char *src, size_t size) {
|
||||
/* Sanity check our size. */
|
||||
AMS_ASSERT(util::IsIntValueRepresentable<s64>(size));
|
||||
|
||||
/* Send the data. */
|
||||
s64 sent;
|
||||
R_TRY(m_driver->Send(std::addressof(sent), src, static_cast<s64>(size), m_channel_id));
|
||||
|
||||
/* Check that we sent the right amount. */
|
||||
R_UNLESS(sent == static_cast<s64>(size), htc::ResultInvalidSize());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void RpcClient::CancelBySocket(s32 handle) {
|
||||
/* Check if we need to cancel each task. */
|
||||
for (size_t i = 0; i < MaxRpcCount; ++i) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Check that the task is active and is an htcs task. */
|
||||
if (!m_task_active[i] || !m_is_htcs_task[i]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Get the htcs task. */
|
||||
auto *htcs_task = m_task_table.Get<htcs::impl::rpc::HtcsTask>(i);
|
||||
|
||||
/* Handle the case where the task handle is the one we're cancelling. */
|
||||
if (this->GetTaskHandle(i) == handle) {
|
||||
/* If the task is complete, free it. */
|
||||
if (htcs_task->GetTaskState() == RpcTaskState::Completed) {
|
||||
m_task_active[i] = false;
|
||||
m_is_htcs_task[i] = false;
|
||||
m_task_table.Delete(i);
|
||||
m_task_id_free_list.Free(i);
|
||||
} else {
|
||||
/* If the task is a send task, notify. */
|
||||
if (htcs_task->GetTaskType() == htcs::impl::rpc::HtcsTaskType::Send) {
|
||||
m_task_queue.Add(i, PacketCategory::Notification);
|
||||
}
|
||||
|
||||
/* Cancel the task. */
|
||||
htcs_task->Cancel(RpcTaskCancelReason::BySocket);
|
||||
}
|
||||
|
||||
/* The task has been cancelled, so we can move on. */
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Handle the case where the task is a select task. */
|
||||
if (htcs_task->GetTaskType() == htcs::impl::rpc::HtcsTaskType::Select) {
|
||||
/* Get the select task. */
|
||||
auto *select_task = m_task_table.Get<htcs::impl::rpc::SelectTask>(i);
|
||||
|
||||
/* Get the handle counts. */
|
||||
const auto num_read = select_task->GetReadHandleCount();
|
||||
const auto num_write = select_task->GetWriteHandleCount();
|
||||
const auto num_exception = select_task->GetExceptionHandleCount();
|
||||
const auto total = num_read + num_write + num_exception;
|
||||
|
||||
/* Get the handle array. */
|
||||
const auto *handles = select_task->GetHandles();
|
||||
|
||||
/* Check each handle. */
|
||||
for (auto handle_idx = 0; handle_idx < total; ++handle_idx) {
|
||||
if (handles[handle_idx] == handle) {
|
||||
/* If the select is complete, free it. */
|
||||
if (select_task->GetTaskState() == RpcTaskState::Completed) {
|
||||
m_task_active[i] = false;
|
||||
m_is_htcs_task[i] = false;
|
||||
m_task_table.Delete(i);
|
||||
m_task_id_free_list.Free(i);
|
||||
} else {
|
||||
/* Cancel the task. */
|
||||
select_task->Cancel(RpcTaskCancelReason::BySocket);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s32 RpcClient::GetTaskHandle(u32 task_id) {
|
||||
/* TODO: Why is this necessary to avoid a bogus array-bounds warning? */
|
||||
AMS_ASSUME(task_id < MaxRpcCount);
|
||||
|
||||
/* Check pre-conditions. */
|
||||
AMS_ASSERT(m_task_active[task_id]);
|
||||
AMS_ASSERT(m_is_htcs_task[task_id]);
|
||||
|
||||
/* Get the htcs task. */
|
||||
auto *task = m_task_table.Get<htcs::impl::rpc::HtcsTask>(task_id);
|
||||
|
||||
/* Check that the task has a handle. */
|
||||
if (!m_task_active[task_id] || !m_is_htcs_task[task_id] || task == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Get the task's type. */
|
||||
const auto type = task->GetTaskType();
|
||||
|
||||
/* Check that the task is new enough. */
|
||||
if (task->GetVersion() == 3) {
|
||||
if (type == htcs::impl::rpc::HtcsTaskType::Receive || type == htcs::impl::rpc::HtcsTaskType::Send) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the handle from the task. */
|
||||
switch (type) {
|
||||
case htcs::impl::rpc::HtcsTaskType::Receive:
|
||||
return static_cast<htcs::impl::rpc::ReceiveTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Send:
|
||||
return static_cast<htcs::impl::rpc::SendTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Shutdown:
|
||||
return static_cast<htcs::impl::rpc::ShutdownTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Close:
|
||||
return -1;
|
||||
case htcs::impl::rpc::HtcsTaskType::Connect:
|
||||
return static_cast<htcs::impl::rpc::ConnectTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Listen:
|
||||
return static_cast<htcs::impl::rpc::ListenTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Accept:
|
||||
return static_cast<htcs::impl::rpc::AcceptTask *>(task)->GetServerHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Socket:
|
||||
return -1;
|
||||
case htcs::impl::rpc::HtcsTaskType::Bind:
|
||||
return static_cast<htcs::impl::rpc::BindTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Fcntl:
|
||||
return static_cast<htcs::impl::rpc::FcntlTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::ReceiveSmall:
|
||||
return static_cast<htcs::impl::rpc::ReceiveSmallTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::SendSmall:
|
||||
return static_cast<htcs::impl::rpc::SendSmallTask *>(task)->GetHandle();
|
||||
case htcs::impl::rpc::HtcsTaskType::Select:
|
||||
return -1;
|
||||
AMS_UNREACHABLE_DEFAULT_CASE();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
#include "../driver/htc_i_driver.hpp"
|
||||
#include "htc_rpc_task_table.hpp"
|
||||
#include "htc_rpc_task_queue.hpp"
|
||||
#include "htc_rpc_task_id_free_list.hpp"
|
||||
#include "../../../htcs/impl/rpc/htcs_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
template<typename T>
|
||||
concept IsRpcTask = std::derived_from<T, Task>;
|
||||
|
||||
struct RpcTaskFunctionTraits {
|
||||
public:
|
||||
template<typename R, typename C, typename... A>
|
||||
static std::tuple<A...> GetSetArgumentsImpl(R(C::*)(A...));
|
||||
template<typename R, typename C, typename... A>
|
||||
static std::tuple<A...> GetGetResultImpl(R(C::*)(A...) const);
|
||||
};
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
using RpcTaskArgumentsType = decltype(RpcTaskFunctionTraits::GetSetArgumentsImpl(&T::SetArguments));
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
using RpcTaskResultsType = decltype(RpcTaskFunctionTraits::GetGetResultImpl(&T::GetResult));
|
||||
|
||||
template<typename T, size_t Ix> requires IsRpcTask<T>
|
||||
using RpcTaskArgumentType = typename std::tuple_element<Ix, RpcTaskArgumentsType<T>>::type;
|
||||
|
||||
template<typename T, size_t Ix> requires IsRpcTask<T>
|
||||
using RpcTaskResultType = typename std::tuple_element<Ix, RpcTaskResultsType<T>>::type;
|
||||
|
||||
class RpcClient {
|
||||
private:
|
||||
/* TODO: where is this value coming from, again? */
|
||||
static constexpr size_t BufferSize = 0xE400;
|
||||
private:
|
||||
mem::StandardAllocator *m_allocator;
|
||||
driver::IDriver *m_driver;
|
||||
htclow::ChannelId m_channel_id;
|
||||
void *m_receive_thread_stack;
|
||||
void *m_send_thread_stack;
|
||||
os::ThreadType m_receive_thread;
|
||||
os::ThreadType m_send_thread;
|
||||
os::SdkMutex &m_mutex;
|
||||
RpcTaskIdFreeList &m_task_id_free_list;
|
||||
RpcTaskTable &m_task_table;
|
||||
bool m_task_active[MaxRpcCount];
|
||||
bool m_is_htcs_task[MaxRpcCount];
|
||||
RpcTaskQueue m_task_queue;
|
||||
bool m_cancelled;
|
||||
bool m_thread_running;
|
||||
os::EventType m_receive_buffer_available_events[MaxRpcCount];
|
||||
os::EventType m_send_buffer_available_events[MaxRpcCount];
|
||||
char m_receive_buffer[BufferSize];
|
||||
char m_send_buffer[BufferSize];
|
||||
private:
|
||||
static void ReceiveThreadEntry(void *arg) { static_cast<RpcClient *>(arg)->ReceiveThread(); }
|
||||
static void SendThreadEntry(void *arg) { static_cast<RpcClient *>(arg)->SendThread(); }
|
||||
|
||||
Result ReceiveThread();
|
||||
Result SendThread();
|
||||
public:
|
||||
RpcClient(driver::IDriver *driver, htclow::ChannelId channel);
|
||||
RpcClient(mem::StandardAllocator *allocator, driver::IDriver *driver, htclow::ChannelId channel);
|
||||
~RpcClient();
|
||||
public:
|
||||
void Open();
|
||||
void Close();
|
||||
|
||||
Result Start();
|
||||
void Cancel();
|
||||
void Wait();
|
||||
|
||||
int WaitAny(htclow::ChannelState state, os::EventType *event);
|
||||
private:
|
||||
Result ReceiveHeader(RpcPacket *header);
|
||||
Result ReceiveBody(char *dst, size_t size);
|
||||
Result SendRequest(const char *src, size_t size);
|
||||
private:
|
||||
s32 GetTaskHandle(u32 task_id);
|
||||
public:
|
||||
void Wait(u32 task_id) {
|
||||
os::WaitEvent(m_task_table.Get<Task>(task_id)->GetEvent());
|
||||
}
|
||||
|
||||
os::NativeHandle DetachReadableHandle(u32 task_id) {
|
||||
return os::DetachReadableHandleOfSystemEvent(m_task_table.Get<Task>(task_id)->GetSystemEvent());
|
||||
}
|
||||
|
||||
void CancelBySocket(s32 handle);
|
||||
|
||||
template<typename T, typename... Args> requires (IsRpcTask<T> && sizeof...(Args) == std::tuple_size<RpcTaskArgumentsType<T>>::value)
|
||||
Result Begin(u32 *out_task_id, Args &&... args) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Allocate a free task id. */
|
||||
u32 task_id{};
|
||||
R_TRY(m_task_id_free_list.Allocate(std::addressof(task_id)));
|
||||
|
||||
/* Create the new task. */
|
||||
T *task = m_task_table.New<T>(task_id);
|
||||
m_task_active[task_id] = true;
|
||||
m_is_htcs_task[task_id] = htcs::impl::rpc::IsHtcsTask<T>;
|
||||
|
||||
/* Ensure we clean up the task, if we fail after this. */
|
||||
auto task_guard = SCOPE_GUARD {
|
||||
m_task_active[task_id] = false;
|
||||
m_is_htcs_task[task_id] = false;
|
||||
m_task_table.Delete<T>(task_id);
|
||||
m_task_id_free_list.Free(task_id);
|
||||
};
|
||||
|
||||
/* Set the task arguments. */
|
||||
R_TRY(task->SetArguments(std::forward<Args>(args)...));
|
||||
|
||||
/* Clear the task's events. */
|
||||
os::ClearEvent(std::addressof(m_receive_buffer_available_events[task_id]));
|
||||
os::ClearEvent(std::addressof(m_send_buffer_available_events[task_id]));
|
||||
|
||||
/* Add the task to our queue if we can, or cancel it. */
|
||||
if (m_thread_running) {
|
||||
m_task_queue.Add(task_id, PacketCategory::Request);
|
||||
} else {
|
||||
task->Cancel(RpcTaskCancelReason::QueueNotAvailable);
|
||||
}
|
||||
|
||||
/* Set the output task id. */
|
||||
*out_task_id = task_id;
|
||||
|
||||
/* We succeeded. */
|
||||
task_guard.Cancel();
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
template<typename T, typename... Args> requires (IsRpcTask<T> && sizeof...(Args) == std::tuple_size<RpcTaskResultsType<T>>::value)
|
||||
Result GetResult(u32 task_id, Args &&... args) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* Check that the task is completed. */
|
||||
R_UNLESS(task->GetTaskState() == RpcTaskState::Completed, htc::ResultTaskNotCompleted());
|
||||
|
||||
/* Get the task's result. */
|
||||
R_TRY(task->GetResult(std::forward<Args>(args)...));
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
template<typename T, typename... Args> requires (IsRpcTask<T> && sizeof...(Args) == std::tuple_size<RpcTaskResultsType<T>>::value)
|
||||
Result End(u32 task_id, Args &&... args) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* Ensure the task is freed if it needs to be, when we're done. */
|
||||
auto task_guard = SCOPE_GUARD {
|
||||
m_task_active[task_id] = false;
|
||||
m_is_htcs_task[task_id] = false;
|
||||
m_task_table.Delete<T>(task_id);
|
||||
m_task_id_free_list.Free(task_id);
|
||||
};
|
||||
|
||||
/* If the task was cancelled, handle that. */
|
||||
if (task->GetTaskState() == RpcTaskState::Cancelled) {
|
||||
switch (task->GetTaskCancelReason()) {
|
||||
case RpcTaskCancelReason::BySocket:
|
||||
task_guard.Cancel();
|
||||
R_THROW(htc::ResultTaskCancelled());
|
||||
case RpcTaskCancelReason::ClientFinalized:
|
||||
R_THROW(htc::ResultCancelled());
|
||||
case RpcTaskCancelReason::QueueNotAvailable:
|
||||
R_THROW(htc::ResultTaskQueueNotAvailable());
|
||||
AMS_UNREACHABLE_DEFAULT_CASE();
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the task's result. */
|
||||
R_TRY(task->GetResult(std::forward<Args>(args)...));
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
Result VerifyTaskIdWithHandle(u32 task_id, s32 handle) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* Check the task handle. */
|
||||
R_UNLESS(task->GetHandle() == handle, htc::ResultInvalidTaskId());
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
Result Notify(u32 task_id) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Check that our queue is available. */
|
||||
R_UNLESS(m_thread_running, htc::ResultTaskQueueNotAvailable());
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* Add notification to our queue. */
|
||||
m_task_queue.Add(task_id, PacketCategory::Notification);
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
void WaitNotification(u32 task_id) {
|
||||
/* Get the task from the table, releasing our lock afterwards. */
|
||||
T *task;
|
||||
{
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
task = m_task_table.Get<T>(task_id);
|
||||
}
|
||||
|
||||
/* Wait for a notification. */
|
||||
task->WaitNotification();
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
bool IsCancelled(u32 task_id) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
|
||||
/* Check the task state. */
|
||||
return task != nullptr && task->GetTaskState() == RpcTaskState::Cancelled;
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
bool IsCompleted(u32 task_id) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
|
||||
/* Check the task state. */
|
||||
return task != nullptr && task->GetTaskState() == RpcTaskState::Completed;
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
Result SendContinue(u32 task_id, const void *buffer, s64 buffer_size) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* If the task was cancelled, handle that. */
|
||||
if (task->GetTaskState() == RpcTaskState::Cancelled) {
|
||||
switch (task->GetTaskCancelReason()) {
|
||||
case RpcTaskCancelReason::QueueNotAvailable:
|
||||
R_THROW(htc::ResultTaskQueueNotAvailable());
|
||||
default:
|
||||
R_THROW(htc::ResultTaskCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
/* Set the task's buffer. */
|
||||
if (buffer_size > 0) {
|
||||
task->SetBuffer(buffer, buffer_size);
|
||||
os::SignalEvent(std::addressof(m_send_buffer_available_events[task_id]));
|
||||
}
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
template<typename T> requires IsRpcTask<T>
|
||||
Result ReceiveContinue(u32 task_id, void *buffer, s64 buffer_size) {
|
||||
/* Get the task's buffer, and prepare to receive. */
|
||||
const void *result_buffer;
|
||||
s64 result_size;
|
||||
{
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Get the task. */
|
||||
T *task = m_task_table.Get<T>(task_id);
|
||||
R_UNLESS(task != nullptr, htc::ResultInvalidTaskId());
|
||||
|
||||
/* If the task was cancelled, handle that. */
|
||||
if (task->GetTaskState() == RpcTaskState::Cancelled) {
|
||||
switch (task->GetTaskCancelReason()) {
|
||||
case RpcTaskCancelReason::QueueNotAvailable:
|
||||
R_THROW(htc::ResultTaskQueueNotAvailable());
|
||||
default:
|
||||
R_THROW(htc::ResultTaskCancelled());
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the result size. */
|
||||
result_size = task->GetResultSize();
|
||||
R_SUCCEED_IF(result_size == 0);
|
||||
|
||||
/* Get the result buffer. */
|
||||
result_buffer = task->GetBuffer();
|
||||
}
|
||||
|
||||
/* Wait for the receive buffer to become available. */
|
||||
os::WaitEvent(std::addressof(m_receive_buffer_available_events[task_id]));
|
||||
|
||||
/* Check that we weren't cancelled. */
|
||||
R_UNLESS(!m_cancelled, htc::ResultCancelled());
|
||||
|
||||
/* Copy the received data. */
|
||||
AMS_ASSERT(0 <= result_size && result_size <= buffer_size);
|
||||
AMS_UNUSED(buffer_size);
|
||||
|
||||
std::memcpy(buffer, result_buffer, result_size);
|
||||
|
||||
R_SUCCEED();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_rpc_tasks.hpp"
|
||||
#include "htc_htcmisc_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
class RpcTaskIdFreeList {
|
||||
private:
|
||||
u32 m_task_ids[MaxRpcCount];
|
||||
u32 m_offset;
|
||||
u32 m_free_count;
|
||||
public:
|
||||
constexpr RpcTaskIdFreeList() : m_task_ids(), m_offset(0), m_free_count(MaxRpcCount) {
|
||||
for (auto i = 0; i < static_cast<int>(MaxRpcCount); ++i) {
|
||||
m_task_ids[i] = i;
|
||||
}
|
||||
}
|
||||
|
||||
Result Allocate(u32 *out) {
|
||||
/* Check that we have free tasks. */
|
||||
R_UNLESS(m_free_count > 0, htc::ResultOutOfRpcTask());
|
||||
|
||||
/* Get index. */
|
||||
const auto index = m_offset;
|
||||
m_offset = (m_offset + 1) % MaxRpcCount;
|
||||
--m_free_count;
|
||||
|
||||
/* Get the task id. */
|
||||
*out = m_task_ids[index];
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
void Free(u32 task_id) {
|
||||
/* Check pre-conditions. */
|
||||
AMS_ASSERT(m_free_count < static_cast<int>(MaxRpcCount));
|
||||
|
||||
/* Determine index. */
|
||||
const auto index = ((m_free_count++) + m_offset) % MaxRpcCount;
|
||||
|
||||
/* Set the task id. */
|
||||
m_task_ids[index] = task_id;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_rpc_tasks.hpp"
|
||||
#include "htc_htcmisc_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
class RpcTaskQueue {
|
||||
private:
|
||||
u32 m_task_ids[MaxRpcCount];
|
||||
PacketCategory m_task_categories[MaxRpcCount];
|
||||
int m_offset;
|
||||
int m_count;
|
||||
os::SdkConditionVariable m_cv;
|
||||
os::SdkMutex m_mutex;
|
||||
bool m_cancelled;
|
||||
public:
|
||||
constexpr RpcTaskQueue() = default;
|
||||
|
||||
void Initialize() {
|
||||
m_offset = 0;
|
||||
m_count = 0;
|
||||
m_cancelled = false;
|
||||
}
|
||||
|
||||
void Finalize() {
|
||||
m_offset = 0;
|
||||
m_count = 0;
|
||||
}
|
||||
|
||||
void Cancel() {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Cancel ourselves. */
|
||||
m_cancelled = true;
|
||||
|
||||
/* Signal to consumers/producers. */
|
||||
m_cv.Signal();
|
||||
}
|
||||
|
||||
void Add(u32 task_id, PacketCategory category) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Check pre-conditions. */
|
||||
AMS_ASSERT(m_count < static_cast<int>(MaxRpcCount));
|
||||
|
||||
/* Determine index. */
|
||||
const auto index = ((m_count++) + m_offset) % MaxRpcCount;
|
||||
|
||||
/* Set task. */
|
||||
m_task_ids[index] = task_id;
|
||||
m_task_categories[index] = category;
|
||||
|
||||
/* Signal. */
|
||||
if (m_count > 0) {
|
||||
m_cv.Signal();
|
||||
}
|
||||
}
|
||||
|
||||
Result Take(u32 *out_id, PacketCategory *out_category) {
|
||||
/* Lock ourselves. */
|
||||
std::scoped_lock lk(m_mutex);
|
||||
|
||||
/* Wait until we can take. */
|
||||
while (m_count == 0 && !m_cancelled) {
|
||||
m_cv.Wait(m_mutex);
|
||||
}
|
||||
|
||||
/* Check that we're not cancelled. */
|
||||
R_UNLESS(!m_cancelled, htc::ResultCancelled());
|
||||
|
||||
/* Determine index. */
|
||||
const auto index = m_offset;
|
||||
|
||||
/* Advance the queue. */
|
||||
m_offset = (m_offset + 1) % MaxRpcCount;
|
||||
--m_count;
|
||||
|
||||
/* Return the task info. */
|
||||
*out_id = m_task_ids[index];
|
||||
*out_category = m_task_categories[index];
|
||||
R_SUCCEED();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
#include "htc_rpc_tasks.hpp"
|
||||
#include "htc_htcmisc_rpc_tasks.hpp"
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
/* For convenience. */
|
||||
template<typename T>
|
||||
concept IsTypeCheckableTask = std::derived_from<T, Task> && requires (T &t) {
|
||||
{ t.GetTaskType() } -> std::convertible_to<decltype(T::TaskType)>;
|
||||
};
|
||||
|
||||
static_assert(!IsTypeCheckableTask<Task>);
|
||||
static_assert(IsTypeCheckableTask<GetEnvironmentVariableTask>);
|
||||
|
||||
class RpcTaskTable {
|
||||
private:
|
||||
/* htcs::ReceiveSmallTask/htcs::ReceiveSendTask are the largest tasks, containing an inline 0xE000 buffer. */
|
||||
/* We allow for ~0x100 task overhead from the additional events those contain. */
|
||||
/* NOTE: Nintendo hardcodes a maximum size of 0xE1D8, despite SendSmallTask being 0xE098 as of latest check. */
|
||||
#if defined(ATMOSPHERE_OS_HORIZON)
|
||||
static constexpr size_t MaxTaskSize = 0xE100;
|
||||
#elif defined(ATMOSPHERE_OS_MACOS)
|
||||
static constexpr size_t MaxTaskSize = 0xE400;
|
||||
#else
|
||||
static constexpr size_t MaxTaskSize = 0xE1D8;
|
||||
#endif
|
||||
struct TaskStorage { alignas(alignof(void *)) std::byte _storage[MaxTaskSize]; };
|
||||
private:
|
||||
bool m_valid[MaxRpcCount]{};
|
||||
TaskStorage m_storages[MaxRpcCount]{};
|
||||
private:
|
||||
template<typename T>
|
||||
ALWAYS_INLINE T *GetPointer(u32 index) {
|
||||
static_assert(alignof(T) <= alignof(TaskStorage));
|
||||
static_assert(sizeof(T) <= sizeof(TaskStorage));
|
||||
return reinterpret_cast<T *>(std::addressof(m_storages[index]));
|
||||
}
|
||||
|
||||
ALWAYS_INLINE bool IsValid(u32 index) {
|
||||
return index < MaxRpcCount && m_valid[index];
|
||||
}
|
||||
public:
|
||||
constexpr RpcTaskTable() = default;
|
||||
|
||||
template<typename T> requires std::derived_from<T, Task>
|
||||
T *New(u32 index) {
|
||||
/* Sanity check input. */
|
||||
AMS_ASSERT(!this->IsValid(index));
|
||||
|
||||
/* Set valid. */
|
||||
m_valid[index] = true;
|
||||
|
||||
/* Allocate the task. */
|
||||
T *task = this->GetPointer<T>(index);
|
||||
|
||||
/* Create the task. */
|
||||
std::construct_at(task);
|
||||
|
||||
/* Return the task. */
|
||||
return task;
|
||||
}
|
||||
|
||||
template<typename T> requires std::derived_from<T, Task>
|
||||
T *Get(u32 index) {
|
||||
/* Check that the task is valid. */
|
||||
if (!this->IsValid(index)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Get the task pointer. */
|
||||
T *task = this->GetPointer<T>(index);
|
||||
|
||||
/* Type check the task. */
|
||||
if constexpr (IsTypeCheckableTask<T>) {
|
||||
if (task->GetTaskType() != T::TaskType) {
|
||||
task = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Return the task. */
|
||||
return task;
|
||||
}
|
||||
|
||||
template<typename T> requires std::derived_from<T, Task>
|
||||
void Delete(u32 index) {
|
||||
/* Check that the task is valid. */
|
||||
if (!this->IsValid(index)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* Delete the task. */
|
||||
std::destroy_at(this->GetPointer<T>(index));
|
||||
|
||||
/* Mark the task as invalid. */
|
||||
m_valid[index] = false;
|
||||
}
|
||||
|
||||
void Delete(u32 index) {
|
||||
if (this->IsValid(index)) {
|
||||
this->Delete<Task>(index);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (c) Atmosphère-NX
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms and conditions of the GNU General Public License,
|
||||
* version 2, as published by the Free Software Foundation.
|
||||
*
|
||||
* This program is distributed in the hope it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stratosphere.hpp>
|
||||
|
||||
namespace ams::htc::server::rpc {
|
||||
|
||||
constexpr inline size_t MaxRpcCount = 0x48;
|
||||
|
||||
enum class PacketCategory : s16 {
|
||||
Request = 0,
|
||||
Response = 1,
|
||||
Notification = 2,
|
||||
};
|
||||
|
||||
struct RpcPacket {
|
||||
s16 protocol;
|
||||
s16 version;
|
||||
PacketCategory category;
|
||||
u16 type;
|
||||
s64 body_size;
|
||||
u32 task_id{};
|
||||
u64 params[5];
|
||||
char data[];
|
||||
};
|
||||
static_assert(sizeof(RpcPacket) == 0x40);
|
||||
|
||||
enum class RpcTaskCancelReason {
|
||||
None = 0,
|
||||
BySocket = 1,
|
||||
ClientFinalized = 2,
|
||||
QueueNotAvailable = 3,
|
||||
};
|
||||
|
||||
enum class RpcTaskState {
|
||||
Started = 0,
|
||||
Completed = 1,
|
||||
Cancelled = 2,
|
||||
Notified = 3,
|
||||
};
|
||||
|
||||
class Task {
|
||||
private:
|
||||
RpcTaskState m_state;
|
||||
RpcTaskCancelReason m_cancel_reason;
|
||||
os::Event m_event;
|
||||
public:
|
||||
Task() : m_state(RpcTaskState::Started), m_cancel_reason(RpcTaskCancelReason::None), m_event(os::EventClearMode_AutoClear) { /* ... */ }
|
||||
virtual ~Task() { /* ... */ }
|
||||
public:
|
||||
void SetTaskState(RpcTaskState state) { m_state = state; }
|
||||
RpcTaskState GetTaskState() const { return m_state; }
|
||||
|
||||
RpcTaskCancelReason GetTaskCancelReason() const { return m_cancel_reason; }
|
||||
|
||||
os::EventType *GetEvent() { return m_event.GetBase(); }
|
||||
|
||||
void Notify() {
|
||||
AMS_ASSERT(m_state == RpcTaskState::Started);
|
||||
|
||||
m_state = RpcTaskState::Notified;
|
||||
}
|
||||
|
||||
void Complete() {
|
||||
AMS_ASSERT(m_state == RpcTaskState::Started || m_state == RpcTaskState::Notified);
|
||||
|
||||
m_state = RpcTaskState::Completed;
|
||||
m_event.Signal();
|
||||
}
|
||||
public:
|
||||
virtual void Cancel(RpcTaskCancelReason reason) {
|
||||
m_state = RpcTaskState::Cancelled;
|
||||
m_cancel_reason = reason;
|
||||
m_event.Signal();
|
||||
}
|
||||
|
||||
virtual Result ProcessResponse(const char *data, size_t size) {
|
||||
AMS_UNUSED(data, size);
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
virtual Result CreateRequest(size_t *out, char *data, size_t size, u32 task_id) {
|
||||
AMS_UNUSED(out, data, size, task_id);
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
virtual Result ProcessNotification(const char *data, size_t size) {
|
||||
AMS_UNUSED(data, size);
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
virtual Result CreateNotification(size_t *out, char *data, size_t size, u32 task_id) {
|
||||
AMS_UNUSED(out, data, size, task_id);
|
||||
R_SUCCEED();
|
||||
}
|
||||
|
||||
virtual bool IsReceiveBufferRequired() {
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual bool IsSendBufferRequired() {
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual os::SystemEventType *GetSystemEvent() {
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user