From 942a105c396828f5ab734cfad68cee1c07ca49ef Mon Sep 17 00:00:00 2001 From: Renan Pires Date: Thu, 8 Oct 2026 13:09:02 -0300 Subject: [PATCH] feat(libkernel): implement pthread_getcpuclockid and per-thread CPU clocks --- core/libs/prx/libkernel/CMakeLists.txt | 10 ++ .../prx/libkernel/Pthread/Posix/Thread.cpp | 8 ++ .../prx/libkernel/Pthread/include/Pthread.hpp | 16 ++- .../libs/prx/libkernel/Pthread/src/Thread.cpp | 87 ++++++++++++++ core/libs/prx/libkernel/Time/Time.cpp | 25 ++++ core/libs/tests/GuestThreadCpuClock.cpp | 111 ++++++++++++++++++ 6 files changed, 256 insertions(+), 1 deletion(-) create mode 100644 core/libs/tests/GuestThreadCpuClock.cpp diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 2520ab477..8272c3748 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -230,6 +230,16 @@ if(BUILD_TESTING) set_tests_properties(guest_freebsd_clocks PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(guest_thread_cpu_clock_tests ${LIBS_INCLUDE_DIR}/tests/GuestThreadCpuClock.cpp) + target_include_directories(guest_thread_cpu_clock_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_thread_cpu_clock_tests PRIVATE libkernel libc) + configure_windows_unwind(guest_thread_cpu_clock_tests) + add_test(NAME guest_thread_cpu_clock COMMAND guest_thread_cpu_clock_tests) + set_tests_properties(guest_thread_cpu_clock PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(guest_thread_cpu_clock PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_nanosleep_tests ${LIBS_INCLUDE_DIR}/tests/GuestNanosleep.cpp) target_include_directories(guest_nanosleep_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_nanosleep_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/Pthread/Posix/Thread.cpp b/core/libs/prx/libkernel/Pthread/Posix/Thread.cpp index 66800ba33..61a9bce56 100644 --- a/core/libs/prx/libkernel/Pthread/Posix/Thread.cpp +++ b/core/libs/prx/libkernel/Pthread/Posix/Thread.cpp @@ -76,6 +76,14 @@ int APS5_VABI pthread_equal_nid_postfix(Pthread first, Pthread second) { return first == second; } +int APS5_VABI pthread_getcpuclockid_nid_postfix(Pthread thread, int* clockId) { + constexpr int guestFault = 14; + if (!thread) return PosixThread::GUEST_EINVAL; + if (!clockId) return guestFault; + *clockId = GuestThreadCpuClockId(thread); + return 0; +} + int APS5_VABI sched_yield_nid_postfix(void) { std::this_thread::yield(); return 0; diff --git a/core/libs/prx/libkernel/Pthread/include/Pthread.hpp b/core/libs/prx/libkernel/Pthread/include/Pthread.hpp index 2f3fb16eb..2921795a4 100644 --- a/core/libs/prx/libkernel/Pthread/include/Pthread.hpp +++ b/core/libs/prx/libkernel/Pthread/include/Pthread.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -62,6 +63,9 @@ struct PthreadSemPrivate { static constexpr KernelCpumask DEFAULT_THREAD_AFFINITY = 0x1FFF; static constexpr int DEFAULT_THREAD_PRIORITY = 700; +static constexpr std::uint32_t CPU_CLOCK_BIT = 0x80000000u; +static constexpr std::uint32_t CPU_CLOCK_PROCESS_BIT = 0x40000000u; +static constexpr std::uint32_t CPU_CLOCK_ID_MASK = ~(CPU_CLOCK_BIT | CPU_CLOCK_PROCESS_BIT); struct PthreadAttrPrivate { void* stackAddress = nullptr; @@ -88,6 +92,11 @@ struct PthreadPrivate { std::atomic waitCount{0}; std::atomic affinity{DEFAULT_THREAD_AFFINITY}; std::atomic priority{DEFAULT_THREAD_PRIORITY}; + int cpuClockThread = 0; +#ifndef _WIN32 + clockid_t hostCpuClock{}; + bool hostCpuClockBound = false; +#endif std::mutex nameLock; std::string name; std::atomic _finished; @@ -97,9 +106,14 @@ struct PthreadPrivate { std::mutex _join_mtx; std::condition_variable _join_cv; - PthreadPrivate() : _finished(false), _retval(nullptr), _detached(false), _adopted(false) {} + PthreadPrivate(); + ~PthreadPrivate(); + PthreadPrivate(const PthreadPrivate&) = delete; + PthreadPrivate& operator=(const PthreadPrivate&) = delete; }; bool GuestThreadStack(std::uintptr_t address, std::uintptr_t* start, std::uintptr_t* end); +int GuestThreadCpuClockId(const PthreadPrivate* thread); +bool GuestThreadCpuNanos(int cpuClockThread, std::uint64_t* nanos); #endif diff --git a/core/libs/prx/libkernel/Pthread/src/Thread.cpp b/core/libs/prx/libkernel/Pthread/src/Thread.cpp index b3c368d80..ff49d0255 100644 --- a/core/libs/prx/libkernel/Pthread/src/Thread.cpp +++ b/core/libs/prx/libkernel/Pthread/src/Thread.cpp @@ -17,6 +17,7 @@ #include #ifndef _WIN32 +#include #include #include #endif @@ -119,6 +120,90 @@ bool GuestThreadStack(std::uintptr_t address, std::uintptr_t* start, std::uintpt } return false; } + +struct CpuClockRegistry { + std::mutex lock; + std::map threads; + int nextThread = 100000; +}; + +static CpuClockRegistry& CpuClocks() { + static auto* registry = new CpuClockRegistry(); + return *registry; +} + +PthreadPrivate::PthreadPrivate() : _finished(false), _retval(nullptr), _detached(false), _adopted(false) { + auto& registry = CpuClocks(); + std::lock_guard lock(registry.lock); + if (registry.nextThread > static_cast(CPU_CLOCK_ID_MASK)) + throw std::runtime_error("Guest thread CPU clock identifiers are exhausted"); + cpuClockThread = registry.nextThread++; + registry.threads.emplace(cpuClockThread, this); +} + +PthreadPrivate::~PthreadPrivate() { + auto& registry = CpuClocks(); + std::lock_guard lock(registry.lock); + registry.threads.erase(cpuClockThread); +} + +static void BindHostCpuClock(PthreadPrivate* self) { +#ifdef _WIN32 + (void)self; +#else + clockid_t clock{}; + const int error = pthread_getcpuclockid(pthread_self(), &clock); + if (error != 0) + throw std::system_error(error, std::generic_category(), "Querying the guest thread CPU clock"); + auto& registry = CpuClocks(); + std::lock_guard lock(registry.lock); + self->hostCpuClock = clock; + self->hostCpuClockBound = true; +#endif +} + +int GuestThreadCpuClockId(const PthreadPrivate* thread) { + return static_cast(CPU_CLOCK_BIT | static_cast(thread->cpuClockThread)); +} + +bool GuestThreadCpuNanos(int cpuClockThread, std::uint64_t* nanos) { + auto& registry = CpuClocks(); + std::lock_guard lock(registry.lock); + const auto found = registry.threads.find(cpuClockThread); + if (found == registry.threads.end()) + return false; + PthreadPrivate* thread = found->second; + if (thread->_finished.load(std::memory_order_acquire)) + return false; +#ifdef _WIN32 + if (thread->nativeHandle == nullptr) { + *nanos = 0; + return true; + } + if (WaitForSingleObject(thread->nativeHandle, 0) == WAIT_OBJECT_0) + return false; + FILETIME creation{}; + FILETIME exitTime{}; + FILETIME kernel{}; + FILETIME user{}; + if (!GetThreadTimes(thread->nativeHandle, &creation, &exitTime, &kernel, &user)) + throw std::system_error(GetLastError(), std::system_category(), "Querying guest thread CPU time"); + const auto toTicks = [](const FILETIME& time) { + return (static_cast(time.dwHighDateTime) << 32) | time.dwLowDateTime; + }; + *nanos = (toTicks(user) + toTicks(kernel)) * 100ULL; +#else + if (!thread->hostCpuClockBound) { + *nanos = 0; + return true; + } + struct timespec time{}; + if (clock_gettime(thread->hostCpuClock, &time) != 0) + throw std::system_error(errno, std::generic_category(), "Querying guest thread CPU time"); + *nanos = static_cast(time.tv_sec) * 1000000000ULL + static_cast(time.tv_nsec); +#endif + return true; +} #ifndef _WIN32 static thread_local std::unique_ptr adoptedThread; // pthread_exit force-unwinds through guest frames, whose personality resolves to @@ -174,6 +259,7 @@ static void RunThread(std::unique_ptr args) { const auto entry = args->entry; void* arg = args->arg; PthreadPrivate* self = args->self; + BindHostCpuClock(self); TimedWait::BindThreadWaitState(&self->waitCount); if (!self->stackAddress) SetStackFromHost(self); currentThread = self; @@ -417,6 +503,7 @@ Pthread APS5_VABI scePthreadSelf() { adoptedThread = std::make_unique(); adoptedThread->_detached = true; adoptedThread->_adopted = true; + BindHostCpuClock(adoptedThread.get()); adoptedThread->threadId = std::this_thread::get_id(); SetStackFromHost(adoptedThread.get()); currentThread = adoptedThread.get(); diff --git a/core/libs/prx/libkernel/Time/Time.cpp b/core/libs/prx/libkernel/Time/Time.cpp index 395f85829..da55e9f20 100644 --- a/core/libs/prx/libkernel/Time/Time.cpp +++ b/core/libs/prx/libkernel/Time/Time.cpp @@ -3,6 +3,7 @@ #include "prx/libc/include/General.hpp" #include "prx/libkernel/KernelErrors.hpp" +#include "prx/libkernel/Pthread/include/Pthread.hpp" #include #include #include @@ -29,6 +30,18 @@ extern "C" int* APS5_VABI __error_nid_postfix(); +static constexpr int GUEST_EINVAL = 22; +static constexpr int GUEST_CLOCK_THREAD_CPUTIME_ID = 14; + +static bool IsCpuClock(int clockId) { + const auto bits = static_cast(clockId); + if ((bits & CPU_CLOCK_BIT) == 0) + return false; + if ((bits & CPU_CLOCK_PROCESS_BIT) != 0) + throw std::runtime_error("clock: unsupported process CPU clock_id " + std::to_string(clockId)); + return true; +} + static std::uint64_t RawMonotonicNanos() { #ifdef _WIN32 return TimedWait::NowNanos(); @@ -329,6 +342,16 @@ int APS5_VABI clock_gettime_nid_postfix(int clockId, KernelTimespec* tp) { if (tp == nullptr) { APS5_INVALID_ARG_EX; } + if (IsCpuClock(clockId)) { + std::uint64_t nanos = 0; + if (!GuestThreadCpuNanos(static_cast(static_cast(clockId) & CPU_CLOCK_ID_MASK), &nanos)) { + *__error_nid_postfix() = GUEST_EINVAL; + return -1; + } + tp->tv_sec = static_cast(nanos / 1000000000ULL); + tp->tv_nsec = static_cast(nanos % 1000000000ULL); + return 0; + } if (clockId == 1 || clockId == 2) { const std::uint64_t nanos = ProcessCpuNanos(clockId == 2); tp->tv_sec = static_cast(nanos / 1000000000ULL); @@ -443,6 +466,8 @@ int APS5_VABI clock_getres_nid_postfix(int clockId, KernelTimespec* res) { if (res == nullptr) { APS5_INVALID_ARG_EX; } + if (IsCpuClock(clockId)) + return clock_getres_nid_postfix(GUEST_CLOCK_THREAD_CPUTIME_ID, res); if (clockId == 1 || clockId == 2) { const std::uint64_t nanos = ProcessCpuResolutionNanos(); res->tv_sec = static_cast(nanos / 1000000000ULL); diff --git a/core/libs/tests/GuestThreadCpuClock.cpp b/core/libs/tests/GuestThreadCpuClock.cpp new file mode 100644 index 000000000..058ed0969 --- /dev/null +++ b/core/libs/tests/GuestThreadCpuClock.cpp @@ -0,0 +1,111 @@ +#include "SceTypes.hpp" +#include +#include +#include +#include +#include + +extern "C" { +int APS5_VABI pthread_getcpuclockid_nid_postfix(Pthread thread, int* clockId); +Pthread APS5_VABI pthread_self_nid_postfix(void); +int APS5_VABI clock_gettime_nid_postfix(int clockId, KernelTimespec* tp); +int APS5_VABI clock_getres_nid_postfix(int clockId, KernelTimespec* res); +int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name); +int APS5_VABI scePthreadJoin(Pthread thread, void** retval); +int* APS5_VABI __error_nid_postfix(); +} + +static constexpr int GUEST_EFAULT = 14; +static constexpr int GUEST_EINVAL = 22; +static constexpr int GUEST_CLOCK_MONOTONIC = 4; +static constexpr int GUEST_CLOCK_THREAD_CPUTIME_ID = 14; +static constexpr std::int64_t NANOS_PER_SECOND = 1000000000LL; +static constexpr std::int64_t NANOS_PER_MILLISECOND = 1000000LL; +static constexpr std::int64_t BURN_NANOS = 200 * NANOS_PER_MILLISECOND; +static constexpr std::int64_t TICK_MARGIN_NANOS = 50 * NANOS_PER_MILLISECOND; +static constexpr std::int64_t GIVE_UP_NANOS = 10 * NANOS_PER_SECOND; + +static void Require(bool value) { if (!value) std::abort(); } + +static std::int64_t Nanos(int clockId) { + KernelTimespec time{-1, -1}; + Require(clock_gettime_nid_postfix(clockId, &time) == 0); + Require(time.tv_sec >= 0); + Require(time.tv_nsec >= 0 && time.tv_nsec < NANOS_PER_SECOND); + return time.tv_sec * NANOS_PER_SECOND + time.tv_nsec; +} + +static int CpuClock(Pthread thread) { + int clockId = 0; + Require(pthread_getcpuclockid_nid_postfix(thread, &clockId) == 0); + return clockId; +} + +static void BurnOwnCpu(std::int64_t nanos) { + const std::int64_t wallStart = Nanos(GUEST_CLOCK_MONOTONIC); + const std::int64_t cpuStart = Nanos(GUEST_CLOCK_THREAD_CPUTIME_ID); + while (Nanos(GUEST_CLOCK_THREAD_CPUTIME_ID) - cpuStart < nanos) + Require(Nanos(GUEST_CLOCK_MONOTONIC) - wallStart < GIVE_UP_NANOS); +} + +static std::atomic workerClock{0}; +static std::atomic workerBurned{false}; +static std::atomic releaseWorker{false}; + +static void* APS5_VABI Worker(void*) { + workerClock.store(CpuClock(pthread_self_nid_postfix())); + BurnOwnCpu(BURN_NANOS); + workerBurned.store(true); + while (!releaseWorker.load()) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + return nullptr; +} + +static void OwnClockFollowsThreadCpuTime() { + const int own = CpuClock(pthread_self_nid_postfix()); + Require((static_cast(own) & 0xC0000000u) == 0x80000000u); + Require(CpuClock(pthread_self_nid_postfix()) == own); + const std::int64_t start = Nanos(own); + BurnOwnCpu(BURN_NANOS); + const std::int64_t before = Nanos(own); + const std::int64_t reference = Nanos(GUEST_CLOCK_THREAD_CPUTIME_ID); + const std::int64_t after = Nanos(own); + Require(before - start >= BURN_NANOS - TICK_MARGIN_NANOS); + Require(before <= reference + TICK_MARGIN_NANOS && reference <= after + TICK_MARGIN_NANOS); + KernelTimespec ownResolution{-1, -1}; + KernelTimespec threadResolution{-1, -1}; + Require(clock_getres_nid_postfix(own, &ownResolution) == 0); + Require(clock_getres_nid_postfix(GUEST_CLOCK_THREAD_CPUTIME_ID, &threadResolution) == 0); + Require(ownResolution.tv_sec == threadResolution.tv_sec && ownResolution.tv_nsec == threadResolution.tv_nsec); +} + +static void OtherThreadClockReadsThatThread() { + Pthread worker = nullptr; + Require(scePthreadCreate(&worker, nullptr, Worker, nullptr, "cpu clock worker") == 0); + const std::int64_t wallStart = Nanos(GUEST_CLOCK_MONOTONIC); + while (!workerBurned.load()) { + Require(Nanos(GUEST_CLOCK_MONOTONIC) - wallStart < GIVE_UP_NANOS); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + const int clockId = workerClock.load(); + Require(clockId == CpuClock(worker)); + Require(clockId != CpuClock(pthread_self_nid_postfix())); + const std::int64_t burned = Nanos(clockId); + Require(burned >= BURN_NANOS - TICK_MARGIN_NANOS); + BurnOwnCpu(BURN_NANOS); + Require(Nanos(clockId) - burned <= TICK_MARGIN_NANOS); + releaseWorker.store(true); + Require(scePthreadJoin(worker, nullptr) == 0); + KernelTimespec time{-1, -1}; + *__error_nid_postfix() = 0; + Require(clock_gettime_nid_postfix(clockId, &time) == -1); + Require(*__error_nid_postfix() == GUEST_EINVAL); +} + +int main() { + int clockId = 0; + Require(pthread_getcpuclockid_nid_postfix(nullptr, &clockId) == GUEST_EINVAL); + Require(pthread_getcpuclockid_nid_postfix(pthread_self_nid_postfix(), nullptr) == GUEST_EFAULT); + OwnClockFollowsThreadCpuTime(); + OtherThreadClockReadsThatThread(); +}