diff --git a/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_impl_program_index_map_info_manager.hpp b/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_impl_program_index_map_info_manager.hpp index 0c43d53f7..34b2c3fff 100644 --- a/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_impl_program_index_map_info_manager.hpp +++ b/libraries/libstratosphere/include/stratosphere/fssrv/impl/fssrv_impl_program_index_map_info_manager.hpp @@ -97,7 +97,7 @@ namespace ams::fssrv::impl { /* Clear the map, and ensure we remain clear if we fail after this point. */ this->ClearImpl(); - auto clear_guard = SCOPE_GUARD { this->ClearImpl(); }; + ON_RESULT_FAILURE { this->ClearImpl(); }; /* Add each info to the list. */ for (int i = 0; i < count; ++i) { @@ -115,8 +115,7 @@ namespace ams::fssrv::impl { } /* We successfully imported the map. */ - clear_guard.Cancel(); - return ResultSuccess(); + R_SUCCEED(); } private: void ClearImpl() { diff --git a/libraries/libstratosphere/include/stratosphere/fssystem/save/fssystem_block_cache_buffered_storage.hpp b/libraries/libstratosphere/include/stratosphere/fssystem/save/fssystem_block_cache_buffered_storage.hpp index d711165d5..815c7fd77 100644 --- a/libraries/libstratosphere/include/stratosphere/fssystem/save/fssystem_block_cache_buffered_storage.hpp +++ b/libraries/libstratosphere/include/stratosphere/fssystem/save/fssystem_block_cache_buffered_storage.hpp @@ -143,12 +143,11 @@ namespace ams::fssystem::save { Result StoreOrDestroyBuffer(const MemoryRange &range, CacheEntry *entry) { AMS_ASSERT(entry != nullptr); - auto buf_guard = SCOPE_GUARD { this->DestroyBuffer(entry, range); }; + ON_RESULT_FAILURE { this->DestroyBuffer(entry, range); }; R_TRY(this->StoreAssociateBuffer(range, *entry)); - buf_guard.Cancel(); - return ResultSuccess(); + R_SUCCEED(); } Result FlushCacheEntry(CacheIndex index, bool invalidate); diff --git a/libraries/libstratosphere/include/stratosphere/kvdb/kvdb_memory_key_value_store.hpp b/libraries/libstratosphere/include/stratosphere/kvdb/kvdb_memory_key_value_store.hpp index 07835329c..d6be4466e 100644 --- a/libraries/libstratosphere/include/stratosphere/kvdb/kvdb_memory_key_value_store.hpp +++ b/libraries/libstratosphere/include/stratosphere/kvdb/kvdb_memory_key_value_store.hpp @@ -325,19 +325,18 @@ namespace ams::kvdb { /* Allocate memory for value. */ void *new_value = m_memory_resource->Allocate(value_size); R_UNLESS(new_value != nullptr, kvdb::ResultAllocationFailed()); - auto value_guard = SCOPE_GUARD { m_memory_resource->Deallocate(new_value, value_size); }; + + /* If we fail before adding to the index, deallocate our value. */ + ON_RESULT_FAILURE { m_memory_resource->Deallocate(new_value, value_size); }; /* Read key and value. */ Key key; R_TRY(reader.ReadEntry(std::addressof(key), sizeof(key), new_value, value_size)); R_TRY(m_index.AddUnsafe(key, new_value, value_size)); - - /* We succeeded, so cancel the value guard to prevent deallocation. */ - value_guard.Cancel(); } } - return ResultSuccess(); + R_SUCCEED(); } Result Save(bool destructive = false) { diff --git a/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp b/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp index af10c89c1..69604e2e4 100644 --- a/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp +++ b/libraries/libstratosphere/include/stratosphere/sf/hipc/sf_hipc_server_session_manager.hpp @@ -98,15 +98,14 @@ namespace ams::sf::hipc { /* Allocate session. */ ServerSession *session_memory = this->AllocateSession(); R_UNLESS(session_memory != nullptr, sf::hipc::ResultOutOfSessionMemory()); + ON_RESULT_FAILURE { this->DestroySession(session_memory); }; /* Register session. */ - auto register_guard = SCOPE_GUARD { this->DestroySession(session_memory); }; R_TRY(ctor(session_memory)); /* Save new session to output. */ - register_guard.Cancel(); *out = session_memory; - return ResultSuccess(); + R_SUCCEED(); } void DestroySession(ServerSession *session); diff --git a/libraries/libstratosphere/include/stratosphere/tipc/tipc_deferral_manager.hpp b/libraries/libstratosphere/include/stratosphere/tipc/tipc_deferral_manager.hpp index 573497068..6e0cc5480 100644 --- a/libraries/libstratosphere/include/stratosphere/tipc/tipc_deferral_manager.hpp +++ b/libraries/libstratosphere/include/stratosphere/tipc/tipc_deferral_manager.hpp @@ -96,6 +96,8 @@ namespace ams::tipc { }; static_assert(std::is_standard_layout::value); + #define TIPC_REGISTER_RETRY_ON_RESULT_REQUEST_DEFERRED(KEY) ON_RESULT_INCLUDED(tipc::ResultRequestDeferred) { this->RegisterRetry(KEY); } + template class DeferrableBaseImplWithBuffer : public DeferrableBaseImpl { private: diff --git a/libraries/libstratosphere/include/stratosphere/tipc/tipc_object_manager.hpp b/libraries/libstratosphere/include/stratosphere/tipc/tipc_object_manager.hpp index 4103cb051..7c1e575ce 100644 --- a/libraries/libstratosphere/include/stratosphere/tipc/tipc_object_manager.hpp +++ b/libraries/libstratosphere/include/stratosphere/tipc/tipc_object_manager.hpp @@ -145,38 +145,44 @@ namespace ams::tipc { /* Get the method id. */ const auto method_id = svc::ipc::MessageBuffer::MessageHeader(message_buffer).GetTag(); - /* Ensure that we clean up any handles that get sent our way. */ - auto handle_guard = SCOPE_GUARD { - const svc::ipc::MessageBuffer::MessageHeader message_header(message_buffer); - const svc::ipc::MessageBuffer::SpecialHeader special_header(message_buffer, message_header); + /* Process for the method id. */ + { + /* Ensure that if we fail, we clean up any handles that get sent our way. */ + ON_RESULT_FAILURE { + const svc::ipc::MessageBuffer::MessageHeader message_header(message_buffer); + const svc::ipc::MessageBuffer::SpecialHeader special_header(message_buffer, message_header); - /* Determine the offset to the start of handles. */ - auto offset = message_buffer.GetSpecialDataIndex(message_header, special_header); - if (special_header.GetHasProcessId()) { - offset += sizeof(u64) / sizeof(u32); - } + /* Determine the offset to the start of handles. */ + auto offset = message_buffer.GetSpecialDataIndex(message_header, special_header); + if (special_header.GetHasProcessId()) { + offset += sizeof(u64) / sizeof(u32); + } - /* Close all copy handles. */ - for (auto i = 0; i < special_header.GetCopyHandleCount(); ++i) { - svc::CloseHandle(message_buffer.GetHandle(offset)); - offset += sizeof(ams::svc::Handle) / sizeof(u32); - } - }; + /* Close all copy handles. */ + for (auto i = 0; i < special_header.GetCopyHandleCount(); ++i) { + svc::CloseHandle(message_buffer.GetHandle(offset)); + offset += sizeof(ams::svc::Handle) / sizeof(u32); + } + }; - /* Check that the method id is valid. */ - R_UNLESS(method_id != MethodId_Invalid, tipc::ResultInvalidMethod()); + /* Check that the method id is valid. */ + R_UNLESS(method_id != MethodId_Invalid, tipc::ResultInvalidMethod()); - /* If we're closing the object, do so. */ - if (method_id == MethodId_CloseSession) { - /* Validate the command format. */ - { + /* Process the request. */ + if (method_id != MethodId_CloseSession) { + /* Process the generic method for the object. */ + R_TRY(object.GetObject()->ProcessRequest()); + } else { + /* Validate that the close request is of valid format. */ using CloseSessionCommandMeta = impl::CommandMetaInfo>; using CloseSessionProcessor = impl::CommandProcessor; - /* Validate that the command is valid. */ R_TRY(CloseSessionProcessor::ValidateCommandFormat(message_buffer)); } + } + /* If we were asked to close the object, do so. */ + if (method_id == MethodId_CloseSession) { /* Get the object handle. */ const auto handle = object.GetHandle(); @@ -187,17 +193,12 @@ namespace ams::tipc { /* NOTE: Nintendo does not check that this succeeds. */ R_ABORT_UNLESS(svc::CloseHandle(handle)); - /* Return result to signify we closed the object (and don't close input handles). */ - handle_guard.Cancel(); - return tipc::ResultSessionClosed(); + /* Return an error to signify we closed the object. */ + R_THROW(tipc::ResultSessionClosed()); } - /* Process the generic method for the object. */ - R_TRY(object.GetObject()->ProcessRequest()); - /* We successfully processed, so we don't need to clean up handles. */ - handle_guard.Cancel(); - return ResultSuccess(); + R_SUCCEED(); } }; diff --git a/libraries/libvapours/include/vapours/results/results_common.hpp b/libraries/libvapours/include/vapours/results/results_common.hpp index 5112851c7..ab93f17b3 100644 --- a/libraries/libvapours/include/vapours/results/results_common.hpp +++ b/libraries/libvapours/include/vapours/results/results_common.hpp @@ -258,15 +258,99 @@ namespace ams { #define R_FAILED(res) (static_cast<::ams::Result>(res).IsFailure()) -/// Evaluates an expression that returns a result, and returns the result if it would fail. -#define R_TRY(res_expr) \ - ({ \ - const auto _tmp_r_try_rc = (res_expr); \ - if (R_FAILED(_tmp_r_try_rc)) { \ - return _tmp_r_try_rc; \ - } \ +/* NOTE: The following are experimental and cannot be safely used yet. */ +/* =================================================================== */ +constinit inline ::ams::Result __TmpCurrentResultReference = ::ams::ResultSuccess(); + +namespace ams::result::impl { + + template + class ScopedResultGuard { + NON_COPYABLE(ScopedResultGuard); + NON_MOVEABLE(ScopedResultGuard); + private: + Result &m_ref; + F m_f; + public: + constexpr ALWAYS_INLINE ScopedResultGuard(Result &ref, F f) : m_ref(ref), m_f(std::move(f)) { } + constexpr ALWAYS_INLINE ~ScopedResultGuard() { if (EvaluateResult(m_ref)) { m_f(); } } + }; + + template + class ResultReferenceForScopedResultGuard { + private: + Result &m_ref; + public: + constexpr ALWAYS_INLINE ResultReferenceForScopedResultGuard(Result &r) : m_ref(r) { /* ... */ } + + constexpr ALWAYS_INLINE operator Result &() const { return m_ref; } + }; + + template + constexpr ALWAYS_INLINE ScopedResultGuard operator+(ResultReferenceForScopedResultGuard ref, F&& f) { + return ScopedResultGuard(static_cast(ref), std::forward(f)); + } + + constexpr ALWAYS_INLINE bool EvaluateResultSuccess(const ::ams::Result &r) { return R_SUCCEEDED(r); } + constexpr ALWAYS_INLINE bool EvaluateResultFailure(const ::ams::Result &r) { return R_FAILED(r); } + + template + constexpr ALWAYS_INLINE bool EvaluateAnyResultIncludes(const ::ams::Result &r) { return (Rs::Includes(r) || ...); } + +} + +#define AMS_DECLARE_CURRENT_RESULT_REFERENCE_AND_STORAGE(COUNTER_VALUE) \ + [[maybe_unused]] constexpr bool HasPrevRef_##COUNTER_VALUE = std::same_as; \ + [[maybe_unused]] auto &PrevRef_##COUNTER_VALUE = __TmpCurrentResultReference; \ + [[maybe_unused]] Result __tmp_result_##COUNTER_VALUE = ResultSuccess(); \ + ::ams::Result &__TmpCurrentResultReference = HasPrevRef_##COUNTER_VALUE ? PrevRef_##COUNTER_VALUE : __tmp_result_##COUNTER_VALUE + +#define ON_RESULT_RETURN_IMPL(EVALUATE_RESULT) \ + static_assert(std::same_as); \ + auto ANONYMOUS_VARIABLE(RESULT_GUARD_STATE_) = ::ams::result::impl::ResultReferenceForScopedResultGuard(__TmpCurrentResultReference) + [&]() ALWAYS_INLINE_LAMBDA + +#define ON_RESULT_FAILURE_2 ON_RESULT_RETURN_IMPL(::ams::result::impl::EvaluateResultFailure) + +#define ON_RESULT_FAILURE \ + AMS_DECLARE_CURRENT_RESULT_REFERENCE_AND_STORAGE(__COUNTER__); \ + ON_RESULT_FAILURE_2 + +#define ON_RESULT_SUCCESS_2 ON_RESULT_RETURN_IMPL(::ams::result::impl::EvaluateResultSuccess) + +#define ON_RESULT_SUCCESS \ + AMS_DECLARE_CURRENT_RESULT_REFERENCE_AND_STORAGE(__COUNTER__); \ + ON_RESULT_SUCCESS_2 + +#define ON_RESULT_INCLUDED_2(RS) ON_RESULT_RETURN_IMPL(::ams::result::impl::EvaluateAnyResultIncludes) + +#define ON_RESULT_INCLUDED(RS) \ + AMS_DECLARE_CURRENT_RESULT_REFERENCE_AND_STORAGE(__COUNTER__); \ + ON_RESULT_INCLUDED_2(RS) + +/* =================================================================== */ + +/// Returns a result. +#define R_THROW(res_expr) \ + ({ \ + const ::ams::Result _tmp_r_throw_rc = (res_expr); \ + if constexpr (std::same_as) { __TmpCurrentResultReference = _tmp_r_throw_rc; } \ + return _tmp_r_throw_rc; \ }) +/// Returns ResultSuccess() +#define R_SUCCEED() R_THROW(::ams::ResultSuccess()) + +/// Evaluates an expression that returns a result, and returns the result if it would fail. +#define R_TRY(res_expr) \ + ({ \ + if (const auto _tmp_r_try_rc = (res_expr); R_FAILED(_tmp_r_try_rc)) { \ + R_THROW(_tmp_r_try_rc); \ + } \ + }) + +/// Return a result. +#define R_RETURN(res_expr) R_THROW(res_expr) + #ifdef AMS_ENABLE_DEBUG_PRINT #define AMS_CALL_ON_RESULT_ASSERTION_IMPL(cond, val) ::ams::result::impl::OnResultAssertion(__FILE__, __LINE__, __PRETTY_FUNCTION__, cond, val) #define AMS_CALL_ON_RESULT_ABORT_IMPL(cond, val) ::ams::result::impl::OnResultAbort(__FILE__, __LINE__, __PRETTY_FUNCTION__, cond, val) @@ -277,39 +361,37 @@ namespace ams { /// Evaluates an expression that returns a result, and asserts the result if it would fail. #ifdef AMS_ENABLE_ASSERTIONS -#define R_ASSERT(res_expr) \ - ({ \ - const auto _tmp_r_assert_rc = (res_expr); \ - if (AMS_UNLIKELY(R_FAILED(_tmp_r_assert_rc))) { \ - AMS_CALL_ON_RESULT_ASSERTION_IMPL(#res_expr, _tmp_r_assert_rc); \ - } \ +#define R_ASSERT(res_expr) \ + ({ \ + if (const auto _tmp_r_assert_rc = (res_expr); AMS_UNLIKELY(R_FAILED(_tmp_r_assert_rc))) { \ + AMS_CALL_ON_RESULT_ASSERTION_IMPL(#res_expr, _tmp_r_assert_rc); \ + } \ }) #else #define R_ASSERT(res_expr) AMS_UNUSED((res_expr)); #endif /// Evaluates an expression that returns a result, and aborts if the result would fail. -#define R_ABORT_UNLESS(res_expr) \ - ({ \ - const auto _tmp_r_abort_rc = (res_expr); \ - if (AMS_UNLIKELY(R_FAILED(_tmp_r_abort_rc))) { \ - AMS_CALL_ON_RESULT_ABORT_IMPL(#res_expr, _tmp_r_abort_rc); \ - } \ +#define R_ABORT_UNLESS(res_expr) \ + ({ \ + if (const auto _tmp_r_abort_rc = (res_expr); AMS_UNLIKELY(R_FAILED(_tmp_r_abort_rc))) { \ + AMS_CALL_ON_RESULT_ABORT_IMPL(#res_expr, _tmp_r_abort_rc); \ + } \ }) /// Evaluates a boolean expression, and returns a result unless that expression is true. #define R_UNLESS(expr, res) \ - ({ \ - if (!(expr)) { \ - return static_cast<::ams::Result>(res); \ - } \ + ({ \ + if (!(expr)) { \ + R_THROW(res); \ + } \ }) /// Evaluates a boolean expression, and succeeds if that expression is true. #define R_SUCCEED_IF(expr) R_UNLESS(!(expr), ResultSuccess()) /// Helpers for pattern-matching on a result expression, if the result would fail. -#define R_CURRENT_RESULT _tmp_r_current_result +#define R_CURRENT_RESULT _tmp_r_try_catch_current_result #define R_TRY_CATCH(res_expr) \ ({ \ @@ -317,17 +399,8 @@ namespace ams { if (R_FAILED(R_CURRENT_RESULT)) { \ if (false) -namespace ams::result::impl { - - template - constexpr ALWAYS_INLINE bool AnyIncludes(Result result) { - return (Rs::Includes(result) || ...); - } - -} - #define R_CATCH(...) \ - } else if (::ams::result::impl::AnyIncludes<__VA_ARGS__>(R_CURRENT_RESULT)) { \ + } else if (::ams::result::impl::EvaluateAnyResultIncludes<__VA_ARGS__>(R_CURRENT_RESULT)) { \ if (true) #define R_CATCH_MODULE(__module__) \ @@ -335,21 +408,21 @@ namespace ams::result::impl { if (true) #define R_CONVERT(catch_type, convert_type) \ - R_CATCH(catch_type) { return static_cast<::ams::Result>(convert_type); } + R_CATCH(catch_type) { R_THROW(static_cast<::ams::Result>(convert_type)); } #define R_CATCH_ALL() \ } else if (R_FAILED(R_CURRENT_RESULT)) { \ if (true) #define R_CONVERT_ALL(convert_type) \ - R_CATCH_ALL() { return static_cast<::ams::Result>(convert_type); } + R_CATCH_ALL() { R_THROW(static_cast<::ams::Result>(convert_type)); } #define R_CATCH_RETHROW(catch_type) \ R_CONVERT(catch_type, R_CURRENT_RESULT) #define R_END_TRY_CATCH \ else if (R_FAILED(R_CURRENT_RESULT)) { \ - return R_CURRENT_RESULT; \ + R_THROW(R_CURRENT_RESULT); \ } \ } \ }) @@ -368,3 +441,5 @@ namespace ams::result::impl { } \ } \ }) + + diff --git a/stratosphere/ro/source/impl/ro_service_impl.cpp b/stratosphere/ro/source/impl/ro_service_impl.cpp index fd5a9a57a..91ef21017 100644 --- a/stratosphere/ro/source/impl/ro_service_impl.cpp +++ b/stratosphere/ro/source/impl/ro_service_impl.cpp @@ -556,23 +556,23 @@ namespace ams::ro::impl { /* Validate the NRO (parsing region extents). */ u64 rx_size = 0, ro_size = 0, rw_size = 0; { - auto unmap_guard = SCOPE_GUARD { UnmapNro(context->GetProcessHandle(), nro_info->base_address, nro_address, bss_address, bss_size, nro_size, 0); }; + ON_RESULT_FAILURE { UnmapNro(context->GetProcessHandle(), nro_info->base_address, nro_address, bss_address, bss_size, nro_size, 0); }; + R_TRY(context->ValidateNro(std::addressof(nro_info->module_id), std::addressof(rx_size), std::addressof(ro_size), std::addressof(rw_size), nro_info->base_address, nro_size, bss_size)); - unmap_guard.Cancel(); } /* Set NRO perms. */ { - auto unmap_guard = SCOPE_GUARD { UnmapNro(context->GetProcessHandle(), nro_info->base_address, nro_address, bss_address, bss_size, rx_size + ro_size, rw_size); }; + ON_RESULT_FAILURE { UnmapNro(context->GetProcessHandle(), nro_info->base_address, nro_address, bss_address, bss_size, rx_size + ro_size, rw_size); }; + R_TRY(SetNroPerms(context->GetProcessHandle(), nro_info->base_address, rx_size, ro_size, rw_size + bss_size)); - unmap_guard.Cancel(); } context->SetNroInfoInUse(nro_info, true); nro_info->code_size = rx_size + ro_size; nro_info->rw_size = rw_size; *out_address = nro_info->base_address; - return ResultSuccess(); + R_SUCCEED(); } Result UnmapManualLoadModuleMemory(size_t context_id, u64 nro_address) { diff --git a/stratosphere/sm/source/impl/sm_service_manager.cpp b/stratosphere/sm/source/impl/sm_service_manager.cpp index ddf219f76..2007ac740 100644 --- a/stratosphere/sm/source/impl/sm_service_manager.cpp +++ b/stratosphere/sm/source/impl/sm_service_manager.cpp @@ -239,7 +239,7 @@ namespace ams::sm::impl { access_control = access_control.GetNextEntry(); } - return sm::ResultNotAllowed(); + R_THROW(sm::ResultNotAllowed()); } Result ValidateAccessControl(AccessControlEntry restriction, AccessControlEntry access) { @@ -249,7 +249,7 @@ namespace ams::sm::impl { access = access.GetNextEntry(); } - return ResultSuccess(); + R_SUCCEED(); } Result ValidateServiceName(ServiceName service) { @@ -269,7 +269,7 @@ namespace ams::sm::impl { R_UNLESS(service.name[name_len++] == 0, sm::ResultInvalidServiceName()); } - return ResultSuccess(); + R_SUCCEED(); } bool ShouldDeferForInit(ServiceName service) { @@ -355,11 +355,11 @@ namespace ams::sm::impl { for (auto &future_mitm : g_future_mitm_list) { if (future_mitm == InvalidServiceName) { future_mitm = service; - return ResultSuccess(); + R_SUCCEED(); } } - return sm::ResultOutOfServices(); + R_THROW(sm::ResultOutOfServices()); } bool HasFutureMitmDeclaration(ServiceName service) { @@ -414,7 +414,7 @@ namespace ams::sm::impl { /* Set the output handles. */ *out_server = server_port; *out_client = client_port; - return ResultSuccess(); + R_SUCCEED(); } Result ConnectToPortImpl(os::NativeHandle *out, os::NativeHandle port) { @@ -424,7 +424,7 @@ namespace ams::sm::impl { /* Set the output handle. */ *out = session; - return ResultSuccess(); + R_SUCCEED(); } Result GetMitmServiceHandleImpl(os::NativeHandle *out, ServiceInfo *service_info, const MitmProcessInfo &client_info) { @@ -456,7 +456,7 @@ namespace ams::sm::impl { mitm_info->waiting_ack_process_id = client_info.process_id; mitm_info->waiting_ack = true; - return ResultSuccess(); + R_SUCCEED(); } Result GetServiceHandleImpl(os::NativeHandle *out, ServiceInfo *service_info, os::ProcessId process_id) { @@ -470,12 +470,12 @@ namespace ams::sm::impl { GetMitmProcessInfo(std::addressof(client_info), process_id); if (!IsMitmDisallowed(client_info.program_id)) { /* Get a mitm service handle. */ - return GetMitmServiceHandleImpl(out, service_info, client_info); + R_RETURN(GetMitmServiceHandleImpl(out, service_info, client_info)); } } /* We're not returning a mitm handle, so just return a normal port handle. */ - return ConnectToPortImpl(out, service_info->port_h); + R_RETURN(ConnectToPortImpl(out, service_info->port_h)); } Result RegisterServiceImpl(os::NativeHandle *out, os::ProcessId process_id, ServiceName service, size_t max_sessions, bool is_light) { @@ -501,7 +501,7 @@ namespace ams::sm::impl { /* This might undefer some requests. */ TriggerResume(service); - return ResultSuccess(); + R_SUCCEED(); } void UnregisterServiceImpl(ServiceInfo *service_info) { @@ -567,7 +567,7 @@ namespace ams::sm::impl { proc->access_control_size = aci_sac_size; std::memcpy(proc->access_control, aci_sac, proc->access_control_size); - return ResultSuccess(); + R_SUCCEED(); } Result UnregisterProcess(os::ProcessId process_id) { @@ -581,7 +581,7 @@ namespace ams::sm::impl { /* Free the process. */ *proc = InvalidProcessInfo; - return ResultSuccess(); + R_SUCCEED(); } /* Service management. */ @@ -593,7 +593,7 @@ namespace ams::sm::impl { R_TRY(ValidateServiceName(service)); *out = HasServiceInfo(service); - return ResultSuccess(); + R_SUCCEED(); } Result WaitService(ServiceName service) { @@ -607,7 +607,7 @@ namespace ams::sm::impl { /* If we don't, we want to wait until the service is registered. */ R_UNLESS(has_service, tipc::ResultRequestDeferred()); - return ResultSuccess(); + R_SUCCEED(); } Result GetServiceHandle(os::NativeHandle *out, os::ProcessId process_id, ServiceName service) { @@ -639,7 +639,7 @@ namespace ams::sm::impl { R_CONVERT(svc::ResultOutOfSessions, sm::ResultOutOfSessions()) } R_END_TRY_CATCH; - return ResultSuccess(); + R_SUCCEED(); } Result RegisterService(os::NativeHandle *out, os::ProcessId process_id, ServiceName service, size_t max_sessions, bool is_light) { @@ -660,14 +660,14 @@ namespace ams::sm::impl { /* Check that the service isn't already registered. */ R_UNLESS(!HasServiceInfo(service), sm::ResultAlreadyRegistered()); - return RegisterServiceImpl(out, process_id, service, max_sessions, is_light); + R_RETURN(RegisterServiceImpl(out, process_id, service, max_sessions, is_light)); } Result RegisterServiceForSelf(os::NativeHandle *out, ServiceName service, size_t max_sessions) { /* Acquire exclusive access to global state. */ std::scoped_lock lk(g_mutex); - return RegisterServiceImpl(out, os::GetCurrentProcessId(), service, max_sessions, false); + R_RETURN(RegisterServiceImpl(out, os::GetCurrentProcessId(), service, max_sessions, false)); } Result UnregisterService(os::ProcessId process_id, ServiceName service) { @@ -692,7 +692,7 @@ namespace ams::sm::impl { /* Unregister the service. */ UnregisterServiceImpl(service_info); - return ResultSuccess(); + R_SUCCEED(); } /* Mitm extensions. */ @@ -706,7 +706,7 @@ namespace ams::sm::impl { /* Get whether we have a mitm. */ *out = HasMitm(service); - return ResultSuccess(); + R_SUCCEED(); } Result WaitMitm(ServiceName service) { @@ -720,7 +720,7 @@ namespace ams::sm::impl { /* If we don't, we want to wait until the mitm is installed. */ R_UNLESS(has_mitm, tipc::ResultRequestDeferred()); - return ResultSuccess(); + R_SUCCEED(); } Result InstallMitm(os::NativeHandle *out, os::NativeHandle *out_query, os::ProcessId process_id, ServiceName service) { @@ -757,7 +757,8 @@ namespace ams::sm::impl { R_TRY(AddFutureMitmDeclaration(service)); } - auto future_guard = SCOPE_GUARD { if (!has_existing_future_declaration) { ClearFutureMitmDeclaration(service); } }; + /* If we fail past this point, clean up the future mitm declaration we just added. */ + ON_RESULT_FAILURE { if (!has_existing_future_declaration) { ClearFutureMitmDeclaration(service); } }; /* Create mitm handles. */ { @@ -766,15 +767,12 @@ namespace ams::sm::impl { R_TRY(CreatePortImpl(std::addressof(hnd), std::addressof(port_hnd), service_info->max_sessions, service_info->is_light, service_info->name)); /* Ensure that we clean up the port handles, if something goes wrong creating the query sessions. */ - auto port_guard = SCOPE_GUARD { os::CloseNativeHandle(hnd); os::CloseNativeHandle(port_hnd); }; + ON_RESULT_FAILURE { os::CloseNativeHandle(hnd); os::CloseNativeHandle(port_hnd); }; /* Create the session for our query service. */ os::NativeHandle qry_hnd, mitm_qry_hnd; R_TRY(svc::CreateSession(std::addressof(qry_hnd), std::addressof(mitm_qry_hnd), false, 0)); - /* We created the query service session, so we no longer need to clean up the port handles. */ - port_guard.Cancel(); - /* Setup the mitm info. */ mitm_info->process_id = process_id; mitm_info->port_h = port_hnd; @@ -791,8 +789,7 @@ namespace ams::sm::impl { TriggerResume(service); } - future_guard.Cancel(); - return ResultSuccess(); + R_SUCCEED(); } Result UninstallMitm(os::ProcessId process_id, ServiceName service) { @@ -833,7 +830,7 @@ namespace ams::sm::impl { service_info->mitm_index = MitmCountMax; } - return ResultSuccess(); + R_SUCCEED(); } Result DeclareFutureMitm(os::ProcessId process_id, ServiceName service) { @@ -857,7 +854,7 @@ namespace ams::sm::impl { /* Try to forward declare it. */ R_TRY(AddFutureMitmDeclaration(service)); - return ResultSuccess(); + R_SUCCEED(); } Result ClearFutureMitm(os::ProcessId process_id, ServiceName service) { @@ -889,7 +886,7 @@ namespace ams::sm::impl { /* Clear the forward declaration. */ ClearFutureMitmDeclaration(service); - return ResultSuccess(); + R_SUCCEED(); } Result AcknowledgeMitmSession(MitmProcessInfo *out_info, os::NativeHandle *out_hnd, os::ProcessId process_id, ServiceName service) { @@ -934,7 +931,7 @@ namespace ams::sm::impl { /* Undefer requests to the session. */ TriggerResume(service); - return ResultSuccess(); + R_SUCCEED(); } /* Deferral extension (works around FS bug). */ @@ -954,7 +951,7 @@ namespace ams::sm::impl { TriggerResume(service_name); } - return ResultSuccess(); + R_SUCCEED(); } } diff --git a/stratosphere/sm/source/sm_manager_service.hpp b/stratosphere/sm/source/sm_manager_service.hpp index f9e2f30d7..a31ecb446 100644 --- a/stratosphere/sm/source/sm_manager_service.hpp +++ b/stratosphere/sm/source/sm_manager_service.hpp @@ -23,11 +23,11 @@ namespace ams::sm { class ManagerService { public: Result RegisterProcess(os::ProcessId process_id, const tipc::InBuffer acid_sac, const tipc::InBuffer aci_sac) { - return impl::RegisterProcess(process_id, ncm::InvalidProgramId, cfg::OverrideStatus{}, acid_sac.GetPointer(), acid_sac.GetSize(), aci_sac.GetPointer(), aci_sac.GetSize()); + R_RETURN(impl::RegisterProcess(process_id, ncm::InvalidProgramId, cfg::OverrideStatus{}, acid_sac.GetPointer(), acid_sac.GetSize(), aci_sac.GetPointer(), aci_sac.GetSize())); } Result UnregisterProcess(os::ProcessId process_id) { - return impl::UnregisterProcess(process_id); + R_RETURN(impl::UnregisterProcess(process_id)); } void AtmosphereEndInitDefers() { @@ -40,7 +40,7 @@ namespace ams::sm { Result AtmosphereRegisterProcess(os::ProcessId process_id, ncm::ProgramId program_id, cfg::OverrideStatus override_status, const tipc::InBuffer acid_sac, const tipc::InBuffer aci_sac) { /* This takes in a program id and override status, unlike RegisterProcess. */ - return impl::RegisterProcess(process_id, program_id, override_status, acid_sac.GetPointer(), acid_sac.GetSize(), aci_sac.GetPointer(), aci_sac.GetSize()); + R_RETURN(impl::RegisterProcess(process_id, program_id, override_status, acid_sac.GetPointer(), acid_sac.GetSize(), aci_sac.GetPointer(), aci_sac.GetSize())); } }; static_assert(sm::impl::IsIManagerInterface); diff --git a/stratosphere/sm/source/sm_user_service.cpp b/stratosphere/sm/source/sm_user_service.cpp index cd1fe68bb..d719970ca 100644 --- a/stratosphere/sm/source/sm_user_service.cpp +++ b/stratosphere/sm/source/sm_user_service.cpp @@ -78,7 +78,7 @@ namespace ams::sm { /* We do not have a pointer buffer, and so our pointer buffer size is zero. */ /* Return the relevant hardcoded response. */ std::memcpy(message_buffer.GetBufferForDebug(), CmifResponseToQueryPointerBufferSize, sizeof(CmifResponseToQueryPointerBufferSize)); - return ResultSuccess(); + R_SUCCEED(); } /* We only support request (with context), from this point forwards. */ @@ -124,7 +124,7 @@ namespace ams::sm { /* Invoke the handler for DetachClient. */ R_ABORT_UNLESS(this->DetachClient(tipc::ClientProcessId{ client_process_id })); } else { - return tipc::ResultInvalidMethod(); + R_THROW(tipc::ResultInvalidMethod()); } /* Serialize output. */ @@ -158,7 +158,7 @@ namespace ams::sm { std::memcpy(out_message_buffer + 0x00, CmifResponseToUnregisterService, sizeof(CmifResponseToUnregisterService)); std::memcpy(out_message_buffer + 0x18, std::addressof(result), sizeof(result)); } else { - return tipc::ResultInvalidMethod(); + R_THROW(tipc::ResultInvalidMethod()); } } else if (std::memcmp(raw_message_buffer, CmifExpectedRequestHeaderForRegisterService, sizeof(CmifExpectedRequestHeaderForRegisterService)) == 0) { /* Get the command id. */ @@ -186,13 +186,13 @@ namespace ams::sm { std::memcpy(out_message_buffer + 0x0C, std::addressof(out_handle), sizeof(out_handle)); std::memcpy(out_message_buffer + 0x18, std::addressof(result), sizeof(result)); } else { - return tipc::ResultInvalidMethod(); + R_THROW(tipc::ResultInvalidMethod()); } } else { - return tipc::ResultInvalidMethod(); + R_THROW(tipc::ResultInvalidMethod()); } - return ResultSuccess(); + R_SUCCEED(); } } diff --git a/stratosphere/sm/source/sm_user_service.hpp b/stratosphere/sm/source/sm_user_service.hpp index df457c71b..43fdde74d 100644 --- a/stratosphere/sm/source/sm_user_service.hpp +++ b/stratosphere/sm/source/sm_user_service.hpp @@ -36,83 +36,96 @@ namespace ams::sm { Result RegisterClient(const tipc::ClientProcessId client_process_id) { m_process_id = client_process_id.value; m_initialized = true; - return ResultSuccess(); + R_SUCCEED(); } Result GetServiceHandle(tipc::OutMoveHandle out_h, ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return this->RegisterRetryIfDeferred(service, [&]() ALWAYS_INLINE_LAMBDA -> Result { - return impl::GetServiceHandle(out_h.GetPointer(), m_process_id, service); - }); + + TIPC_REGISTER_RETRY_ON_RESULT_REQUEST_DEFERRED(service); + + R_RETURN(impl::GetServiceHandle(out_h.GetPointer(), m_process_id, service)); } Result RegisterService(tipc::OutMoveHandle out_h, ServiceName service, u32 max_sessions, bool is_light) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::RegisterService(out_h.GetPointer(), m_process_id, service, max_sessions, is_light); + + R_RETURN(impl::RegisterService(out_h.GetPointer(), m_process_id, service, max_sessions, is_light)); } Result UnregisterService(ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::UnregisterService(m_process_id, service); + + R_RETURN(impl::UnregisterService(m_process_id, service)); } Result DetachClient(const tipc::ClientProcessId client_process_id) { AMS_UNUSED(client_process_id); m_initialized = false; - return ResultSuccess(); + + R_SUCCEED(); } /* Atmosphere commands. */ Result AtmosphereInstallMitm(tipc::OutMoveHandle srv_h, tipc::OutMoveHandle qry_h, ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return this->RegisterRetryIfDeferred(service, [&]() ALWAYS_INLINE_LAMBDA -> Result { - return impl::InstallMitm(srv_h.GetPointer(), qry_h.GetPointer(), m_process_id, service); - }); + + TIPC_REGISTER_RETRY_ON_RESULT_REQUEST_DEFERRED(service); + + R_RETURN(impl::InstallMitm(srv_h.GetPointer(), qry_h.GetPointer(), m_process_id, service)); } Result AtmosphereUninstallMitm(ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::UninstallMitm(m_process_id, service); + + R_RETURN(impl::UninstallMitm(m_process_id, service)); } Result AtmosphereAcknowledgeMitmSession(tipc::Out client_info, tipc::OutMoveHandle fwd_h, ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::AcknowledgeMitmSession(client_info.GetPointer(), fwd_h.GetPointer(), m_process_id, service); + + R_RETURN(impl::AcknowledgeMitmSession(client_info.GetPointer(), fwd_h.GetPointer(), m_process_id, service)); } Result AtmosphereHasMitm(tipc::Out out, ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::HasMitm(out.GetPointer(), service); + + R_RETURN(impl::HasMitm(out.GetPointer(), service)); } Result AtmosphereWaitMitm(ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return this->RegisterRetryIfDeferred(service, [&]() ALWAYS_INLINE_LAMBDA -> Result { - return impl::WaitMitm(service); - }); + + TIPC_REGISTER_RETRY_ON_RESULT_REQUEST_DEFERRED(service); + + R_RETURN(impl::WaitMitm(service)); } Result AtmosphereDeclareFutureMitm(ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::DeclareFutureMitm(m_process_id, service); + + R_RETURN(impl::DeclareFutureMitm(m_process_id, service)); } Result AtmosphereClearFutureMitm(ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::ClearFutureMitm(m_process_id, service); + + R_RETURN(impl::ClearFutureMitm(m_process_id, service)); } Result AtmosphereHasService(tipc::Out out, ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return impl::HasService(out.GetPointer(), service); + + R_RETURN(impl::HasService(out.GetPointer(), service)); } Result AtmosphereWaitService(ServiceName service) { R_UNLESS(m_initialized, sm::ResultInvalidClient()); - return this->RegisterRetryIfDeferred(service, [&]() ALWAYS_INLINE_LAMBDA -> Result { - return impl::WaitService(service); - }); + + TIPC_REGISTER_RETRY_ON_RESULT_REQUEST_DEFERRED(service); + + R_RETURN(impl::WaitService(service)); } public: /* Backwards compatibility layer for cmif. */