From 024ccc1be78e2b563835c535bbcfc499483c1582 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:22:17 +0100 Subject: [PATCH 01/10] feat(libkernel): let other libraries observe closed guest descriptors --- core/libs/prx/libkernel/Equeue/Equeue.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/core/libs/prx/libkernel/Equeue/Equeue.cpp b/core/libs/prx/libkernel/Equeue/Equeue.cpp index 1256cc939168..011e260ef328 100644 --- a/core/libs/prx/libkernel/Equeue/Equeue.cpp +++ b/core/libs/prx/libkernel/Equeue/Equeue.cpp @@ -764,8 +764,26 @@ KernelEqueueEvent EqueueDescriptorEvent(int descriptor, int16_t filter, uint16_t return event; } +static std::mutex g_closeObserverMutex; +static std::vector g_closeObservers; + +extern "C" void RegisterDescriptorCloseObserver_nid_no_patch(void (*observer)(int descriptor)) { + std::lock_guard lock(g_closeObserverMutex); + g_closeObservers.push_back(observer); +} + +static void NotifyDescriptorCloseObservers(int descriptor) { + std::vector observers; + { + std::lock_guard lock(g_closeObserverMutex); + observers = g_closeObservers; + } + for (const auto observer : observers) observer(descriptor); +} + void EqueueDescriptorClosed(int descriptor) { KqueueDescriptorClosed(descriptor); + NotifyDescriptorCloseObservers(descriptor); std::vector owners; { std::unique_lock lock(g_equeueMutex); From 19e1af6fc380104b46f7e1c432c0acb61034f7da Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:22:17 +0100 Subject: [PATCH 02/10] feat(libkernel_sys): implement the unnamed ksem semaphores --- core/libs/prx/libkernel_sys/CMakeLists.txt | 1 + .../prx/libkernel_sys/Export.Discovery.cpp | 35 ---- core/libs/prx/libkernel_sys/Ksem.cpp | 163 ++++++++++++++++++ 3 files changed, 164 insertions(+), 35 deletions(-) create mode 100644 core/libs/prx/libkernel_sys/Ksem.cpp diff --git a/core/libs/prx/libkernel_sys/CMakeLists.txt b/core/libs/prx/libkernel_sys/CMakeLists.txt index 6938d0c456ae..b53c2597a6bd 100644 --- a/core/libs/prx/libkernel_sys/CMakeLists.txt +++ b/core/libs/prx/libkernel_sys/CMakeLists.txt @@ -1,3 +1,4 @@ add_library(${LIB_NAME} SHARED EXCLUDE_FROM_ALL Export.cpp Export.Discovery.cpp) target_include_directories(${LIB_NAME} PRIVATE ${LIBS_INCLUDE_DIR}) +target_sources(${LIB_NAME} PRIVATE Ksem.cpp) configure_windows_unwind(${LIB_NAME}) diff --git a/core/libs/prx/libkernel_sys/Export.Discovery.cpp b/core/libs/prx/libkernel_sys/Export.Discovery.cpp index 8b3da583e470..8820c3d7f70c 100644 --- a/core/libs/prx/libkernel_sys/Export.Discovery.cpp +++ b/core/libs/prx/libkernel_sys/Export.Discovery.cpp @@ -233,51 +233,16 @@ int APS5_VABI ksem_close_nid_postfix(void) { return 0; } -int APS5_VABI ksem_destroy_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_getvalue_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_init_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI ksem_open_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; } -int APS5_VABI ksem_post_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_timedwait_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_trywait_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI ksem_unlink_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; } -int APS5_VABI ksem_wait_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI ktimer_create_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; diff --git a/core/libs/prx/libkernel_sys/Ksem.cpp b/core/libs/prx/libkernel_sys/Ksem.cpp new file mode 100644 index 000000000000..57910db95d50 --- /dev/null +++ b/core/libs/prx/libkernel_sys/Ksem.cpp @@ -0,0 +1,163 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#else +#include +#include +#endif + +extern "C" int* APS5_VABI __error_nid_postfix(); +extern "C" int APS5_VABI close_nid_postfix(int descriptor); +extern "C" void RegisterDescriptorCloseObserver_nid_no_patch(void (*observer)(int descriptor)); + +namespace { + +constexpr int GuestEfault = 14; +constexpr int GuestEbusy = 16; +constexpr int GuestEinval = 22; +constexpr int GuestEnfile = 23; +constexpr int GuestEmfile = 24; +constexpr int GuestEagain = 35; +constexpr int GuestEtimedout = 60; +constexpr int GuestEoverflow = 84; +constexpr unsigned SemValueMax = 0x7fffffffu; + +struct GuestTimespec { + std::int64_t seconds; + std::int64_t nanoseconds; +}; + +struct Ksem { + std::mutex lock; + std::condition_variable available; + unsigned count = 0; + unsigned waiters = 0; +}; + +std::mutex g_ksemLock; +std::map> g_ksems; + +int Fail(int error) { + *__error_nid_postfix() = error; + return -1; +} + +std::shared_ptr Find(std::intptr_t id) { + if (id < 0 || id > INT_MAX) return {}; + std::lock_guard lock(g_ksemLock); + const auto found = g_ksems.find(static_cast(id)); + return found != g_ksems.end() ? found->second : std::shared_ptr{}; +} + +int ReserveDescriptor() { +#ifdef _WIN32 + return ::_open("NUL", _O_RDONLY | _O_BINARY); +#else + return ::open("/dev/null", O_RDONLY | O_CLOEXEC); +#endif +} + +void DescriptorClosed(int descriptor) { + std::lock_guard lock(g_ksemLock); + g_ksems.erase(descriptor); +} + +const bool g_observerRegistered = [] { + RegisterDescriptorCloseObserver_nid_no_patch(DescriptorClosed); + return true; +}(); + +int Wait(std::intptr_t id, bool once, const GuestTimespec* abstime) { + const auto ksem = Find(id); + if (!ksem) return Fail(GuestEinval); + std::unique_lock lock(ksem->lock); + if (ksem->count == 0) { + if (once) return Fail(GuestEagain); + ++ksem->waiters; + bool ready = true; + if (abstime == nullptr) { + ksem->available.wait(lock, [&] { return ksem->count > 0; }); + } else { + const auto deadline = std::chrono::system_clock::time_point(std::chrono::duration_cast( + std::chrono::seconds(abstime->seconds) + std::chrono::nanoseconds(abstime->nanoseconds))); + ready = ksem->available.wait_until(lock, deadline, [&] { return ksem->count > 0; }); + } + --ksem->waiters; + if (!ready) return Fail(GuestEtimedout); + } + --ksem->count; + return 0; +} + +} + +extern "C" { + +int APS5_VABI ksem_init_nid_postfix(std::intptr_t* idp, unsigned int value) { + if (value > SemValueMax) return Fail(GuestEinval); + if (idp == nullptr) return Fail(GuestEfault); + const int descriptor = ReserveDescriptor(); + if (descriptor < 0) return Fail(errno == ENFILE ? GuestEnfile : GuestEmfile); + auto ksem = std::make_shared(); + ksem->count = value; + { + std::lock_guard lock(g_ksemLock); + g_ksems[descriptor] = std::move(ksem); + } + *idp = descriptor; + return 0; +} + +int APS5_VABI ksem_post_nid_postfix(std::intptr_t id) { + const auto ksem = Find(id); + if (!ksem) return Fail(GuestEinval); + std::lock_guard lock(ksem->lock); + if (ksem->count == SemValueMax) return Fail(GuestEoverflow); + ++ksem->count; + ksem->available.notify_one(); + return 0; +} + +int APS5_VABI ksem_wait_nid_postfix(std::intptr_t id) { + return Wait(id, false, nullptr); +} + +int APS5_VABI ksem_trywait_nid_postfix(std::intptr_t id) { + return Wait(id, true, nullptr); +} + +int APS5_VABI ksem_timedwait_nid_postfix(std::intptr_t id, const GuestTimespec* abstime) { + if (abstime != nullptr && (abstime->nanoseconds < 0 || abstime->nanoseconds >= 1000000000)) return Fail(GuestEinval); + return Wait(id, false, abstime); +} + +int APS5_VABI ksem_getvalue_nid_postfix(std::intptr_t id, int* value) { + const auto ksem = Find(id); + if (!ksem) return Fail(GuestEinval); + if (value == nullptr) return Fail(GuestEfault); + std::lock_guard lock(ksem->lock); + *value = static_cast(ksem->count); + return 0; +} + +int APS5_VABI ksem_destroy_nid_postfix(std::intptr_t id) { + const auto ksem = Find(id); + if (!ksem) return Fail(GuestEinval); + { + std::lock_guard lock(ksem->lock); + if (ksem->waiters != 0) return Fail(GuestEbusy); + } + return close_nid_postfix(static_cast(id)); +} + +} From 5f8cd77b2435e206b2967402883a5dd28c1a55cc Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:22:17 +0100 Subject: [PATCH 03/10] test(libkernel_sys): cover the unnamed ksem semaphores, including closed and replaced ids --- core/libs/CMakeLists.txt | 11 ++ core/libs/tests/GuestKernelSysKsem.cpp | 146 +++++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 core/libs/tests/GuestKernelSysKsem.cpp diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 737f8fa20f62..83642d356aad 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -514,6 +514,17 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() + add_test_executable(guest_kernel_sys_ksem_tests tests/GuestKernelSysKsem.cpp) + target_include_directories(guest_kernel_sys_ksem_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_kernel_sys_ksem_tests PRIVATE libkernel_sys libkernel libc) + configure_windows_unwind(guest_kernel_sys_ksem_tests) + add_test(NAME guest_kernel_sys_ksem COMMAND guest_kernel_sys_ksem_tests) + set_tests_properties(guest_kernel_sys_ksem PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(guest_kernel_sys_ksem PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + add_test_executable(guest_system_gesture_tests tests/GuestSystemGesture.cpp) target_include_directories(guest_system_gesture_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(guest_system_gesture_tests PRIVATE libSceSystemGesture libc) diff --git a/core/libs/tests/GuestKernelSysKsem.cpp b/core/libs/tests/GuestKernelSysKsem.cpp new file mode 100644 index 000000000000..8753686a368f --- /dev/null +++ b/core/libs/tests/GuestKernelSysKsem.cpp @@ -0,0 +1,146 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/general/VabiMacros.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +int* APS5_VABI __error_nid_postfix(); +int APS5_VABI open_nid_postfix(const char* path, int flags, int mode); +int APS5_VABI close_nid_postfix(int descriptor); +int APS5_VABI dup2_nid_postfix(int from, int to); +int APS5_VABI ksem_init_nid_postfix(std::intptr_t* idp, unsigned int value); +int APS5_VABI ksem_post_nid_postfix(std::intptr_t id); +int APS5_VABI ksem_wait_nid_postfix(std::intptr_t id); +int APS5_VABI ksem_trywait_nid_postfix(std::intptr_t id); +int APS5_VABI ksem_timedwait_nid_postfix(std::intptr_t id, const void* abstime); +int APS5_VABI ksem_getvalue_nid_postfix(std::intptr_t id, int* value); +int APS5_VABI ksem_destroy_nid_postfix(std::intptr_t id); +} + +namespace { + +constexpr int Efault = 14; +constexpr int Ebusy = 16; +constexpr int Einval = 22; +constexpr int Eagain = 35; +constexpr int Etimedout = 60; +constexpr int Eoverflow = 84; + +struct Timespec { + std::int64_t seconds; + std::int64_t nanoseconds; +}; + +void Require(bool condition, std::source_location location = std::source_location::current()) { + if (condition) return; + std::fprintf(stderr, "check failed at line %u\n", static_cast(location.line())); + std::exit(1); +} + +int Error() { + return *__error_nid_postfix(); +} + +Timespec FromNow(std::chrono::milliseconds delay) { + const auto when = std::chrono::system_clock::now() + delay; + const auto nanoseconds = std::chrono::duration_cast(when.time_since_epoch()).count(); + return {nanoseconds / 1000000000, nanoseconds % 1000000000}; +} + +int Value(std::intptr_t id) { + int value = -1; + Require(ksem_getvalue_nid_postfix(id, &value) == 0); + return value; +} + +void Counting() { + std::intptr_t id = -1; + Require(ksem_init_nid_postfix(&id, 0x80000000u) == -1 && Error() == Einval); + Require(ksem_init_nid_postfix(nullptr, 1) == -1 && Error() == Efault); + Require(ksem_init_nid_postfix(&id, 2) == 0 && id >= 0); + Require(Value(id) == 2); + Require(ksem_trywait_nid_postfix(id) == 0 && ksem_wait_nid_postfix(id) == 0 && Value(id) == 0); + Require(ksem_trywait_nid_postfix(id) == -1 && Error() == Eagain); + Require(ksem_post_nid_postfix(id) == 0 && Value(id) == 1); + Require(ksem_getvalue_nid_postfix(id, nullptr) == -1 && Error() == Efault); + Require(ksem_destroy_nid_postfix(id) == 0); + Require(ksem_post_nid_postfix(id) == -1 && Error() == Einval); + Require(ksem_init_nid_postfix(&id, 0x7fffffffu) == 0); + Require(ksem_post_nid_postfix(id) == -1 && Error() == Eoverflow); + Require(ksem_destroy_nid_postfix(id) == 0); +} + +void Timed() { + std::intptr_t id = -1; + Require(ksem_init_nid_postfix(&id, 0) == 0); + const Timespec invalid{0, 1000000000}; + Require(ksem_timedwait_nid_postfix(id, &invalid) == -1 && Error() == Einval); + const auto deadline = FromNow(std::chrono::milliseconds(150)); + const auto start = std::chrono::steady_clock::now(); + Require(ksem_timedwait_nid_postfix(id, &deadline) == -1 && Error() == Etimedout); + Require(std::chrono::steady_clock::now() - start >= std::chrono::milliseconds(100)); + Require(ksem_post_nid_postfix(id) == 0); + const auto later = FromNow(std::chrono::seconds(5)); + Require(ksem_timedwait_nid_postfix(id, &later) == 0 && Value(id) == 0); + Require(ksem_destroy_nid_postfix(id) == 0); +} + +void Blocking() { + std::intptr_t id = -1; + Require(ksem_init_nid_postfix(&id, 0) == 0); + std::atomic result{-2}; + std::thread waiter([&] { result = ksem_wait_nid_postfix(id); }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + Require(result == -2); + Require(ksem_destroy_nid_postfix(id) == -1 && Error() == Ebusy); + Require(ksem_post_nid_postfix(id) == 0); + waiter.join(); + Require(result == 0 && Value(id) == 0); + Require(ksem_destroy_nid_postfix(id) == 0); +} + +void Identifiers() { + Require(ksem_post_nid_postfix(-1) == -1 && Error() == Einval); + const auto path = (std::filesystem::temp_directory_path() / "anyps5-ksem-stale.bin").string(); + { std::ofstream stream(path); stream << "x"; } + const int plain = open_nid_postfix(path.c_str(), 0, 0); + Require(plain >= 0); + Require(ksem_post_nid_postfix(plain) == -1 && Error() == Einval); + Require(close_nid_postfix(plain) == 0); + std::intptr_t id = -1; + Require(ksem_init_nid_postfix(&id, 1) == 0); + Require(close_nid_postfix(static_cast(id)) == 0); + Require(ksem_post_nid_postfix(id) == -1 && Error() == Einval); + const int reused = open_nid_postfix(path.c_str(), 0, 0); + Require(reused >= 0); + Require(ksem_post_nid_postfix(reused) == -1 && Error() == Einval); + Require(ksem_getvalue_nid_postfix(reused, nullptr) == -1 && Error() == Einval); + Require(close_nid_postfix(reused) == 0); + Require(ksem_init_nid_postfix(&id, 1) == 0); + const int other = open_nid_postfix(path.c_str(), 0, 0); + Require(other >= 0 && other != id); + Require(dup2_nid_postfix(other, static_cast(id)) == static_cast(id)); + Require(ksem_post_nid_postfix(id) == -1 && Error() == Einval); + Require(ksem_trywait_nid_postfix(id) == -1 && Error() == Einval); + Require(close_nid_postfix(static_cast(id)) == 0 && close_nid_postfix(other) == 0); + std::filesystem::remove(path); +} + +} + +int main() { + Counting(); + Timed(); + Blocking(); + Identifiers(); + std::puts("ksem unnamed semaphores passed"); + return 0; +} From 8f56721ca5f02179585fb206d0d619086581a4fa Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:22:18 +0100 Subject: [PATCH 04/10] docs(debt): record the ksem descriptor limits in libkernel_sys --- docs/dev/debt/libkernel_sys.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dev/debt/libkernel_sys.md b/docs/dev/debt/libkernel_sys.md index 25499ae3d143..6bd127de22ce 100644 --- a/docs/dev/debt/libkernel_sys.md +++ b/docs/dev/debt/libkernel_sys.md @@ -10,6 +10,7 @@ - [fchmodat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `chmod`; any other relative path is joined to the descriptor's host directory the same way as for `openat`, so guest path aliases and case-insensitive name matching do not apply to it and a `..` component is not kept inside the guest root. A flag other than `0` or `AT_SYMLINK_NOFOLLOW` (0x200) returns `EINVAL`; the mode is masked to `07777`. With `AT_SYMLINK_NOFOLLOW` a symbolic link returns success silently on Windows and Linux, since the host cannot change a link's own mode, while a regular file is changed either way. The mode maps to the host file mode, which on Windows is only the CRT's read-only bit. PPSA99621 calls it through `std::filesystem::permissions`. Console behaviour is unverified - [pathconf](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) looks the path up as FreeBSD 11's `kern_pathconf` does (links followed, `ENAMETOOLONG` for a path of 1024 bytes or more or a component over 255) and returns the constants of FreeBSD 11's UFS `ufs_pathconf` for files and directories alike: `_PC_LINK_MAX` 32767, `_PC_NAME_MAX` 255, `_PC_PATH_MAX` and `_PC_SYMLINK_MAX` 1024, `_PC_PIPE_BUF` 512, `_PC_CHOWN_RESTRICTED` and `_PC_NO_TRUNC` 1, `_PC_FILESIZEBITS` 64, `_PC_REC_MAX_XFER_SIZE` -1, `_PC_PRIO_IO` and `_PC_SYNC_IO` 0. Whether the console's filesystems report the same is not verified. It throws for the names whose UFS value depends on the mount (`_PC_ALLOC_SIZE_MIN`, `_PC_REC_INCR_XFER_SIZE`, `_PC_REC_MIN_XFER_SIZE`, `_PC_MIN_HOLE_SIZE`), the kernel options (`_PC_ACL_EXTENDED`, `_PC_ACL_PATH_MAX`, `_PC_ACL_NFS4`, `_PC_MAC_PRESENT`) or the page size (`_PC_REC_XFER_ALIGN`), and on which UFS and `vop_stdpathconf` disagree (`_PC_MAX_CANON`, `_PC_MAX_INPUT`, `_PC_VDISABLE`, `_PC_ASYNC_IO`); other names fail with `EINVAL` - [mkdirat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `mkdir`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. On Windows, `mode` is ignored. Console behaviour is unverified +- [ksem_init, ksem_post, ksem_wait, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy](../../../core/libs/prx/libkernel_sys/Ksem.cpp) (libkernel_sys) keep each semaphore in a table keyed by a descriptor reserved on the host null device, as FreeBSD 11 `uipc_sem.c` makes a ksem id a descriptor. A guest `close` or `dup2` over the id drops the semaphore through libkernel's close notification, but `dup` of an id gives a descriptor that is not a semaphore, where FreeBSD shares it, and a guest signal does not interrupt a wait with `EINTR` - [readlink](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) on Windows reads a symbolic link's target from its reparse data and returns it with `/` separators, only when the target is relative, as `symlink` creates them. A symbolic link with an absolute target returns its print name, or its substitute name when the print name is empty, without a `\??\` or `\\?\` prefix. A directory junction returns the same kind of name when it is a drive path (`X:\...`), using the print name when that is a drive path and the substitute name otherwise. A mounted volume, whose substitute name is `\??\Volume{GUID}\`, stays a throw, because the name left after the prefix is not a drive path. Any other reparse point throws too, where FreeBSD reports `EINVAL` for a file that is not a link - [readlinkat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `readlink`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. Console behaviour is unverified - [fstatat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `stat`, or to `lstat` with `AT_SYMLINK_NOFOLLOW` (0x200). Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory, and flags other than `AT_SYMLINK_NOFOLLOW` return `EINVAL`. PPSA74126 imports it. Console behaviour is unverified From 28841448079a50531f29aad57b5e5f89fbef7063 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:25:51 +0100 Subject: [PATCH 05/10] feat(libkernel_sys): implement named ksem semaphores --- .../prx/libkernel_sys/Export.Discovery.cpp | 15 ----- core/libs/prx/libkernel_sys/Ksem.cpp | 56 ++++++++++++++++++- 2 files changed, 55 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libkernel_sys/Export.Discovery.cpp b/core/libs/prx/libkernel_sys/Export.Discovery.cpp index 8820c3d7f70c..ba6f60109da1 100644 --- a/core/libs/prx/libkernel_sys/Export.Discovery.cpp +++ b/core/libs/prx/libkernel_sys/Export.Discovery.cpp @@ -228,21 +228,6 @@ int APS5_VABI kmq_unlink_nid_postfix(void) { return 0; } -int APS5_VABI ksem_close_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_open_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_unlink_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI ktimer_create_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; diff --git a/core/libs/prx/libkernel_sys/Ksem.cpp b/core/libs/prx/libkernel_sys/Ksem.cpp index 57910db95d50..c7abf7e9f6ec 100644 --- a/core/libs/prx/libkernel_sys/Ksem.cpp +++ b/core/libs/prx/libkernel_sys/Ksem.cpp @@ -5,9 +5,11 @@ #include #include #include +#include #include #include #include +#include #ifdef _WIN32 #include #include @@ -22,14 +24,20 @@ extern "C" void RegisterDescriptorCloseObserver_nid_no_patch(void (*observer)(in namespace { +constexpr int GuestEnoent = 2; constexpr int GuestEfault = 14; constexpr int GuestEbusy = 16; +constexpr int GuestEexist = 17; constexpr int GuestEinval = 22; constexpr int GuestEnfile = 23; constexpr int GuestEmfile = 24; constexpr int GuestEagain = 35; constexpr int GuestEtimedout = 60; +constexpr int GuestEnametoolong = 63; constexpr int GuestEoverflow = 84; +constexpr int GuestOCreat = 0x0200; +constexpr int GuestOExcl = 0x0800; +constexpr std::size_t GuestPathMax = 1024; constexpr unsigned SemValueMax = 0x7fffffffu; struct GuestTimespec { @@ -42,10 +50,12 @@ struct Ksem { std::condition_variable available; unsigned count = 0; unsigned waiters = 0; + bool named = false; }; std::mutex g_ksemLock; std::map> g_ksems; +std::map> g_named; int Fail(int error) { *__error_nid_postfix() = error; @@ -152,7 +162,7 @@ int APS5_VABI ksem_getvalue_nid_postfix(std::intptr_t id, int* value) { int APS5_VABI ksem_destroy_nid_postfix(std::intptr_t id) { const auto ksem = Find(id); - if (!ksem) return Fail(GuestEinval); + if (!ksem || ksem->named) return Fail(GuestEinval); { std::lock_guard lock(ksem->lock); if (ksem->waiters != 0) return Fail(GuestEbusy); @@ -160,4 +170,48 @@ int APS5_VABI ksem_destroy_nid_postfix(std::intptr_t id) { return close_nid_postfix(static_cast(id)); } +int APS5_VABI ksem_open_nid_postfix(std::intptr_t* idp, const char* name, int oflag, unsigned int mode, unsigned int value) { + (void)mode; + if (value > SemValueMax) return Fail(GuestEinval); + if (name == nullptr) return Fail(GuestEfault); + const std::string path(name, strnlen(name, GuestPathMax)); + if (path.size() >= GuestPathMax) return Fail(GuestEnametoolong); + if (path.empty() || path[0] != '/') return Fail(GuestEinval); + if ((oflag & ~(GuestOCreat | GuestOExcl)) != 0) return Fail(GuestEinval); + if (idp == nullptr) return Fail(GuestEfault); + std::lock_guard lock(g_ksemLock); + std::shared_ptr ksem; + const auto found = g_named.find(path); + if (found == g_named.end()) { + if ((oflag & GuestOCreat) == 0) return Fail(GuestEnoent); + ksem = std::make_shared(); + ksem->count = value; + ksem->named = true; + } else { + if ((oflag & (GuestOCreat | GuestOExcl)) == (GuestOCreat | GuestOExcl)) return Fail(GuestEexist); + ksem = found->second; + } + const int descriptor = ReserveDescriptor(); + if (descriptor < 0) return Fail(errno == ENFILE ? GuestEnfile : GuestEmfile); + if (found == g_named.end()) g_named[path] = ksem; + g_ksems[descriptor] = std::move(ksem); + *idp = descriptor; + return 0; +} + +int APS5_VABI ksem_close_nid_postfix(std::intptr_t id) { + const auto ksem = Find(id); + if (!ksem || !ksem->named) return Fail(GuestEinval); + return close_nid_postfix(static_cast(id)); +} + +int APS5_VABI ksem_unlink_nid_postfix(const char* name) { + if (name == nullptr) return Fail(GuestEfault); + const std::string path(name, strnlen(name, GuestPathMax)); + if (path.size() >= GuestPathMax) return Fail(GuestEnametoolong); + std::lock_guard lock(g_ksemLock); + if (g_named.erase(path) == 0) return Fail(GuestEnoent); + return 0; +} + } From 6b8ccababf2e3f4cb72d90a377592dfe61912941 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:25:52 +0100 Subject: [PATCH 06/10] test(libkernel_sys): cover named ksem open, close and unlink --- core/libs/tests/GuestKernelSysKsem.cpp | 46 +++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/core/libs/tests/GuestKernelSysKsem.cpp b/core/libs/tests/GuestKernelSysKsem.cpp index 8753686a368f..904df9c07d6b 100644 --- a/core/libs/tests/GuestKernelSysKsem.cpp +++ b/core/libs/tests/GuestKernelSysKsem.cpp @@ -23,11 +23,19 @@ int APS5_VABI ksem_trywait_nid_postfix(std::intptr_t id); int APS5_VABI ksem_timedwait_nid_postfix(std::intptr_t id, const void* abstime); int APS5_VABI ksem_getvalue_nid_postfix(std::intptr_t id, int* value); int APS5_VABI ksem_destroy_nid_postfix(std::intptr_t id); +int APS5_VABI ksem_open_nid_postfix(std::intptr_t* idp, const char* name, int oflag, unsigned int mode, unsigned int value); +int APS5_VABI ksem_close_nid_postfix(std::intptr_t id); +int APS5_VABI ksem_unlink_nid_postfix(const char* name); } namespace { +constexpr int Enoent = 2; constexpr int Efault = 14; +constexpr int Eexist = 17; +constexpr int Enametoolong = 63; +constexpr int OCreat = 0x0200; +constexpr int OExcl = 0x0800; constexpr int Ebusy = 16; constexpr int Einval = 22; constexpr int Eagain = 35; @@ -134,6 +142,41 @@ void Identifiers() { std::filesystem::remove(path); } +void Named() { + const std::string name = "/anyps5-ksem-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); + std::intptr_t first = -1; + std::intptr_t second = -1; + Require(ksem_open_nid_postfix(&first, name.c_str(), 0, 0600, 1) == -1 && Error() == Enoent); + Require(ksem_open_nid_postfix(&first, "relative", OCreat, 0600, 1) == -1 && Error() == Einval); + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat | 0x1, 0600, 1) == -1 && Error() == Einval); + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat, 0600, 0x80000000u) == -1 && Error() == Einval); + Require(ksem_open_nid_postfix(&first, nullptr, OCreat, 0600, 1) == -1 && Error() == Efault); + const std::string longName = "/" + std::string(1100, 'a'); + Require(ksem_open_nid_postfix(&first, longName.c_str(), OCreat, 0600, 1) == -1 && Error() == Enametoolong); + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat, 0600, 1) == 0 && first >= 0); + Require(ksem_open_nid_postfix(&second, name.c_str(), OCreat | OExcl, 0600, 1) == -1 && Error() == Eexist); + Require(ksem_open_nid_postfix(&second, name.c_str(), OCreat, 0600, 9) == 0 && second >= 0 && second != first); + Require(Value(second) == 1); + Require(ksem_post_nid_postfix(first) == 0 && Value(second) == 2); + Require(ksem_destroy_nid_postfix(first) == -1 && Error() == Einval); + std::intptr_t unnamed = -1; + Require(ksem_init_nid_postfix(&unnamed, 0) == 0); + Require(ksem_close_nid_postfix(unnamed) == -1 && Error() == Einval); + Require(ksem_destroy_nid_postfix(unnamed) == 0); + Require(ksem_unlink_nid_postfix(name.c_str()) == 0); + Require(ksem_unlink_nid_postfix(name.c_str()) == -1 && Error() == Enoent); + Require(ksem_unlink_nid_postfix(nullptr) == -1 && Error() == Efault); + std::intptr_t third = -1; + Require(ksem_open_nid_postfix(&third, name.c_str(), 0, 0600, 0) == -1 && Error() == Enoent); + Require(ksem_trywait_nid_postfix(first) == 0 && Value(second) == 1); + Require(ksem_close_nid_postfix(first) == 0); + Require(ksem_post_nid_postfix(first) == -1 && Error() == Einval); + Require(Value(second) == 1); + Require(ksem_close_nid_postfix(second) == 0); + Require(ksem_open_nid_postfix(&third, name.c_str(), OCreat, 0600, 5) == 0 && Value(third) == 5); + Require(ksem_close_nid_postfix(third) == 0 && ksem_unlink_nid_postfix(name.c_str()) == 0); +} + } int main() { @@ -141,6 +184,7 @@ int main() { Timed(); Blocking(); Identifiers(); - std::puts("ksem unnamed semaphores passed"); + Named(); + std::puts("ksem unnamed and named semaphores passed"); return 0; } From 77ddb1460efa6642763f6ff7ed0091c004964831 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:25:52 +0100 Subject: [PATCH 07/10] docs(debt): record that libkernel_sys named ksem semaphores are process-local --- docs/dev/debt/libkernel_sys.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dev/debt/libkernel_sys.md b/docs/dev/debt/libkernel_sys.md index 6bd127de22ce..531d1eff8c52 100644 --- a/docs/dev/debt/libkernel_sys.md +++ b/docs/dev/debt/libkernel_sys.md @@ -11,6 +11,7 @@ - [pathconf](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) looks the path up as FreeBSD 11's `kern_pathconf` does (links followed, `ENAMETOOLONG` for a path of 1024 bytes or more or a component over 255) and returns the constants of FreeBSD 11's UFS `ufs_pathconf` for files and directories alike: `_PC_LINK_MAX` 32767, `_PC_NAME_MAX` 255, `_PC_PATH_MAX` and `_PC_SYMLINK_MAX` 1024, `_PC_PIPE_BUF` 512, `_PC_CHOWN_RESTRICTED` and `_PC_NO_TRUNC` 1, `_PC_FILESIZEBITS` 64, `_PC_REC_MAX_XFER_SIZE` -1, `_PC_PRIO_IO` and `_PC_SYNC_IO` 0. Whether the console's filesystems report the same is not verified. It throws for the names whose UFS value depends on the mount (`_PC_ALLOC_SIZE_MIN`, `_PC_REC_INCR_XFER_SIZE`, `_PC_REC_MIN_XFER_SIZE`, `_PC_MIN_HOLE_SIZE`), the kernel options (`_PC_ACL_EXTENDED`, `_PC_ACL_PATH_MAX`, `_PC_ACL_NFS4`, `_PC_MAC_PRESENT`) or the page size (`_PC_REC_XFER_ALIGN`), and on which UFS and `vop_stdpathconf` disagree (`_PC_MAX_CANON`, `_PC_MAX_INPUT`, `_PC_VDISABLE`, `_PC_ASYNC_IO`); other names fail with `EINVAL` - [mkdirat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `mkdir`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. On Windows, `mode` is ignored. Console behaviour is unverified - [ksem_init, ksem_post, ksem_wait, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy](../../../core/libs/prx/libkernel_sys/Ksem.cpp) (libkernel_sys) keep each semaphore in a table keyed by a descriptor reserved on the host null device, as FreeBSD 11 `uipc_sem.c` makes a ksem id a descriptor. A guest `close` or `dup2` over the id drops the semaphore through libkernel's close notification, but `dup` of an id gives a descriptor that is not a semaphore, where FreeBSD shares it, and a guest signal does not interrupt a wait with `EINTR` +- [ksem_open, ksem_close and ksem_unlink](../../../core/libs/prx/libkernel_sys/Ksem.cpp) (libkernel_sys) keep named semaphores in a table of this process, as the guest is one process: `mode` is accepted without checking, and the owner and permission checks of FreeBSD 11 `uipc_sem.c` are not modelled - [readlink](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) on Windows reads a symbolic link's target from its reparse data and returns it with `/` separators, only when the target is relative, as `symlink` creates them. A symbolic link with an absolute target returns its print name, or its substitute name when the print name is empty, without a `\??\` or `\\?\` prefix. A directory junction returns the same kind of name when it is a drive path (`X:\...`), using the print name when that is a drive path and the substitute name otherwise. A mounted volume, whose substitute name is `\??\Volume{GUID}\`, stays a throw, because the name left after the prefix is not a drive path. Any other reparse point throws too, where FreeBSD reports `EINVAL` for a file that is not a link - [readlinkat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `readlink`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. Console behaviour is unverified - [fstatat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `stat`, or to `lstat` with `AT_SYMLINK_NOFOLLOW` (0x200). Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory, and flags other than `AT_SYMLINK_NOFOLLOW` return `EINVAL`. PPSA74126 imports it. Console behaviour is unverified From 38fd999c90f9cd694f2ebbaa631d201848a4c785 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 21:41:57 +0100 Subject: [PATCH 08/10] test(libkernel_sys): open the ksem stale-descriptor file by a guest-relative name An absolute host temp path is not mapped by the Linux guest resolver. Found by xXPBSXx on #9097. --- core/libs/tests/GuestKernelSysKsem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/tests/GuestKernelSysKsem.cpp b/core/libs/tests/GuestKernelSysKsem.cpp index 8753686a368f..7a544d00c61e 100644 --- a/core/libs/tests/GuestKernelSysKsem.cpp +++ b/core/libs/tests/GuestKernelSysKsem.cpp @@ -109,7 +109,7 @@ void Blocking() { void Identifiers() { Require(ksem_post_nid_postfix(-1) == -1 && Error() == Einval); - const auto path = (std::filesystem::temp_directory_path() / "anyps5-ksem-stale.bin").string(); + const auto path = "anyps5-ksem-stale-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".bin"; { std::ofstream stream(path); stream << "x"; } const int plain = open_nid_postfix(path.c_str(), 0, 0); Require(plain >= 0); From 8db8924c7b9965e0c0a06b505bf8c4ee7b2bcb77 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 21:46:21 +0100 Subject: [PATCH 09/10] refactor(libkernel): move the unnamed ksem calls into libkernel The PS5 3.20 export lists have ksem_* in libkernel as well as libkernel_sys, and on Windows a libkernel import never reaches libkernel_sys, so titles importing them from libkernel did not find them. Following pipe1os's review on #9284, also: ENOSPC from ksem_init when no descriptor is left, the SEM_MAX limit of 30 with ENOSPC, and dup/dup2 from a ksem id throwing as for a kqueue. --- core/libs/prx/libkernel/CMakeLists.txt | 1 + core/libs/prx/libkernel/File/src/Stdio.cpp | 3 ++ .../prx/libkernel/Semaphore/include/Ksem.hpp | 6 +++ .../Semaphore/src}/Ksem.cpp | 28 ++++++++++---- core/libs/prx/libkernel_sys/CMakeLists.txt | 1 - core/libs/tests/GuestKernelSysKsem.cpp | 38 +++++++++++++++++++ docs/dev/debt/libkernel.md | 1 + docs/dev/debt/libkernel_sys.md | 1 - 8 files changed, 69 insertions(+), 10 deletions(-) create mode 100644 core/libs/prx/libkernel/Semaphore/include/Ksem.hpp rename core/libs/prx/{libkernel_sys => libkernel/Semaphore/src}/Ksem.cpp (88%) diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 8613c79da046..2b30880b7318 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -20,6 +20,7 @@ add_library(libkernel SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/File/src/SandboxCertificates.cpp ${CMAKE_CURRENT_SOURCE_DIR}/File/src/Stdio.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../libc/src/Rename.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Semaphore/src/Ksem.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Semaphore/src/Semaphore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/SyncOnAddress/src/SyncOnAddress.cpp ${CMAKE_CURRENT_SOURCE_DIR}/DirectMemory/Export.cpp diff --git a/core/libs/prx/libkernel/File/src/Stdio.cpp b/core/libs/prx/libkernel/File/src/Stdio.cpp index 2146bbe2d67b..3b079d25c104 100644 --- a/core/libs/prx/libkernel/File/src/Stdio.cpp +++ b/core/libs/prx/libkernel/File/src/Stdio.cpp @@ -22,6 +22,7 @@ #include "prx/libc/include/AppArchive.hpp" #include "prx/libkernel/KernelErrors.hpp" #include "prx/libkernel/Equeue/Equeue.hpp" +#include "prx/libkernel/Semaphore/include/Ksem.hpp" #include "prx/libkernel/Socket/include/SocketRuntime.hpp" #include "prx/libkernel/Socket/include/SocketPoll.hpp" #include @@ -761,6 +762,7 @@ int APS5_VABI dup_nid_postfix(int d) { if (GuestSockets::IsOpen(d)) return GuestSockets::Duplicate(d); if (d < 0) return PosixFailure(GUEST_EBADF); if (IsKqueueDescriptor(d)) throw std::runtime_error(std::string(__func__) + ": duplicating a kqueue descriptor is not supported"); + if (IsKsemDescriptor(d)) throw std::runtime_error(std::string(__func__) + ": duplicating a ksem id is not supported"); #ifdef _WIN32 const int duplicate = WithoutParameterHandler([d] { return ::_dup(d); }); if (duplicate >= 0) File::DuplicateDirectoryDescriptor(d, duplicate); @@ -791,6 +793,7 @@ int APS5_VABI dup2_nid_postfix(int from, int to) { } const bool sourceIsRandom = File::IsRandomDevice(from); if (from != to && IsKqueueDescriptor(from)) throw std::runtime_error(std::string(__func__) + ": duplicating a kqueue descriptor is not supported"); + if (from != to && IsKsemDescriptor(from)) throw std::runtime_error(std::string(__func__) + ": duplicating a ksem id is not supported"); #ifdef _WIN32 if (WithoutParameterHandler([from] { return ::_get_osfhandle(from) == -1 ? -1 : 0; }) != 0) return PosixFailure(GUEST_EBADF); if (from == to) return to; diff --git a/core/libs/prx/libkernel/Semaphore/include/Ksem.hpp b/core/libs/prx/libkernel/Semaphore/include/Ksem.hpp new file mode 100644 index 000000000000..55d99485ae62 --- /dev/null +++ b/core/libs/prx/libkernel/Semaphore/include/Ksem.hpp @@ -0,0 +1,6 @@ +#ifndef CORE_LIBS_PRX_LIBKERNEL_SEMAPHORE_KSEM_HPP +#define CORE_LIBS_PRX_LIBKERNEL_SEMAPHORE_KSEM_HPP + +bool IsKsemDescriptor(int descriptor); + +#endif diff --git a/core/libs/prx/libkernel_sys/Ksem.cpp b/core/libs/prx/libkernel/Semaphore/src/Ksem.cpp similarity index 88% rename from core/libs/prx/libkernel_sys/Ksem.cpp rename to core/libs/prx/libkernel/Semaphore/src/Ksem.cpp index 57910db95d50..743b919295b3 100644 --- a/core/libs/prx/libkernel_sys/Ksem.cpp +++ b/core/libs/prx/libkernel/Semaphore/src/Ksem.cpp @@ -1,6 +1,6 @@ #include "SceTypes.hpp" #include "prx/libc/include/General.hpp" -#include +#include "prx/libkernel/Semaphore/include/Ksem.hpp" #include #include #include @@ -25,12 +25,12 @@ namespace { constexpr int GuestEfault = 14; constexpr int GuestEbusy = 16; constexpr int GuestEinval = 22; -constexpr int GuestEnfile = 23; -constexpr int GuestEmfile = 24; +constexpr int GuestEnospc = 28; constexpr int GuestEagain = 35; constexpr int GuestEtimedout = 60; constexpr int GuestEoverflow = 84; constexpr unsigned SemValueMax = 0x7fffffffu; +constexpr std::size_t SemMax = 30; struct GuestTimespec { std::int64_t seconds; @@ -101,21 +101,33 @@ int Wait(std::intptr_t id, bool once, const GuestTimespec* abstime) { } +bool IsKsemDescriptor(int descriptor) { + std::lock_guard lock(g_ksemLock); + return g_ksems.count(descriptor) != 0; +} + extern "C" { int APS5_VABI ksem_init_nid_postfix(std::intptr_t* idp, unsigned int value) { if (value > SemValueMax) return Fail(GuestEinval); - if (idp == nullptr) return Fail(GuestEfault); const int descriptor = ReserveDescriptor(); - if (descriptor < 0) return Fail(errno == ENFILE ? GuestEnfile : GuestEmfile); + if (descriptor < 0) return Fail(GuestEnospc); + if (idp == nullptr) { + close_nid_postfix(descriptor); + return Fail(GuestEfault); + } + *idp = descriptor; auto ksem = std::make_shared(); ksem->count = value; { std::lock_guard lock(g_ksemLock); - g_ksems[descriptor] = std::move(ksem); + if (g_ksems.size() < SemMax) { + g_ksems[descriptor] = std::move(ksem); + return 0; + } } - *idp = descriptor; - return 0; + close_nid_postfix(descriptor); + return Fail(GuestEnospc); } int APS5_VABI ksem_post_nid_postfix(std::intptr_t id) { diff --git a/core/libs/prx/libkernel_sys/CMakeLists.txt b/core/libs/prx/libkernel_sys/CMakeLists.txt index b53c2597a6bd..6938d0c456ae 100644 --- a/core/libs/prx/libkernel_sys/CMakeLists.txt +++ b/core/libs/prx/libkernel_sys/CMakeLists.txt @@ -1,4 +1,3 @@ add_library(${LIB_NAME} SHARED EXCLUDE_FROM_ALL Export.cpp Export.Discovery.cpp) target_include_directories(${LIB_NAME} PRIVATE ${LIBS_INCLUDE_DIR}) -target_sources(${LIB_NAME} PRIVATE Ksem.cpp) configure_windows_unwind(${LIB_NAME}) diff --git a/core/libs/tests/GuestKernelSysKsem.cpp b/core/libs/tests/GuestKernelSysKsem.cpp index 7a544d00c61e..abb42ae46152 100644 --- a/core/libs/tests/GuestKernelSysKsem.cpp +++ b/core/libs/tests/GuestKernelSysKsem.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -15,6 +16,7 @@ extern "C" { int* APS5_VABI __error_nid_postfix(); int APS5_VABI open_nid_postfix(const char* path, int flags, int mode); int APS5_VABI close_nid_postfix(int descriptor); +int APS5_VABI dup_nid_postfix(int descriptor); int APS5_VABI dup2_nid_postfix(int from, int to); int APS5_VABI ksem_init_nid_postfix(std::intptr_t* idp, unsigned int value); int APS5_VABI ksem_post_nid_postfix(std::intptr_t id); @@ -30,6 +32,7 @@ namespace { constexpr int Efault = 14; constexpr int Ebusy = 16; constexpr int Einval = 22; +constexpr int Enospc = 28; constexpr int Eagain = 35; constexpr int Etimedout = 60; constexpr int Eoverflow = 84; @@ -134,6 +137,39 @@ void Identifiers() { std::filesystem::remove(path); } +bool Throws(void (*call)(int), int argument) { + try { + call(argument); + } catch (const std::runtime_error&) { + return true; + } + return false; +} + +void Duplicates() { + std::intptr_t id = -1; + std::intptr_t target = -1; + Require(ksem_init_nid_postfix(&id, 1) == 0 && ksem_init_nid_postfix(&target, 1) == 0); + Require(Throws([](int descriptor) { dup_nid_postfix(descriptor); }, static_cast(id))); + static int destination = -1; + destination = static_cast(target); + Require(Throws([](int descriptor) { dup2_nid_postfix(descriptor, destination); }, static_cast(id))); + Require(dup2_nid_postfix(static_cast(id), static_cast(id)) == static_cast(id)); + Require(Value(id) == 1 && Value(target) == 1); + Require(ksem_destroy_nid_postfix(id) == 0 && ksem_destroy_nid_postfix(target) == 0); +} + +void Limit() { + std::intptr_t ids[30] = {}; + for (auto& id : ids) Require(ksem_init_nid_postfix(&id, 0) == 0); + std::intptr_t extra = -1; + Require(ksem_init_nid_postfix(&extra, 0) == -1 && Error() == Enospc && extra >= 0); + Require(ksem_post_nid_postfix(extra) == -1 && Error() == Einval); + Require(ksem_destroy_nid_postfix(ids[0]) == 0); + Require(ksem_init_nid_postfix(&ids[0], 0) == 0); + for (const auto id : ids) Require(ksem_destroy_nid_postfix(id) == 0); +} + } int main() { @@ -141,6 +177,8 @@ int main() { Timed(); Blocking(); Identifiers(); + Duplicates(); + Limit(); std::puts("ksem unnamed semaphores passed"); return 0; } diff --git a/docs/dev/debt/libkernel.md b/docs/dev/debt/libkernel.md index 381e5098897f..845ff9dd43d1 100644 --- a/docs/dev/debt/libkernel.md +++ b/docs/dev/debt/libkernel.md @@ -14,6 +14,7 @@ - [sceKernelError](../../../core/libs/prx/libkernel/System/src/Error.cpp) follows [shadPS4's kernel implementation](https://github.com/shadps4-emu/shadPS4/blob/23c41333822fe8eca4c609b43119180af63ae4ac/src/core/libraries/kernel/kernel.cpp): zero returns zero; other guest POSIX error values receive the `0x80020000` bias without modifying errno. Arithmetic is defined modulo 32 bits to avoid signed overflow for inputs outside the errno domain. Console behavior for those inputs and PS5 equivalence have not been measured. - [physhm_open, physhm_unlink](../../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel, NIDs `n371J5cP+uo` and `AUqJNkobQ1c`) - declared as throwing stubs: the PS5 physical shared memory API is not documented, and [shadPS4's module generator](https://github.com/shadps4-emu/moduleGenerator/blob/main/libraries/kernel.cpp) also declares both with no arguments and returns `ORBIS_OK`, so the signature, the handle a success would return and the console's behaviour are unmeasured. The no-argument `int` signature follows shadPS4. Forever Launcher (PPSA99030) imports both and stops at load on `physhm_open`, and the relinker resolves no call site for either in that title, so no handle is fabricated and both throw +- [ksem_init, ksem_post, ksem_wait, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy](../../../core/libs/prx/libkernel/Semaphore/src/Ksem.cpp) (libkernel) - `dup` of a ksem id, or `dup2` from one, throws, where FreeBSD shares the semaphore, and a guest signal does not interrupt a wait with `EINTR`. Otherwise they follow FreeBSD 11 `uipc_sem.c`: each semaphore is kept in a table keyed by a descriptor reserved on the host null device, as a ksem id is a descriptor there; a guest `close`, or `dup2` over the id, drops it through libkernel's close notification; `ksem_init` fails with `ENOSPC` when no descriptor is left or 30 semaphores (`SEM_MAX`) exist - [getlogin_r](../../../core/libs/prx/libkernel/System/src/Login.cpp) (libkernel) returns the host effective account name: `GetUserNameW` as UTF-8 on Windows and `getpwuid_r(geteuid())` on POSIX. A valid account returns a name even without a login session; host `getlogin_r`, `USER` and `LOGNAME` are not consulted. The console's login name and behaviour without a session are unknown. Account lookup or encoding failures, a missing or empty account name, and POSIX account records exceeding the 16 KiB lookup buffer throw; there is no replacement name or retry. A short guest buffer returns `ERANGE` without modifying it, and a null output returns `EFAULT`. - [sceKernelGetSystemSwVersion](../../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports baseline system software version `0x01000000` ("01.000.000") for ProsperoStore (PPSA99000); the console's firmware version is not modeled. Measured on PS5 firmware 13.42: record values 0, 24, 39, 40, 41, 48 and 64 in the leading 64-bit field are accepted and preserved, the 28-byte string at offset 8 and packed version at 0x24 are filled, and bytes from 0x28 onward remain untouched. This API reports "13.590.001" / `0x13590001` in that environment, while the Prospero variant reports "13.420.000" / `0x13420000`; their values must not be assumed identical. A null pointer still returns `SCE_KERNEL_ERROR_EFAULT`, which was not measured; other firmware versions and record values remain unverified. - [kern.rng_pseudo](../../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) - `sysctlbyname` draws a new block of 64 bytes from the host's `std::random_device` for each read (no new value) that passes a buffer and a length, and sizes its answers as a payload process on a PS5 (firmware 12.70) sees it: a size query reports 64; a buffer of 64 bytes or more gets 64 bytes and a length of 64 (tried up to 65536); a smaller buffer gets as many bytes as its length, which is left as given, and a null length gets none, both with -1 and `ENOMEM`; a null buffer with a null length returns 0. `errno` is kept when the call succeeds. A write returns -1 with `EPERM`, which was not tried on the console. The only caller seen is mbedTLS's `mbedtls_hardware_poll` in the catalog's ProsperoLight boilerplate, which asks for 64-byte blocks and fails if fewer come back. The console's generator is unknown, and a title process was not measured. On the console `sysctlnametomib` gives MIB {1, 50} for the name, and `sysctl` with it answers reads of 0, 1, 63, 64, 65 and 128 bytes, a size query, a null length and a null buffer with a null length as the name does; here `sysctlnametomib` maps the name to {1, 50} and `sysctl` {1, 50} answers as the name does; a write through the MIB was not measured and throws diff --git a/docs/dev/debt/libkernel_sys.md b/docs/dev/debt/libkernel_sys.md index 6bd127de22ce..25499ae3d143 100644 --- a/docs/dev/debt/libkernel_sys.md +++ b/docs/dev/debt/libkernel_sys.md @@ -10,7 +10,6 @@ - [fchmodat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `chmod`; any other relative path is joined to the descriptor's host directory the same way as for `openat`, so guest path aliases and case-insensitive name matching do not apply to it and a `..` component is not kept inside the guest root. A flag other than `0` or `AT_SYMLINK_NOFOLLOW` (0x200) returns `EINVAL`; the mode is masked to `07777`. With `AT_SYMLINK_NOFOLLOW` a symbolic link returns success silently on Windows and Linux, since the host cannot change a link's own mode, while a regular file is changed either way. The mode maps to the host file mode, which on Windows is only the CRT's read-only bit. PPSA99621 calls it through `std::filesystem::permissions`. Console behaviour is unverified - [pathconf](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) looks the path up as FreeBSD 11's `kern_pathconf` does (links followed, `ENAMETOOLONG` for a path of 1024 bytes or more or a component over 255) and returns the constants of FreeBSD 11's UFS `ufs_pathconf` for files and directories alike: `_PC_LINK_MAX` 32767, `_PC_NAME_MAX` 255, `_PC_PATH_MAX` and `_PC_SYMLINK_MAX` 1024, `_PC_PIPE_BUF` 512, `_PC_CHOWN_RESTRICTED` and `_PC_NO_TRUNC` 1, `_PC_FILESIZEBITS` 64, `_PC_REC_MAX_XFER_SIZE` -1, `_PC_PRIO_IO` and `_PC_SYNC_IO` 0. Whether the console's filesystems report the same is not verified. It throws for the names whose UFS value depends on the mount (`_PC_ALLOC_SIZE_MIN`, `_PC_REC_INCR_XFER_SIZE`, `_PC_REC_MIN_XFER_SIZE`, `_PC_MIN_HOLE_SIZE`), the kernel options (`_PC_ACL_EXTENDED`, `_PC_ACL_PATH_MAX`, `_PC_ACL_NFS4`, `_PC_MAC_PRESENT`) or the page size (`_PC_REC_XFER_ALIGN`), and on which UFS and `vop_stdpathconf` disagree (`_PC_MAX_CANON`, `_PC_MAX_INPUT`, `_PC_VDISABLE`, `_PC_ASYNC_IO`); other names fail with `EINVAL` - [mkdirat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `mkdir`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. On Windows, `mode` is ignored. Console behaviour is unverified -- [ksem_init, ksem_post, ksem_wait, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy](../../../core/libs/prx/libkernel_sys/Ksem.cpp) (libkernel_sys) keep each semaphore in a table keyed by a descriptor reserved on the host null device, as FreeBSD 11 `uipc_sem.c` makes a ksem id a descriptor. A guest `close` or `dup2` over the id drops the semaphore through libkernel's close notification, but `dup` of an id gives a descriptor that is not a semaphore, where FreeBSD shares it, and a guest signal does not interrupt a wait with `EINTR` - [readlink](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) on Windows reads a symbolic link's target from its reparse data and returns it with `/` separators, only when the target is relative, as `symlink` creates them. A symbolic link with an absolute target returns its print name, or its substitute name when the print name is empty, without a `\??\` or `\\?\` prefix. A directory junction returns the same kind of name when it is a drive path (`X:\...`), using the print name when that is a drive path and the substitute name otherwise. A mounted volume, whose substitute name is `\??\Volume{GUID}\`, stays a throw, because the name left after the prefix is not a drive path. Any other reparse point throws too, where FreeBSD reports `EINVAL` for a file that is not a link - [readlinkat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `readlink`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. Console behaviour is unverified - [fstatat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `stat`, or to `lstat` with `AT_SYMLINK_NOFOLLOW` (0x200). Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory, and flags other than `AT_SYMLINK_NOFOLLOW` return `EINVAL`. PPSA74126 imports it. Console behaviour is unverified From b0d85e3c281f1debfaa27ebf7210e1eb064c7c0a Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 22:28:22 +0100 Subject: [PATCH 10/10] docs(debt): list the unnamed ksem calls under Functional --- docs/dev/debt/libkernel.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/debt/libkernel.md b/docs/dev/debt/libkernel.md index 845ff9dd43d1..4c41f6e6f484 100644 --- a/docs/dev/debt/libkernel.md +++ b/docs/dev/debt/libkernel.md @@ -14,7 +14,6 @@ - [sceKernelError](../../../core/libs/prx/libkernel/System/src/Error.cpp) follows [shadPS4's kernel implementation](https://github.com/shadps4-emu/shadPS4/blob/23c41333822fe8eca4c609b43119180af63ae4ac/src/core/libraries/kernel/kernel.cpp): zero returns zero; other guest POSIX error values receive the `0x80020000` bias without modifying errno. Arithmetic is defined modulo 32 bits to avoid signed overflow for inputs outside the errno domain. Console behavior for those inputs and PS5 equivalence have not been measured. - [physhm_open, physhm_unlink](../../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel, NIDs `n371J5cP+uo` and `AUqJNkobQ1c`) - declared as throwing stubs: the PS5 physical shared memory API is not documented, and [shadPS4's module generator](https://github.com/shadps4-emu/moduleGenerator/blob/main/libraries/kernel.cpp) also declares both with no arguments and returns `ORBIS_OK`, so the signature, the handle a success would return and the console's behaviour are unmeasured. The no-argument `int` signature follows shadPS4. Forever Launcher (PPSA99030) imports both and stops at load on `physhm_open`, and the relinker resolves no call site for either in that title, so no handle is fabricated and both throw -- [ksem_init, ksem_post, ksem_wait, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy](../../../core/libs/prx/libkernel/Semaphore/src/Ksem.cpp) (libkernel) - `dup` of a ksem id, or `dup2` from one, throws, where FreeBSD shares the semaphore, and a guest signal does not interrupt a wait with `EINTR`. Otherwise they follow FreeBSD 11 `uipc_sem.c`: each semaphore is kept in a table keyed by a descriptor reserved on the host null device, as a ksem id is a descriptor there; a guest `close`, or `dup2` over the id, drops it through libkernel's close notification; `ksem_init` fails with `ENOSPC` when no descriptor is left or 30 semaphores (`SEM_MAX`) exist - [getlogin_r](../../../core/libs/prx/libkernel/System/src/Login.cpp) (libkernel) returns the host effective account name: `GetUserNameW` as UTF-8 on Windows and `getpwuid_r(geteuid())` on POSIX. A valid account returns a name even without a login session; host `getlogin_r`, `USER` and `LOGNAME` are not consulted. The console's login name and behaviour without a session are unknown. Account lookup or encoding failures, a missing or empty account name, and POSIX account records exceeding the 16 KiB lookup buffer throw; there is no replacement name or retry. A short guest buffer returns `ERANGE` without modifying it, and a null output returns `EFAULT`. - [sceKernelGetSystemSwVersion](../../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports baseline system software version `0x01000000` ("01.000.000") for ProsperoStore (PPSA99000); the console's firmware version is not modeled. Measured on PS5 firmware 13.42: record values 0, 24, 39, 40, 41, 48 and 64 in the leading 64-bit field are accepted and preserved, the 28-byte string at offset 8 and packed version at 0x24 are filled, and bytes from 0x28 onward remain untouched. This API reports "13.590.001" / `0x13590001` in that environment, while the Prospero variant reports "13.420.000" / `0x13420000`; their values must not be assumed identical. A null pointer still returns `SCE_KERNEL_ERROR_EFAULT`, which was not measured; other firmware versions and record values remain unverified. - [kern.rng_pseudo](../../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) - `sysctlbyname` draws a new block of 64 bytes from the host's `std::random_device` for each read (no new value) that passes a buffer and a length, and sizes its answers as a payload process on a PS5 (firmware 12.70) sees it: a size query reports 64; a buffer of 64 bytes or more gets 64 bytes and a length of 64 (tried up to 65536); a smaller buffer gets as many bytes as its length, which is left as given, and a null length gets none, both with -1 and `ENOMEM`; a null buffer with a null length returns 0. `errno` is kept when the call succeeds. A write returns -1 with `EPERM`, which was not tried on the console. The only caller seen is mbedTLS's `mbedtls_hardware_poll` in the catalog's ProsperoLight boilerplate, which asks for 64-byte blocks and fails if fewer come back. The console's generator is unknown, and a title process was not measured. On the console `sysctlnametomib` gives MIB {1, 50} for the name, and `sysctl` with it answers reads of 0, 1, 63, 64, 65 and 128 bytes, a size query, a null length and a null buffer with a null length as the name does; here `sysctlnametomib` maps the name to {1, 50} and `sysctl` {1, 50} answers as the name does; a write through the MIB was not measured and throws @@ -149,6 +148,7 @@ - [sceKernelGetFsSandboxRandomWord](../../../core/libs/prx/libkernel/System/src/Sandbox.cpp) (libkernel) returns a fixed directory name, `gkbHtXc3Wq`. On the console the name is the process's randomized path (syscall 602, `randomized_path`), and the sandbox exposes system files under it, such as `common/lib` and `common/cert`. Nothing is mounted under the name here, so `/gkbHtXc3Wq/common/...` resolves under the guest root like any other path and does not exist, except `/gkbHtXc3Wq/common/cert/CA_LIST.cer`, which [SandboxCertificates.cpp](../../../core/libs/prx/libkernel/File/src/SandboxCertificates.cpp) serves from the host trust store - [The sandbox CA list](../../../core/libs/prx/libkernel/File/src/SandboxCertificates.cpp) (libkernel), `//common/cert/CA_LIST.cer`, is a PEM bundle of the host's trust anchors, written once per process to `cert_cache/CA_LIST.cer` in the run directory with the owner write bit cleared: on Windows the current user's `ROOT` store, filtered through Disallowed and the combined EKU extension/property for TLS server authentication (Windows fetches missing roots on demand, so a root that was never fetched is absent), elsewhere `SSL_CERT_FILE` or the first of `/etc/ssl/certs/ca-certificates.crt`, `/etc/pki/tls/certs/ca-bundle.crt`, `/etc/ssl/ca-bundle.pem` and `/etc/ssl/cert.pem` that exists. On macOS, `/etc/ssl/cert.pem` is a static snapshot and does not reflect roots added to or distrusted in the Keychain. Existing guest files, explicit aliases and blocked mounts take precedence over the provider. The PEM snapshot does not carry Windows CTL restrictions beyond EKU, native revocation policy or later trust-store changes. Without any certificate the path does not exist. The console file's format is unverified: only that bundled OpenSSL accepts a PEM bundle there is shown (ProsperoRadio PPSA99001 and SwanStation PPSA98510, #5001). The other entries of the console's `common/cert` directory, the directory itself (it does not exist here) and the error a write open gets (`EACCES` from the host here) are unverified - [getcontext and setcontext](../../../core/libs/prx/libkernel/System/src/UserContext.cpp) (libkernel) and [makecontext](../../../core/libs/prx/libSceLibcInternal/UserContext.cpp) (libSceLibcInternal) use FreeBSD 11's amd64 `ucontext_t` (`mcontext` at 0x10, `mc_len` 800, `uc_link` at 0x330, `uc_stack` at 0x338, 0x370 bytes), the layout homebrew built against FreeBSD's headers passes: PPSA99039's OpenSSL `ASYNC` (`crypto/async/arch/async_posix.c`) captures into a 0x370-byte stack buffer. `getcontext` writes the 0x330 bytes before `uc_link`, as FreeBSD's `UC_COPY_SIZE`. The console's own layout for these functions is not verified; the exception handler's context is a different one (see `sceKernelRaiseException`) +- [ksem_init, ksem_post, ksem_wait, ksem_trywait, ksem_timedwait, ksem_getvalue and ksem_destroy](../../../core/libs/prx/libkernel/Semaphore/src/Ksem.cpp) (libkernel) - `dup` of a ksem id, or `dup2` from one, throws, where FreeBSD shares the semaphore, and a guest signal does not interrupt a wait with `EINTR`. Otherwise they follow FreeBSD 11 `uipc_sem.c`: each semaphore is kept in a table keyed by a descriptor reserved on the host null device, as a ksem id is a descriptor there; a guest `close`, or `dup2` over the id, drops it through libkernel's close notification; `ksem_init` fails with `ENOSPC` when no descriptor is left or 30 semaphores (`SEM_MAX`) exist - [getcontext and setcontext](../../../core/libs/prx/libkernel/System/src/UserContext.cpp) (libkernel) keep the 512-byte FXSAVE image in `mc_fpstate` (x87, MXCSR, XMM0-15), so the upper halves of YMM0-15 are neither saved nor restored, and `getcontext` leaves `mc_xfpustate` and `mc_xfpustate_len` 0. `getcontext` sets `mc_fpformat` and `mc_ownedfp` to FreeBSD's `_MC_FPFMT_XMM` and `_MC_FPOWNED_FPU`, `mc_cs` and `mc_ss` to the host selectors, and `mc_flags`, `mc_fsbase` and `mc_gsbase` to 0. `setcontext` loads `mc_fpstate` whatever `mc_fpformat` and `mc_ownedfp` say, and restores neither the segment selectors, `mc_fsbase` and `mc_gsbase` nor the extended state, which FreeBSD restores when `mc_flags` asks for them - [setcontext](../../../core/libs/prx/libkernel/System/src/UserContext.cpp) (libkernel) and [longjmp](../../../core/libs/prx/libc/src/JumpBuffer.cpp) (libc) on Windows set the thread's stack bounds in the TEB to the stack they switch to: a `makecontext` stack, or else the committed region around the target stack pointer. A switch to any other guest stack, such as a context built by hand, gets the bounds of that region only - [scePthreadAttrGet](../../../core/libs/prx/libkernel/Pthread/src/Attr.cpp) (libkernel) - the answer for a thread that has ended is not measured on the console, and [`pthread_attr_get_np`](../../../core/libs/prx/libkernel/Pthread/Posix/Attr.cpp) still returns 0 for such a thread, reading a detached one's object after it is freed. `scePthreadAttrGet` returns `ESRCH` (`0x80020003`) for a thread that has ended, joined or not and detached or not, as FreeBSD 11.4's [`_pthread_attr_get_np`](https://github.com/freebsd/freebsd-src/blob/releng/11.4/lib/libthr/thread/thr_attr.c#L139-L172) does through `_thr_find_thread`; a thread counts as ended once its thread-specific data destructors have run, where FreeBSD marks it `PS_DEAD`. On Windows a host thread adopted by `scePthreadSelf` that ends without `scePthreadExit` keeps answering 0. Monster Hunter Wilds (PPSA24191) reuses a slot of its thread table only when `scePthreadAttrGet` returns `0x80020003`