diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 737f8fa20f62..63bec641c38a 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) @@ -528,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/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/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); 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/Semaphore/src/Ksem.cpp b/core/libs/prx/libkernel/Semaphore/src/Ksem.cpp new file mode 100644 index 000000000000..743b919295b3 --- /dev/null +++ b/core/libs/prx/libkernel/Semaphore/src/Ksem.cpp @@ -0,0 +1,175 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libkernel/Semaphore/include/Ksem.hpp" +#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 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; + 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; +} + +} + +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); + const int descriptor = ReserveDescriptor(); + 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); + if (g_ksems.size() < SemMax) { + g_ksems[descriptor] = std::move(ksem); + return 0; + } + } + close_nid_postfix(descriptor); + return Fail(GuestEnospc); +} + +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)); +} + +} diff --git a/core/libs/prx/libkernel_sys/CMakeLists.txt b/core/libs/prx/libkernel_sys/CMakeLists.txt index 6938d0c456ae..f0a9a36072e4 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 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 8b3da583e470..99dc97057f01 100644 --- a/core/libs/prx/libkernel_sys/Export.Discovery.cpp +++ b/core/libs/prx/libkernel_sys/Export.Discovery.cpp @@ -198,86 +198,21 @@ 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 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; } -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/Mqueue.cpp b/core/libs/prx/libkernel_sys/Mqueue.cpp new file mode 100644 index 000000000000..6afe60e7d4b1 --- /dev/null +++ b/core/libs/prx/libkernel_sys/Mqueue.cpp @@ -0,0 +1,283 @@ +#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 GuestEbusy = 16; +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; +constexpr int SigevNone = 0; +constexpr int SigevSignal = 1; +constexpr int SigevThreadId = 4; +constexpr int SignalMax = 128; + +struct GuestMqAttr { + std::int64_t flags; + std::int64_t maxmsg; + std::int64_t msgsize; + std::int64_t curmsgs; + std::int64_t reserved[4]; +}; + +struct GuestSigevent { + int notify; + int signo; +}; + +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; + unsigned receivers = 0; + int notifier = -1; +}; + +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::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 = [] { + 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)); + if (queue.receivers != 0) queue.readable.notify_one(); + else queue.notifier = -1; + 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(); }; + ++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; +} + +} diff --git a/core/libs/tests/GuestKernelSysKsem.cpp b/core/libs/tests/GuestKernelSysKsem.cpp new file mode 100644 index 000000000000..abb42ae46152 --- /dev/null +++ b/core/libs/tests/GuestKernelSysKsem.cpp @@ -0,0 +1,184 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/general/VabiMacros.hpp" +#include +#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 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); +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 Enospc = 28; +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 = "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); + 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); +} + +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() { + Counting(); + Timed(); + Blocking(); + Identifiers(); + Duplicates(); + Limit(); + std::puts("ksem unnamed semaphores passed"); + return 0; +} diff --git a/core/libs/tests/GuestKernelSysMqueue.cpp b/core/libs/tests/GuestKernelSysMqueue.cpp new file mode 100644 index 000000000000..d7b959575175 --- /dev/null +++ b/core/libs/tests/GuestKernelSysMqueue.cpp @@ -0,0 +1,250 @@ +#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 Sigevent { + int notify; + int signo; + std::int64_t value; + std::int64_t extra[6]; +}; + +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); +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; +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 = "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); + 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); +} + +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() { + OpenRules(); + Messages(); + Waiting(); + Access(); + Notify(); + std::puts("message queues passed"); + return 0; +} diff --git a/docs/dev/debt/libkernel.md b/docs/dev/debt/libkernel.md index 381e5098897f..4c41f6e6f484 100644 --- a/docs/dev/debt/libkernel.md +++ b/docs/dev/debt/libkernel.md @@ -148,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` diff --git a/docs/dev/debt/libkernel_sys.md b/docs/dev/debt/libkernel_sys.md index 25499ae3d143..e08b189ec816 100644 --- a/docs/dev/debt/libkernel_sys.md +++ b/docs/dev/debt/libkernel_sys.md @@ -17,4 +17,6 @@ - [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 +- [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