From ba512363b1b32707f54da22f7571962b38fe7c2b Mon Sep 17 00:00:00 2001 From: DotDebian Date: Fri, 2 Oct 2026 13:22:36 +0200 Subject: [PATCH] feat(libkernel): implement sceKernelSyncOnAddressWait and sceKernelSyncOnAddressWake sceKernelSyncOnAddressWait parks the calling thread while the 32-bit word at the address still holds the expected value, until sceKernelSyncOnAddressWake releases it or the timeout expires. sceKernelSyncOnAddressWake releases up to the requested number of threads parked on the address, in arrival order. The libc.prx bundled with SDK 9 titles imports both for its once primitive, so those titles stopped at load with an unresolved import. # Conflicts: # docs/dev/TechnicalDebt.md --- core/libs/prx/libkernel/CMakeLists.txt | 11 ++ .../SyncOnAddress/src/SyncOnAddress.cpp | 96 +++++++++++ core/libs/tests/GuestSyncOnAddress.cpp | 150 ++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 4 files changed, 258 insertions(+) create mode 100644 core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp create mode 100644 core/libs/tests/GuestSyncOnAddress.cpp diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 907294a56..1eb28c92b 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -8,6 +8,7 @@ add_library(libkernel SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/File/src/Open.cpp ${CMAKE_CURRENT_SOURCE_DIR}/File/src/Stdio.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Semaphore/src/Semaphore.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/SyncOnAddress/src/SyncOnAddress.cpp ${CMAKE_CURRENT_SOURCE_DIR}/DirectMemory/Export.cpp ${CMAKE_CURRENT_SOURCE_DIR}/DirectMemory/DirectMemory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/DirectMemory/PosixMemory.cpp @@ -154,6 +155,16 @@ if(BUILD_TESTING) set_tests_properties(guest_signals PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(guest_sync_on_address_tests ${LIBS_INCLUDE_DIR}/tests/GuestSyncOnAddress.cpp) + target_include_directories(guest_sync_on_address_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_sync_on_address_tests PRIVATE libkernel libc) + configure_windows_unwind(guest_sync_on_address_tests) + add_test(NAME guest_sync_on_address COMMAND guest_sync_on_address_tests) + set_tests_properties(guest_sync_on_address PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_sync_on_address PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_kernel_error_tests ${LIBS_INCLUDE_DIR}/tests/GuestKernelErrors.cpp) target_include_directories(guest_kernel_error_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_kernel_error_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp b/core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp new file mode 100644 index 000000000..87944ae04 --- /dev/null +++ b/core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libkernel/KernelErrors.hpp" +#include "prx/libkernel/Time/include/Time.hpp" +#include "prx/libkernel/Time/include/TimedWait.hpp" + +namespace { + +constexpr int SYNC_ON_ADDRESS_OK = 0; + +struct AddressWaiter { + TimedWait::Condition condition; + bool woken = false; +}; + +std::mutex g_waitersLock; +std::unordered_map> g_waiters; + +bool IsWordAddress(std::uintptr_t address) { + return address != 0 && address % alignof(std::uint32_t) == 0; +} + +} // namespace + +extern "C" { + +int APS5_VABI sceKernelSyncOnAddressWait(std::uint32_t* address, std::uint32_t expected, const KernelUseconds* timeout, const char* name) { + (void)name; + const auto key = reinterpret_cast(address); + if (!IsWordAddress(key)) { + APS5_INVALID_ARG_EX; + } + + std::unique_lock lock(g_waitersLock); + if (std::atomic_ref(*address).load() != expected) { + return SYNC_ON_ADDRESS_OK; + } + + AddressWaiter waiter; + auto& queue = g_waiters[key]; + const auto position = queue.insert(queue.end(), &waiter); + const auto isWoken = [&] { return waiter.woken; }; + const auto waitStart = std::chrono::steady_clock::now(); + if (timeout == nullptr) { + waiter.condition.Wait(lock, isWoken); + } else { + waiter.condition.WaitUntil(lock, TimedWait::DeadlineNanos(*timeout), isWoken); + } + const auto waited = std::chrono::duration_cast(std::chrono::steady_clock::now() - waitStart); + + const bool woken = waiter.woken; + if (!woken) { + queue.erase(position); + if (queue.empty()) { + g_waiters.erase(key); + } + } + lock.unlock(); + KernelTraceWait_nid_postfix("addr", __builtin_return_address(0), static_cast(waited.count()), !woken); + return woken ? SYNC_ON_ADDRESS_OK : SCE_KERNEL_ERROR_ETIMEDOUT; +} + +int APS5_VABI sceKernelSyncOnAddressWake(void* address, std::int32_t count) { + const auto key = reinterpret_cast(address); + if (!IsWordAddress(key) || count < 0) { + APS5_INVALID_ARG_EX; + } + + std::lock_guard lock(g_waitersLock); + const auto entry = g_waiters.find(key); + if (entry == g_waiters.end()) { + return SYNC_ON_ADDRESS_OK; + } + auto& queue = entry->second; + for (; count > 0 && !queue.empty(); --count) { + AddressWaiter* waiter = queue.front(); + queue.pop_front(); + waiter->woken = true; + waiter->condition.NotifyOne(); + } + if (queue.empty()) { + g_waiters.erase(entry); + } + return SYNC_ON_ADDRESS_OK; +} + +} diff --git a/core/libs/tests/GuestSyncOnAddress.cpp b/core/libs/tests/GuestSyncOnAddress.cpp new file mode 100644 index 000000000..363c35d9a --- /dev/null +++ b/core/libs/tests/GuestSyncOnAddress.cpp @@ -0,0 +1,150 @@ +#include "SceTypes.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +int APS5_VABI sceKernelSyncOnAddressWait(std::uint32_t* address, std::uint32_t expected, const KernelUseconds* timeout, const char* name); +int APS5_VABI sceKernelSyncOnAddressWake(void* address, std::int32_t count); +} + +static constexpr int SCE_OK = 0; +static constexpr int SCE_KERNEL_ERROR_ETIMEDOUT = static_cast(0x8002003C); +static constexpr KernelUseconds FAILSAFE_TIMEOUT = 10000000; +static constexpr auto SETTLE = std::chrono::milliseconds(100); + +static void Require(bool value) { if (!value) std::abort(); } + +template +static bool Rejects(TCall call) { + try { call(); } + catch (const std::invalid_argument&) { return true; } + return false; +} + +static void AwaitCount(const std::atomic& counter, int value) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (counter.load() != value) { + Require(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } +} + +static void ReturnsWhenTheValueDiffers() { + std::uint32_t word = 2; + Require(sceKernelSyncOnAddressWait(&word, 1, nullptr, "differs") == SCE_OK); + const KernelUseconds timeout = 0; + Require(sceKernelSyncOnAddressWait(&word, 1, &timeout, nullptr) == SCE_OK); +} + +static void TimesOutWhileTheValueMatches() { + std::uint32_t word = 1; + const KernelUseconds none = 0; + Require(sceKernelSyncOnAddressWait(&word, 1, &none, "timeout") == SCE_KERNEL_ERROR_ETIMEDOUT); + + const KernelUseconds timeout = 20000; + const auto start = std::chrono::steady_clock::now(); + Require(sceKernelSyncOnAddressWait(&word, 1, &timeout, "timeout") == SCE_KERNEL_ERROR_ETIMEDOUT); + Require(std::chrono::steady_clock::now() - start >= std::chrono::milliseconds(15)); + Require(sceKernelSyncOnAddressWake(&word, INT_MAX) == SCE_OK); +} + +static void WakeReleasesAWaiterWithoutAValueChange() { + std::uint32_t word = 1; + std::atomic finished{0}; + int result = -1; + std::thread waiter([&] { + result = sceKernelSyncOnAddressWait(&word, 1, &FAILSAFE_TIMEOUT, "wake"); + ++finished; + }); + while (finished.load() == 0) { + Require(sceKernelSyncOnAddressWake(&word, 1) == SCE_OK); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + waiter.join(); + Require(result == SCE_OK); +} + +static void WakeHonoursTheCountAndTheAddress() { + std::uint32_t word = 1; + std::uint32_t other = 1; + std::atomic started{0}; + std::atomic finished{0}; + std::atomic otherFinished{0}; + std::vector results(3, -1); + int otherResult = -1; + + std::vector waiters; + for (int i = 0; i < 3; ++i) { + waiters.emplace_back([&, i] { + ++started; + results[i] = sceKernelSyncOnAddressWait(&word, 1, &FAILSAFE_TIMEOUT, "count"); + ++finished; + }); + } + std::thread otherWaiter([&] { + ++started; + otherResult = sceKernelSyncOnAddressWait(&other, 1, &FAILSAFE_TIMEOUT, "other"); + ++otherFinished; + }); + AwaitCount(started, 4); + std::this_thread::sleep_for(SETTLE); + + Require(sceKernelSyncOnAddressWake(&word, 0) == SCE_OK); + std::this_thread::sleep_for(SETTLE); + Require(finished.load() == 0); + + Require(sceKernelSyncOnAddressWake(&word, 1) == SCE_OK); + AwaitCount(finished, 1); + std::this_thread::sleep_for(SETTLE); + Require(finished.load() == 1); + + Require(sceKernelSyncOnAddressWake(&word, INT_MAX) == SCE_OK); + AwaitCount(finished, 3); + std::this_thread::sleep_for(SETTLE); + Require(otherFinished.load() == 0); + + Require(sceKernelSyncOnAddressWake(&other, 1) == SCE_OK); + for (auto& waiter : waiters) waiter.join(); + otherWaiter.join(); + for (const int result : results) Require(result == SCE_OK); + Require(otherResult == SCE_OK); +} + +static void WaitsOnTheLowHalfOfAnOnceState() { + std::atomic state{1}; + auto* word = reinterpret_cast(&state); + std::thread waiter([&] { + while (state.load() == 1) { + Require(sceKernelSyncOnAddressWait(word, 1, nullptr, "once") == SCE_OK); + } + }); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + state.store(2); + Require(sceKernelSyncOnAddressWake(word, INT_MAX) == SCE_OK); + waiter.join(); +} + +static void RejectsInvalidArguments() { + std::uint32_t words[2] = {1, 1}; + auto* misaligned = reinterpret_cast(reinterpret_cast(words) + 1); + Require(Rejects([&] { sceKernelSyncOnAddressWait(nullptr, 1, nullptr, nullptr); })); + Require(Rejects([&] { sceKernelSyncOnAddressWait(misaligned, 1, nullptr, nullptr); })); + Require(Rejects([&] { sceKernelSyncOnAddressWake(nullptr, 1); })); + Require(Rejects([&] { sceKernelSyncOnAddressWake(misaligned, 1); })); + Require(Rejects([&] { sceKernelSyncOnAddressWake(words, -1); })); +} + +int main() { + ReturnsWhenTheValueDiffers(); + TimesOutWhileTheValueMatches(); + WakeReleasesAWaiterWithoutAValueChange(); + WakeHonoursTheCountAndTheAddress(); + WaitsOnTheLowHalfOfAnOnceState(); + RejectsInvalidArguments(); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 33d7db145..77367372c 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -28,6 +28,7 @@ Throughout the project, every function at every stage either **does exactly what - [V++UgBtQhn0](../../core/libs/prx/libSceAgc/Misc/src/PacketInfo.cpp) (libSceAgc) - unknown name - [gQkqkLttcpw](../../core/libs/prx/libSceAgc/Acb/src/Control.cpp) (libSceAgc) - unknown name, signature - [sceKernelInternalMemoryGetModuleSegmentInfo](../../core/libs/prx/libkernel/Module/src/Module.cpp) (libkernel) - unknown signature +- [sceKernelSyncOnAddressWait](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - the only known caller passes a null timeout and a name string as the fourth argument; the timeout is assumed to point to microseconds like the other kernel waits, and the name is ignored - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 unknown; only the sceKernelMapNamedFlexibleMemory flags are accepted - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature - [sceLibcInternalHeapErrorReportForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature