From 024ccc1be78e2b563835c535bbcfc499483c1582 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:22:17 +0100 Subject: [PATCH 01/14] 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/14] 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/14] 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/14] 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 60d4f0db2a27387a0db5a0e8f33e51ff4c8bb488 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:40:09 +0100 Subject: [PATCH 05/14] feat(libkernel_sys): implement POSIX message queues --- core/libs/prx/libkernel_sys/CMakeLists.txt | 1 + .../prx/libkernel_sys/Export.Discovery.cpp | 25 -- core/libs/prx/libkernel_sys/Mqueue.cpp | 238 ++++++++++++++++++ 3 files changed, 239 insertions(+), 25 deletions(-) create mode 100644 core/libs/prx/libkernel_sys/Mqueue.cpp diff --git a/core/libs/prx/libkernel_sys/CMakeLists.txt b/core/libs/prx/libkernel_sys/CMakeLists.txt index b53c2597a6bd..90379f1b9ec6 100644 --- a/core/libs/prx/libkernel_sys/CMakeLists.txt +++ b/core/libs/prx/libkernel_sys/CMakeLists.txt @@ -1,4 +1,5 @@ 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) +target_sources(${LIB_NAME} PRIVATE Mqueue.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 8820c3d7f70c..4e5ce3d02d65 100644 --- a/core/libs/prx/libkernel_sys/Export.Discovery.cpp +++ b/core/libs/prx/libkernel_sys/Export.Discovery.cpp @@ -203,31 +203,6 @@ int APS5_VABI kmq_notify_nid_postfix(void) { return 0; } -int APS5_VABI kmq_open_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI kmq_setattr_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI kmq_timedreceive_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI kmq_timedsend_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI kmq_unlink_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI ksem_close_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; diff --git a/core/libs/prx/libkernel_sys/Mqueue.cpp b/core/libs/prx/libkernel_sys/Mqueue.cpp new file mode 100644 index 000000000000..5970634c1a04 --- /dev/null +++ b/core/libs/prx/libkernel_sys/Mqueue.cpp @@ -0,0 +1,238 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include +#include +#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" void RegisterDescriptorCloseObserver_nid_no_patch(void (*observer)(int descriptor)); + +namespace { + +constexpr int GuestEnoent = 2; +constexpr int GuestEbadf = 9; +constexpr int GuestEfault = 14; +constexpr int GuestEexist = 17; +constexpr int GuestEinval = 22; +constexpr int GuestEnfile = 23; +constexpr int GuestEmfile = 24; +constexpr int GuestEagain = 35; +constexpr int GuestEmsgsize = 40; +constexpr int GuestEtimedout = 60; +constexpr int GuestEnametoolong = 63; +constexpr int GuestOAccmode = 0x0003; +constexpr int GuestOWronly = 0x0001; +constexpr int GuestORdwr = 0x0002; +constexpr int GuestONonblock = 0x0004; +constexpr int GuestOCreat = 0x0200; +constexpr int GuestOExcl = 0x0800; +constexpr int GuestOExec = 0x00040000; +constexpr std::int64_t MaxMessages = 100; +constexpr std::int64_t MaxMessageSize = 16384; +constexpr std::int64_t DefaultMessages = 10; +constexpr std::int64_t DefaultMessageSize = 1024; +constexpr unsigned PriorityMax = 64; +constexpr std::size_t NameBytes = 256; + +struct GuestMqAttr { + std::int64_t flags; + std::int64_t maxmsg; + std::int64_t msgsize; + std::int64_t curmsgs; + std::int64_t reserved[4]; +}; + +struct GuestTimespec { + std::int64_t seconds; + std::int64_t nanoseconds; +}; + +struct Message { + unsigned priority; + std::vector bytes; +}; + +struct Queue { + std::mutex lock; + std::condition_variable readable; + std::condition_variable writable; + std::int64_t maxmsg = DefaultMessages; + std::int64_t msgsize = DefaultMessageSize; + std::vector messages; +}; + +struct Open { + std::shared_ptr queue; + int access = 0; + bool nonblocking = false; +}; + +std::mutex g_mqueueLock; +std::map> g_opens; +std::map> g_queues; + +int Fail(int error) { + *__error_nid_postfix() = error; + return -1; +} + +std::shared_ptr Find(int descriptor) { + std::lock_guard lock(g_mqueueLock); + const auto found = g_opens.find(descriptor); + return found != g_opens.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_mqueueLock); + g_opens.erase(descriptor); +} + +const bool g_observerRegistered = [] { + RegisterDescriptorCloseObserver_nid_no_patch(DescriptorClosed); + return true; +}(); + +int CheckName(const char* path, std::string& name) { + if (path == nullptr) return GuestEfault; + const std::size_t length = strnlen(path, NameBytes); + if (length == NameBytes) return GuestEnametoolong; + name.assign(path, length); + if (length < 2 || name[0] != '/' || name.find('/', 1) != std::string::npos) return GuestEinval; + return 0; +} + +std::chrono::system_clock::time_point Deadline(const GuestTimespec* abstime) { + return std::chrono::system_clock::time_point(std::chrono::duration_cast( + std::chrono::seconds(abstime->seconds) + std::chrono::nanoseconds(abstime->nanoseconds))); +} + +template +int WaitFor(const Open& open, std::unique_lock& lock, std::condition_variable& signal, const GuestTimespec* abstime, Ready ready) { + if (ready()) return 0; + if (open.nonblocking) return GuestEagain; + if (abstime == nullptr) { + signal.wait(lock, ready); + return 0; + } + if (abstime->nanoseconds < 0 || abstime->nanoseconds >= 1000000000) return GuestEinval; + return signal.wait_until(lock, Deadline(abstime), ready) ? 0 : GuestEtimedout; +} + +} + +extern "C" { + +int APS5_VABI kmq_open_nid_postfix(const char* path, int flags, unsigned int mode, const GuestMqAttr* attr) { + (void)mode; + if ((flags & GuestOAccmode) == GuestOAccmode || (flags & GuestOExec) != 0) return Fail(GuestEinval); + const bool create = (flags & GuestOCreat) != 0; + if (create && attr != nullptr) { + if (attr->maxmsg <= 0 || attr->maxmsg > MaxMessages) return Fail(GuestEinval); + if (attr->msgsize <= 0 || attr->msgsize > MaxMessageSize) return Fail(GuestEinval); + } + std::string name; + if (const int error = CheckName(path, name)) return Fail(error); + std::lock_guard lock(g_mqueueLock); + std::shared_ptr queue; + const auto found = g_queues.find(name); + if (found == g_queues.end()) { + if (!create) return Fail(GuestEnoent); + queue = std::make_shared(); + if (attr != nullptr) { + queue->maxmsg = attr->maxmsg; + queue->msgsize = attr->msgsize; + } + } else { + if ((flags & (GuestOCreat | GuestOExcl)) == (GuestOCreat | GuestOExcl)) return Fail(GuestEexist); + queue = found->second; + } + const int descriptor = ReserveDescriptor(); + if (descriptor < 0) return Fail(errno == ENFILE ? GuestEnfile : GuestEmfile); + if (found == g_queues.end()) g_queues[name] = queue; + auto open = std::make_shared(); + open->queue = std::move(queue); + open->access = flags & GuestOAccmode; + open->nonblocking = (flags & GuestONonblock) != 0; + g_opens[descriptor] = std::move(open); + return descriptor; +} + +int APS5_VABI kmq_unlink_nid_postfix(const char* path) { + std::string name; + if (const int error = CheckName(path, name)) return Fail(error); + std::lock_guard lock(g_mqueueLock); + if (g_queues.erase(name) == 0) return Fail(GuestEnoent); + return 0; +} + +int APS5_VABI kmq_setattr_nid_postfix(int descriptor, const GuestMqAttr* attr, GuestMqAttr* oattr) { + if (attr != nullptr && (attr->flags & ~static_cast(GuestONonblock)) != 0) return Fail(GuestEinval); + const auto open = Find(descriptor); + if (!open) return Fail(GuestEbadf); + if (oattr != nullptr) { + std::lock_guard lock(open->queue->lock); + *oattr = GuestMqAttr{open->nonblocking ? GuestONonblock : 0, open->queue->maxmsg, open->queue->msgsize, + static_cast(open->queue->messages.size()), {}}; + } + if (attr != nullptr) open->nonblocking = (attr->flags & GuestONonblock) != 0; + return 0; +} + +int APS5_VABI kmq_timedsend_nid_postfix(int descriptor, const char* message, std::size_t length, unsigned int priority, const GuestTimespec* abstime) { + const auto open = Find(descriptor); + if (!open || (open->access != GuestOWronly && open->access != GuestORdwr)) return Fail(GuestEbadf); + auto& queue = *open->queue; + if (priority >= PriorityMax) return Fail(GuestEinval); + if (length > static_cast(queue.msgsize)) return Fail(GuestEmsgsize); + if (message == nullptr && length != 0) return Fail(GuestEfault); + Message entry{priority, std::vector(message, message + length)}; + std::unique_lock lock(queue.lock); + const auto space = [&] { return static_cast(queue.messages.size()) < queue.maxmsg; }; + if (const int error = WaitFor(*open, lock, queue.writable, abstime, space)) return Fail(error); + auto position = queue.messages.begin(); + while (position != queue.messages.end() && position->priority >= priority) ++position; + queue.messages.insert(position, std::move(entry)); + queue.readable.notify_one(); + return 0; +} + +std::int64_t APS5_VABI kmq_timedreceive_nid_postfix(int descriptor, char* buffer, std::size_t length, unsigned int* priority, const GuestTimespec* abstime) { + const auto open = Find(descriptor); + if (!open || open->access == GuestOWronly) return Fail(GuestEbadf); + auto& queue = *open->queue; + if (length < static_cast(queue.msgsize)) return Fail(GuestEmsgsize); + std::unique_lock lock(queue.lock); + const auto available = [&] { return !queue.messages.empty(); }; + if (const int error = WaitFor(*open, lock, queue.readable, abstime, available)) return Fail(error); + Message entry = std::move(queue.messages.front()); + queue.messages.erase(queue.messages.begin()); + queue.writable.notify_one(); + lock.unlock(); + if (!entry.bytes.empty()) std::memcpy(buffer, entry.bytes.data(), entry.bytes.size()); + if (priority != nullptr) *priority = entry.priority; + return static_cast(entry.bytes.size()); +} + +} From c3861fb14b4b8c22c205ce378ff6eabc7dea8273 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:40:10 +0100 Subject: [PATCH 06/14] test(libkernel_sys): cover message queue open, send, receive, attributes and access --- core/libs/CMakeLists.txt | 11 ++ core/libs/tests/GuestKernelSysMqueue.cpp | 208 +++++++++++++++++++++++ 2 files changed, 219 insertions(+) create mode 100644 core/libs/tests/GuestKernelSysMqueue.cpp diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 83642d356aad..63bec641c38a 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -539,6 +539,17 @@ if(BUILD_TESTING) add_subdirectory(tests/register_context) endif() + add_test_executable(guest_kernel_sys_mqueue_tests tests/GuestKernelSysMqueue.cpp) + target_include_directories(guest_kernel_sys_mqueue_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_kernel_sys_mqueue_tests PRIVATE libkernel_sys libkernel libc) + configure_windows_unwind(guest_kernel_sys_mqueue_tests) + add_test(NAME guest_kernel_sys_mqueue COMMAND guest_kernel_sys_mqueue_tests) + set_tests_properties(guest_kernel_sys_mqueue PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(guest_kernel_sys_mqueue PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + add_test_executable(savedata_memory_metadata_tests tests/SaveDataMemoryMetadata.cpp) target_include_directories(savedata_memory_metadata_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(savedata_memory_metadata_tests PRIVATE libSceSaveData.native) diff --git a/core/libs/tests/GuestKernelSysMqueue.cpp b/core/libs/tests/GuestKernelSysMqueue.cpp new file mode 100644 index 000000000000..7adc83d92a41 --- /dev/null +++ b/core/libs/tests/GuestKernelSysMqueue.cpp @@ -0,0 +1,208 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/general/VabiMacros.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +struct MqAttr { + std::int64_t flags; + std::int64_t maxmsg; + std::int64_t msgsize; + std::int64_t curmsgs; + std::int64_t reserved[4]; +}; + +struct Timespec { + std::int64_t seconds; + std::int64_t nanoseconds; +}; + +} + +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 kmq_open_nid_postfix(const char* path, int flags, unsigned int mode, const MqAttr* attr); +int APS5_VABI kmq_unlink_nid_postfix(const char* path); +int APS5_VABI kmq_setattr_nid_postfix(int descriptor, const MqAttr* attr, MqAttr* oattr); +int APS5_VABI kmq_timedsend_nid_postfix(int descriptor, const char* message, std::size_t length, unsigned int priority, const Timespec* abstime); +std::int64_t APS5_VABI kmq_timedreceive_nid_postfix(int descriptor, char* buffer, std::size_t length, unsigned int* priority, const Timespec* abstime); +} + +namespace { + +constexpr int Enoent = 2; +constexpr int Ebadf = 9; +constexpr int Efault = 14; +constexpr int Eexist = 17; +constexpr int Einval = 22; +constexpr int Eagain = 35; +constexpr int Emsgsize = 40; +constexpr int Etimedout = 60; +constexpr int Enametoolong = 63; +constexpr int ORdonly = 0x0000; +constexpr int OWronly = 0x0001; +constexpr int ORdwr = 0x0002; +constexpr int ONonblock = 0x0004; +constexpr int OCreat = 0x0200; +constexpr int OExcl = 0x0800; + +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(); +} + +std::string Name(const char* tag) { + return std::string("/anyps5-mq-") + tag + "-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); +} + +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}; +} + +std::string Receive(int queue, unsigned* priority = nullptr) { + char buffer[16]{}; + const auto length = kmq_timedreceive_nid_postfix(queue, buffer, sizeof(buffer), priority, nullptr); + Require(length >= 0); + return std::string(buffer, static_cast(length)); +} + +void OpenRules() { + const auto name = Name("open"); + const MqAttr zero{0, 0, 16, 0, {}}; + const MqAttr many{0, 101, 16, 0, {}}; + const MqAttr empty{0, 2, 0, 0, {}}; + const MqAttr huge{0, 2, 16385, 0, {}}; + Require(kmq_open_nid_postfix(name.c_str(), 3 | OCreat, 0600, nullptr) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &zero) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &many) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &empty) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &huge) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix("relative", ORdwr | OCreat, 0600, nullptr) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix("/", ORdwr | OCreat, 0600, nullptr) == -1 && Error() == Einval); + Require(kmq_open_nid_postfix("/a/b", ORdwr | OCreat, 0600, nullptr) == -1 && Error() == Einval); + const std::string longName = "/" + std::string(300, 'q'); + Require(kmq_open_nid_postfix(longName.c_str(), ORdwr | OCreat, 0600, nullptr) == -1 && Error() == Enametoolong); + Require(kmq_open_nid_postfix(nullptr, ORdwr | OCreat, 0600, nullptr) == -1 && Error() == Efault); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr, 0600, nullptr) == -1 && Error() == Enoent); + const int queue = kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, nullptr); + Require(queue >= 0); + MqAttr attributes{}; + Require(kmq_setattr_nid_postfix(queue, nullptr, &attributes) == 0); + Require(attributes.maxmsg == 10 && attributes.msgsize == 1024 && attributes.curmsgs == 0 && attributes.flags == 0); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat | OExcl, 0600, nullptr) == -1 && Error() == Eexist); + Require(close_nid_postfix(queue) == 0); + Require(kmq_unlink_nid_postfix(name.c_str()) == 0); + Require(kmq_unlink_nid_postfix(name.c_str()) == -1 && Error() == Enoent); + Require(kmq_unlink_nid_postfix("bad") == -1 && Error() == Einval); +} + +void Messages() { + const auto name = Name("messages"); + const MqAttr small{0, 3, 16, 0, {}}; + const int queue = kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &small); + Require(queue >= 0); + Require(kmq_timedsend_nid_postfix(queue, "x", 1, 64, nullptr) == -1 && Error() == Einval); + Require(kmq_timedsend_nid_postfix(queue, "0123456789abcdefg", 17, 1, nullptr) == -1 && Error() == Emsgsize); + Require(kmq_timedsend_nid_postfix(queue, "low", 3, 1, nullptr) == 0); + Require(kmq_timedsend_nid_postfix(queue, "high", 4, 5, nullptr) == 0); + Require(kmq_timedsend_nid_postfix(queue, "low2", 4, 1, nullptr) == 0); + MqAttr attributes{}; + const MqAttr nonblocking{ONonblock, 0, 0, 0, {}}; + const MqAttr bad{0x1, 0, 0, 0, {}}; + Require(kmq_setattr_nid_postfix(queue, &bad, nullptr) == -1 && Error() == Einval); + Require(kmq_setattr_nid_postfix(queue, &nonblocking, &attributes) == 0 && attributes.flags == 0 && attributes.curmsgs == 3); + Require(kmq_setattr_nid_postfix(queue, nullptr, &attributes) == 0 && attributes.flags == ONonblock); + Require(kmq_timedsend_nid_postfix(queue, "more", 4, 1, nullptr) == -1 && Error() == Eagain); + char tiny[8]{}; + Require(kmq_timedreceive_nid_postfix(queue, tiny, sizeof(tiny), nullptr, nullptr) == -1 && Error() == Emsgsize); + unsigned priority = 99; + Require(Receive(queue, &priority) == "high" && priority == 5); + Require(Receive(queue, &priority) == "low" && priority == 1); + Require(Receive(queue, &priority) == "low2" && priority == 1); + char buffer[16]{}; + Require(kmq_timedreceive_nid_postfix(queue, buffer, sizeof(buffer), nullptr, nullptr) == -1 && Error() == Eagain); + Require(close_nid_postfix(queue) == 0 && kmq_unlink_nid_postfix(name.c_str()) == 0); +} + +void Waiting() { + const auto name = Name("waiting"); + const MqAttr one{0, 1, 16, 0, {}}; + const int queue = kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &one); + Require(queue >= 0); + char buffer[16]{}; + const Timespec invalid{0, 1000000000}; + Require(kmq_timedreceive_nid_postfix(queue, buffer, sizeof(buffer), nullptr, &invalid) == -1 && Error() == Einval); + const auto deadline = FromNow(std::chrono::milliseconds(150)); + const auto start = std::chrono::steady_clock::now(); + Require(kmq_timedreceive_nid_postfix(queue, buffer, sizeof(buffer), nullptr, &deadline) == -1 && Error() == Etimedout); + Require(std::chrono::steady_clock::now() - start >= std::chrono::milliseconds(100)); + Require(kmq_timedsend_nid_postfix(queue, "a", 1, 0, &invalid) == 0); + Require(kmq_timedsend_nid_postfix(queue, "b", 1, 0, &invalid) == -1 && Error() == Einval); + Require(kmq_timedreceive_nid_postfix(queue, buffer, sizeof(buffer), nullptr, &invalid) == 1 && buffer[0] == 'a'); + std::atomic received{-2}; + std::thread reader([&] { + char local[16]{}; + received = kmq_timedreceive_nid_postfix(queue, local, sizeof(local), nullptr, nullptr); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + Require(received == -2); + Require(kmq_timedsend_nid_postfix(queue, "wake", 4, 3, nullptr) == 0); + reader.join(); + Require(received == 4); + Require(close_nid_postfix(queue) == 0 && kmq_unlink_nid_postfix(name.c_str()) == 0); +} + +void Access() { + const auto name = Name("access"); + const int both = kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, nullptr); + const int reader = kmq_open_nid_postfix(name.c_str(), ORdonly, 0600, nullptr); + const int writer = kmq_open_nid_postfix(name.c_str(), OWronly | ONonblock, 0600, nullptr); + Require(both >= 0 && reader >= 0 && writer >= 0); + char buffer[1024]{}; + Require(kmq_timedsend_nid_postfix(reader, "x", 1, 0, nullptr) == -1 && Error() == Ebadf); + Require(kmq_timedreceive_nid_postfix(writer, buffer, sizeof(buffer), nullptr, nullptr) == -1 && Error() == Ebadf); + Require(kmq_timedsend_nid_postfix(writer, "shared", 6, 0, nullptr) == 0); + Require(kmq_unlink_nid_postfix(name.c_str()) == 0); + Require(kmq_open_nid_postfix(name.c_str(), ORdwr, 0600, nullptr) == -1 && Error() == Enoent); + Require(kmq_timedreceive_nid_postfix(reader, buffer, sizeof(buffer), nullptr, nullptr) == 6); + Require(close_nid_postfix(both) == 0 && close_nid_postfix(reader) == 0); + Require(kmq_timedreceive_nid_postfix(reader, buffer, sizeof(buffer), nullptr, nullptr) == -1 && Error() == Ebadf); + const auto path = (std::filesystem::temp_directory_path() / "anyps5-mq-stale.bin").string(); + { std::ofstream stream(path); stream << "x"; } + const int plain = open_nid_postfix(path.c_str(), 0, 0); + Require(plain >= 0); + Require(kmq_timedsend_nid_postfix(plain, "x", 1, 0, nullptr) == -1 && Error() == Ebadf); + Require(kmq_setattr_nid_postfix(plain, nullptr, nullptr) == -1 && Error() == Ebadf); + Require(close_nid_postfix(plain) == 0 && close_nid_postfix(writer) == 0); + std::filesystem::remove(path); +} + +} + +int main() { + OpenRules(); + Messages(); + Waiting(); + Access(); + std::puts("message queues passed"); + return 0; +} From d68969732c2448fa17a0956fbe365269d1c4382a Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:40:10 +0100 Subject: [PATCH 07/14] docs(debt): record the libkernel_sys message queue limits --- 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..734ea615227d 100644 --- a/docs/dev/debt/libkernel_sys.md +++ b/docs/dev/debt/libkernel_sys.md @@ -18,4 +18,5 @@ - [renameat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `rename`. Any other relative path is joined to its descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to relative descriptors, 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 - [fork](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) throws: creating a child process is not supported. PPSA19111 imports it and fails to load without it. Its engine calls `fork` in `Posix_Daemonize`, only with `-daemonize`, and in `Platform_ShellExecute` before `execvp("xdg-open")`, which the main menu's Previews button reaches, so pressing Previews ends in this throw. [setsid](../../../core/libs/prx/libkernel_sys/Export.cpp) fails with `EPERM`, as FreeBSD's does for a process group leader, since the guest is taken to lead its own process group (see `kill`). [umask](../../../core/libs/prx/libkernel_sys/Export.cpp) keeps the guest's mask (initially 022, masked to 07777) and returns the previous one, Linux named shared-memory creation applies it, but ordinary files are still created with the host process's mask - [chroot](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) follows FreeBSD 11.4's [`sys_chroot`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_syscalls.c#L776-L807) and [`pwd_chroot`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L3059-L3085) for a root caller: `EFAULT` for a null path, `ENOENT` for an empty or missing one, `ENAMETOOLONG` for a path of 1024 bytes or more or a component over 255, and `ENOTDIR` for a path that is not a directory or passes through a file. A directory that is the guest root (`/`, `/..`, or `.` after `fchdir` to a descriptor of `/`) succeeds and changes nothing, as the root stays the same directory; the guest is taken never to have changed its root, so open directory descriptors do not make it fail with `EPERM` (`kern.chroot_allow_open_directories` 1). Any other directory throws, naming the path: the guest path resolver has a fixed root and mount aliases (`/app0`, `/savedata0`) that do not move with it. On the console a title starts in a sandbox root, where `pwd_chroot` refuses with `EPERM` while a directory is open; whether that holds for titles, and whether a title holds `PRIV_VFS_CHROOT`, are unverified. Porpoise (PPSA99764) weak-imports it and calls it only as `fchdir` to its saved descriptor of `/` then `chroot(".")`, to put its sandbox root back after a jailbreak daemon replaced it ([`put_root_back`](https://github.com/elripalda/Porpoise-Dolphin-Emulator-for-PS5/blob/2ed1ab5a06995aa198f7bccd4da0f90c3fc29d39/src/porpoise_jailbreak.cpp#L303-L331)) +- [kmq_open, kmq_unlink, kmq_setattr, kmq_timedsend and kmq_timedreceive](../../../core/libs/prx/libkernel_sys/Mqueue.cpp) (libkernel_sys) follow FreeBSD 11 `uipc_mqueue.c` with each open queue on a descriptor reserved on the host null device and the names in a table of this process: `mode` is accepted without checking, the owner and permission checks are not modelled, a queue descriptor cannot be waited on with `select`, `poll` or `kevent`, and `dup` of one does not give a queue - [fchown](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) - ownership is not modelled: the guest's own owner and group (0) and the unchanged value (-1) are accepted, a descriptor that is not open fails with `EBADF`, and any other owner or group throws, naming it. The check reads the descriptor with `fstat`, ignoring the CRT's invalid-parameter handler on Windows as `DescriptorControl` does. The console's ownership rules are unverified. Morrowind (`mshivam019/morrowind-ps5`) imports it From 738379e67a4c56bea30576c99adced64e3d3b5eb Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:47:57 +0100 Subject: [PATCH 08/14] feat(libkernel_sys): implement kmq_notify registration --- .../prx/libkernel_sys/Export.Discovery.cpp | 5 -- core/libs/prx/libkernel_sys/Mqueue.cpp | 53 +++++++++++++++++-- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libkernel_sys/Export.Discovery.cpp b/core/libs/prx/libkernel_sys/Export.Discovery.cpp index 4e5ce3d02d65..99dc97057f01 100644 --- a/core/libs/prx/libkernel_sys/Export.Discovery.cpp +++ b/core/libs/prx/libkernel_sys/Export.Discovery.cpp @@ -198,11 +198,6 @@ int APS5_VABI kldunload_nid_postfix(void) { return 0; } -int APS5_VABI kmq_notify_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI ksem_close_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; diff --git a/core/libs/prx/libkernel_sys/Mqueue.cpp b/core/libs/prx/libkernel_sys/Mqueue.cpp index 5970634c1a04..6afe60e7d4b1 100644 --- a/core/libs/prx/libkernel_sys/Mqueue.cpp +++ b/core/libs/prx/libkernel_sys/Mqueue.cpp @@ -26,6 +26,7 @@ namespace { constexpr int GuestEnoent = 2; constexpr int GuestEbadf = 9; constexpr int GuestEfault = 14; +constexpr int GuestEbusy = 16; constexpr int GuestEexist = 17; constexpr int GuestEinval = 22; constexpr int GuestEnfile = 23; @@ -47,6 +48,10 @@ constexpr std::int64_t DefaultMessages = 10; constexpr std::int64_t DefaultMessageSize = 1024; constexpr unsigned PriorityMax = 64; constexpr std::size_t NameBytes = 256; +constexpr int SigevNone = 0; +constexpr int SigevSignal = 1; +constexpr int SigevThreadId = 4; +constexpr int SignalMax = 128; struct GuestMqAttr { std::int64_t flags; @@ -56,6 +61,11 @@ struct GuestMqAttr { std::int64_t reserved[4]; }; +struct GuestSigevent { + int notify; + int signo; +}; + struct GuestTimespec { std::int64_t seconds; std::int64_t nanoseconds; @@ -73,6 +83,8 @@ struct Queue { std::int64_t maxmsg = DefaultMessages; std::int64_t msgsize = DefaultMessageSize; std::vector messages; + unsigned receivers = 0; + int notifier = -1; }; struct Open { @@ -105,8 +117,16 @@ int ReserveDescriptor() { } void DescriptorClosed(int descriptor) { - std::lock_guard lock(g_mqueueLock); - g_opens.erase(descriptor); + std::shared_ptr closed; + { + std::lock_guard lock(g_mqueueLock); + const auto found = g_opens.find(descriptor); + if (found == g_opens.end()) return; + closed = std::move(found->second); + g_opens.erase(found); + } + std::lock_guard lock(closed->queue->lock); + if (closed->queue->notifier == descriptor) closed->queue->notifier = -1; } const bool g_observerRegistered = [] { @@ -214,7 +234,8 @@ int APS5_VABI kmq_timedsend_nid_postfix(int descriptor, const char* message, std auto position = queue.messages.begin(); while (position != queue.messages.end() && position->priority >= priority) ++position; queue.messages.insert(position, std::move(entry)); - queue.readable.notify_one(); + if (queue.receivers != 0) queue.readable.notify_one(); + else queue.notifier = -1; return 0; } @@ -225,14 +246,38 @@ std::int64_t APS5_VABI kmq_timedreceive_nid_postfix(int descriptor, char* buffer if (length < static_cast(queue.msgsize)) return Fail(GuestEmsgsize); std::unique_lock lock(queue.lock); const auto available = [&] { return !queue.messages.empty(); }; - if (const int error = WaitFor(*open, lock, queue.readable, abstime, available)) return Fail(error); + ++queue.receivers; + const int error = WaitFor(*open, lock, queue.readable, abstime, available); + --queue.receivers; + if (error != 0) return Fail(error); Message entry = std::move(queue.messages.front()); queue.messages.erase(queue.messages.begin()); queue.writable.notify_one(); + if (queue.receivers == 0 && !queue.messages.empty()) queue.notifier = -1; lock.unlock(); if (!entry.bytes.empty()) std::memcpy(buffer, entry.bytes.data(), entry.bytes.size()); if (priority != nullptr) *priority = entry.priority; return static_cast(entry.bytes.size()); } +int APS5_VABI kmq_notify_nid_postfix(int descriptor, const GuestSigevent* event) { + if (event != nullptr) { + if (event->notify != SigevNone && event->notify != SigevSignal && event->notify != SigevThreadId) return Fail(GuestEinval); + if (event->notify != SigevNone && (event->signo <= 0 || event->signo > SignalMax)) return Fail(GuestEinval); + } + const auto open = Find(descriptor); + if (!open) return Fail(GuestEbadf); + auto& queue = *open->queue; + std::lock_guard lock(queue.lock); + if (event == nullptr) { + if (queue.notifier == descriptor) queue.notifier = -1; + return 0; + } + if (queue.notifier != -1) return Fail(GuestEbusy); + if (event->notify != SigevNone) NotImplemented_nid_no_patch("kmq_notify delivering a signal"); + queue.notifier = descriptor; + if (queue.receivers == 0 && !queue.messages.empty()) queue.notifier = -1; + return 0; +} + } From 2d64dc63a4abf3522918dab60392cbf8353ba866 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:47:57 +0100 Subject: [PATCH 09/14] test(libkernel_sys): cover kmq_notify registration, consumption and removal --- core/libs/tests/GuestKernelSysMqueue.cpp | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/core/libs/tests/GuestKernelSysMqueue.cpp b/core/libs/tests/GuestKernelSysMqueue.cpp index 7adc83d92a41..a50e49db087b 100644 --- a/core/libs/tests/GuestKernelSysMqueue.cpp +++ b/core/libs/tests/GuestKernelSysMqueue.cpp @@ -22,6 +22,13 @@ struct MqAttr { std::int64_t reserved[4]; }; +struct Sigevent { + int notify; + int signo; + std::int64_t value; + std::int64_t extra[6]; +}; + struct Timespec { std::int64_t seconds; std::int64_t nanoseconds; @@ -38,12 +45,14 @@ int APS5_VABI kmq_unlink_nid_postfix(const char* path); int APS5_VABI kmq_setattr_nid_postfix(int descriptor, const MqAttr* attr, MqAttr* oattr); int APS5_VABI kmq_timedsend_nid_postfix(int descriptor, const char* message, std::size_t length, unsigned int priority, const Timespec* abstime); std::int64_t APS5_VABI kmq_timedreceive_nid_postfix(int descriptor, char* buffer, std::size_t length, unsigned int* priority, const Timespec* abstime); +int APS5_VABI kmq_notify_nid_postfix(int descriptor, const Sigevent* event); } namespace { constexpr int Enoent = 2; constexpr int Ebadf = 9; +constexpr int Ebusy = 16; constexpr int Efault = 14; constexpr int Eexist = 17; constexpr int Einval = 22; @@ -196,6 +205,38 @@ void Access() { std::filesystem::remove(path); } +void Notify() { + const auto name = Name("notify"); + const MqAttr sixteen{0, 10, 16, 0, {}}; + const int first = kmq_open_nid_postfix(name.c_str(), ORdwr | OCreat, 0600, &sixteen); + const int second = kmq_open_nid_postfix(name.c_str(), ORdwr, 0600, nullptr); + Require(first >= 0 && second >= 0); + const Sigevent none{0, 0, 0, {}}; + const Sigevent thread{2, 0, 0, {}}; + const Sigevent noSignal{1, 0, 0, {}}; + const Sigevent badSignal{1, 129, 0, {}}; + Require(kmq_notify_nid_postfix(first, &thread) == -1 && Error() == Einval); + Require(kmq_notify_nid_postfix(first, &noSignal) == -1 && Error() == Einval); + Require(kmq_notify_nid_postfix(-1, &badSignal) == -1 && Error() == Einval); + Require(kmq_notify_nid_postfix(-1, nullptr) == -1 && Error() == Ebadf); + Require(kmq_notify_nid_postfix(-1, &none) == -1 && Error() == Ebadf); + Require(kmq_notify_nid_postfix(first, &none) == 0); + Require(kmq_notify_nid_postfix(first, &none) == -1 && Error() == Ebusy); + Require(kmq_notify_nid_postfix(second, &none) == -1 && Error() == Ebusy); + Require(kmq_notify_nid_postfix(second, nullptr) == 0); + Require(kmq_notify_nid_postfix(second, &none) == -1 && Error() == Ebusy); + Require(kmq_timedsend_nid_postfix(first, "ring", 4, 0, nullptr) == 0); + Require(kmq_notify_nid_postfix(second, &none) == 0); + Require(kmq_notify_nid_postfix(second, &none) == 0); + Require(Receive(first) == "ring"); + Require(kmq_notify_nid_postfix(first, &none) == 0); + Require(kmq_notify_nid_postfix(first, nullptr) == 0); + Require(kmq_notify_nid_postfix(second, &none) == 0); + Require(close_nid_postfix(second) == 0); + Require(kmq_notify_nid_postfix(first, &none) == 0); + Require(close_nid_postfix(first) == 0 && kmq_unlink_nid_postfix(name.c_str()) == 0); +} + } int main() { @@ -203,6 +244,7 @@ int main() { Messages(); Waiting(); Access(); + Notify(); std::puts("message queues passed"); return 0; } From 9241cdb15bea6d16282d01a0b1c08ee289481520 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 18:47:58 +0100 Subject: [PATCH 10/14] docs(debt): record that libkernel_sys kmq_notify cannot deliver signals --- 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 734ea615227d..0465388d0724 100644 --- a/docs/dev/debt/libkernel_sys.md +++ b/docs/dev/debt/libkernel_sys.md @@ -19,4 +19,5 @@ - [fork](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) throws: creating a child process is not supported. PPSA19111 imports it and fails to load without it. Its engine calls `fork` in `Posix_Daemonize`, only with `-daemonize`, and in `Platform_ShellExecute` before `execvp("xdg-open")`, which the main menu's Previews button reaches, so pressing Previews ends in this throw. [setsid](../../../core/libs/prx/libkernel_sys/Export.cpp) fails with `EPERM`, as FreeBSD's does for a process group leader, since the guest is taken to lead its own process group (see `kill`). [umask](../../../core/libs/prx/libkernel_sys/Export.cpp) keeps the guest's mask (initially 022, masked to 07777) and returns the previous one, Linux named shared-memory creation applies it, but ordinary files are still created with the host process's mask - [chroot](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) follows FreeBSD 11.4's [`sys_chroot`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_syscalls.c#L776-L807) and [`pwd_chroot`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L3059-L3085) for a root caller: `EFAULT` for a null path, `ENOENT` for an empty or missing one, `ENAMETOOLONG` for a path of 1024 bytes or more or a component over 255, and `ENOTDIR` for a path that is not a directory or passes through a file. A directory that is the guest root (`/`, `/..`, or `.` after `fchdir` to a descriptor of `/`) succeeds and changes nothing, as the root stays the same directory; the guest is taken never to have changed its root, so open directory descriptors do not make it fail with `EPERM` (`kern.chroot_allow_open_directories` 1). Any other directory throws, naming the path: the guest path resolver has a fixed root and mount aliases (`/app0`, `/savedata0`) that do not move with it. On the console a title starts in a sandbox root, where `pwd_chroot` refuses with `EPERM` while a directory is open; whether that holds for titles, and whether a title holds `PRIV_VFS_CHROOT`, are unverified. Porpoise (PPSA99764) weak-imports it and calls it only as `fchdir` to its saved descriptor of `/` then `chroot(".")`, to put its sandbox root back after a jailbreak daemon replaced it ([`put_root_back`](https://github.com/elripalda/Porpoise-Dolphin-Emulator-for-PS5/blob/2ed1ab5a06995aa198f7bccd4da0f90c3fc29d39/src/porpoise_jailbreak.cpp#L303-L331)) - [kmq_open, kmq_unlink, kmq_setattr, kmq_timedsend and kmq_timedreceive](../../../core/libs/prx/libkernel_sys/Mqueue.cpp) (libkernel_sys) follow FreeBSD 11 `uipc_mqueue.c` with each open queue on a descriptor reserved on the host null device and the names in a table of this process: `mode` is accepted without checking, the owner and permission checks are not modelled, a queue descriptor cannot be waited on with `select`, `poll` or `kevent`, and `dup` of one does not give a queue +- [kmq_notify](../../../core/libs/prx/libkernel_sys/Mqueue.cpp) (libkernel_sys) registers and removes `SIGEV_NONE` notifications as FreeBSD 11 `kern_kmq_notify` does (`EBUSY` while one is registered, consumed by a message on a queue with no receiver waiting). A `SIGEV_SIGNAL` or `SIGEV_THREAD_ID` registration throws, because delivering a guest signal with its `sigev_value` is not modelled - [fchown](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) - ownership is not modelled: the guest's own owner and group (0) and the unchanged value (-1) are accepted, a descriptor that is not open fails with `EBADF`, and any other owner or group throws, naming it. The check reads the descriptor with `fstat`, ignoring the CRT's invalid-parameter handler on Windows as `DescriptorControl` does. The console's ownership rules are unverified. Morrowind (`mshivam019/morrowind-ps5`) imports it From 38fd999c90f9cd694f2ebbaa631d201848a4c785 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 21:41:57 +0100 Subject: [PATCH 11/14] 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 d821664c0ce40dc30a279343426d99118add3afe Mon Sep 17 00:00:00 2001 From: David Date: Wed, 21 Oct 2026 21:42:16 +0100 Subject: [PATCH 12/14] test(libkernel_sys): open the kmq 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/GuestKernelSysMqueue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/tests/GuestKernelSysMqueue.cpp b/core/libs/tests/GuestKernelSysMqueue.cpp index 7adc83d92a41..4bca92e3bfc0 100644 --- a/core/libs/tests/GuestKernelSysMqueue.cpp +++ b/core/libs/tests/GuestKernelSysMqueue.cpp @@ -186,7 +186,7 @@ void Access() { Require(kmq_timedreceive_nid_postfix(reader, buffer, sizeof(buffer), nullptr, nullptr) == 6); Require(close_nid_postfix(both) == 0 && close_nid_postfix(reader) == 0); Require(kmq_timedreceive_nid_postfix(reader, buffer, sizeof(buffer), nullptr, nullptr) == -1 && Error() == Ebadf); - const auto path = (std::filesystem::temp_directory_path() / "anyps5-mq-stale.bin").string(); + const auto path = "anyps5-mq-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 13/14] 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 14/14] 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`