diff options
Diffstat (limited to 'src/core')
49 files changed, 495 insertions, 246 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 4a1a8bb43..75e0c4f38 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -454,7 +454,6 @@ add_library(core STATIC hle/service/filesystem/fsp_srv.h hle/service/fgm/fgm.cpp hle/service/fgm/fgm.h - hle/service/friend/errors.h hle/service/friend/friend.cpp hle/service/friend/friend.h hle/service/friend/friend_interface.cpp diff --git a/src/core/core_timing.cpp b/src/core/core_timing.cpp index 3a63b52e3..cd4df4522 100644 --- a/src/core/core_timing.cpp +++ b/src/core/core_timing.cpp @@ -6,6 +6,10 @@ #include <string> #include <tuple> +#ifdef _WIN32 +#include "common/windows/timer_resolution.h" +#endif + #include "common/microprofile.h" #include "core/core_timing.h" #include "core/core_timing_util.h" @@ -38,7 +42,8 @@ struct CoreTiming::Event { }; CoreTiming::CoreTiming() - : clock{Common::CreateBestMatchingClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)} {} + : cpu_clock{Common::CreateBestMatchingClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)}, + event_clock{Common::CreateStandardWallClock(Hardware::BASE_CLOCK_RATE, Hardware::CNTFREQ)} {} CoreTiming::~CoreTiming() { Reset(); @@ -48,7 +53,7 @@ void CoreTiming::ThreadEntry(CoreTiming& instance) { static constexpr char name[] = "HostTiming"; MicroProfileOnThreadCreate(name); Common::SetCurrentThreadName(name); - Common::SetCurrentThreadPriority(Common::ThreadPriority::Critical); + Common::SetCurrentThreadPriority(Common::ThreadPriority::High); instance.on_thread_init(); instance.ThreadLoop(); MicroProfileOnThreadExit(); @@ -185,15 +190,15 @@ void CoreTiming::ResetTicks() { } u64 CoreTiming::GetCPUTicks() const { - if (is_multicore) { - return clock->GetCPUCycles(); + if (is_multicore) [[likely]] { + return cpu_clock->GetCPUCycles(); } return ticks; } u64 CoreTiming::GetClockTicks() const { - if (is_multicore) { - return clock->GetClockCycles(); + if (is_multicore) [[likely]] { + return cpu_clock->GetClockCycles(); } return CpuCyclesToClockCycles(ticks); } @@ -252,21 +257,20 @@ void CoreTiming::ThreadLoop() { const auto next_time = Advance(); if (next_time) { // There are more events left in the queue, wait until the next event. - const auto wait_time = *next_time - GetGlobalTimeNs().count(); + auto wait_time = *next_time - GetGlobalTimeNs().count(); if (wait_time > 0) { #ifdef _WIN32 - // Assume a timer resolution of 1ms. - static constexpr s64 TimerResolutionNS = 1000000; + const auto timer_resolution_ns = + Common::Windows::GetCurrentTimerResolution().count(); - // Sleep in discrete intervals of the timer resolution, and spin the rest. - const auto sleep_time = wait_time - (wait_time % TimerResolutionNS); - if (sleep_time > 0) { - event.WaitFor(std::chrono::nanoseconds(sleep_time)); - } + while (!paused && !event.IsSet() && wait_time > 0) { + wait_time = *next_time - GetGlobalTimeNs().count(); - while (!paused && !event.IsSet() && GetGlobalTimeNs().count() < *next_time) { - // Yield to reduce thread starvation. - std::this_thread::yield(); + if (wait_time >= timer_resolution_ns) { + Common::Windows::SleepForOneTick(); + } else { + std::this_thread::yield(); + } } if (event.IsSet()) { @@ -285,9 +289,9 @@ void CoreTiming::ThreadLoop() { } paused_set = true; - clock->Pause(true); + event_clock->Pause(true); pause_event.Wait(); - clock->Pause(false); + event_clock->Pause(false); } } @@ -303,16 +307,23 @@ void CoreTiming::Reset() { has_started = false; } +std::chrono::nanoseconds CoreTiming::GetCPUTimeNs() const { + if (is_multicore) [[likely]] { + return cpu_clock->GetTimeNS(); + } + return CyclesToNs(ticks); +} + std::chrono::nanoseconds CoreTiming::GetGlobalTimeNs() const { - if (is_multicore) { - return clock->GetTimeNS(); + if (is_multicore) [[likely]] { + return event_clock->GetTimeNS(); } return CyclesToNs(ticks); } std::chrono::microseconds CoreTiming::GetGlobalTimeUs() const { - if (is_multicore) { - return clock->GetTimeUS(); + if (is_multicore) [[likely]] { + return event_clock->GetTimeUS(); } return CyclesToUs(ticks); } diff --git a/src/core/core_timing.h b/src/core/core_timing.h index da366637b..4b89c0c39 100644 --- a/src/core/core_timing.h +++ b/src/core/core_timing.h @@ -122,6 +122,9 @@ public: /// Returns current time in emulated in Clock cycles u64 GetClockTicks() const; + /// Returns current time in nanoseconds. + std::chrono::nanoseconds GetCPUTimeNs() const; + /// Returns current time in microseconds. std::chrono::microseconds GetGlobalTimeUs() const; @@ -139,7 +142,8 @@ private: void Reset(); - std::unique_ptr<Common::WallClock> clock; + std::unique_ptr<Common::WallClock> cpu_clock; + std::unique_ptr<Common::WallClock> event_clock; s64 global_timer = 0; diff --git a/src/core/cpu_manager.cpp b/src/core/cpu_manager.cpp index 04a11f444..980bb97f9 100644 --- a/src/core/cpu_manager.cpp +++ b/src/core/cpu_manager.cpp @@ -192,7 +192,7 @@ void CpuManager::RunThread(std::stop_token token, std::size_t core) { } MicroProfileOnThreadCreate(name.c_str()); Common::SetCurrentThreadName(name.c_str()); - Common::SetCurrentThreadPriority(Common::ThreadPriority::High); + Common::SetCurrentThreadPriority(Common::ThreadPriority::Critical); auto& data = core_data[core]; data.host_context = Common::Fiber::ThreadToFiber(); diff --git a/src/core/hardware_properties.h b/src/core/hardware_properties.h index 45567b840..191c28bb4 100644 --- a/src/core/hardware_properties.h +++ b/src/core/hardware_properties.h @@ -13,11 +13,9 @@ namespace Core { namespace Hardware { -// The below clock rate is based on Switch's clockspeed being widely known as 1.020GHz -// The exact value used is of course unverified. -constexpr u64 BASE_CLOCK_RATE = 1019215872; // Switch cpu frequency is 1020MHz un/docked -constexpr u64 CNTFREQ = 19200000; // Switch's hardware clock speed -constexpr u32 NUM_CPU_CORES = 4; // Number of CPU Cores +constexpr u64 BASE_CLOCK_RATE = 1'020'000'000; // Default CPU Frequency = 1020 MHz +constexpr u64 CNTFREQ = 19'200'000; // CNTPCT_EL0 Frequency = 19.2 MHz +constexpr u32 NUM_CPU_CORES = 4; // Number of CPU Cores // Virtual to Physical core map. constexpr std::array<s32, Common::BitSize<u64>()> VirtualToPhysicalCoreMap{ diff --git a/src/core/hle/kernel/k_address_arbiter.cpp b/src/core/hle/kernel/k_address_arbiter.cpp index fb86451ea..a4c16eca9 100644 --- a/src/core/hle/kernel/k_address_arbiter.cpp +++ b/src/core/hle/kernel/k_address_arbiter.cpp @@ -237,10 +237,11 @@ Result KAddressArbiter::SignalAndModifyByWaitingCountIfEqual(VAddr addr, s32 val Result KAddressArbiter::WaitIfLessThan(VAddr addr, s32 value, bool decrement, s64 timeout) { // Prepare to wait. KThread* cur_thread = GetCurrentThreadPointer(kernel); + KHardwareTimer* timer{}; ThreadQueueImplForKAddressArbiter wait_queue(kernel, std::addressof(thread_tree)); { - KScopedSchedulerLockAndSleep slp{kernel, cur_thread, timeout}; + KScopedSchedulerLockAndSleep slp{kernel, std::addressof(timer), cur_thread, timeout}; // Check that the thread isn't terminating. if (cur_thread->IsTerminationRequested()) { @@ -279,6 +280,7 @@ Result KAddressArbiter::WaitIfLessThan(VAddr addr, s32 value, bool decrement, s6 thread_tree.insert(*cur_thread); // Wait for the thread to finish. + wait_queue.SetHardwareTimer(timer); cur_thread->BeginWait(std::addressof(wait_queue)); cur_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::Arbitration); } @@ -290,10 +292,11 @@ Result KAddressArbiter::WaitIfLessThan(VAddr addr, s32 value, bool decrement, s6 Result KAddressArbiter::WaitIfEqual(VAddr addr, s32 value, s64 timeout) { // Prepare to wait. KThread* cur_thread = GetCurrentThreadPointer(kernel); + KHardwareTimer* timer{}; ThreadQueueImplForKAddressArbiter wait_queue(kernel, std::addressof(thread_tree)); { - KScopedSchedulerLockAndSleep slp{kernel, cur_thread, timeout}; + KScopedSchedulerLockAndSleep slp{kernel, std::addressof(timer), cur_thread, timeout}; // Check that the thread isn't terminating. if (cur_thread->IsTerminationRequested()) { @@ -325,6 +328,7 @@ Result KAddressArbiter::WaitIfEqual(VAddr addr, s32 value, s64 timeout) { thread_tree.insert(*cur_thread); // Wait for the thread to finish. + wait_queue.SetHardwareTimer(timer); cur_thread->BeginWait(std::addressof(wait_queue)); cur_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::Arbitration); } diff --git a/src/core/hle/kernel/k_address_space_info.cpp b/src/core/hle/kernel/k_address_space_info.cpp index 97972ebae..c36eb5dc4 100644 --- a/src/core/hle/kernel/k_address_space_info.cpp +++ b/src/core/hle/kernel/k_address_space_info.cpp @@ -44,11 +44,11 @@ const KAddressSpaceInfo& GetAddressSpaceInfo(size_t width, KAddressSpaceInfo::Ty } // namespace -uintptr_t KAddressSpaceInfo::GetAddressSpaceStart(size_t width, KAddressSpaceInfo::Type type) { +std::size_t KAddressSpaceInfo::GetAddressSpaceStart(size_t width, KAddressSpaceInfo::Type type) { return GetAddressSpaceInfo(width, type).address; } -size_t KAddressSpaceInfo::GetAddressSpaceSize(size_t width, KAddressSpaceInfo::Type type) { +std::size_t KAddressSpaceInfo::GetAddressSpaceSize(size_t width, KAddressSpaceInfo::Type type) { return GetAddressSpaceInfo(width, type).size; } diff --git a/src/core/hle/kernel/k_address_space_info.h b/src/core/hle/kernel/k_address_space_info.h index 69e9d77f2..9a26f6b90 100644 --- a/src/core/hle/kernel/k_address_space_info.h +++ b/src/core/hle/kernel/k_address_space_info.h @@ -18,7 +18,7 @@ struct KAddressSpaceInfo final { Count, }; - static u64 GetAddressSpaceStart(std::size_t width, Type type); + static std::size_t GetAddressSpaceStart(std::size_t width, Type type); static std::size_t GetAddressSpaceSize(std::size_t width, Type type); const std::size_t bit_width{}; diff --git a/src/core/hle/kernel/k_condition_variable.cpp b/src/core/hle/kernel/k_condition_variable.cpp index f40cf92b1..458f4c94e 100644 --- a/src/core/hle/kernel/k_condition_variable.cpp +++ b/src/core/hle/kernel/k_condition_variable.cpp @@ -266,11 +266,12 @@ void KConditionVariable::Signal(u64 cv_key, s32 count) { Result KConditionVariable::Wait(VAddr addr, u64 key, u32 value, s64 timeout) { // Prepare to wait. KThread* cur_thread = GetCurrentThreadPointer(kernel); + KHardwareTimer* timer{}; ThreadQueueImplForKConditionVariableWaitConditionVariable wait_queue( kernel, std::addressof(thread_tree)); { - KScopedSchedulerLockAndSleep slp(kernel, cur_thread, timeout); + KScopedSchedulerLockAndSleep slp(kernel, std::addressof(timer), cur_thread, timeout); // Check that the thread isn't terminating. if (cur_thread->IsTerminationRequested()) { @@ -320,6 +321,7 @@ Result KConditionVariable::Wait(VAddr addr, u64 key, u32 value, s64 timeout) { thread_tree.insert(*cur_thread); // Begin waiting. + wait_queue.SetHardwareTimer(timer); cur_thread->BeginWait(std::addressof(wait_queue)); cur_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::ConditionVar); cur_thread->SetMutexWaitAddressForDebugging(addr); diff --git a/src/core/hle/kernel/k_device_address_space.h b/src/core/hle/kernel/k_device_address_space.h index 4709df995..b4a014c38 100644 --- a/src/core/hle/kernel/k_device_address_space.h +++ b/src/core/hle/kernel/k_device_address_space.h @@ -21,9 +21,9 @@ public: ~KDeviceAddressSpace(); Result Initialize(u64 address, u64 size); - void Finalize(); + void Finalize() override; - bool IsInitialized() const { + bool IsInitialized() const override { return m_is_initialized; } static void PostDestroy(uintptr_t arg) {} diff --git a/src/core/hle/kernel/k_light_condition_variable.cpp b/src/core/hle/kernel/k_light_condition_variable.cpp index cade99cfd..8fce2bc71 100644 --- a/src/core/hle/kernel/k_light_condition_variable.cpp +++ b/src/core/hle/kernel/k_light_condition_variable.cpp @@ -40,13 +40,14 @@ private: void KLightConditionVariable::Wait(KLightLock* lock, s64 timeout, bool allow_terminating_thread) { // Create thread queue. KThread* owner = GetCurrentThreadPointer(kernel); + KHardwareTimer* timer{}; ThreadQueueImplForKLightConditionVariable wait_queue(kernel, std::addressof(wait_list), allow_terminating_thread); // Sleep the thread. { - KScopedSchedulerLockAndSleep lk(kernel, owner, timeout); + KScopedSchedulerLockAndSleep lk(kernel, std::addressof(timer), owner, timeout); if (!allow_terminating_thread && owner->IsTerminationRequested()) { lk.CancelSleep(); @@ -59,6 +60,7 @@ void KLightConditionVariable::Wait(KLightLock* lock, s64 timeout, bool allow_ter wait_list.push_back(*owner); // Begin waiting. + wait_queue.SetHardwareTimer(timer); owner->BeginWait(std::addressof(wait_queue)); } diff --git a/src/core/hle/kernel/k_process.h b/src/core/hle/kernel/k_process.h index 09bf2f1d0..549809000 100644 --- a/src/core/hle/kernel/k_process.h +++ b/src/core/hle/kernel/k_process.h @@ -310,10 +310,10 @@ public: /// Clears the signaled state of the process if and only if it's signaled. /// /// @pre The process must not be already terminated. If this is called on a - /// terminated process, then ERR_INVALID_STATE will be returned. + /// terminated process, then ResultInvalidState will be returned. /// /// @pre The process must be in a signaled state. If this is called on a - /// process instance that is not signaled, ERR_INVALID_STATE will be + /// process instance that is not signaled, ResultInvalidState will be /// returned. Result Reset(); diff --git a/src/core/hle/kernel/k_resource_limit.cpp b/src/core/hle/kernel/k_resource_limit.cpp index b9d22b414..626517619 100644 --- a/src/core/hle/kernel/k_resource_limit.cpp +++ b/src/core/hle/kernel/k_resource_limit.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later #include "common/assert.h" +#include "common/overflow.h" #include "core/core.h" #include "core/core_timing.h" #include "core/hle/kernel/k_resource_limit.h" @@ -104,7 +105,7 @@ bool KResourceLimit::Reserve(LimitableResource which, s64 value, s64 timeout) { ASSERT(current_hints[index] <= current_values[index]); // If we would overflow, don't allow to succeed. - if (current_values[index] + value <= current_values[index]) { + if (Common::WrappingAdd(current_values[index], value) <= current_values[index]) { break; } diff --git a/src/core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h b/src/core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h index 76db65a4d..14b83a819 100644 --- a/src/core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h +++ b/src/core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h @@ -13,16 +13,22 @@ namespace Kernel { class [[nodiscard]] KScopedSchedulerLockAndSleep { public: - explicit KScopedSchedulerLockAndSleep(KernelCore& kernel_, KThread* t, s64 timeout) - : kernel(kernel_), thread(t), timeout_tick(timeout) { + explicit KScopedSchedulerLockAndSleep(KernelCore& kernel_, KHardwareTimer** out_timer, + KThread* t, s64 timeout) + : kernel(kernel_), timeout_tick(timeout), thread(t), timer() { // Lock the scheduler. kernel.GlobalSchedulerContext().scheduler_lock.Lock(); + + // Set our timer only if the time is positive. + timer = (timeout_tick > 0) ? std::addressof(kernel.HardwareTimer()) : nullptr; + + *out_timer = timer; } ~KScopedSchedulerLockAndSleep() { // Register the sleep. if (timeout_tick > 0) { - kernel.HardwareTimer().RegisterTask(thread, timeout_tick); + timer->RegisterTask(thread, timeout_tick); } // Unlock the scheduler. @@ -35,8 +41,9 @@ public: private: KernelCore& kernel; - KThread* thread{}; s64 timeout_tick{}; + KThread* thread{}; + KHardwareTimer* timer{}; }; } // namespace Kernel diff --git a/src/core/hle/kernel/k_synchronization_object.cpp b/src/core/hle/kernel/k_synchronization_object.cpp index 802dca046..40fd0c038 100644 --- a/src/core/hle/kernel/k_synchronization_object.cpp +++ b/src/core/hle/kernel/k_synchronization_object.cpp @@ -79,12 +79,13 @@ Result KSynchronizationObject::Wait(KernelCore& kernel_ctx, s32* out_index, // Prepare for wait. KThread* thread = GetCurrentThreadPointer(kernel_ctx); + KHardwareTimer* timer{}; ThreadQueueImplForKSynchronizationObjectWait wait_queue(kernel_ctx, objects, thread_nodes.data(), num_objects); { // Setup the scheduling lock and sleep. - KScopedSchedulerLockAndSleep slp(kernel_ctx, thread, timeout); + KScopedSchedulerLockAndSleep slp(kernel_ctx, std::addressof(timer), thread, timeout); // Check if the thread should terminate. if (thread->IsTerminationRequested()) { @@ -131,6 +132,7 @@ Result KSynchronizationObject::Wait(KernelCore& kernel_ctx, s32* out_index, thread->SetSyncedIndex(-1); // Wait for an object to be signaled. + wait_queue.SetHardwareTimer(timer); thread->BeginWait(std::addressof(wait_queue)); thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::Synchronization); } diff --git a/src/core/hle/kernel/k_thread.cpp b/src/core/hle/kernel/k_thread.cpp index 8c403f5fd..26e3700e4 100644 --- a/src/core/hle/kernel/k_thread.cpp +++ b/src/core/hle/kernel/k_thread.cpp @@ -49,6 +49,7 @@ static void ResetThreadContext32(Core::ARM_Interface::ThreadContext32& context, context.cpu_registers[0] = arg; context.cpu_registers[15] = entry_point; context.cpu_registers[13] = stack_top; + context.fpscr = 0; } static void ResetThreadContext64(Core::ARM_Interface::ThreadContext64& context, VAddr stack_top, @@ -58,8 +59,8 @@ static void ResetThreadContext64(Core::ARM_Interface::ThreadContext64& context, context.cpu_registers[18] = Kernel::KSystemControl::GenerateRandomU64() | 1; context.pc = entry_point; context.sp = stack_top; - // TODO(merry): Perform a hardware test to determine the below value. context.fpcr = 0; + context.fpsr = 0; } } // namespace @@ -815,6 +816,27 @@ void KThread::Continue() { KScheduler::OnThreadStateChanged(kernel, this, old_state); } +void KThread::CloneFpuStatus() { + // We shouldn't reach here when starting kernel threads. + ASSERT(this->GetOwnerProcess() != nullptr); + ASSERT(this->GetOwnerProcess() == GetCurrentProcessPointer(kernel)); + + if (this->GetOwnerProcess()->Is64BitProcess()) { + // Clone FPSR and FPCR. + ThreadContext64 cur_ctx{}; + kernel.System().CurrentArmInterface().SaveContext(cur_ctx); + + this->GetContext64().fpcr = cur_ctx.fpcr; + this->GetContext64().fpsr = cur_ctx.fpsr; + } else { + // Clone FPSCR. + ThreadContext32 cur_ctx{}; + kernel.System().CurrentArmInterface().SaveContext(cur_ctx); + + this->GetContext32().fpscr = cur_ctx.fpscr; + } +} + Result KThread::SetActivity(Svc::ThreadActivity activity) { // Lock ourselves. KScopedLightLock lk(activity_pause_lock); @@ -1268,9 +1290,10 @@ Result KThread::Sleep(s64 timeout) { ASSERT(timeout > 0); ThreadQueueImplForKThreadSleep wait_queue_(kernel); + KHardwareTimer* timer{}; { // Setup the scheduling lock and sleep. - KScopedSchedulerLockAndSleep slp(kernel, this, timeout); + KScopedSchedulerLockAndSleep slp(kernel, std::addressof(timer), this, timeout); // Check if the thread should terminate. if (this->IsTerminationRequested()) { @@ -1279,6 +1302,7 @@ Result KThread::Sleep(s64 timeout) { } // Wait for the sleep to end. + wait_queue_.SetHardwareTimer(timer); this->BeginWait(std::addressof(wait_queue_)); SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::Sleep); } diff --git a/src/core/hle/kernel/k_thread.h b/src/core/hle/kernel/k_thread.h index bd125f5f1..9423f08ca 100644 --- a/src/core/hle/kernel/k_thread.h +++ b/src/core/hle/kernel/k_thread.h @@ -254,6 +254,8 @@ public: thread_context_32.tpidr = static_cast<u32>(value); } + void CloneFpuStatus(); + [[nodiscard]] ThreadContext32& GetContext32() { return thread_context_32; } diff --git a/src/core/hle/kernel/k_thread_queue.cpp b/src/core/hle/kernel/k_thread_queue.cpp index 5f1dc97eb..fe648447b 100644 --- a/src/core/hle/kernel/k_thread_queue.cpp +++ b/src/core/hle/kernel/k_thread_queue.cpp @@ -22,7 +22,9 @@ void KThreadQueue::EndWait(KThread* waiting_thread, Result wait_result) { waiting_thread->ClearWaitQueue(); // Cancel the thread task. - kernel.HardwareTimer().CancelTask(waiting_thread); + if (m_hardware_timer != nullptr) { + m_hardware_timer->CancelTask(waiting_thread); + } } void KThreadQueue::CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) { @@ -36,8 +38,8 @@ void KThreadQueue::CancelWait(KThread* waiting_thread, Result wait_result, bool waiting_thread->ClearWaitQueue(); // Cancel the thread task. - if (cancel_timer_task) { - kernel.HardwareTimer().CancelTask(waiting_thread); + if (cancel_timer_task && m_hardware_timer != nullptr) { + m_hardware_timer->CancelTask(waiting_thread); } } diff --git a/src/core/hle/kernel/k_thread_queue.h b/src/core/hle/kernel/k_thread_queue.h index 8d76ece81..01e330e2e 100644 --- a/src/core/hle/kernel/k_thread_queue.h +++ b/src/core/hle/kernel/k_thread_queue.h @@ -8,11 +8,17 @@ namespace Kernel { +class KHardwareTimer; + class KThreadQueue { public: - explicit KThreadQueue(KernelCore& kernel_) : kernel{kernel_} {} + explicit KThreadQueue(KernelCore& kernel_) : kernel{kernel_}, m_hardware_timer{} {} virtual ~KThreadQueue() = default; + void SetHardwareTimer(KHardwareTimer* timer) { + m_hardware_timer = timer; + } + virtual void NotifyAvailable(KThread* waiting_thread, KSynchronizationObject* signaled_object, Result wait_result); virtual void EndWait(KThread* waiting_thread, Result wait_result); @@ -20,7 +26,7 @@ public: private: KernelCore& kernel; - KThread::WaiterList wait_list{}; + KHardwareTimer* m_hardware_timer{}; }; class KThreadQueueWithoutEndWait : public KThreadQueue { diff --git a/src/core/hle/kernel/svc/svc_synchronization.cpp b/src/core/hle/kernel/svc/svc_synchronization.cpp index 1a8f7e191..9e7bf9530 100644 --- a/src/core/hle/kernel/svc/svc_synchronization.cpp +++ b/src/core/hle/kernel/svc/svc_synchronization.cpp @@ -48,19 +48,15 @@ Result ResetSignal(Core::System& system, Handle handle) { return ResultInvalidHandle; } -/// Wait for the given handles to synchronize, timeout after the specified nanoseconds -Result WaitSynchronization(Core::System& system, s32* index, VAddr handles_address, s32 num_handles, - s64 nano_seconds) { - LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, num_handles={}, nano_seconds={}", - handles_address, num_handles, nano_seconds); - +static Result WaitSynchronization(Core::System& system, int32_t* out_index, const Handle* handles, + int32_t num_handles, int64_t timeout_ns) { // Ensure number of handles is valid. - R_UNLESS(0 <= num_handles && num_handles <= ArgumentHandleCountMax, ResultOutOfRange); + R_UNLESS(0 <= num_handles && num_handles <= Svc::ArgumentHandleCountMax, ResultOutOfRange); + // Get the synchronization context. auto& kernel = system.Kernel(); + auto& handle_table = GetCurrentProcess(kernel).GetHandleTable(); std::vector<KSynchronizationObject*> objs(num_handles); - const auto& handle_table = GetCurrentProcess(kernel).GetHandleTable(); - Handle* handles = system.Memory().GetPointer<Handle>(handles_address); // Copy user handles. if (num_handles > 0) { @@ -68,21 +64,38 @@ Result WaitSynchronization(Core::System& system, s32* index, VAddr handles_addre R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs.data(), handles, num_handles), ResultInvalidHandle); - for (const auto& obj : objs) { - kernel.RegisterInUseObject(obj); - } } // Ensure handles are closed when we're done. SCOPE_EXIT({ - for (s32 i = 0; i < num_handles; ++i) { - kernel.UnregisterInUseObject(objs[i]); + for (auto i = 0; i < num_handles; ++i) { objs[i]->Close(); } }); - return KSynchronizationObject::Wait(kernel, index, objs.data(), static_cast<s32>(objs.size()), - nano_seconds); + // Wait on the objects. + Result res = KSynchronizationObject::Wait(kernel, out_index, objs.data(), + static_cast<s32>(objs.size()), timeout_ns); + + R_SUCCEED_IF(res == ResultSessionClosed); + R_RETURN(res); +} + +/// Wait for the given handles to synchronize, timeout after the specified nanoseconds +Result WaitSynchronization(Core::System& system, int32_t* out_index, VAddr user_handles, + int32_t num_handles, int64_t timeout_ns) { + LOG_TRACE(Kernel_SVC, "called user_handles={:#x}, num_handles={}, timeout_ns={}", user_handles, + num_handles, timeout_ns); + + // Ensure number of handles is valid. + R_UNLESS(0 <= num_handles && num_handles <= Svc::ArgumentHandleCountMax, ResultOutOfRange); + + std::vector<Handle> handles(num_handles); + if (num_handles > 0) { + system.Memory().ReadBlock(user_handles, handles.data(), num_handles * sizeof(Handle)); + } + + R_RETURN(WaitSynchronization(system, out_index, handles.data(), num_handles, timeout_ns)); } /// Resumes a thread waiting on WaitSynchronization diff --git a/src/core/hle/kernel/svc/svc_thread.cpp b/src/core/hle/kernel/svc/svc_thread.cpp index b39807841..9bc1ebe74 100644 --- a/src/core/hle/kernel/svc/svc_thread.cpp +++ b/src/core/hle/kernel/svc/svc_thread.cpp @@ -82,6 +82,9 @@ Result CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, // Commit the thread reservation. thread_reservation.Commit(); + // Clone the current fpu status to the new thread. + thread->CloneFpuStatus(); + // Register the new thread. KThread::Register(kernel, thread); diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp index ddc3a6dbe..120282aa4 100644 --- a/src/core/hle/service/acc/acc.cpp +++ b/src/core/hle/service/acc/acc.cpp @@ -30,12 +30,6 @@ namespace Service::Account { -constexpr Result ERR_INVALID_USER_ID{ErrorModule::Account, 20}; -constexpr Result ERR_INVALID_APPLICATION_ID{ErrorModule::Account, 22}; -constexpr Result ERR_INVALID_BUFFER{ErrorModule::Account, 30}; -constexpr Result ERR_INVALID_BUFFER_SIZE{ErrorModule::Account, 31}; -constexpr Result ERR_FAILED_SAVE_DATA{ErrorModule::Account, 100}; - // Thumbnails are hard coded to be at least this size constexpr std::size_t THUMBNAIL_SIZE = 0x24000; @@ -384,7 +378,7 @@ protected: if (user_data.size() < sizeof(UserData)) { LOG_ERROR(Service_ACC, "UserData buffer too small!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_BUFFER); + rb.Push(Account::ResultInvalidArrayLength); return; } @@ -394,7 +388,7 @@ protected: if (!profile_manager.SetProfileBaseAndData(user_id, base, data)) { LOG_ERROR(Service_ACC, "Failed to update user data and base!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_FAILED_SAVE_DATA); + rb.Push(Account::ResultAccountUpdateFailed); return; } @@ -417,7 +411,7 @@ protected: if (user_data.size() < sizeof(UserData)) { LOG_ERROR(Service_ACC, "UserData buffer too small!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_BUFFER); + rb.Push(Account::ResultInvalidArrayLength); return; } @@ -432,7 +426,7 @@ protected: !profile_manager.SetProfileBaseAndData(user_id, base, data)) { LOG_ERROR(Service_ACC, "Failed to update profile data, base, and image!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_FAILED_SAVE_DATA); + rb.Push(Account::ResultAccountUpdateFailed); return; } @@ -764,7 +758,7 @@ void Module::Interface::InitializeApplicationInfoRestricted(HLERequestContext& c Result Module::Interface::InitializeApplicationInfoBase() { if (application_info) { LOG_ERROR(Service_ACC, "Application already initialized"); - return ERR_ACCOUNTINFO_ALREADY_INITIALIZED; + return Account::ResultApplicationInfoAlreadyInitialized; } // TODO(ogniK): This should be changed to reflect the target process for when we have multiple @@ -775,7 +769,7 @@ Result Module::Interface::InitializeApplicationInfoBase() { if (launch_property.Failed()) { LOG_ERROR(Service_ACC, "Failed to get launch property"); - return ERR_ACCOUNTINFO_BAD_APPLICATION; + return Account::ResultInvalidApplication; } switch (launch_property->base_game_storage_id) { @@ -791,7 +785,7 @@ Result Module::Interface::InitializeApplicationInfoBase() { default: LOG_ERROR(Service_ACC, "Invalid game storage ID! storage_id={}", launch_property->base_game_storage_id); - return ERR_ACCOUNTINFO_BAD_APPLICATION; + return Account::ResultInvalidApplication; } LOG_WARNING(Service_ACC, "ApplicationInfo init required"); @@ -899,20 +893,20 @@ void Module::Interface::StoreSaveDataThumbnail(HLERequestContext& ctx, const Com if (tid == 0) { LOG_ERROR(Service_ACC, "TitleID is not valid!"); - rb.Push(ERR_INVALID_APPLICATION_ID); + rb.Push(Account::ResultInvalidApplication); return; } if (uuid.IsInvalid()) { LOG_ERROR(Service_ACC, "User ID is not valid!"); - rb.Push(ERR_INVALID_USER_ID); + rb.Push(Account::ResultInvalidUserId); return; } const auto thumbnail_size = ctx.GetReadBufferSize(); if (thumbnail_size != THUMBNAIL_SIZE) { LOG_ERROR(Service_ACC, "Buffer size is empty! size={:X} expecting {:X}", thumbnail_size, THUMBNAIL_SIZE); - rb.Push(ERR_INVALID_BUFFER_SIZE); + rb.Push(Account::ResultInvalidArrayLength); return; } diff --git a/src/core/hle/service/acc/errors.h b/src/core/hle/service/acc/errors.h index e9c16b951..433ebfe9d 100644 --- a/src/core/hle/service/acc/errors.h +++ b/src/core/hle/service/acc/errors.h @@ -7,7 +7,13 @@ namespace Service::Account { -constexpr Result ERR_ACCOUNTINFO_BAD_APPLICATION{ErrorModule::Account, 22}; -constexpr Result ERR_ACCOUNTINFO_ALREADY_INITIALIZED{ErrorModule::Account, 41}; +constexpr Result ResultCancelledByUser{ErrorModule::Account, 1}; +constexpr Result ResultNoNotifications{ErrorModule::Account, 15}; +constexpr Result ResultInvalidUserId{ErrorModule::Account, 20}; +constexpr Result ResultInvalidApplication{ErrorModule::Account, 22}; +constexpr Result ResultNullptr{ErrorModule::Account, 30}; +constexpr Result ResultInvalidArrayLength{ErrorModule::Account, 32}; +constexpr Result ResultApplicationInfoAlreadyInitialized{ErrorModule::Account, 41}; +constexpr Result ResultAccountUpdateFailed{ErrorModule::Account, 100}; } // namespace Service::Account diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp index f74c7b550..f17df5124 100644 --- a/src/core/hle/service/am/am.cpp +++ b/src/core/hle/service/am/am.cpp @@ -39,9 +39,9 @@ namespace Service::AM { -constexpr Result ERR_NO_DATA_IN_CHANNEL{ErrorModule::AM, 2}; -constexpr Result ERR_NO_MESSAGES{ErrorModule::AM, 3}; -constexpr Result ERR_SIZE_OUT_OF_BOUNDS{ErrorModule::AM, 503}; +constexpr Result ResultNoDataInChannel{ErrorModule::AM, 2}; +constexpr Result ResultNoMessages{ErrorModule::AM, 3}; +constexpr Result ResultInvalidOffset{ErrorModule::AM, 503}; enum class LaunchParameterKind : u32 { ApplicationSpecific = 1, @@ -758,7 +758,7 @@ void ICommonStateGetter::ReceiveMessage(HLERequestContext& ctx) { if (message == AppletMessageQueue::AppletMessage::None) { LOG_ERROR(Service_AM, "Message queue is empty"); - rb.Push(ERR_NO_MESSAGES); + rb.Push(AM::ResultNoMessages); rb.PushEnum<AppletMessageQueue::AppletMessage>(message); return; } @@ -1028,7 +1028,7 @@ private: LOG_DEBUG(Service_AM, "storage is a nullptr. There is no data in the current normal channel"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NO_DATA_IN_CHANNEL); + rb.Push(AM::ResultNoDataInChannel); return; } @@ -1059,7 +1059,7 @@ private: LOG_DEBUG(Service_AM, "storage is a nullptr. There is no data in the current interactive channel"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NO_DATA_IN_CHANNEL); + rb.Push(AM::ResultNoDataInChannel); return; } @@ -1138,7 +1138,7 @@ void IStorageAccessor::Write(HLERequestContext& ctx) { backing.GetSize(), size, offset); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_SIZE_OUT_OF_BOUNDS); + rb.Push(AM::ResultInvalidOffset); return; } @@ -1161,7 +1161,7 @@ void IStorageAccessor::Read(HLERequestContext& ctx) { backing.GetSize(), size, offset); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_SIZE_OUT_OF_BOUNDS); + rb.Push(AM::ResultInvalidOffset); return; } @@ -1502,7 +1502,7 @@ void IApplicationFunctions::PopLaunchParameter(HLERequestContext& ctx) { LOG_ERROR(Service_AM, "Attempted to load launch parameter but none was found!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NO_DATA_IN_CHANNEL); + rb.Push(AM::ResultNoDataInChannel); } void IApplicationFunctions::CreateApplicationAndRequestToStartForQuest(HLERequestContext& ctx) { @@ -1799,7 +1799,7 @@ void IApplicationFunctions::TryPopFromFriendInvitationStorageChannel(HLERequestC LOG_WARNING(Service_AM, "(STUBBED) called"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NO_DATA_IN_CHANNEL); + rb.Push(AM::ResultNoDataInChannel); } void IApplicationFunctions::GetNotificationStorageChannelEvent(HLERequestContext& ctx) { diff --git a/src/core/hle/service/am/applets/applet_cabinet.cpp b/src/core/hle/service/am/applets/applet_cabinet.cpp index d0969b0f1..162687b29 100644 --- a/src/core/hle/service/am/applets/applet_cabinet.cpp +++ b/src/core/hle/service/am/applets/applet_cabinet.cpp @@ -119,7 +119,7 @@ void Cabinet::DisplayCompleted(bool apply_changes, std::string_view amiibo_name) case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings: { Service::NFP::AmiiboName name{}; std::memcpy(name.data(), amiibo_name.data(), std::min(amiibo_name.size(), name.size() - 1)); - nfp_device->SetNicknameAndOwner(name); + nfp_device->SetRegisterInfoPrivate(name); break; } case Service::NFP::CabinetMode::StartGameDataEraser: @@ -129,7 +129,7 @@ void Cabinet::DisplayCompleted(bool apply_changes, std::string_view amiibo_name) nfp_device->RestoreAmiibo(); break; case Service::NFP::CabinetMode::StartFormatter: - nfp_device->DeleteAllData(); + nfp_device->Format(); break; default: UNIMPLEMENTED_MSG("Unknown CabinetMode={}", applet_input_common.applet_mode); diff --git a/src/core/hle/service/am/applets/applet_controller.cpp b/src/core/hle/service/am/applets/applet_controller.cpp index b418031de..58484519b 100644 --- a/src/core/hle/service/am/applets/applet_controller.cpp +++ b/src/core/hle/service/am/applets/applet_controller.cpp @@ -19,10 +19,9 @@ namespace Service::AM::Applets { -// This error code (0x183ACA) is thrown when the applet fails to initialize. -[[maybe_unused]] constexpr Result ERR_CONTROLLER_APPLET_3101{ErrorModule::HID, 3101}; -// This error code (0x183CCA) is thrown when the u32 result in ControllerSupportResultInfo is 2. -[[maybe_unused]] constexpr Result ERR_CONTROLLER_APPLET_3102{ErrorModule::HID, 3102}; +[[maybe_unused]] constexpr Result ResultControllerSupportCanceled{ErrorModule::HID, 3101}; +[[maybe_unused]] constexpr Result ResultControllerSupportNotSupportedNpadStyle{ErrorModule::HID, + 3102}; static Core::Frontend::ControllerParameters ConvertToFrontendParameters( ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text, diff --git a/src/core/hle/service/am/applets/applet_profile_select.cpp b/src/core/hle/service/am/applets/applet_profile_select.cpp index c738db028..1d69f5447 100644 --- a/src/core/hle/service/am/applets/applet_profile_select.cpp +++ b/src/core/hle/service/am/applets/applet_profile_select.cpp @@ -7,13 +7,12 @@ #include "common/string_util.h" #include "core/core.h" #include "core/frontend/applets/profile_select.h" +#include "core/hle/service/acc/errors.h" #include "core/hle/service/am/am.h" #include "core/hle/service/am/applets/applet_profile_select.h" namespace Service::AM::Applets { -constexpr Result ERR_USER_CANCELLED_SELECTION{ErrorModule::Account, 1}; - ProfileSelect::ProfileSelect(Core::System& system_, LibraryAppletMode applet_mode_, const Core::Frontend::ProfileSelectApplet& frontend_) : Applet{system_, applet_mode_}, frontend{frontend_}, system{system_} {} @@ -63,8 +62,8 @@ void ProfileSelect::SelectionComplete(std::optional<Common::UUID> uuid) { output.result = 0; output.uuid_selected = *uuid; } else { - status = ERR_USER_CANCELLED_SELECTION; - output.result = ERR_USER_CANCELLED_SELECTION.raw; + status = Account::ResultCancelledByUser; + output.result = Account::ResultCancelledByUser.raw; output.uuid_selected = Common::InvalidUUID; } diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp index 0a6830ffa..7086d4750 100644 --- a/src/core/hle/service/audio/audren_u.cpp +++ b/src/core/hle/service/audio/audren_u.cpp @@ -170,7 +170,7 @@ private: if (impl->GetSystem().GetExecutionMode() == AudioCore::ExecutionMode::Manual) { IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NOT_SUPPORTED); + rb.Push(Audio::ResultNotSupported); return; } @@ -448,7 +448,7 @@ void AudRenU::OpenAudioRenderer(HLERequestContext& ctx) { if (impl->GetSessionCount() + 1 > AudioCore::MaxRendererSessions) { LOG_ERROR(Service_Audio, "Too many AudioRenderer sessions open!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_MAXIMUM_SESSIONS_REACHED); + rb.Push(Audio::ResultOutOfSessions); return; } @@ -461,7 +461,7 @@ void AudRenU::OpenAudioRenderer(HLERequestContext& ctx) { if (session_id == -1) { LOG_ERROR(Service_Audio, "Tried to open a session that's already in use!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_MAXIMUM_SESSIONS_REACHED); + rb.Push(Audio::ResultOutOfSessions); return; } diff --git a/src/core/hle/service/audio/errors.h b/src/core/hle/service/audio/errors.h index d706978cb..3d3d3d97a 100644 --- a/src/core/hle/service/audio/errors.h +++ b/src/core/hle/service/audio/errors.h @@ -7,17 +7,17 @@ namespace Service::Audio { -constexpr Result ERR_INVALID_DEVICE_NAME{ErrorModule::Audio, 1}; -constexpr Result ERR_OPERATION_FAILED{ErrorModule::Audio, 2}; -constexpr Result ERR_INVALID_SAMPLE_RATE{ErrorModule::Audio, 3}; -constexpr Result ERR_INSUFFICIENT_BUFFER_SIZE{ErrorModule::Audio, 4}; -constexpr Result ERR_MAXIMUM_SESSIONS_REACHED{ErrorModule::Audio, 5}; -constexpr Result ERR_BUFFER_COUNT_EXCEEDED{ErrorModule::Audio, 8}; -constexpr Result ERR_INVALID_CHANNEL_COUNT{ErrorModule::Audio, 10}; -constexpr Result ERR_INVALID_UPDATE_DATA{ErrorModule::Audio, 41}; -constexpr Result ERR_POOL_MAPPING_FAILED{ErrorModule::Audio, 42}; -constexpr Result ERR_NOT_SUPPORTED{ErrorModule::Audio, 513}; -constexpr Result ERR_INVALID_PROCESS_HANDLE{ErrorModule::Audio, 1536}; -constexpr Result ERR_INVALID_REVISION{ErrorModule::Audio, 1537}; +constexpr Result ResultNotFound{ErrorModule::Audio, 1}; +constexpr Result ResultOperationFailed{ErrorModule::Audio, 2}; +constexpr Result ResultInvalidSampleRate{ErrorModule::Audio, 3}; +constexpr Result ResultInsufficientBuffer{ErrorModule::Audio, 4}; +constexpr Result ResultOutOfSessions{ErrorModule::Audio, 5}; +constexpr Result ResultBufferCountReached{ErrorModule::Audio, 8}; +constexpr Result ResultInvalidChannelCount{ErrorModule::Audio, 10}; +constexpr Result ResultInvalidUpdateInfo{ErrorModule::Audio, 41}; +constexpr Result ResultInvalidAddressInfo{ErrorModule::Audio, 42}; +constexpr Result ResultNotSupported{ErrorModule::Audio, 513}; +constexpr Result ResultInvalidHandle{ErrorModule::Audio, 1536}; +constexpr Result ResultInvalidRevision{ErrorModule::Audio, 1537}; } // namespace Service::Audio diff --git a/src/core/hle/service/friend/errors.h b/src/core/hle/service/friend/errors.h deleted file mode 100644 index ff525d865..000000000 --- a/src/core/hle/service/friend/errors.h +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -#pragma once - -#include "core/hle/result.h" - -namespace Service::Friend { - -constexpr Result ERR_NO_NOTIFICATIONS{ErrorModule::Account, 15}; -} diff --git a/src/core/hle/service/friend/friend.cpp b/src/core/hle/service/friend/friend.cpp index 447deab8b..9d05f9801 100644 --- a/src/core/hle/service/friend/friend.cpp +++ b/src/core/hle/service/friend/friend.cpp @@ -6,7 +6,7 @@ #include "common/uuid.h" #include "core/core.h" #include "core/hle/kernel/k_event.h" -#include "core/hle/service/friend/errors.h" +#include "core/hle/service/acc/errors.h" #include "core/hle/service/friend/friend.h" #include "core/hle/service/friend/friend_interface.h" #include "core/hle/service/ipc_helpers.h" @@ -259,7 +259,7 @@ private: if (notifications.empty()) { LOG_ERROR(Service_Friend, "No notifications in queue!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NO_NOTIFICATIONS); + rb.Push(Account::ResultNoNotifications); return; } diff --git a/src/core/hle/service/glue/arp.cpp b/src/core/hle/service/glue/arp.cpp index 9db136bac..929dcca0d 100644 --- a/src/core/hle/service/glue/arp.cpp +++ b/src/core/hle/service/glue/arp.cpp @@ -61,7 +61,7 @@ void ARP_R::GetApplicationLaunchProperty(HLERequestContext& ctx) { if (!title_id.has_value()) { LOG_ERROR(Service_ARP, "Failed to get title ID for process ID!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NOT_REGISTERED); + rb.Push(Glue::ResultProcessIdNotRegistered); return; } @@ -109,7 +109,7 @@ void ARP_R::GetApplicationControlProperty(HLERequestContext& ctx) { if (!title_id.has_value()) { LOG_ERROR(Service_ARP, "Failed to get title ID for process ID!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NOT_REGISTERED); + rb.Push(Glue::ResultProcessIdNotRegistered); return; } @@ -178,7 +178,7 @@ private: if (process_id == 0) { LOG_ERROR(Service_ARP, "Must have non-zero process ID!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_PROCESS_ID); + rb.Push(Glue::ResultInvalidProcessId); return; } @@ -186,7 +186,7 @@ private: LOG_ERROR(Service_ARP, "Attempted to issue registrar, but registrar is already issued!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_ACCESS); + rb.Push(Glue::ResultAlreadyBound); return; } @@ -205,7 +205,7 @@ private: Service_ARP, "Attempted to set application launch property, but registrar is already issued!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_ACCESS); + rb.Push(Glue::ResultAlreadyBound); return; } @@ -224,7 +224,7 @@ private: Service_ARP, "Attempted to set application control property, but registrar is already issued!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_ACCESS); + rb.Push(Glue::ResultAlreadyBound); return; } @@ -263,7 +263,7 @@ void ARP_W::AcquireRegistrar(HLERequestContext& ctx) { system, [this](u64 process_id, ApplicationLaunchProperty launch, std::vector<u8> control) { const auto res = GetTitleIDForProcessID(system, process_id); if (!res.has_value()) { - return ERR_NOT_REGISTERED; + return Glue::ResultProcessIdNotRegistered; } return manager.Register(*res, launch, std::move(control)); @@ -283,7 +283,7 @@ void ARP_W::UnregisterApplicationInstance(HLERequestContext& ctx) { if (process_id == 0) { LOG_ERROR(Service_ARP, "Must have non-zero process ID!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_PROCESS_ID); + rb.Push(Glue::ResultInvalidProcessId); return; } @@ -292,7 +292,7 @@ void ARP_W::UnregisterApplicationInstance(HLERequestContext& ctx) { if (!title_id.has_value()) { LOG_ERROR(Service_ARP, "No title ID for process ID!"); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_NOT_REGISTERED); + rb.Push(Glue::ResultProcessIdNotRegistered); return; } diff --git a/src/core/hle/service/glue/errors.h b/src/core/hle/service/glue/errors.h index d4ce7f44e..30feaa5c0 100644 --- a/src/core/hle/service/glue/errors.h +++ b/src/core/hle/service/glue/errors.h @@ -7,9 +7,8 @@ namespace Service::Glue { -constexpr Result ERR_INVALID_RESOURCE{ErrorModule::ARP, 30}; -constexpr Result ERR_INVALID_PROCESS_ID{ErrorModule::ARP, 31}; -constexpr Result ERR_INVALID_ACCESS{ErrorModule::ARP, 42}; -constexpr Result ERR_NOT_REGISTERED{ErrorModule::ARP, 102}; +constexpr Result ResultInvalidProcessId{ErrorModule::ARP, 31}; +constexpr Result ResultAlreadyBound{ErrorModule::ARP, 42}; +constexpr Result ResultProcessIdNotRegistered{ErrorModule::ARP, 102}; } // namespace Service::Glue diff --git a/src/core/hle/service/glue/glue_manager.cpp b/src/core/hle/service/glue/glue_manager.cpp index 8a654cdca..4bf67921b 100644 --- a/src/core/hle/service/glue/glue_manager.cpp +++ b/src/core/hle/service/glue/glue_manager.cpp @@ -17,12 +17,12 @@ ARPManager::~ARPManager() = default; ResultVal<ApplicationLaunchProperty> ARPManager::GetLaunchProperty(u64 title_id) const { if (title_id == 0) { - return ERR_INVALID_PROCESS_ID; + return Glue::ResultInvalidProcessId; } const auto iter = entries.find(title_id); if (iter == entries.end()) { - return ERR_NOT_REGISTERED; + return Glue::ResultProcessIdNotRegistered; } return iter->second.launch; @@ -30,12 +30,12 @@ ResultVal<ApplicationLaunchProperty> ARPManager::GetLaunchProperty(u64 title_id) ResultVal<std::vector<u8>> ARPManager::GetControlProperty(u64 title_id) const { if (title_id == 0) { - return ERR_INVALID_PROCESS_ID; + return Glue::ResultInvalidProcessId; } const auto iter = entries.find(title_id); if (iter == entries.end()) { - return ERR_NOT_REGISTERED; + return Glue::ResultProcessIdNotRegistered; } return iter->second.control; @@ -44,12 +44,12 @@ ResultVal<std::vector<u8>> ARPManager::GetControlProperty(u64 title_id) const { Result ARPManager::Register(u64 title_id, ApplicationLaunchProperty launch, std::vector<u8> control) { if (title_id == 0) { - return ERR_INVALID_PROCESS_ID; + return Glue::ResultInvalidProcessId; } const auto iter = entries.find(title_id); if (iter != entries.end()) { - return ERR_INVALID_ACCESS; + return Glue::ResultAlreadyBound; } entries.insert_or_assign(title_id, MapEntry{launch, std::move(control)}); @@ -58,12 +58,12 @@ Result ARPManager::Register(u64 title_id, ApplicationLaunchProperty launch, Result ARPManager::Unregister(u64 title_id) { if (title_id == 0) { - return ERR_INVALID_PROCESS_ID; + return Glue::ResultInvalidProcessId; } const auto iter = entries.find(title_id); if (iter == entries.end()) { - return ERR_NOT_REGISTERED; + return Glue::ResultProcessIdNotRegistered; } entries.erase(iter); diff --git a/src/core/hle/service/glue/glue_manager.h b/src/core/hle/service/glue/glue_manager.h index cd0b092ac..1cf53d9d9 100644 --- a/src/core/hle/service/glue/glue_manager.h +++ b/src/core/hle/service/glue/glue_manager.h @@ -30,23 +30,23 @@ public: ~ARPManager(); // Returns the ApplicationLaunchProperty corresponding to the provided title ID if it was - // previously registered, otherwise ERR_NOT_REGISTERED if it was never registered or - // ERR_INVALID_PROCESS_ID if the title ID is 0. + // previously registered, otherwise ResultProcessIdNotRegistered if it was never registered or + // ResultInvalidProcessId if the title ID is 0. ResultVal<ApplicationLaunchProperty> GetLaunchProperty(u64 title_id) const; // Returns a vector of the raw bytes of NACP data (necessarily 0x4000 in size) corresponding to - // the provided title ID if it was previously registered, otherwise ERR_NOT_REGISTERED if it was - // never registered or ERR_INVALID_PROCESS_ID if the title ID is 0. + // the provided title ID if it was previously registered, otherwise ResultProcessIdNotRegistered + // if it was never registered or ResultInvalidProcessId if the title ID is 0. ResultVal<std::vector<u8>> GetControlProperty(u64 title_id) const; // Adds a new entry to the internal database with the provided parameters, returning - // ERR_INVALID_ACCESS if attempting to re-register a title ID without an intermediate Unregister - // step, and ERR_INVALID_PROCESS_ID if the title ID is 0. + // ResultProcessIdNotRegistered if attempting to re-register a title ID without an intermediate + // Unregister step, and ResultInvalidProcessId if the title ID is 0. Result Register(u64 title_id, ApplicationLaunchProperty launch, std::vector<u8> control); // Removes the registration for the provided title ID from the database, returning - // ERR_NOT_REGISTERED if it doesn't exist in the database and ERR_INVALID_PROCESS_ID if the - // title ID is 0. + // ResultProcessIdNotRegistered if it doesn't exist in the database and ResultInvalidProcessId + // if the title ID is 0. Result Unregister(u64 title_id); // Removes all entries from the database, always succeeds. Should only be used when resetting diff --git a/src/core/hle/service/hid/controllers/stubbed.cpp b/src/core/hle/service/hid/controllers/stubbed.cpp index df9ee0c3f..9e2f3ab21 100644 --- a/src/core/hle/service/hid/controllers/stubbed.cpp +++ b/src/core/hle/service/hid/controllers/stubbed.cpp @@ -26,7 +26,7 @@ void Controller_Stubbed::OnUpdate(const Core::Timing::CoreTiming& core_timing) { } CommonHeader header{}; - header.timestamp = core_timing.GetCPUTicks(); + header.timestamp = core_timing.GetGlobalTimeNs().count(); header.total_entry_count = 17; header.entry_count = 0; header.last_entry_index = 0; diff --git a/src/core/hle/service/hid/controllers/touchscreen.cpp b/src/core/hle/service/hid/controllers/touchscreen.cpp index d90a4e732..3ef91df4b 100644 --- a/src/core/hle/service/hid/controllers/touchscreen.cpp +++ b/src/core/hle/service/hid/controllers/touchscreen.cpp @@ -32,7 +32,7 @@ void Controller_Touchscreen::OnInit() {} void Controller_Touchscreen::OnRelease() {} void Controller_Touchscreen::OnUpdate(const Core::Timing::CoreTiming& core_timing) { - shared_memory->touch_screen_lifo.timestamp = core_timing.GetCPUTicks(); + shared_memory->touch_screen_lifo.timestamp = core_timing.GetGlobalTimeNs().count(); if (!IsControllerActivated()) { shared_memory->touch_screen_lifo.buffer_count = 0; @@ -85,7 +85,7 @@ void Controller_Touchscreen::OnUpdate(const Core::Timing::CoreTiming& core_timin const auto active_fingers_count = static_cast<std::size_t>(std::distance(active_fingers.begin(), end_iter)); - const u64 tick = core_timing.GetCPUTicks(); + const u64 timestamp = static_cast<u64>(core_timing.GetGlobalTimeNs().count()); const auto& last_entry = shared_memory->touch_screen_lifo.ReadCurrentEntry().state; next_state.sampling_number = last_entry.sampling_number + 1; @@ -102,8 +102,8 @@ void Controller_Touchscreen::OnUpdate(const Core::Timing::CoreTiming& core_timin touch_entry.diameter_x = Settings::values.touchscreen.diameter_x; touch_entry.diameter_y = Settings::values.touchscreen.diameter_y; touch_entry.rotation_angle = Settings::values.touchscreen.rotation_angle; - touch_entry.delta_time = tick - active_fingers[id].last_touch; - fingers[active_fingers[id].id].last_touch = tick; + touch_entry.delta_time = timestamp - active_fingers[id].last_touch; + fingers[active_fingers[id].id].last_touch = timestamp; touch_entry.finger = active_fingers[id].id; touch_entry.attribute.raw = active_fingers[id].attribute.raw; } else { diff --git a/src/core/hle/service/ipc_helpers.h b/src/core/hle/service/ipc_helpers.h index 3e67123c7..8703b57ca 100644 --- a/src/core/hle/service/ipc_helpers.h +++ b/src/core/hle/service/ipc_helpers.h @@ -19,7 +19,7 @@ namespace IPC { -constexpr Result ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301}; +constexpr Result ResultSessionClosed{ErrorModule::HIPC, 301}; class RequestHelperBase { protected: diff --git a/src/core/hle/service/nfp/amiibo_crypto.cpp b/src/core/hle/service/nfp/amiibo_crypto.cpp index ffb2f959c..ddf04b1d7 100644 --- a/src/core/hle/service/nfp/amiibo_crypto.cpp +++ b/src/core/hle/service/nfp/amiibo_crypto.cpp @@ -80,13 +80,16 @@ NTAG215File NfcDataToEncodedData(const EncryptedNTAG215File& nfc_data) { encoded_data.hmac_data = nfc_data.user_memory.hmac_data; encoded_data.constant_value = nfc_data.user_memory.constant_value; encoded_data.write_counter = nfc_data.user_memory.write_counter; + encoded_data.amiibo_version = nfc_data.user_memory.amiibo_version; encoded_data.settings = nfc_data.user_memory.settings; encoded_data.owner_mii = nfc_data.user_memory.owner_mii; - encoded_data.title_id = nfc_data.user_memory.title_id; - encoded_data.applicaton_write_counter = nfc_data.user_memory.applicaton_write_counter; + encoded_data.application_id = nfc_data.user_memory.application_id; + encoded_data.application_write_counter = nfc_data.user_memory.application_write_counter; encoded_data.application_area_id = nfc_data.user_memory.application_area_id; + encoded_data.application_id_byte = nfc_data.user_memory.application_id_byte; encoded_data.unknown = nfc_data.user_memory.unknown; encoded_data.unknown2 = nfc_data.user_memory.unknown2; + encoded_data.application_area_crc = nfc_data.user_memory.application_area_crc; encoded_data.application_area = nfc_data.user_memory.application_area; encoded_data.hmac_tag = nfc_data.user_memory.hmac_tag; encoded_data.lock_bytes = nfc_data.uuid.lock_bytes; @@ -111,13 +114,16 @@ EncryptedNTAG215File EncodedDataToNfcData(const NTAG215File& encoded_data) { nfc_data.user_memory.hmac_data = encoded_data.hmac_data; nfc_data.user_memory.constant_value = encoded_data.constant_value; nfc_data.user_memory.write_counter = encoded_data.write_counter; + nfc_data.user_memory.amiibo_version = encoded_data.amiibo_version; nfc_data.user_memory.settings = encoded_data.settings; nfc_data.user_memory.owner_mii = encoded_data.owner_mii; - nfc_data.user_memory.title_id = encoded_data.title_id; - nfc_data.user_memory.applicaton_write_counter = encoded_data.applicaton_write_counter; + nfc_data.user_memory.application_id = encoded_data.application_id; + nfc_data.user_memory.application_write_counter = encoded_data.application_write_counter; nfc_data.user_memory.application_area_id = encoded_data.application_area_id; + nfc_data.user_memory.application_id_byte = encoded_data.application_id_byte; nfc_data.user_memory.unknown = encoded_data.unknown; nfc_data.user_memory.unknown2 = encoded_data.unknown2; + nfc_data.user_memory.application_area_crc = encoded_data.application_area_crc; nfc_data.user_memory.application_area = encoded_data.application_area; nfc_data.user_memory.hmac_tag = encoded_data.hmac_tag; nfc_data.user_memory.model_info = encoded_data.model_info; diff --git a/src/core/hle/service/nfp/nfp_device.cpp b/src/core/hle/service/nfp/nfp_device.cpp index 1bdc42741..ddff90d6a 100644 --- a/src/core/hle/service/nfp/nfp_device.cpp +++ b/src/core/hle/service/nfp/nfp_device.cpp @@ -174,8 +174,8 @@ Result NfpDevice::StopDetection() { if (device_state == DeviceState::TagFound || device_state == DeviceState::TagMounted) { CloseAmiibo(); - return ResultSuccess; } + if (device_state == DeviceState::SearchingForTag || device_state == DeviceState::TagRemoved) { device_state = DeviceState::Initialized; return ResultSuccess; @@ -204,9 +204,7 @@ Result NfpDevice::Flush() { const auto& current_date = GetAmiiboDate(current_posix_time); if (settings.write_date.raw_date != current_date.raw_date) { settings.write_date = current_date; - settings.crc_counter++; - // TODO: Find how to calculate the crc check - // settings.crc = CalculateCRC(settings); + UpdateSettingsCrc(); } tag_data.write_counter++; @@ -318,7 +316,7 @@ Result NfpDevice::GetCommonInfo(CommonInfo& common_info) const { common_info = { .last_write_date = settings.write_date.GetWriteDate(), .write_counter = tag_data.write_counter, - .version = 0, + .version = tag_data.amiibo_version, .application_area_size = sizeof(ApplicationArea), }; return ResultSuccess; @@ -370,13 +368,95 @@ Result NfpDevice::GetRegisterInfo(RegisterInfo& register_info) const { .mii_char_info = manager.ConvertV3ToCharInfo(tag_data.owner_mii), .creation_date = settings.init_date.GetWriteDate(), .amiibo_name = GetAmiiboName(settings), - .font_region = {}, + .font_region = settings.settings.font_region, + }; + + return ResultSuccess; +} + +Result NfpDevice::GetAdminInfo(AdminInfo& admin_info) const { + if (device_state != DeviceState::TagMounted) { + LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); + if (device_state == DeviceState::TagRemoved) { + return TagRemoved; + } + return WrongDeviceState; + } + + if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { + LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); + return WrongDeviceState; + } + + u8 flags = static_cast<u8>(tag_data.settings.settings.raw >> 0x4); + if (tag_data.settings.settings.amiibo_initialized == 0) { + flags = flags & 0xfe; + } + + u64 application_id = 0; + u32 application_area_id = 0; + AppAreaVersion app_area_version = AppAreaVersion::NotSet; + if (tag_data.settings.settings.appdata_initialized != 0) { + application_id = tag_data.application_id; + app_area_version = + static_cast<AppAreaVersion>(application_id >> application_id_version_offset & 0xf); + + // Restore application id to original value + if (application_id >> 0x38 != 0) { + const u8 application_byte = tag_data.application_id_byte & 0xf; + application_id = RemoveVersionByte(application_id) | + (static_cast<u64>(application_byte) << application_id_version_offset); + } + + application_area_id = tag_data.application_area_id; + } + + // TODO: Validate this data + admin_info = { + .application_id = application_id, + .application_area_id = application_area_id, + .crc_change_counter = tag_data.settings.crc_counter, + .flags = flags, + .tag_type = PackedTagType::Type2, + .app_area_version = app_area_version, }; return ResultSuccess; } -Result NfpDevice::SetNicknameAndOwner(const AmiiboName& amiibo_name) { +Result NfpDevice::DeleteRegisterInfo() { + if (device_state != DeviceState::TagMounted) { + LOG_ERROR(Service_NFC, "Wrong device state {}", device_state); + if (device_state == DeviceState::TagRemoved) { + return TagRemoved; + } + return WrongDeviceState; + } + + if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) { + LOG_ERROR(Service_NFC, "Amiibo is read only", device_state); + return WrongDeviceState; + } + + if (tag_data.settings.settings.amiibo_initialized == 0) { + return RegistrationIsNotInitialized; + } + + Common::TinyMT rng{}; + rng.GenerateRandomBytes(&tag_data.owner_mii, sizeof(tag_data.owner_mii)); + rng.GenerateRandomBytes(&tag_data.settings.amiibo_name, sizeof(tag_data.settings.amiibo_name)); + rng.GenerateRandomBytes(&tag_data.unknown, sizeof(u8)); + rng.GenerateRandomBytes(&tag_data.unknown2[0], sizeof(u32)); + rng.GenerateRandomBytes(&tag_data.unknown2[1], sizeof(u32)); + rng.GenerateRandomBytes(&tag_data.application_area_crc, sizeof(u32)); + rng.GenerateRandomBytes(&tag_data.settings.init_date, sizeof(u32)); + tag_data.settings.settings.font_region.Assign(0); + tag_data.settings.settings.amiibo_initialized.Assign(0); + + return Flush(); +} + +Result NfpDevice::SetRegisterInfoPrivate(const AmiiboName& amiibo_name) { if (device_state != DeviceState::TagMounted) { LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); if (device_state == DeviceState::TagRemoved) { @@ -393,16 +473,23 @@ Result NfpDevice::SetNicknameAndOwner(const AmiiboName& amiibo_name) { Service::Mii::MiiManager manager; auto& settings = tag_data.settings; - settings.init_date = GetAmiiboDate(current_posix_time); - settings.write_date = GetAmiiboDate(current_posix_time); - settings.crc_counter++; - // TODO: Find how to calculate the crc check - // settings.crc = CalculateCRC(settings); + if (tag_data.settings.settings.amiibo_initialized == 0) { + settings.init_date = GetAmiiboDate(current_posix_time); + settings.write_date.raw_date = 0; + } SetAmiiboName(settings, amiibo_name); tag_data.owner_mii = manager.ConvertCharInfoToV3(manager.BuildDefault(0)); + tag_data.unknown = 0; + tag_data.unknown2[6] = 0; + settings.country_code_id = 0; + settings.settings.font_region.Assign(0); settings.settings.amiibo_initialized.Assign(1); + // TODO: this is a mix of tag.file input + std::array<u8, 0x7e> unknown_input{}; + tag_data.application_area_crc = CalculateCrc(unknown_input); + return Flush(); } @@ -425,23 +512,17 @@ Result NfpDevice::RestoreAmiibo() { return ResultSuccess; } -Result NfpDevice::DeleteAllData() { - const auto result = DeleteApplicationArea(); - if (result.IsError()) { - return result; - } +Result NfpDevice::Format() { + auto result1 = DeleteApplicationArea(); + auto result2 = DeleteRegisterInfo(); - if (device_state != DeviceState::TagMounted) { - LOG_ERROR(Service_NFP, "Wrong device state {}", device_state); - if (device_state == DeviceState::TagRemoved) { - return TagRemoved; - } - return WrongDeviceState; + if (result1.IsError()) { + return result1; } - Common::TinyMT rng{}; - rng.GenerateRandomBytes(&tag_data.owner_mii, sizeof(tag_data.owner_mii)); - tag_data.settings.settings.amiibo_initialized.Assign(0); + if (result2.IsError()) { + return result2; + } return Flush(); } @@ -569,7 +650,10 @@ Result NfpDevice::SetApplicationArea(std::span<const u8> data) { rng.GenerateRandomBytes(tag_data.application_area.data() + data.size(), sizeof(ApplicationArea) - data.size()); - tag_data.applicaton_write_counter++; + if (tag_data.application_write_counter != counter_limit) { + tag_data.application_write_counter++; + } + is_data_moddified = true; return ResultSuccess; @@ -617,14 +701,25 @@ Result NfpDevice::RecreateApplicationArea(u32 access_id, std::span<const u8> dat rng.GenerateRandomBytes(tag_data.application_area.data() + data.size(), sizeof(ApplicationArea) - data.size()); - // TODO: Investigate why the title id needs to be moddified - tag_data.title_id = system.GetApplicationProcessProgramID(); - tag_data.title_id = tag_data.title_id | 0x30000000ULL; + if (tag_data.application_write_counter != counter_limit) { + tag_data.application_write_counter++; + } + + const u64 application_id = system.GetApplicationProcessProgramID(); + + tag_data.application_id_byte = + static_cast<u8>(application_id >> application_id_version_offset & 0xf); + tag_data.application_id = + RemoveVersionByte(application_id) | + (static_cast<u64>(AppAreaVersion::NintendoSwitch) << application_id_version_offset); tag_data.settings.settings.appdata_initialized.Assign(1); tag_data.application_area_id = access_id; - tag_data.applicaton_write_counter++; tag_data.unknown = {}; + // TODO: this is a mix of tag_data input + std::array<u8, 0x7e> unknown_input{}; + tag_data.application_area_crc = CalculateCrc(unknown_input); + return Flush(); } @@ -642,12 +737,20 @@ Result NfpDevice::DeleteApplicationArea() { return WrongDeviceState; } + if (tag_data.settings.settings.appdata_initialized == 0) { + return ApplicationAreaIsNotInitialized; + } + + if (tag_data.application_write_counter != counter_limit) { + tag_data.application_write_counter++; + } + Common::TinyMT rng{}; rng.GenerateRandomBytes(tag_data.application_area.data(), sizeof(ApplicationArea)); - rng.GenerateRandomBytes(&tag_data.title_id, sizeof(u64)); + rng.GenerateRandomBytes(&tag_data.application_id, sizeof(u64)); rng.GenerateRandomBytes(&tag_data.application_area_id, sizeof(u32)); + rng.GenerateRandomBytes(&tag_data.application_id_byte, sizeof(u8)); tag_data.settings.settings.appdata_initialized.Assign(0); - tag_data.applicaton_write_counter++; tag_data.unknown = {}; return Flush(); @@ -719,4 +822,45 @@ AmiiboDate NfpDevice::GetAmiiboDate(s64 posix_time) const { return amiibo_date; } +u64 NfpDevice::RemoveVersionByte(u64 application_id) const { + return application_id & ~(0xfULL << application_id_version_offset); +} + +void NfpDevice::UpdateSettingsCrc() { + auto& settings = tag_data.settings; + + if (settings.crc_counter != counter_limit) { + settings.crc_counter++; + } + + // TODO: this reads data from a global, find what it is + std::array<u8, 8> unknown_input{}; + settings.crc = CalculateCrc(unknown_input); +} + +u32 NfpDevice::CalculateCrc(std::span<const u8> data) { + constexpr u32 magic = 0xedb88320; + u32 crc = 0xffffffff; + + if (data.size() == 0) { + return 0; + } + + for (u8 input : data) { + u32 temp = (crc ^ input) >> 1; + if (((crc ^ input) & 1) != 0) { + temp = temp ^ magic; + } + + for (std::size_t step = 0; step < 7; ++step) { + crc = temp >> 1; + if ((temp & 1) != 0) { + crc = temp >> 1 ^ magic; + } + } + } + + return ~crc; +} + } // namespace Service::NFP diff --git a/src/core/hle/service/nfp/nfp_device.h b/src/core/hle/service/nfp/nfp_device.h index b6a46f2ac..06386401d 100644 --- a/src/core/hle/service/nfp/nfp_device.h +++ b/src/core/hle/service/nfp/nfp_device.h @@ -47,10 +47,12 @@ public: Result GetCommonInfo(CommonInfo& common_info) const; Result GetModelInfo(ModelInfo& model_info) const; Result GetRegisterInfo(RegisterInfo& register_info) const; + Result GetAdminInfo(AdminInfo& admin_info) const; - Result SetNicknameAndOwner(const AmiiboName& amiibo_name); + Result DeleteRegisterInfo(); + Result SetRegisterInfoPrivate(const AmiiboName& amiibo_name); Result RestoreAmiibo(); - Result DeleteAllData(); + Result Format(); Result OpenApplicationArea(u32 access_id); Result GetApplicationAreaId(u32& application_area_id) const; @@ -76,6 +78,9 @@ private: AmiiboName GetAmiiboName(const AmiiboSettings& settings) const; void SetAmiiboName(AmiiboSettings& settings, const AmiiboName& amiibo_name); AmiiboDate GetAmiiboDate(s64 posix_time) const; + u64 RemoveVersionByte(u64 application_id) const; + void UpdateSettingsCrc(); + u32 CalculateCrc(std::span<const u8>); bool is_controller_set{}; int callback_key; diff --git a/src/core/hle/service/nfp/nfp_types.h b/src/core/hle/service/nfp/nfp_types.h index fc228c2b2..142343d6e 100644 --- a/src/core/hle/service/nfp/nfp_types.h +++ b/src/core/hle/service/nfp/nfp_types.h @@ -10,6 +10,8 @@ namespace Service::NFP { static constexpr std::size_t amiibo_name_length = 0xA; +static constexpr std::size_t application_id_version_offset = 0x1c; +static constexpr std::size_t counter_limit = 0xffff; enum class ServiceType : u32 { User, @@ -99,6 +101,14 @@ enum class TagProtocol : u32 { All = 0xFFFFFFFFU, }; +enum class AppAreaVersion : u8 { + Nintendo3DS = 0, + NintendoWiiU = 1, + Nintendo3DSv2 = 2, + NintendoSwitch = 3, + NotSet = 0xFF, +}; + enum class CabinetMode : u8 { StartNicknameAndOwnerSettings, StartGameDataEraser, @@ -197,6 +207,7 @@ struct Settings { union { u8 raw{}; + BitField<0, 4, u8> font_region; BitField<4, 1, u8> amiibo_initialized; BitField<5, 1, u8> appdata_initialized; }; @@ -236,18 +247,20 @@ static_assert(sizeof(NTAG215Password) == 0x8, "NTAG215Password is an invalid siz struct EncryptedAmiiboFile { u8 constant_value; // Must be A5 u16_be write_counter; // Number of times the amiibo has been written? - INSERT_PADDING_BYTES(0x1); // Unknown 1 + u8 amiibo_version; // Amiibo file version AmiiboSettings settings; // Encrypted amiibo settings HashData hmac_tag; // Hash AmiiboModelInfo model_info; // Encrypted amiibo model info HashData keygen_salt; // Salt HashData hmac_data; // Hash Service::Mii::Ver3StoreData owner_mii; // Encrypted Mii data - u64_be title_id; // Encrypted Game id - u16_be applicaton_write_counter; // Encrypted Counter + u64_be application_id; // Encrypted Game id + u16_be application_write_counter; // Encrypted Counter u32_be application_area_id; // Encrypted Game id - std::array<u8, 0x2> unknown; - std::array<u32, 0x8> unknown2; + u8 application_id_byte; + u8 unknown; + std::array<u32, 0x7> unknown2; + u32_be application_area_crc; ApplicationArea application_area; // Encrypted Game data }; static_assert(sizeof(EncryptedAmiiboFile) == 0x1F8, "AmiiboFile is an invalid size"); @@ -259,14 +272,16 @@ struct NTAG215File { HashData hmac_data; // Hash u8 constant_value; // Must be A5 u16_be write_counter; // Number of times the amiibo has been written? - INSERT_PADDING_BYTES(0x1); // Unknown 1 + u8 amiibo_version; // Amiibo file version AmiiboSettings settings; - Service::Mii::Ver3StoreData owner_mii; // Encrypted Mii data - u64_be title_id; - u16_be applicaton_write_counter; // Encrypted Counter + Service::Mii::Ver3StoreData owner_mii; // Mii data + u64_be application_id; // Game id + u16_be application_write_counter; // Counter u32_be application_area_id; - std::array<u8, 0x2> unknown; - std::array<u32, 0x8> unknown2; + u8 application_id_byte; + u8 unknown; + std::array<u32, 0x7> unknown2; + u32_be application_area_crc; ApplicationArea application_area; // Encrypted Game data HashData hmac_tag; // Hash UniqueSerialNumber uid; // Unique serial number @@ -336,6 +351,18 @@ struct RegisterInfo { }; static_assert(sizeof(RegisterInfo) == 0x100, "RegisterInfo is an invalid size"); +struct AdminInfo { + u64 application_id; + u32 application_area_id; + u16 crc_change_counter; + u8 flags; + PackedTagType tag_type; + AppAreaVersion app_area_version; + INSERT_PADDING_BYTES(0x7); + INSERT_PADDING_BYTES(0x28); +}; +static_assert(sizeof(AdminInfo) == 0x40, "AdminInfo is an invalid size"); + struct SectorKey { MifareCmd command; u8 unknown; // Usually 1 diff --git a/src/core/hle/service/ns/errors.h b/src/core/hle/service/ns/errors.h index 8a7621798..16d2ea6f7 100644 --- a/src/core/hle/service/ns/errors.h +++ b/src/core/hle/service/ns/errors.h @@ -7,5 +7,6 @@ namespace Service::NS { -constexpr Result ERR_APPLICATION_LANGUAGE_NOT_FOUND{ErrorModule::NS, 300}; -}
\ No newline at end of file +constexpr Result ResultApplicationLanguageNotFound{ErrorModule::NS, 300}; + +} diff --git a/src/core/hle/service/ns/ns.cpp b/src/core/hle/service/ns/ns.cpp index d6f0faea2..376067a95 100644 --- a/src/core/hle/service/ns/ns.cpp +++ b/src/core/hle/service/ns/ns.cpp @@ -416,14 +416,14 @@ ResultVal<u8> IApplicationManagerInterface::GetApplicationDesiredLanguage( if (application_language == std::nullopt) { LOG_ERROR(Service_NS, "Could not convert application language! language_code={}", language_code); - return ERR_APPLICATION_LANGUAGE_NOT_FOUND; + return Service::NS::ResultApplicationLanguageNotFound; } const auto priority_list = GetApplicationLanguagePriorityList(*application_language); if (!priority_list) { LOG_ERROR(Service_NS, "Could not find application language priorities! application_language={}", *application_language); - return ERR_APPLICATION_LANGUAGE_NOT_FOUND; + return Service::NS::ResultApplicationLanguageNotFound; } // Try to find a valid language. @@ -436,7 +436,7 @@ ResultVal<u8> IApplicationManagerInterface::GetApplicationDesiredLanguage( LOG_ERROR(Service_NS, "Could not find a valid language! supported_languages={:08X}", supported_languages); - return ERR_APPLICATION_LANGUAGE_NOT_FOUND; + return Service::NS::ResultApplicationLanguageNotFound; } void IApplicationManagerInterface::ConvertApplicationLanguageToLanguageCode( @@ -461,7 +461,7 @@ ResultVal<u64> IApplicationManagerInterface::ConvertApplicationLanguageToLanguag ConvertToLanguageCode(static_cast<ApplicationLanguage>(application_language)); if (language_code == std::nullopt) { LOG_ERROR(Service_NS, "Language not found! application_language={}", application_language); - return ERR_APPLICATION_LANGUAGE_NOT_FOUND; + return Service::NS::ResultApplicationLanguageNotFound; } return static_cast<u64>(*language_code); diff --git a/src/core/hle/service/server_manager.cpp b/src/core/hle/service/server_manager.cpp index c91f6d880..bd04cd023 100644 --- a/src/core/hle/service/server_manager.cpp +++ b/src/core/hle/service/server_manager.cpp @@ -404,7 +404,7 @@ Result ServerManager::CompleteSyncRequest(RequestState&& request) { rc = request.session->SendReplyHLE(); // If the session has been closed, we're done. - if (rc == Kernel::ResultSessionClosed || service_rc == IPC::ERR_REMOTE_PROCESS_DEAD) { + if (rc == Kernel::ResultSessionClosed || service_rc == IPC::ResultSessionClosed) { // Close the session. request.session->Close(); diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index eed615377..69cdb5918 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -176,7 +176,7 @@ Result ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session, case IPC::CommandType::TIPC_Close: { IPC::ResponseBuilder rb{ctx, 2}; rb.Push(ResultSuccess); - result = IPC::ERR_REMOTE_PROCESS_DEAD; + result = IPC::ResultSessionClosed; break; } case IPC::CommandType::ControlWithContext: diff --git a/src/core/hle/service/set/set.cpp b/src/core/hle/service/set/set.cpp index 88df52331..f5788b481 100644 --- a/src/core/hle/service/set/set.cpp +++ b/src/core/hle/service/set/set.cpp @@ -74,7 +74,7 @@ constexpr std::array<std::pair<LanguageCode, KeyboardLayout>, 18> language_to_la constexpr std::size_t PRE_4_0_0_MAX_ENTRIES = 0xF; constexpr std::size_t POST_4_0_0_MAX_ENTRIES = 0x40; -constexpr Result ERR_INVALID_LANGUAGE{ErrorModule::Settings, 625}; +constexpr Result ResultInvalidLanguage{ErrorModule::Settings, 625}; void PushResponseLanguageCode(HLERequestContext& ctx, std::size_t num_language_codes) { IPC::ResponseBuilder rb{ctx, 3}; @@ -130,7 +130,7 @@ void SET::MakeLanguageCode(HLERequestContext& ctx) { if (index >= available_language_codes.size()) { LOG_ERROR(Service_SET, "Invalid language code index! index={}", index); IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ERR_INVALID_LANGUAGE); + rb.Push(Set::ResultInvalidLanguage); return; } diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp index a46f47d3e..b4046d3ce 100644 --- a/src/core/hle/service/sm/sm.cpp +++ b/src/core/hle/service/sm/sm.cpp @@ -18,10 +18,10 @@ namespace Service::SM { -constexpr Result ERR_NOT_INITIALIZED(ErrorModule::SM, 2); -constexpr Result ERR_ALREADY_REGISTERED(ErrorModule::SM, 4); -constexpr Result ERR_INVALID_NAME(ErrorModule::SM, 6); -constexpr Result ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7); +constexpr Result ResultInvalidClient(ErrorModule::SM, 2); +constexpr Result ResultAlreadyRegistered(ErrorModule::SM, 4); +constexpr Result ResultInvalidServiceName(ErrorModule::SM, 6); +constexpr Result ResultNotRegistered(ErrorModule::SM, 7); ServiceManager::ServiceManager(Kernel::KernelCore& kernel_) : kernel{kernel_} { controller_interface = std::make_unique<Controller>(kernel.System()); @@ -45,7 +45,7 @@ void ServiceManager::InvokeControlRequest(HLERequestContext& context) { static Result ValidateServiceName(const std::string& name) { if (name.empty() || name.size() > 8) { LOG_ERROR(Service_SM, "Invalid service name! service={}", name); - return ERR_INVALID_NAME; + return Service::SM::ResultInvalidServiceName; } return ResultSuccess; } @@ -58,7 +58,7 @@ Result ServiceManager::RegisterService(std::string name, u32 max_sessions, std::scoped_lock lk{lock}; if (registered_services.find(name) != registered_services.end()) { LOG_ERROR(Service_SM, "Service is already registered! service={}", name); - return ERR_ALREADY_REGISTERED; + return Service::SM::ResultAlreadyRegistered; } auto* port = Kernel::KPort::Create(kernel); @@ -80,7 +80,7 @@ Result ServiceManager::UnregisterService(const std::string& name) { const auto iter = registered_services.find(name); if (iter == registered_services.end()) { LOG_ERROR(Service_SM, "Server is not registered! service={}", name); - return ERR_SERVICE_NOT_REGISTERED; + return Service::SM::ResultNotRegistered; } registered_services.erase(iter); @@ -96,7 +96,7 @@ ResultVal<Kernel::KPort*> ServiceManager::GetServicePort(const std::string& name auto it = service_ports.find(name); if (it == service_ports.end()) { LOG_WARNING(Service_SM, "Server is not registered! service={}", name); - return ERR_SERVICE_NOT_REGISTERED; + return Service::SM::ResultNotRegistered; } return it->second; @@ -160,7 +160,7 @@ static std::string PopServiceName(IPC::RequestParser& rp) { ResultVal<Kernel::KClientSession*> SM::GetServiceImpl(HLERequestContext& ctx) { if (!ctx.GetManager()->GetIsInitializedForSm()) { - return ERR_NOT_INITIALIZED; + return Service::SM::ResultInvalidClient; } IPC::RequestParser rp{ctx}; @@ -168,15 +168,15 @@ ResultVal<Kernel::KClientSession*> SM::GetServiceImpl(HLERequestContext& ctx) { // Find the named port. auto port_result = service_manager.GetServicePort(name); - if (port_result.Code() == ERR_INVALID_NAME) { + if (port_result.Code() == Service::SM::ResultInvalidServiceName) { LOG_ERROR(Service_SM, "Invalid service name '{}'", name); - return ERR_INVALID_NAME; + return Service::SM::ResultInvalidServiceName; } if (port_result.Failed()) { LOG_INFO(Service_SM, "Waiting for service {} to become available", name); ctx.SetIsDeferred(); - return ERR_SERVICE_NOT_REGISTERED; + return Service::SM::ResultNotRegistered; } auto& port = port_result.Unwrap(); diff --git a/src/core/perf_stats.cpp b/src/core/perf_stats.cpp index f09c176f8..1231c0dc8 100644 --- a/src/core/perf_stats.cpp +++ b/src/core/perf_stats.cpp @@ -126,8 +126,8 @@ double PerfStats::GetLastFrameTimeScale() const { } void SpeedLimiter::DoSpeedLimiting(microseconds current_system_time_us) { - if (!Settings::values.use_speed_limit.GetValue() || - Settings::values.use_multi_core.GetValue()) { + if (Settings::values.use_multi_core.GetValue() || + !Settings::values.use_speed_limit.GetValue()) { return; } |