libstrat: refactor for R_TRY

This commit is contained in:
Michael Scire 2019-06-20 05:01:24 -07:00
parent 7c9df9cfd8
commit 4a120c3c16
17 changed files with 345 additions and 418 deletions

View File

@ -20,6 +20,8 @@ SOURCES := source
DATA := data DATA := data
INCLUDES := include INCLUDES := include
DEFINES := -DRESULT_ABORT_ON_ASSERT
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
# options for code generation # options for code generation
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------

View File

@ -20,6 +20,7 @@
#include <vector> #include <vector>
#include "iwaitable.hpp" #include "iwaitable.hpp"
#include "results.hpp"
class IEvent : public IWaitable { class IEvent : public IWaitable {
public: public:
@ -115,9 +116,7 @@ static IEvent *CreateHosEvent(F f, bool autoclear = false) {
template <class F> template <class F>
static IEvent *CreateSystemEvent(F f, bool autoclear = false) { static IEvent *CreateSystemEvent(F f, bool autoclear = false) {
Handle w_h, r_h; Handle w_h, r_h;
if (R_FAILED(svcCreateEvent(&w_h, &r_h))) { R_ASSERT(svcCreateEvent(&w_h, &r_h));
std::abort();
}
return new HosEvent<F>(r_h, w_h, std::move(f), autoclear); return new HosEvent<F>(r_h, w_h, std::move(f), autoclear);
} }
@ -125,9 +124,7 @@ template <class F>
static IEvent *CreateInterruptEvent(F f, u64 irq, bool autoclear = false) { static IEvent *CreateInterruptEvent(F f, u64 irq, bool autoclear = false) {
Handle r_h; Handle r_h;
/* flag is "rising edge vs level". */ /* flag is "rising edge vs level". */
if (R_FAILED(svcCreateInterruptEvent(&r_h, irq, autoclear ? 0 : 1))) { R_ASSERT(svcCreateInterruptEvent(&r_h, irq, autoclear ? 0 : 1));
std::abort();
}
return new HosEvent<F>(r_h, INVALID_HANDLE, std::move(f), autoclear); return new HosEvent<F>(r_h, INVALID_HANDLE, std::move(f), autoclear);
} }

View File

@ -18,6 +18,7 @@
#include <switch.h> #include <switch.h>
#include <switch/arm/counter.h> #include <switch/arm/counter.h>
#include <mutex> #include <mutex>
#include "results.hpp"
class HosMutex { class HosMutex {
private: private:
@ -273,11 +274,9 @@ class HosThread {
} }
Result Join() { Result Join() {
Result rc = threadWaitForExit(&this->thr); R_TRY(threadWaitForExit(&this->thr));
if (R_SUCCEEDED(rc)) { R_TRY(threadClose(&this->thr));
rc = threadClose(&this->thr); return ResultSuccess;
}
return rc;
} }
Result CancelSynchronization() { Result CancelSynchronization() {

View File

@ -572,11 +572,7 @@ constexpr Result WrapIpcCommandImpl(IpcResponseContext *ctx) {
ipcInitialize(&ctx->reply); ipcInitialize(&ctx->reply);
memset(ctx->out_data, 0, CommandMetaData::OutRawArgSize); memset(ctx->out_data, 0, CommandMetaData::OutRawArgSize);
Result rc = Validator::Validate<CommandMetaData>(ctx); R_TRY(Validator::Validate<CommandMetaData>(ctx));
if (R_FAILED(rc)) {
return rc;
}
ClassType *this_ptr = nullptr; ClassType *this_ptr = nullptr;
if (IsDomainObject(ctx->obj_holder)) { if (IsDomainObject(ctx->obj_holder)) {
@ -588,32 +584,11 @@ constexpr Result WrapIpcCommandImpl(IpcResponseContext *ctx) {
return ResultServiceFrameworkTargetNotFound; return ResultServiceFrameworkTargetNotFound;
} }
size_t num_out_objects;
std::shared_ptr<IServiceObject> out_objects[CommandMetaData::NumOutSessions]; std::shared_ptr<IServiceObject> out_objects[CommandMetaData::NumOutSessions];
/* Allocate out object IDs. */ auto cleanup_guard = SCOPE_GUARD {
size_t num_out_objects;
if (IsDomainObject(ctx->obj_holder)) {
for (num_out_objects = 0; num_out_objects < CommandMetaData::NumOutSessions; num_out_objects++) {
if (R_FAILED((rc = ctx->obj_holder->GetServiceObject<IDomainObject>()->ReserveObject(&ctx->out_object_ids[num_out_objects])))) {
break;
}
ctx->out_objs[num_out_objects] = &out_objects[num_out_objects];
}
} else {
for (num_out_objects = 0; num_out_objects < CommandMetaData::NumOutSessions; num_out_objects++) {
Handle server_h, client_h;
if (R_FAILED((rc = SessionManagerBase::CreateSessionHandles(&server_h, &client_h)))) {
break;
}
ctx->out_object_server_handles[num_out_objects] = server_h;
ctx->out_handles[CommandMetaData::NumOutHandles + num_out_objects].handle = client_h;
ctx->out_objs[num_out_objects] = &out_objects[num_out_objects];
}
}
ON_SCOPE_EXIT {
/* Clean up objects as necessary. */ /* Clean up objects as necessary. */
if (R_FAILED(rc)) {
if (IsDomainObject(ctx->obj_holder)) { if (IsDomainObject(ctx->obj_holder)) {
for (unsigned int i = 0; i < num_out_objects; i++) { for (unsigned int i = 0; i < num_out_objects; i++) {
ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->out_object_ids[i]); ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->out_object_ids[i]);
@ -624,32 +599,54 @@ constexpr Result WrapIpcCommandImpl(IpcResponseContext *ctx) {
svcCloseHandle(ctx->out_handles[CommandMetaData::NumOutHandles + i].handle); svcCloseHandle(ctx->out_handles[CommandMetaData::NumOutHandles + i].handle);
} }
} }
}
for (unsigned int i = 0; i < num_out_objects; i++) { for (unsigned int i = 0; i < num_out_objects; i++) {
ctx->out_objs[i] = nullptr; ctx->out_objs[i] = nullptr;
} }
}; };
if (R_SUCCEEDED(rc)) { /* Allocate out object IDs. */
if (IsDomainObject(ctx->obj_holder)) {
for (num_out_objects = 0; num_out_objects < CommandMetaData::NumOutSessions; num_out_objects++) {
R_TRY_CLEANUP(ctx->obj_holder->GetServiceObject<IDomainObject>()->ReserveObject(&ctx->out_object_ids[num_out_objects]), {
std::apply(Encoder<CommandMetaData, typename CommandMetaData::Args>::EncodeFailure, std::tuple_cat(std::make_tuple(ctx), std::make_tuple(R_CLEANUP_RESULT)));
});
ctx->out_objs[num_out_objects] = &out_objects[num_out_objects];
}
} else {
for (num_out_objects = 0; num_out_objects < CommandMetaData::NumOutSessions; num_out_objects++) {
Handle server_h, client_h;
R_TRY_CLEANUP(SessionManagerBase::CreateSessionHandles(&server_h, &client_h), {
std::apply(Encoder<CommandMetaData, typename CommandMetaData::Args>::EncodeFailure, std::tuple_cat(std::make_tuple(ctx), std::make_tuple(R_CLEANUP_RESULT)));
});
ctx->out_object_server_handles[num_out_objects] = server_h;
ctx->out_handles[CommandMetaData::NumOutHandles + num_out_objects].handle = client_h;
ctx->out_objs[num_out_objects] = &out_objects[num_out_objects];
}
}
/* Decode, apply, encode. */
{
auto args = Decoder<CommandMetaData>::Decode(ctx); auto args = Decoder<CommandMetaData>::Decode(ctx);
if constexpr (CommandMetaData::ReturnsResult) { if constexpr (CommandMetaData::ReturnsResult) {
rc = std::apply( [=](auto&&... args) { return (this_ptr->*IpcCommandImpl)(args...); }, args); R_TRY_CLEANUP(std::apply( [=](auto&&... args) { return (this_ptr->*IpcCommandImpl)(args...); }, args), {
std::apply(Encoder<CommandMetaData, decltype(args)>::EncodeFailure, std::tuple_cat(std::make_tuple(ctx), std::make_tuple(R_CLEANUP_RESULT)));
});
} else { } else {
std::apply( [=](auto&&... args) { (this_ptr->*IpcCommandImpl)(args...); }, args); std::apply( [=](auto&&... args) { (this_ptr->*IpcCommandImpl)(args...); }, args);
} }
if (R_SUCCEEDED(rc)) {
std::apply(Encoder<CommandMetaData, decltype(args)>::EncodeSuccess, std::tuple_cat(std::make_tuple(ctx), args)); std::apply(Encoder<CommandMetaData, decltype(args)>::EncodeSuccess, std::tuple_cat(std::make_tuple(ctx), args));
} else {
std::apply(Encoder<CommandMetaData, decltype(args)>::EncodeFailure, std::tuple_cat(std::make_tuple(ctx), std::make_tuple(rc)));
}
} else {
std::apply(Encoder<CommandMetaData, typename CommandMetaData::Args>::EncodeFailure, std::tuple_cat(std::make_tuple(ctx), std::make_tuple(rc)));
} }
return rc; /* Cancel object guard, clear remaining object references. */
cleanup_guard.Cancel();
for (unsigned int i = 0; i < num_out_objects; i++) {
ctx->out_objs[i] = nullptr;
}
return ResultSuccess;
} }

View File

@ -75,12 +75,10 @@ class ServiceSession : public IWaitable
} }
/* Receive. */ /* Receive. */
Result rc = svcReplyAndReceive(&handle_index, &this->session_handle, 1, 0, U64_MAX); R_TRY(svcReplyAndReceive(&handle_index, &this->session_handle, 1, 0, U64_MAX));
if (R_SUCCEEDED(rc)) {
std::memcpy(this->backup_tls, armGetTls(), sizeof(this->backup_tls));
}
return rc; std::memcpy(this->backup_tls, armGetTls(), sizeof(this->backup_tls));
return ResultSuccess;
} }
Result Reply() { Result Reply() {
@ -130,7 +128,6 @@ class ServiceSession : public IWaitable
} }
virtual Result GetResponse(IpcResponseContext *ctx) { virtual Result GetResponse(IpcResponseContext *ctx) {
Result rc = ResultKernelConnectionClosed;
FirmwareVersion fw = GetRuntimeFirmwareVersion(); FirmwareVersion fw = GetRuntimeFirmwareVersion();
const ServiceCommandMeta *dispatch_table = ctx->obj_holder->GetDispatchTable(); const ServiceCommandMeta *dispatch_table = ctx->obj_holder->GetDispatchTable();
@ -156,12 +153,12 @@ class ServiceSession : public IWaitable
for (size_t i = 0; i < entry_count; i++) { for (size_t i = 0; i < entry_count; i++) {
if (ctx->cmd_id == dispatch_table[i].cmd_id && dispatch_table[i].fw_low <= fw && fw <= dispatch_table[i].fw_high) { if (ctx->cmd_id == dispatch_table[i].cmd_id && dispatch_table[i].fw_low <= fw && fw <= dispatch_table[i].fw_high) {
rc = dispatch_table[i].handler(ctx); R_TRY(dispatch_table[i].handler(ctx));
break; break;
} }
} }
return rc; return ResultSuccess;
} }
virtual Result HandleReceived() { virtual Result HandleReceived() {
@ -233,22 +230,25 @@ class ServiceSession : public IWaitable
virtual Result HandleDeferred() override { virtual Result HandleDeferred() override {
memcpy(armGetTls(), this->backup_tls, sizeof(this->backup_tls)); memcpy(armGetTls(), this->backup_tls, sizeof(this->backup_tls));
Result rc = this->HandleReceived();
if (rc != ResultServiceFrameworkRequestDeferredByUser) { auto defer_guard = SCOPE_GUARD {
this->SetDeferred(false); this->SetDeferred(false);
};
R_TRY_CATCH(this->HandleReceived()) {
R_CATCH(ResultServiceFrameworkRequestDeferredByUser) {
defer_guard.Cancel();
return ResultServiceFrameworkRequestDeferredByUser;
} }
return rc; } R_END_TRY_CATCH;
return ResultSuccess;
} }
virtual Result HandleSignaled(u64 timeout) { virtual Result HandleSignaled(u64 timeout) {
Result rc; R_TRY(this->Receive());
R_TRY(this->HandleReceived());
if (R_SUCCEEDED(rc = this->Receive())) { return ResultSuccess;
rc = this->HandleReceived();
}
return rc;
} }
virtual void PreProcessRequest(IpcResponseContext *ctx) { virtual void PreProcessRequest(IpcResponseContext *ctx) {
@ -286,10 +286,7 @@ class ServiceSession : public IWaitable
/* Reserve an object in the domain for our session. */ /* Reserve an object in the domain for our session. */
u32 reserved_id; u32 reserved_id;
Result rc = new_domain->ReserveObject(&reserved_id); R_TRY(new_domain->ReserveObject(&reserved_id));
if (R_FAILED(rc)) {
return rc;
}
new_domain->SetObject(reserved_id, std::move(this->session->obj_holder)); new_domain->SetObject(reserved_id, std::move(this->session->obj_holder));
this->session->obj_holder = std::move(ServiceObjectHolder(std::move(new_domain))); this->session->obj_holder = std::move(ServiceObjectHolder(std::move(new_domain)));
@ -311,10 +308,7 @@ class ServiceSession : public IWaitable
} }
Handle server_h, client_h; Handle server_h, client_h;
if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) { R_ASSERT(SessionManagerBase::CreateSessionHandles(&server_h, &client_h));
/* N aborts here. Should we error code? */
std::abort();
}
this->session->GetSessionManager()->AddSession(server_h, std::move(object->Clone())); this->session->GetSessionManager()->AddSession(server_h, std::move(object->Clone()));
out_h.SetValue(client_h); out_h.SetValue(client_h);
@ -323,10 +317,7 @@ class ServiceSession : public IWaitable
void CloneCurrentObject(Out<MovedHandle> out_h) { void CloneCurrentObject(Out<MovedHandle> out_h) {
Handle server_h, client_h; Handle server_h, client_h;
if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) { R_ASSERT(SessionManagerBase::CreateSessionHandles(&server_h, &client_h));
/* N aborts here. Should we error code? */
std::abort();
}
this->session->GetSessionManager()->AddSession(server_h, std::move(this->session->obj_holder.Clone())); this->session->GetSessionManager()->AddSession(server_h, std::move(this->session->obj_holder.Clone()));
out_h.SetValue(client_h); out_h.SetValue(client_h);

View File

@ -41,9 +41,7 @@ class MitmServer : public IWaitable {
DoWithSmMitmSession([&]() { DoWithSmMitmSession([&]() {
strncpy(mitm_name, service_name, 8); strncpy(mitm_name, service_name, 8);
mitm_name[8] = '\x00'; mitm_name[8] = '\x00';
if (R_FAILED(smMitMInstall(&this->port_handle, &query_h, mitm_name))) { R_ASSERT(smMitMInstall(&this->port_handle, &query_h, mitm_name));
std::abort();
}
}); });
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
@ -53,9 +51,7 @@ class MitmServer : public IWaitable {
virtual ~MitmServer() override { virtual ~MitmServer() override {
if (this->port_handle) { if (this->port_handle) {
DoWithSmMitmSession([&]() { DoWithSmMitmSession([&]() {
if (R_FAILED(smMitMUninstall(this->mitm_name))) { R_ASSERT(smMitMUninstall(this->mitm_name));
std::abort();
}
}); });
svcCloseHandle(port_handle); svcCloseHandle(port_handle);
} }
@ -73,10 +69,7 @@ class MitmServer : public IWaitable {
virtual Result HandleSignaled(u64 timeout) override { virtual Result HandleSignaled(u64 timeout) override {
/* If this server's port was signaled, accept a new session. */ /* If this server's port was signaled, accept a new session. */
Handle session_h; Handle session_h;
Result rc = svcAcceptSession(&session_h, this->port_handle); R_TRY(svcAcceptSession(&session_h, this->port_handle));
if (R_FAILED(rc)) {
return rc;
}
/* Create a forward service for this instance. */ /* Create a forward service for this instance. */
std::shared_ptr<Service> forward_service(new Service(), [](Service *s) { std::shared_ptr<Service> forward_service(new Service(), [](Service *s) {
@ -88,9 +81,7 @@ class MitmServer : public IWaitable {
u64 client_pid; u64 client_pid;
DoWithSmMitmSession([&]() { DoWithSmMitmSession([&]() {
if (R_FAILED(smMitMAcknowledgeSession(forward_service.get(), &client_pid, mitm_name))) { R_ASSERT(smMitMAcknowledgeSession(forward_service.get(), &client_pid, mitm_name));
std::abort();
}
}); });
this->GetSessionManager()->AddWaitable(new MitmSession(session_h, client_pid, forward_service, MakeShared(forward_service, client_pid))); this->GetSessionManager()->AddWaitable(new MitmSession(session_h, client_pid, forward_service, MakeShared(forward_service, client_pid)));

View File

@ -49,9 +49,7 @@ class MitmSession final : public ServiceSession {
this->service_post_process_ctx->handler = T::PostProcess; this->service_post_process_ctx->handler = T::PostProcess;
size_t pbs; size_t pbs;
if (R_FAILED(ipcQueryPointerBufferSize(forward_service->handle, &pbs))) { R_ASSERT(ipcQueryPointerBufferSize(forward_service->handle, &pbs));
std::abort();
}
this->pointer_buffer.resize(pbs); this->pointer_buffer.resize(pbs);
this->control_holder.Reset(); this->control_holder.Reset();
this->control_holder = std::move(ServiceObjectHolder(std::move(std::make_shared<IMitmHipcControlService>(this)))); this->control_holder = std::move(ServiceObjectHolder(std::move(std::make_shared<IMitmHipcControlService>(this))));
@ -65,9 +63,7 @@ class MitmSession final : public ServiceSession {
this->service_post_process_ctx = ppc; this->service_post_process_ctx = ppc;
size_t pbs; size_t pbs;
if (R_FAILED(ipcQueryPointerBufferSize(forward_service->handle, &pbs))) { R_ASSERT(ipcQueryPointerBufferSize(forward_service->handle, &pbs));
std::abort();
}
this->pointer_buffer.resize(pbs); this->pointer_buffer.resize(pbs);
this->control_holder.Reset(); this->control_holder.Reset();
this->control_holder = std::move(ServiceObjectHolder(std::move(std::make_shared<IMitmHipcControlService>(this)))); this->control_holder = std::move(ServiceObjectHolder(std::move(std::make_shared<IMitmHipcControlService>(this))));
@ -84,9 +80,12 @@ class MitmSession final : public ServiceSession {
} }
Result ForwardRequest(IpcResponseContext *ctx) { Result ForwardRequest(IpcResponseContext *ctx) {
/* Dispatch forwards. */
R_TRY(serviceIpcDispatch(this->forward_service.get()));
/* Parse. */
{
IpcParsedCommand r; IpcParsedCommand r;
Result rc = serviceIpcDispatch(this->forward_service.get());
if (R_SUCCEEDED(rc)) {
if (ctx->request.IsDomainRequest) { if (ctx->request.IsDomainRequest) {
/* We never work with out object ids, so this should be fine. */ /* We never work with out object ids, so this should be fine. */
ipcParseDomainResponse(&r, 0); ipcParseDomainResponse(&r, 0);
@ -99,19 +98,19 @@ class MitmSession final : public ServiceSession {
u64 result; u64 result;
} *resp = (decltype(resp))r.Raw; } *resp = (decltype(resp))r.Raw;
rc = resp->result;
for (unsigned int i = 0; i < r.NumHandles; i++) { for (unsigned int i = 0; i < r.NumHandles; i++) {
if (r.WasHandleCopied[i]) { if (r.WasHandleCopied[i]) {
this->fwd_copy_hnds[num_fwd_copy_hnds++] = r.Handles[i]; this->fwd_copy_hnds[num_fwd_copy_hnds++] = r.Handles[i];
} }
} }
R_TRY(resp->result);
} }
return rc;
return ResultSuccess;
} }
virtual Result GetResponse(IpcResponseContext *ctx) { virtual Result GetResponse(IpcResponseContext *ctx) {
Result rc = ResultKernelConnectionClosed;
FirmwareVersion fw = GetRuntimeFirmwareVersion(); FirmwareVersion fw = GetRuntimeFirmwareVersion();
const ServiceCommandMeta *dispatch_table = ctx->obj_holder->GetDispatchTable(); const ServiceCommandMeta *dispatch_table = ctx->obj_holder->GetDispatchTable();
@ -125,31 +124,29 @@ class MitmSession final : public ServiceSession {
{ {
auto sub_obj = ctx->obj_holder->GetServiceObject<IDomainObject>()->GetObject(ctx->request.InThisObjectId); auto sub_obj = ctx->obj_holder->GetServiceObject<IDomainObject>()->GetObject(ctx->request.InThisObjectId);
if (sub_obj == nullptr) { if (sub_obj == nullptr) {
rc = ForwardRequest(ctx); R_TRY(ForwardRequest(ctx));
return rc; return ResultSuccess;
} }
if (sub_obj->IsMitmObject()) { if (sub_obj->IsMitmObject()) {
rc = ForwardRequest(ctx); R_TRY(ForwardRequest(ctx));
if (R_SUCCEEDED(rc)) {
ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->request.InThisObjectId); ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->request.InThisObjectId);
}
} else { } else {
rc = ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->request.InThisObjectId); R_TRY(ctx->obj_holder->GetServiceObject<IDomainObject>()->FreeObject(ctx->request.InThisObjectId));
} }
if (R_SUCCEEDED(rc) && ctx->request.InThisObjectId == serviceGetObjectId(this->forward_service.get()) && !this->service_post_process_ctx->closed) { if (ctx->request.InThisObjectId == serviceGetObjectId(this->forward_service.get()) && !this->service_post_process_ctx->closed) {
/* If we're not longer MitMing anything, we'll no longer do any postprocessing. */ /* If we're not longer MitMing anything, we'll no longer do any postprocessing. */
this->service_post_process_ctx->closed = true; this->service_post_process_ctx->closed = true;
} }
return rc; return ResultSuccess;
} }
case DomainMessageType_SendMessage: case DomainMessageType_SendMessage:
{ {
auto sub_obj = ctx->obj_holder->GetServiceObject<IDomainObject>()->GetObject(ctx->request.InThisObjectId); auto sub_obj = ctx->obj_holder->GetServiceObject<IDomainObject>()->GetObject(ctx->request.InThisObjectId);
if (sub_obj == nullptr) { if (sub_obj == nullptr) {
rc = ForwardRequest(ctx); R_TRY(ForwardRequest(ctx));
return rc; return ResultSuccess;
} }
dispatch_table = sub_obj->GetDispatchTable(); dispatch_table = sub_obj->GetDispatchTable();
entry_count = sub_obj->GetDispatchTableEntryCount(); entry_count = sub_obj->GetDispatchTableEntryCount();
@ -157,22 +154,29 @@ class MitmSession final : public ServiceSession {
} }
} }
bool found_entry = false; Result (*handler)(IpcResponseContext *ctx) = nullptr;
for (size_t i = 0; i < entry_count; i++) { for (size_t i = 0; i < entry_count; i++) {
if (ctx->cmd_id == dispatch_table[i].cmd_id && dispatch_table[i].fw_low <= fw && fw <= dispatch_table[i].fw_high) { if (ctx->cmd_id == dispatch_table[i].cmd_id && dispatch_table[i].fw_low <= fw && fw <= dispatch_table[i].fw_high) {
rc = dispatch_table[i].handler(ctx); handler = dispatch_table[i].handler;
found_entry = true;
break; break;
} }
} }
if (!found_entry || rc == ResultAtmosphereMitmShouldForwardToSession) { if (handler == nullptr) {
memcpy(armGetTls(), this->backup_tls, sizeof(this->backup_tls)); R_TRY(ForwardRequest(ctx));
rc = ForwardRequest(ctx); return ResultSuccess;
} }
return rc; R_TRY_CATCH(handler(ctx)) {
R_CATCH(ResultAtmosphereMitmShouldForwardToSession) {
std::memcpy(armGetTls(), this->backup_tls, sizeof(this->backup_tls));
R_TRY(ForwardRequest(ctx));
return ResultSuccess;
}
} R_END_TRY_CATCH;
return ResultSuccess;
} }
virtual void PostProcessResponse(IpcResponseContext *ctx) override { virtual void PostProcessResponse(IpcResponseContext *ctx) override {
@ -231,10 +235,7 @@ class MitmSession final : public ServiceSession {
return ResultKernelConnectionClosed; return ResultKernelConnectionClosed;
} }
Result rc = serviceConvertToDomain(this->session->forward_service.get()); R_TRY(serviceConvertToDomain(this->session->forward_service.get()));
if (R_FAILED(rc)) {
return rc;
}
u32 expected_id = serviceGetObjectId(this->session->forward_service.get()); u32 expected_id = serviceGetObjectId(this->session->forward_service.get());
@ -276,29 +277,24 @@ class MitmSession final : public ServiceSession {
buf[7] = 0; buf[7] = 0;
buf[8] = id; buf[8] = id;
buf[9] = 0; buf[9] = 0;
Result rc = ipcDispatch(this->session->forward_service->handle); R_TRY(ipcDispatch(this->session->forward_service->handle));
if (R_SUCCEEDED(rc)) { {
IpcParsedCommand r; IpcParsedCommand r;
ipcParse(&r); ipcParse(&r);
struct { struct {
u64 magic; u64 magic;
u64 result; u64 result;
} *raw = (decltype(raw))r.Raw; } *raw = (decltype(raw))r.Raw;
rc = raw->result; R_TRY(raw->result);
if (R_SUCCEEDED(rc)) {
out_h.SetValue(r.Handles[0]); out_h.SetValue(r.Handles[0]);
this->session->fwd_copy_hnds[this->session->num_fwd_copy_hnds++] = r.Handles[0]; this->session->fwd_copy_hnds[this->session->num_fwd_copy_hnds++] = r.Handles[0];
} }
} return ResultSuccess;
return rc;
} }
Handle server_h, client_h; Handle server_h, client_h;
if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) { R_ASSERT(SessionManagerBase::CreateSessionHandles(&server_h, &client_h));
/* N aborts here. Should we error code? */
std::abort();
}
out_h.SetValue(client_h); out_h.SetValue(client_h);
if (id == serviceGetObjectId(this->session->forward_service.get())) { if (id == serviceGetObjectId(this->session->forward_service.get())) {
@ -311,10 +307,7 @@ class MitmSession final : public ServiceSession {
void CloneCurrentObject(Out<MovedHandle> out_h) { void CloneCurrentObject(Out<MovedHandle> out_h) {
Handle server_h, client_h; Handle server_h, client_h;
if (R_FAILED(SessionManagerBase::CreateSessionHandles(&server_h, &client_h))) { R_ASSERT(SessionManagerBase::CreateSessionHandles(&server_h, &client_h));
/* N aborts here. Should we error code? */
std::abort();
}
this->session->GetSessionManager()->AddWaitable(new MitmSession(server_h, this->session->client_pid, this->session->forward_service, std::move(this->session->obj_holder.Clone()), this->session->service_post_process_ctx)); this->session->GetSessionManager()->AddWaitable(new MitmSession(server_h, this->session->client_pid, this->session->forward_service, std::move(this->session->obj_holder.Clone()), this->session->service_post_process_ctx));
out_h.SetValue(client_h); out_h.SetValue(client_h);

View File

@ -75,12 +75,14 @@ extern "C" {
}) })
/// Evaluates an expression that returns a result, and returns the result (after evaluating a cleanup expression) if it would fail. /// Evaluates an expression that returns a result, and returns the result (after evaluating a cleanup expression) if it would fail.
#define R_CLEANUP_RESULT _tmp_r_try_cleanup_rc
#define R_TRY_CLEANUP(res_expr, cleanup_expr) \ #define R_TRY_CLEANUP(res_expr, cleanup_expr) \
({ \ ({ \
const Result _tmp_r_try_cleanup_rc = res_expr; \ const Result R_CLEANUP_RESULT = res_expr; \
if (R_FAILED(_tmp_r_try_cleanup_rc)) { \ if (R_FAILED(R_CLEANUP_RESULT)) { \
({ cleanup_expr }); \ ({ cleanup_expr }); \
return _tmp_r_try_cleanup_rc; \ return R_CLEANUP_RESULT; \
} \ } \
}) })

View File

@ -49,10 +49,7 @@ class IServer : public IWaitable {
virtual Result HandleSignaled(u64 timeout) override { virtual Result HandleSignaled(u64 timeout) override {
/* If this server's port was signaled, accept a new session. */ /* If this server's port was signaled, accept a new session. */
Handle session_h; Handle session_h;
Result rc = svcAcceptSession(&session_h, this->port_handle); R_TRY(svcAcceptSession(&session_h, this->port_handle));
if (R_FAILED(rc)) {
return rc;
}
this->GetSessionManager()->AddSession(session_h, std::move(ServiceObjectHolder(std::move(MakeShared())))); this->GetSessionManager()->AddSession(session_h, std::move(ServiceObjectHolder(std::move(MakeShared()))));
return ResultSuccess; return ResultSuccess;
@ -64,9 +61,7 @@ class ServiceServer : public IServer<T, MakeShared> {
public: public:
ServiceServer(const char *service_name, unsigned int max_s) : IServer<T, MakeShared>(max_s) { ServiceServer(const char *service_name, unsigned int max_s) : IServer<T, MakeShared>(max_s) {
DoWithSmSession([&]() { DoWithSmSession([&]() {
if (R_FAILED(smRegisterService(&this->port_handle, service_name, false, this->max_sessions))) { R_ASSERT(smRegisterService(&this->port_handle, service_name, false, this->max_sessions));
std::abort();
}
}); });
} }
}; };
@ -83,8 +78,6 @@ template <typename T, auto MakeShared = std::make_shared<T>>
class ManagedPortServer : public IServer<T, MakeShared> { class ManagedPortServer : public IServer<T, MakeShared> {
public: public:
ManagedPortServer(const char *service_name, unsigned int max_s) : IServer<T, MakeShared>(max_s) { ManagedPortServer(const char *service_name, unsigned int max_s) : IServer<T, MakeShared>(max_s) {
if (R_FAILED(svcManageNamedPort(&this->port_handle, service_name, this->max_sessions))) { R_ASSERT(svcManageNamedPort(&this->port_handle, service_name, this->max_sessions));
std::abort();
}
} }
}; };

View File

@ -70,51 +70,41 @@ static inline Result SmcGetConfig(SplConfigItem config_item, u64 *out_config) {
args.X[0] = 0xC3000002; /* smcGetConfig */ args.X[0] = 0xC3000002; /* smcGetConfig */
args.X[1] = (u64)config_item; /* config item */ args.X[1] = (u64)config_item; /* config item */
Result rc = svcCallSecureMonitor(&args); R_TRY(svcCallSecureMonitor(&args));
if (R_SUCCEEDED(rc)) { if (args.X[0] != 0) {
if (args.X[0] == 0) { /* SPL result n = SMC result n */
return MAKERESULT(26, args.X[0]);
}
if (out_config) { if (out_config) {
*out_config = args.X[1]; *out_config = args.X[1];
} }
} else { return ResultSuccess;
/* SPL result n = SMC result n */
rc = MAKERESULT(26, args.X[0]);
}
}
return rc;
} }
static inline Result GetRcmBugPatched(bool *out) { static inline Result GetRcmBugPatched(bool *out) {
u64 tmp = 0; u64 tmp = 0;
Result rc = SmcGetConfig((SplConfigItem)65004, &tmp); R_TRY(SmcGetConfig((SplConfigItem)65004, &tmp));
if (R_SUCCEEDED(rc)) {
*out = (tmp != 0); *out = (tmp != 0);
} return ResultSuccess;
return rc;
} }
static inline bool IsRcmBugPatched() { static inline bool IsRcmBugPatched() {
bool rcm_bug_patched; bool rcm_bug_patched;
if (R_FAILED(GetRcmBugPatched(&rcm_bug_patched))) { R_ASSERT(GetRcmBugPatched(&rcm_bug_patched));
std::abort();
}
return rcm_bug_patched; return rcm_bug_patched;
} }
static inline Result GetShouldBlankProdInfo(bool *out) { static inline Result GetShouldBlankProdInfo(bool *out) {
u64 tmp = 0; u64 tmp = 0;
Result rc = SmcGetConfig((SplConfigItem)65005, &tmp); R_TRY(SmcGetConfig((SplConfigItem)65005, &tmp));
if (R_SUCCEEDED(rc)) {
*out = (tmp != 0); *out = (tmp != 0);
} return ResultSuccess;
return rc;
} }
static inline bool ShouldBlankProdInfo() { static inline bool ShouldBlankProdInfo() {
bool should_blank_prodinfo; bool should_blank_prodinfo;
if (R_FAILED(GetShouldBlankProdInfo(&should_blank_prodinfo))) { R_ASSERT(GetShouldBlankProdInfo(&should_blank_prodinfo));
std::abort();
}
return should_blank_prodinfo; return should_blank_prodinfo;
} }
@ -125,13 +115,8 @@ template<typename F>
static void DoWithSmSession(F f) { static void DoWithSmSession(F f) {
std::scoped_lock<HosRecursiveMutex &> lk(GetSmSessionMutex()); std::scoped_lock<HosRecursiveMutex &> lk(GetSmSessionMutex());
{ {
Result rc; R_ASSERT(smInitialize());
if (R_SUCCEEDED((rc = smInitialize()))) {
f(); f();
} else {
/* TODO: fatalSimple(rc); ? */
std::abort();
}
smExit(); smExit();
} }
} }
@ -140,13 +125,8 @@ template<typename F>
static void DoWithSmMitmSession(F f) { static void DoWithSmMitmSession(F f) {
std::scoped_lock<HosRecursiveMutex &> lk(GetSmMitmSessionMutex()); std::scoped_lock<HosRecursiveMutex &> lk(GetSmMitmSessionMutex());
{ {
Result rc; R_ASSERT(smMitMInitialize());
if (R_SUCCEEDED((rc = smMitMInitialize()))) {
f(); f();
} else {
/* TODO: fatalSimple(rc); ? */
std::abort();
}
smMitMExit(); smMitMExit();
} }
} }

View File

@ -75,16 +75,11 @@ class WaitableManager : public SessionManagerBase {
public: public:
WaitableManager(u32 n, u32 ss = 0x8000) : num_extra_threads(n-1) { WaitableManager(u32 n, u32 ss = 0x8000) : num_extra_threads(n-1) {
u32 prio; u32 prio;
Result rc;
if (num_extra_threads) { if (num_extra_threads) {
threads = new HosThread[num_extra_threads]; threads = new HosThread[num_extra_threads];
if (R_FAILED((rc = svcGetThreadPriority(&prio, CUR_THREAD_HANDLE)))) { R_ASSERT(svcGetThreadPriority(&prio, CUR_THREAD_HANDLE));
fatalSimple(rc);
}
for (unsigned int i = 0; i < num_extra_threads; i++) { for (unsigned int i = 0; i < num_extra_threads; i++) {
if (R_FAILED(threads[i].Initialize(&WaitableManager::ProcessLoop, this, ss, prio))) { R_ASSERT(threads[i].Initialize(&WaitableManager::ProcessLoop, this, ss, prio));
std::abort();
}
} }
} }
} }
@ -130,11 +125,8 @@ class WaitableManager : public SessionManagerBase {
/* Set main thread handle. */ /* Set main thread handle. */
this->main_thread_handle = GetCurrentThreadHandle(); this->main_thread_handle = GetCurrentThreadHandle();
Result rc;
for (unsigned int i = 0; i < num_extra_threads; i++) { for (unsigned int i = 0; i < num_extra_threads; i++) {
if (R_FAILED((rc = threads[i].Start()))) { R_ASSERT(threads[i].Start());
fatalSimple(rc);
}
} }
ProcessLoop(this); ProcessLoop(this);
@ -167,8 +159,7 @@ class WaitableManager : public SessionManagerBase {
} }
} }
if (w) { if (w) {
Result rc = w->HandleSignaled(0); if (w->HandleSignaled(0) == ResultKernelConnectionClosed) {
if (rc == ResultKernelConnectionClosed) {
/* Close! */ /* Close! */
delete w; delete w;
} else { } else {
@ -189,11 +180,11 @@ class WaitableManager : public SessionManagerBase {
undeferred_any = false; undeferred_any = false;
for (auto it = this_ptr->deferred_waitables.begin(); it != this_ptr->deferred_waitables.end();) { for (auto it = this_ptr->deferred_waitables.begin(); it != this_ptr->deferred_waitables.end();) {
auto w = *it; auto w = *it;
Result rc = w->HandleDeferred(); const bool closed = (w->HandleDeferred() == ResultKernelConnectionClosed);
if (rc == ResultKernelConnectionClosed || !w->IsDeferred()) { if (closed || !w->IsDeferred()) {
/* Remove from the deferred list, set iterator. */ /* Remove from the deferred list, set iterator. */
it = this_ptr->deferred_waitables.erase(it); it = this_ptr->deferred_waitables.erase(it);
if (rc == ResultKernelConnectionClosed) { if (closed) {
/* Delete the closed waitable. */ /* Delete the closed waitable. */
delete w; delete w;
} else { } else {
@ -249,7 +240,6 @@ class WaitableManager : public SessionManagerBase {
std::vector<IWaitable *> wait_list; std::vector<IWaitable *> wait_list;
int handle_index = 0; int handle_index = 0;
Result rc;
while (result == nullptr) { while (result == nullptr) {
/* Sort waitables by priority. */ /* Sort waitables by priority. */
std::sort(this->waitables.begin(), this->waitables.end(), IWaitable::Compare); std::sort(this->waitables.begin(), this->waitables.end(), IWaitable::Compare);
@ -269,21 +259,21 @@ class WaitableManager : public SessionManagerBase {
} }
/* Wait forever. */ /* Wait forever. */
rc = svcWaitSynchronization(&handle_index, handles.data(), num_handles, U64_MAX); const Result wait_res = svcWaitSynchronization(&handle_index, handles.data(), num_handles, U64_MAX);
if (this->should_stop) { if (this->should_stop) {
return nullptr; return nullptr;
} }
if (R_SUCCEEDED(rc)) { if (R_SUCCEEDED(wait_res)) {
IWaitable *w = wait_list[handle_index]; IWaitable *w = wait_list[handle_index];
size_t w_ind = std::distance(this->waitables.begin(), std::find(this->waitables.begin(), this->waitables.end(), w)); size_t w_ind = std::distance(this->waitables.begin(), std::find(this->waitables.begin(), this->waitables.end(), w));
std::for_each(waitables.begin(), waitables.begin() + w_ind + 1, std::mem_fn(&IWaitable::UpdatePriority)); std::for_each(waitables.begin(), waitables.begin() + w_ind + 1, std::mem_fn(&IWaitable::UpdatePriority));
result = w; result = w;
} else if (rc == ResultKernelTimedOut) { } else if (wait_res == ResultKernelTimedOut) {
/* Timeout: Just update priorities. */ /* Timeout: Just update priorities. */
std::for_each(waitables.begin(), waitables.end(), std::mem_fn(&IWaitable::UpdatePriority)); std::for_each(waitables.begin(), waitables.end(), std::mem_fn(&IWaitable::UpdatePriority));
} else if (rc == ResultKernelCancelled) { } else if (wait_res == ResultKernelCancelled) {
/* svcCancelSynchronization was called. */ /* svcCancelSynchronization was called. */
AddWaitablesInternal(); AddWaitablesInternal();
{ {

View File

@ -80,7 +80,8 @@ static void _CacheValues(void)
args.X[0] = 0xF0000404; /* smcAmsGetEmunandConfig */ args.X[0] = 0xF0000404; /* smcAmsGetEmunandConfig */
args.X[1] = 0; /* NAND */ args.X[1] = 0; /* NAND */
args.X[2] = reinterpret_cast<u64>(&paths); /* path output */ args.X[2] = reinterpret_cast<u64>(&paths); /* path output */
if (R_FAILED(svcCallSecureMonitor(&args)) || args.X[0] != 0) { R_ASSERT(svcCallSecureMonitor(&args));
if (args.X[0] != 0) {
std::abort(); std::abort();
} }
std::memcpy(&g_exo_emummc_config, &args.X[1], sizeof(args) - sizeof(args.X[0])); std::memcpy(&g_exo_emummc_config, &args.X[1], sizeof(args) - sizeof(args.X[0]));

View File

@ -39,7 +39,8 @@ static void _CacheValues(void)
SecmonArgs args = {0}; SecmonArgs args = {0};
args.X[0] = 0xC3000002; /* smcGetConfig */ args.X[0] = 0xC3000002; /* smcGetConfig */
args.X[1] = 65000; /* ConfigItem_ExosphereVersion */ args.X[1] = 65000; /* ConfigItem_ExosphereVersion */
if (R_FAILED(svcCallSecureMonitor(&args)) || args.X[0] != 0) { R_ASSERT(svcCallSecureMonitor(&args));
if (args.X[0] != 0) {
std::abort(); std::abort();
} }

View File

@ -23,20 +23,21 @@ static std::vector<u64> g_known_tids;
static HosMutex g_pid_tid_mutex; static HosMutex g_pid_tid_mutex;
Result MitmQueryUtils::GetAssociatedTidForPid(u64 pid, u64 *tid) { Result MitmQueryUtils::GetAssociatedTidForPid(u64 pid, u64 *tid) {
Result rc = ResultAtmosphereMitmProcessNotAssociated; std::scoped_lock lk(g_pid_tid_mutex);
std::scoped_lock lk{g_pid_tid_mutex};
for (unsigned int i = 0; i < g_known_pids.size(); i++) { for (unsigned int i = 0; i < g_known_pids.size(); i++) {
if (g_known_pids[i] == pid) { if (g_known_pids[i] == pid) {
*tid = g_known_tids[i]; *tid = g_known_tids[i];
rc = ResultSuccess; return ResultSuccess;
break;
} }
} }
return rc;
return ResultAtmosphereMitmProcessNotAssociated;
} }
void MitmQueryUtils::AssociatePidToTid(u64 pid, u64 tid) { void MitmQueryUtils::AssociatePidToTid(u64 pid, u64 tid) {
std::scoped_lock lk{g_pid_tid_mutex}; std::scoped_lock lk(g_pid_tid_mutex);
g_known_pids.push_back(pid); g_known_pids.push_back(pid);
g_known_tids.push_back(tid); g_known_tids.push_back(tid);
} }

View File

@ -40,11 +40,7 @@ void RegisterMitmServerQueryHandle(Handle query_h, ServiceObjectHolder &&service
/* If this is our first time, launch thread. */ /* If this is our first time, launch thread. */
if (!exists) { if (!exists) {
if (R_FAILED(g_server_query_manager_thread.Initialize(&ServerQueryManagerThreadFunc, nullptr, 0x4000, 27))) { R_ASSERT(g_server_query_manager_thread.Initialize(&ServerQueryManagerThreadFunc, nullptr, 0x4000, 27));
std::abort(); R_ASSERT(g_server_query_manager_thread.Start());
}
if (R_FAILED(g_server_query_manager_thread.Start())) {
std::abort();
}
} }
} }

View File

@ -120,14 +120,9 @@ void StratosphereCrashHandler(ThreadExceptionDump *ctx) {
/* Default exception handler behavior. */ /* Default exception handler behavior. */
void __attribute__((weak)) __libstratosphere_exception_handler(AtmosphereFatalErrorContext *ctx) { void __attribute__((weak)) __libstratosphere_exception_handler(AtmosphereFatalErrorContext *ctx) {
Result rc = bpcAmsInitialize(); R_ASSERT(bpcAmsInitialize());
if (R_SUCCEEDED(rc)) { R_ASSERT(bpcAmsRebootToFatalError(ctx));
rc = bpcAmsRebootToFatalError(ctx);
bpcAmsExit(); bpcAmsExit();
}
if (R_FAILED(rc)) {
std::abort();
}
while (1) { } while (1) { }
} }

View File

@ -34,9 +34,7 @@ class XorShiftGenerator {
/* Seed using process entropy. */ /* Seed using process entropy. */
u64 val = 0; u64 val = 0;
for (size_t i = 0; i < num_seed_dwords; i++) { for (size_t i = 0; i < num_seed_dwords; i++) {
if (R_FAILED(svcGetInfo(&val, 0xB, 0, i))) { R_ASSERT(svcGetInfo(&val, 0xB, 0, i));
std::abort();
}
this->random_state[i] = result_type(val); this->random_state[i] = result_type(val);
} }
} }