Merge pull request #349 from DotDebian/feat/sync-on-address

feat(libkernel): implement sceKernelSyncOnAddressWait and sceKernelSyncOnAddressWake
This commit is contained in:
boykopovar
2026-10-02 22:31:45 +03:00
committed by GitHub
4 changed files with 258 additions and 0 deletions
+11
View File
@@ -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:$<TARGET_FILE_DIR:libkernel>")
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:$<TARGET_FILE_DIR:libkernel>")
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)
@@ -0,0 +1,96 @@
#include <atomic>
#include <chrono>
#include <cstdint>
#include <list>
#include <mutex>
#include <stdexcept>
#include <string>
#include <unordered_map>
#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<std::uintptr_t, std::list<AddressWaiter*>> 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<std::uintptr_t>(address);
if (!IsWordAddress(key)) {
APS5_INVALID_ARG_EX;
}
std::unique_lock<std::mutex> lock(g_waitersLock);
if (std::atomic_ref<std::uint32_t>(*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::nanoseconds>(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<std::uint64_t>(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<std::uintptr_t>(address);
if (!IsWordAddress(key) || count < 0) {
APS5_INVALID_ARG_EX;
}
std::lock_guard<std::mutex> 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;
}
}
+150
View File
@@ -0,0 +1,150 @@
#include "SceTypes.hpp"
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <thread>
#include <vector>
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<int>(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 <class TCall>
static bool Rejects(TCall call) {
try { call(); }
catch (const std::invalid_argument&) { return true; }
return false;
}
static void AwaitCount(const std::atomic<int>& 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<int> 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<int> started{0};
std::atomic<int> finished{0};
std::atomic<int> otherFinished{0};
std::vector<int> results(3, -1);
int otherResult = -1;
std::vector<std::thread> 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<std::uint64_t> state{1};
auto* word = reinterpret_cast<std::uint32_t*>(&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<std::uint32_t*>(reinterpret_cast<unsigned char*>(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();
}
+1
View File
@@ -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