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/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..a5a892ebd532 --- /dev/null +++ b/core/libs/prx/libkernel/Semaphore/src/Ksem.cpp @@ -0,0 +1,254 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libkernel/Semaphore/include/Ksem.hpp" +#include +#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" int APS5_VABI close_nid_postfix(int descriptor); +extern "C" void RegisterDescriptorCloseObserver_nid_no_patch(void (*observer)(int descriptor)); + +namespace { + +constexpr int GuestEnoent = 2; +constexpr int GuestEfault = 14; +constexpr int GuestEbusy = 16; +constexpr int GuestEexist = 17; +constexpr int GuestEinval = 22; +constexpr int GuestEnfile = 23; +constexpr int GuestEmfile = 24; +constexpr int GuestEnospc = 28; +constexpr int GuestEagain = 35; +constexpr int GuestEtimedout = 60; +constexpr int GuestEnametoolong = 63; +constexpr int GuestEoverflow = 84; +constexpr int GuestOCreat = 0x0200; +constexpr int GuestOExcl = 0x0800; +constexpr std::size_t GuestPathMax = 1024; +constexpr unsigned SemValueMax = 0x7fffffffu; +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; + bool named = false; +}; + +std::mutex g_ksemLock; +std::map> g_ksems; +std::map> g_named; + +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 +} + +std::size_t Objects() { + std::set objects; + for (const auto& [descriptor, ksem] : g_ksems) objects.insert(ksem.get()); + for (const auto& [path, ksem] : g_named) objects.insert(ksem.get()); + return objects.size(); +} + +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 (Objects() < 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 || ksem->named) return Fail(GuestEinval); + { + std::lock_guard lock(ksem->lock); + if (ksem->waiters != 0) return Fail(GuestEbusy); + } + return close_nid_postfix(static_cast(id)); +} + +int APS5_VABI ksem_open_nid_postfix(std::intptr_t* idp, const char* name, int oflag, unsigned int mode, unsigned int value) { + (void)mode; + if ((oflag & ~(GuestOCreat | GuestOExcl)) != 0) return Fail(GuestEinval); + if (value > SemValueMax) return Fail(GuestEinval); + const int descriptor = ReserveDescriptor(); + if (descriptor < 0) return Fail(errno == ENFILE ? GuestEnfile : GuestEmfile); + const auto fail = [descriptor](int error) { + close_nid_postfix(descriptor); + return Fail(error); + }; + if (idp == nullptr) return fail(GuestEfault); + *idp = descriptor; + if (name == nullptr) return fail(GuestEfault); + const std::string path(name, strnlen(name, GuestPathMax)); + if (path.size() >= GuestPathMax) return fail(GuestEnametoolong); + if (path[0] != '/') return fail(GuestEinval); + std::unique_lock lock(g_ksemLock); + std::shared_ptr ksem; + const auto found = g_named.find(path); + if (found == g_named.end()) { + if ((oflag & GuestOCreat) == 0) { + lock.unlock(); + return fail(GuestEnoent); + } + if (Objects() >= SemMax) { + lock.unlock(); + return fail(GuestEnfile); + } + ksem = std::make_shared(); + ksem->count = value; + ksem->named = true; + g_named[path] = ksem; + } else { + if ((oflag & (GuestOCreat | GuestOExcl)) == (GuestOCreat | GuestOExcl)) { + lock.unlock(); + return fail(GuestEexist); + } + ksem = found->second; + } + g_ksems[descriptor] = std::move(ksem); + return 0; +} + +int APS5_VABI ksem_close_nid_postfix(std::intptr_t id) { + const auto ksem = Find(id); + if (!ksem || !ksem->named) return Fail(GuestEinval); + return close_nid_postfix(static_cast(id)); +} + +int APS5_VABI ksem_unlink_nid_postfix(const char* name) { + if (name == nullptr) return Fail(GuestEfault); + const std::string path(name, strnlen(name, GuestPathMax)); + if (path.size() >= GuestPathMax) return Fail(GuestEnametoolong); + std::lock_guard lock(g_ksemLock); + if (g_named.erase(path) == 0) return Fail(GuestEnoent); + return 0; +} + +} diff --git a/core/libs/prx/libkernel_sys/Export.Discovery.cpp b/core/libs/prx/libkernel_sys/Export.Discovery.cpp index 8b3da583e470..ba6f60109da1 100644 --- a/core/libs/prx/libkernel_sys/Export.Discovery.cpp +++ b/core/libs/prx/libkernel_sys/Export.Discovery.cpp @@ -228,56 +228,6 @@ int APS5_VABI kmq_unlink_nid_postfix(void) { return 0; } -int APS5_VABI ksem_close_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI ksem_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/tests/GuestKernelSysKsem.cpp b/core/libs/tests/GuestKernelSysKsem.cpp new file mode 100644 index 000000000000..3db04a6786c2 --- /dev/null +++ b/core/libs/tests/GuestKernelSysKsem.cpp @@ -0,0 +1,252 @@ +#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); +int APS5_VABI ksem_open_nid_postfix(std::intptr_t* idp, const char* name, int oflag, unsigned int mode, unsigned int value); +int APS5_VABI ksem_close_nid_postfix(std::intptr_t id); +int APS5_VABI ksem_unlink_nid_postfix(const char* name); +} + +namespace { + +constexpr int Enoent = 2; +constexpr int Efault = 14; +constexpr int Eexist = 17; +constexpr int Enametoolong = 63; +constexpr int OCreat = 0x0200; +constexpr int OExcl = 0x0800; +constexpr int Ebusy = 16; +constexpr int Einval = 22; +constexpr int Enfile = 23; +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); +} + +void Named() { + const std::string name = "/anyps5-ksem-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); + std::intptr_t first = -1; + std::intptr_t second = -1; + Require(ksem_open_nid_postfix(&first, name.c_str(), 0, 0600, 1) == -1 && Error() == Enoent); + Require(ksem_open_nid_postfix(&first, "relative", OCreat, 0600, 1) == -1 && Error() == Einval); + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat | 0x1, 0600, 1) == -1 && Error() == Einval); + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat, 0600, 0x80000000u) == -1 && Error() == Einval); + Require(ksem_open_nid_postfix(&first, nullptr, OCreat, 0600, 1) == -1 && Error() == Efault); + const std::string longName = "/" + std::string(1100, 'a'); + Require(ksem_open_nid_postfix(&first, longName.c_str(), OCreat, 0600, 1) == -1 && Error() == Enametoolong); + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat, 0600, 1) == 0 && first >= 0); + Require(ksem_open_nid_postfix(&second, name.c_str(), OCreat | OExcl, 0600, 1) == -1 && Error() == Eexist); + Require(ksem_open_nid_postfix(&second, name.c_str(), OCreat, 0600, 9) == 0 && second >= 0 && second != first); + Require(Value(second) == 1); + Require(ksem_post_nid_postfix(first) == 0 && Value(second) == 2); + Require(ksem_destroy_nid_postfix(first) == -1 && Error() == Einval); + std::intptr_t unnamed = -1; + Require(ksem_init_nid_postfix(&unnamed, 0) == 0); + Require(ksem_close_nid_postfix(unnamed) == -1 && Error() == Einval); + Require(ksem_destroy_nid_postfix(unnamed) == 0); + Require(ksem_unlink_nid_postfix(name.c_str()) == 0); + Require(ksem_unlink_nid_postfix(name.c_str()) == -1 && Error() == Enoent); + Require(ksem_unlink_nid_postfix(nullptr) == -1 && Error() == Efault); + std::intptr_t third = -1; + Require(ksem_open_nid_postfix(&third, name.c_str(), 0, 0600, 0) == -1 && Error() == Enoent); + Require(ksem_trywait_nid_postfix(first) == 0 && Value(second) == 1); + Require(ksem_close_nid_postfix(first) == 0); + Require(ksem_post_nid_postfix(first) == -1 && Error() == Einval); + Require(Value(second) == 1); + Require(ksem_close_nid_postfix(second) == 0); + Require(ksem_open_nid_postfix(&third, name.c_str(), OCreat, 0600, 5) == 0 && Value(third) == 5); + Require(ksem_close_nid_postfix(third) == 0 && ksem_unlink_nid_postfix(name.c_str()) == 0); +} + +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); +} + +void NamedLimit() { + const std::string name = "/anyps5-ksem-limit-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); + std::intptr_t written = -1; + Require(ksem_open_nid_postfix(&written, nullptr, OCreat, 0600, 0) == -1 && Error() == Efault && written >= 0); + Require(ksem_post_nid_postfix(written) == -1 && Error() == Einval); + std::intptr_t first = -1; + std::intptr_t second = -1; + Require(ksem_open_nid_postfix(&first, name.c_str(), OCreat, 0600, 0) == 0); + Require(ksem_open_nid_postfix(&second, name.c_str(), 0, 0600, 0) == 0); + std::intptr_t ids[29] = {}; + for (auto& id : ids) Require(ksem_init_nid_postfix(&id, 0) == 0); + Require(ksem_close_nid_postfix(first) == 0 && ksem_close_nid_postfix(second) == 0); + std::intptr_t extra = -1; + Require(ksem_init_nid_postfix(&extra, 0) == -1 && Error() == Enospc); + const std::string other = name + "-other"; + Require(ksem_open_nid_postfix(&extra, other.c_str(), OCreat, 0600, 0) == -1 && Error() == Enfile); + Require(ksem_open_nid_postfix(&first, name.c_str(), 0, 0600, 0) == 0 && ksem_close_nid_postfix(first) == 0); + Require(ksem_unlink_nid_postfix(name.c_str()) == 0); + Require(ksem_init_nid_postfix(&extra, 0) == 0 && ksem_destroy_nid_postfix(extra) == 0); + for (const auto id : ids) Require(ksem_destroy_nid_postfix(id) == 0); +} + +} + +int main() { + Counting(); + Timed(); + Blocking(); + Identifiers(); + Duplicates(); + Limit(); + Named(); + NamedLimit(); + std::puts("ksem unnamed and named semaphores passed"); + return 0; +} diff --git a/docs/dev/debt/libkernel.md b/docs/dev/debt/libkernel.md index 381e5098897f..92dae08bc210 100644 --- a/docs/dev/debt/libkernel.md +++ b/docs/dev/debt/libkernel.md @@ -148,6 +148,8 @@ - [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 +- [ksem_open, ksem_close and ksem_unlink](../../../core/libs/prx/libkernel/Semaphore/src/Ksem.cpp) (libkernel) - named semaphores live in a table of this process, as the guest is one process: `mode` is accepted without checking, and the owner and permission checks of FreeBSD 11 `uipc_sem.c` are not modelled. A name stays linked, and counts toward the 30 semaphores (`ENFILE` for a new name past them), until `ksem_unlink` - [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`