#include "prx/libkernel/Pthread/include/Mutex.hpp" #include "prx/libkernel/Pthread/include/Cond.hpp" #include "prx/libkernel/include/Api.hpp" #include "prx/libc/include/Api.hpp" #include "prx/libkernel/Time/include/Time.hpp" #include "prx/libkernel/Time/include/TimedWait.hpp" #include "prx/libkernel/Time/include/SleepWake.hpp" #include "prx/libkernel/Pthread/include/Cancel.hpp" #include "prx/libc/include/General.hpp" #include "prx/libc/include/SonyCrt.hpp" #include "prx/libc/include/GuestArena.hpp" #include "prx/libc/include/GuestTime.hpp" #include "prx/libc/include/HostErrno.hpp" #include "prx/libkernel/KernelErrors.hpp" #include "prx/libkernel/Pthread/include/Pthread.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "prx/libc/include/GuestCpu.hpp" #ifdef _WIN32 #include #else #include #include #include #include #ifdef __linux__ #include #include #include #include #include #elif defined(__APPLE__) #include #include #include #endif #endif static constexpr int GUEST_EPERM = 1; static constexpr int GUEST_EIO = 5; static constexpr int GUEST_EFAULT = 14; static constexpr int GUEST_EINVAL = 22; static constexpr int GUEST_CLOCK_THREAD_CPUTIME_ID = 14; static constexpr int GUEST_CLOCK_PROCESS_CPUTIME_ID = 15; static bool ReadGuestTime(void* destination, const void* source, std::size_t bytes) { if (bytes == 0) return true; const auto start = reinterpret_cast(source); if (start == 0 || bytes > UINTPTR_MAX - start) return false; GuestArena::GuestArenaPrepareHostRead_nid_no_patch(source, bytes); #ifdef _WIN32 SIZE_T copied = 0; return ReadProcessMemory(GetCurrentProcess(), source, destination, bytes, &copied) != 0 && copied == bytes; #elif defined(__linux__) iovec local{destination, bytes}; iovec remote{const_cast(source), bytes}; const int saved = errno; const auto copied = ::process_vm_readv(::getpid(), &local, 1, &remote, 1, 0); if (copied < 0 && errno != EFAULT) throw std::runtime_error("time: process_vm_readv failed with errno " + std::to_string(errno)); errno = saved; return copied >= 0 && static_cast(copied) == bytes; #elif defined(__APPLE__) mach_vm_size_t copied = 0; return ::mach_vm_read_overwrite(::mach_task_self(), reinterpret_cast(source), bytes, reinterpret_cast(destination), &copied) == KERN_SUCCESS && copied == bytes; #else throw std::runtime_error("time: checked guest reads are not implemented on this host"); #endif } static bool IsCpuClock(int clockId) { return (static_cast(clockId) & CPU_CLOCK_BIT) != 0; } static std::uint64_t RawMonotonicNanos() { #ifdef _WIN32 return TimedWait::NowNanos(); #else struct timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast(ts.tv_sec) * 1000000000ULL + static_cast(ts.tv_nsec); #endif } // Debug aid: APS5_TIME_SCALE= slows (or speeds) the guest's monotonic clocks and TSC, so a // title running far below its frame rate sees plausible frame times. Sleeps still take real time. static double TimeScale() { static const double scale = [] { const char* value = std::getenv("APS5_TIME_SCALE"); const double parsed = value ? std::strtod(value, nullptr) : 1.0; return parsed > 0.0 ? parsed : 1.0; }(); return scale; } static std::uint64_t ClockOrigin() { static const std::uint64_t origin = RawMonotonicNanos(); return origin; } namespace { struct GuestClockPause { std::mutex mutex; unsigned depth = 0; std::atomic sequence{0}; std::atomic paused{false}; std::atomic pausedAt{0}; std::atomic pausedNanos{0}; }; GuestClockPause& ClockPause() { static GuestClockPause pause; return pause; } } static std::uint64_t PausedRawMonotonicNanos() { auto& pause = ClockPause(); for (;;) { const auto sequence = pause.sequence.load(); if ((sequence & 1u) != 0) continue; const auto now = pause.paused.load() ? pause.pausedAt.load() : RawMonotonicNanos() - pause.pausedNanos.load(); if (pause.sequence.load() == sequence) return now; } } static std::uint64_t GetMonotonicNanos() { if (TimeScale() == 1.0) return PausedRawMonotonicNanos(); const auto origin = ClockOrigin(); const auto raw = PausedRawMonotonicNanos(); return origin + static_cast(static_cast(raw - origin) * TimeScale()); } extern "C" void KernelPauseGuestClock_nid_no_patch() { auto& pause = ClockPause(); std::lock_guard lock(pause.mutex); if (pause.depth++ != 0) return; pause.sequence.fetch_add(1); pause.pausedAt.store(RawMonotonicNanos() - pause.pausedNanos.load()); pause.paused.store(true); pause.sequence.fetch_add(1); } extern "C" void KernelResumeGuestClock_nid_no_patch() { auto& pause = ClockPause(); std::lock_guard lock(pause.mutex); if (pause.depth == 0 || --pause.depth != 0) return; pause.sequence.fetch_add(1); pause.pausedNanos.store(RawMonotonicNanos() - pause.pausedAt.load()); pause.paused.store(false); pause.sequence.fetch_add(1); } static std::uint64_t GetStartNanos() { static const std::uint64_t start = GetMonotonicNanos(); return start; } static const std::uint64_t g_processStart = GetStartNanos(); #ifdef _WIN32 static std::uint64_t APS5_VABI LibcMonotonicNanos() { return GetMonotonicNanos(); } #endif static const bool g_clockSourceInstalled = [] { LibcSetProcessTimeSource_nid_no_patch(&sceKernelGetProcessTime); #ifdef _WIN32 LibcSetMonotonicTimeSource_nid_no_patch(&LibcMonotonicNanos); #endif return true; }(); #ifdef _WIN32 // Every relative wait in the process (winpthreads nanosleep, std::condition_variable::wait_for, the // GPU driver's poll sleeps) rounds up to the scheduler tick, 15.6 ms by default; a console game and // its driver hand labels between queues dozens of times per frame, so the tick is raised to 0.5 ms at // load, and Windows 11 is told not to drop it while the window is unfocused. APS5_NO_TIMER_RESOLUTION=1 // keeps the default for comparison. static const bool g_timerResolutionRaised = [] { if (std::getenv("APS5_NO_TIMER_RESOLUTION") != nullptr) return false; using NtSetTimerResolutionFn = LONG(WINAPI*)(ULONG, BOOLEAN, PULONG); const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); const auto setResolution = ntdll ? reinterpret_cast(reinterpret_cast(GetProcAddress(ntdll, "NtSetTimerResolution"))) : nullptr; ULONG previous = 0; const bool raised = setResolution != nullptr && setResolution(5000, TRUE, &previous) >= 0; PROCESS_POWER_THROTTLING_STATE throttling{}; throttling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION; throttling.ControlMask = PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION; throttling.StateMask = 0; SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &throttling, sizeof(throttling)); using NtQueryTimerResolutionFn = LONG(WINAPI*)(PULONG, PULONG, PULONG); const auto queryResolution = ntdll ? reinterpret_cast(reinterpret_cast(GetProcAddress(ntdll, "NtQueryTimerResolution"))) : nullptr; ULONG minimum = 0, maximum = 0, current = 0; if (queryResolution) queryResolution(&minimum, &maximum, ¤t); const double timerLateUs = TimedWait::Coarse() ? 0.0 : static_cast(TimedWait::TimerLateNanos()) / 1000.0; std::fprintf(stderr, "[time] scheduler tick %s (was %.2f ms, now %.2f ms, timed waits %s, timers fire %.0f us late)\n", raised ? "raised to 0.5 ms" : "unchanged", previous / 10000.0, current / 10000.0, TimedWait::Coarse() ? "coarse" : "fine", timerLateUs); return raised; }(); static void ReportTimedWait(const char* name, const std::function& body) { std::vector samples(200); for (auto& sample : samples) { const std::uint64_t start = TimedWait::NowNanos(); body(); sample = static_cast(TimedWait::NowNanos() - start) / 1000.0; } std::sort(samples.begin(), samples.end()); double sum = 0.0; for (const double sample : samples) sum += sample; std::fprintf(stderr, "[timers] %-44s mean %8.1f p50 %8.1f max %8.1f us\n", name, sum / static_cast(samples.size()), samples[samples.size() / 2], samples.back()); } static const bool g_timerSelfTest = [] { if (std::getenv("APS5_TRACE_TIMERS") == nullptr) return false; std::mutex mutex; std::condition_variable cv; ReportTimedWait("std::condition_variable::wait_for(1 ms)", [&] { std::unique_lock lock(mutex); cv.wait_for(lock, std::chrono::milliseconds(1)); }); PthreadCond cond = nullptr; PthreadMutex guestMutex = nullptr; scePthreadCondInit(&cond, nullptr, nullptr); scePthreadMutexInit(&guestMutex, nullptr, nullptr); scePthreadMutexLock(&guestMutex); ReportTimedWait("scePthreadCondTimedwait(1000 us)", [&] { scePthreadCondTimedwait(&cond, &guestMutex, 1000); }); ReportTimedWait("scePthreadCondTimedwait(13000 us)", [&] { scePthreadCondTimedwait(&cond, &guestMutex, 13000); }); scePthreadMutexUnlock(&guestMutex); scePthreadMutexDestroy(&guestMutex); scePthreadCondDestroy(&cond); ReportTimedWait("sceKernelUsleep(1000)", [&] { sceKernelUsleep_nid_postfix(1000); }); ReportTimedWait("Sleep(1)", [&] { Sleep(1); }); HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr); ReportTimedWait("WaitForSingleObject(event, 1)", [&] { WaitForSingleObject(event, 1); }); CloseHandle(event); HANDLE timer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); ReportTimedWait("high-resolution waitable timer 1 ms", [&] { LARGE_INTEGER due{}; due.QuadPart = -10000; SetWaitableTimer(timer, &due, 0, nullptr, nullptr, FALSE); WaitForSingleObject(timer, INFINITE); }); CloseHandle(timer); return true; }(); #endif namespace { class CurrentCpuPin { public: CurrentCpuPin() { #ifdef _WIN32 previous = SetThreadAffinityMask(GetCurrentThread(), DWORD_PTR{1} << GetCurrentProcessorNumber()); #elif defined(__linux__) const int cpu = sched_getcpu(); if (cpu < 0 || cpu >= CPU_SETSIZE || pthread_getaffinity_np(pthread_self(), sizeof(previous), &previous) != 0) return; cpu_set_t one; CPU_ZERO(&one); CPU_SET(cpu, &one); pinned = pthread_setaffinity_np(pthread_self(), sizeof(one), &one) == 0; #endif } ~CurrentCpuPin() { #ifdef _WIN32 if (previous != 0) SetThreadAffinityMask(GetCurrentThread(), previous); #elif defined(__linux__) if (pinned) pthread_setaffinity_np(pthread_self(), sizeof(previous), &previous); #endif } CurrentCpuPin(const CurrentCpuPin&) = delete; CurrentCpuPin& operator=(const CurrentCpuPin&) = delete; private: #ifdef _WIN32 DWORD_PTR previous = 0; #elif defined(__linux__) cpu_set_t previous{}; bool pinned = false; #endif }; } extern "C" { std::uint64_t APS5_VABI sceKernelGetProcessTime() { const std::uint64_t start = GetStartNanos(); return (GetMonotonicNanos() - start) / 1000ULL; } std::uint64_t APS5_VABI sceKernelGetProcessTimeCounter() { const std::uint64_t nanos = GetMonotonicNanos() - GetStartNanos(); const std::uint64_t frequency = sceKernelGetTscFrequency(); return nanos / 1000000000ULL * frequency + nanos % 1000000000ULL * frequency / 1000000000ULL; } std::uint64_t APS5_VABI sceKernelGetProcessTimeCounterFrequency() { return sceKernelGetTscFrequency(); } static std::string DescribeCallSite(const void* caller) { const auto address = reinterpret_cast(caller); char text[192]; #ifdef _WIN32 const auto image = reinterpret_cast(GetModuleHandleW(nullptr)); std::snprintf(text, sizeof(text), "exe+0x%llx", static_cast(address - image)); #elif defined(__linux__) Dl_info info{}; link_map* map = nullptr; if (dladdr1(caller, &info, reinterpret_cast(&map), RTLD_DL_LINKMAP) == 0 || map == nullptr) { std::snprintf(text, sizeof(text), "0x%llx", static_cast(address)); return text; } const char* path = map->l_name; const char* slash = path == nullptr ? nullptr : std::strrchr(path, '/'); const char* module = path == nullptr || *path == '\0' ? "exe" : slash == nullptr ? path : slash + 1; std::snprintf(text, sizeof(text), "%s+0x%llx", module, static_cast(address - map->l_addr)); #else std::snprintf(text, sizeof(text), "0x%llx", static_cast(address)); #endif return text; } static unsigned long CurrentThreadIdForTrace() { #ifdef _WIN32 return GetCurrentThreadId(); #elif defined(__linux__) return static_cast(gettid()); #else return 0; #endif } // Debug aid: APS5_TRACE_USLEEP reports every 2000 calls which guest call sites sleep, so a CPU // thread polling for GPU or I/O completion can be found (offsets are relative to the executable). static void TraceSleep(const void* caller, std::uint64_t microseconds) { static const bool enabled = std::getenv("APS5_TRACE_USLEEP") != nullptr; if (!enabled) return; static std::mutex mutex; static std::unordered_map> sites; static std::uint64_t calls = 0; std::lock_guard lock(mutex); auto& site = sites[reinterpret_cast(caller)]; ++site.first; site.second += microseconds; if (++calls % 2000 != 0) return; std::vector>> hot(sites.begin(), sites.end()); std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second.first > b.second.first; }); std::fprintf(stderr, "[usleep] %llu calls:", static_cast(calls)); for (std::size_t i = 0; i < hot.size() && i < 6; ++i) std::fprintf(stderr, " %s x%llu (%llu us)", DescribeCallSite(reinterpret_cast(hot[i].first)).c_str(), static_cast(hot[i].second.first), static_cast(hot[i].second.second)); std::fprintf(stderr, "\n"); } void KernelTraceWait_nid_postfix(const char* kind, const void* caller, std::uint64_t waitedNanos, bool timedOut) { if (!KernelTraceWaitEnabled()) return; struct Site { std::uint64_t calls = 0; std::uint64_t timeouts = 0; std::uint64_t nanos = 0; std::uint64_t longest = 0; unsigned long lastThread = 0; }; static std::mutex mutex; static std::unordered_map sites; static std::uint64_t lastReport = 0; static std::unordered_map callSites; char key[224]; const unsigned long thread = CurrentThreadIdForTrace(); std::lock_guard lock(mutex); auto callSite = callSites.find(caller); if (callSite == callSites.end()) callSite = callSites.emplace(caller, DescribeCallSite(caller)).first; std::snprintf(key, sizeof(key), "%s %s", kind, callSite->second.c_str()); auto& site = sites[key]; ++site.calls; site.timeouts += timedOut ? 1u : 0u; site.nanos += waitedNanos; site.longest = std::max(site.longest, waitedNanos); site.lastThread = thread; const auto now = GetMonotonicNanos(); if (lastReport == 0) lastReport = now; if (now - lastReport < 3000000000ULL) return; lastReport = now; std::vector> hot(sites.begin(), sites.end()); std::erase_if(hot, [](const auto& item) { return item.second.calls == 0; }); std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second.nanos > b.second.nanos; }); std::fprintf(stderr, "[waits]"); for (std::size_t i = 0; i < hot.size() && i < 8; ++i) { const auto& s = hot[i].second; std::fprintf(stderr, " | %s x%llu %.1fs (avg %.1f ms, max %.0f ms, %llu timeouts, tid %lu)", hot[i].first.c_str(), static_cast(s.calls), s.nanos / 1e9, s.nanos / 1e6 / static_cast(s.calls), s.longest / 1e6, static_cast(s.timeouts), s.lastThread); } std::fprintf(stderr, "\n"); for (auto& [name, s] : sites) s = Site{}; } static void CancellableSleep(std::uint64_t nanos) { ThreadCancel::Check(); const int savedErrno = errno; if (nanos <= SleepWake::MAX_WAKEABLE_NANOS) { SleepWake::Sleep(nanos); } else { const auto now = TimedWait::NowNanos(); const auto deadline = now + std::min(nanos, std::numeric_limits::max() - now); std::mutex mutex; TimedWait::Condition condition; std::unique_lock lock(mutex); while (!ThreadCancel::Requested() && TimedWait::NowNanos() < deadline) { ThreadCancel::Wait(condition, lock, deadline); } } errno = savedErrno; ThreadCancel::Check(); } static void SleepUntilComplete(std::uint64_t nanos) { ThreadCancel::Check(); SleepWake::Sleep(nanos); ThreadCancel::Check(); } int APS5_VABI sceKernelUsleep_nid_postfix(KernelUseconds microseconds) { TraceSleep(__builtin_return_address(0), microseconds); SleepUntilComplete(static_cast(microseconds) * 1000ULL); return 0; } static int SleepForRequest(const KernelTimespec* rqtp, bool cancellable) { constexpr int guestFault = 14; constexpr int guestInvalid = 22; KernelTimespec request{}; const int savedErrno = errno; const bool readable = ReadGuestTime(&request, rqtp, sizeof(request)); errno = savedErrno; if (!readable) return guestFault; rqtp = &request; if (rqtp->tv_nsec < 0 || rqtp->tv_nsec >= 1000000000LL) return guestInvalid; constexpr std::int64_t longestSleepSeconds = INT32_MAX / 2; if (rqtp->tv_sec >= 0) { const auto nanos = static_cast( std::min(static_cast(rqtp->tv_sec), longestSleepSeconds)) * 1000000000ULL + static_cast(rqtp->tv_nsec); if (cancellable) CancellableSleep(nanos); else SleepUntilComplete(nanos); } return 0; } int APS5_VABI sceKernelNanosleep(const KernelTimespec* rqtp, KernelTimespec* rmtp) { const int error = SleepForRequest(rqtp, false); return error == 0 ? 0 : SceKernelError(error); } int APS5_VABI nanosleep_nid_postfix(const KernelTimespec* rqtp, KernelTimespec* rmtp) { const int error = SleepForRequest(rqtp, true); if (error == 0) return 0; *__error_nid_postfix() = error; return -1; } int APS5_VABI _nanosleep_nid_postfix(const KernelTimespec* rqtp, KernelTimespec* rmtp) { return nanosleep_nid_postfix(rqtp, rmtp); } int APS5_VABI usleep_nid_postfix(KernelUseconds microseconds) { CancellableSleep(static_cast(microseconds) * 1000ULL); return 0; } #ifdef _WIN32 int APS5_VABI ClockTimeWin32ErrorToGuestErrno_nid_no_patch(std::uint32_t error) { if (error == ERROR_NOACCESS) return GUEST_EFAULT; if (error == ERROR_ACCESS_DENIED) return GUEST_EPERM; return GUEST_EIO; } static bool InvariantTsc() { static const bool invariant = GuestCpu::Cpuid(0x80000000u, 0)[0] >= 0x80000007u && (GuestCpu::Cpuid(0x80000007u, 0)[3] & (1u << 8u)) != 0; return invariant; } bool HostThreadCpuNanos_nid_no_patch(void* thread, std::uint64_t* nanos) { if (InvariantTsc()) { const std::uint64_t frequency = HostTscFrequency_nid_no_patch(); ULONG64 cycles = 0; if (!QueryThreadCycleTime(static_cast(thread), &cycles)) return false; *nanos = cycles / frequency * 1000000000ULL + cycles % frequency * 1000000000ULL / frequency; return true; } FILETIME creation{}; FILETIME exitTime{}; FILETIME kernel{}; FILETIME user{}; if (!GetThreadTimes(static_cast(thread), &creation, &exitTime, &kernel, &user)) return false; const auto toTicks = [](const FILETIME& time) { return (static_cast(time.dwHighDateTime) << 32) | time.dwLowDateTime; }; *nanos = (toTicks(user) + toTicks(kernel)) * 100ULL; return true; } static bool ThreadCpuTimeNanos(std::uint64_t* nanos) { if (HostThreadCpuNanos_nid_no_patch(GetCurrentThread(), nanos)) return true; *__error_nid_postfix() = ClockTimeWin32ErrorToGuestErrno_nid_no_patch(GetLastError()); return false; } static bool ProcessCpuTimeNanos(bool countKernel, std::uint64_t* nanos) { FILETIME creation{}; FILETIME exitTime{}; FILETIME kernel{}; FILETIME user{}; if (!GetProcessTimes(GetCurrentProcess(), &creation, &exitTime, &kernel, &user)) { *__error_nid_postfix() = ClockTimeWin32ErrorToGuestErrno_nid_no_patch(GetLastError()); return false; } const auto toTicks = [](const FILETIME& time) { return (static_cast(time.dwHighDateTime) << 32) | time.dwLowDateTime; }; *nanos = (toTicks(user) + (countKernel ? toTicks(kernel) : 0ULL)) * 100ULL; return true; } #else #ifdef __APPLE__ static std::uint64_t CurrentThreadCpuNanos() { thread_basic_info_data_t info{}; mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; if (thread_info(pthread_mach_thread_np(pthread_self()), THREAD_BASIC_INFO, reinterpret_cast(&info), &count) != KERN_SUCCESS) throw std::runtime_error("clock_gettime: thread_info failed"); const auto microseconds = (static_cast(info.user_time.seconds) + static_cast(info.system_time.seconds)) * 1000000ULL + static_cast(info.user_time.microseconds) + static_cast(info.system_time.microseconds); return microseconds * 1000ULL; } #endif static bool ProcessCpuTimeNanos(bool countSystem, std::uint64_t* nanos) { struct rusage usage{}; if (::getrusage(RUSAGE_SELF, &usage) != 0) { *__error_nid_postfix() = GuestErrnoFromHost_nid_no_patch(errno); return false; } const auto toMicros = [](const struct timeval& time) { return static_cast(time.tv_sec) * 1000000ULL + static_cast(time.tv_usec); }; *nanos = (toMicros(usage.ru_utime) + (countSystem ? toMicros(usage.ru_stime) : 0ULL)) * 1000ULL; return true; } #endif static constexpr int SLOW_CLOCK_ID = 20; #ifdef APS5_MQUEUE_TESTING static std::atomic g_realtimeClockHookForTesting{nullptr}; void SetRealtimeClockHookForTesting(RealtimeClockHookForTesting hook) { g_realtimeClockHookForTesting.store(hook, std::memory_order_release); } #endif static int ReadClock(int clockId, KernelTimespec* tp) { #ifdef APS5_MQUEUE_TESTING if (clockId == 0) { if (const auto hook = g_realtimeClockHookForTesting.load(std::memory_order_acquire)) return hook(tp); } #endif if (clockId == 21) { if (ReadClock(2, tp) != 0) return -1; tp->tv_nsec -= tp->tv_nsec % 1000; return 0; } if (clockId == SLOW_CLOCK_ID) { KernelTimespec monotonic{}; if (ReadClock(4, &monotonic) != 0) return -1; constexpr std::int64_t rateDivisor = 64; constexpr std::int64_t ticksPerSecond = 32768; constexpr std::int64_t monotonicTicksPerSecond = ticksPerSecond / rateDivisor; const auto ticks = (monotonic.tv_sec % rateDivisor) * monotonicTicksPerSecond + monotonic.tv_nsec * monotonicTicksPerSecond / 1000000000; tp->tv_sec = monotonic.tv_sec / rateDivisor; tp->tv_nsec = (ticks * 1000000 / ticksPerSecond) * 1000; return 0; } if (IsCpuClock(clockId)) { const int id = static_cast(static_cast(clockId) & CPU_CLOCK_ID_MASK); const bool process = (static_cast(clockId) & CPU_CLOCK_PROCESS_BIT) != 0; if (process && id == getpid_nid_postfix()) return ReadClock(GUEST_CLOCK_PROCESS_CPUTIME_ID, tp); std::uint64_t nanos = 0; if (process || !GuestThreadCpuNanos(id, &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) { std::uint64_t nanos = 0; if (!ProcessCpuTimeNanos(clockId == 2, &nanos)) return -1; tp->tv_sec = static_cast(nanos / 1000000000ULL); tp->tv_nsec = static_cast(nanos % 1000000000ULL); return 0; } #ifdef _WIN32 if (clockId == 0 || clockId == 9) { FILETIME ft{}; GetSystemTimePreciseAsFileTime(&ft); std::uint64_t t = (static_cast(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; t -= 116444736000000000ULL; t *= 100ULL; tp->tv_sec = static_cast(t / 1000000000ULL); tp->tv_nsec = static_cast(t % 1000000000ULL); return 0; } if (clockId == 10 || clockId == 13) { FILETIME ft{}; GetSystemTimeAsFileTime(&ft); std::uint64_t t = (static_cast(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; t -= 116444736000000000ULL; t *= 100ULL; tp->tv_sec = static_cast(t / 1000000000ULL); tp->tv_nsec = clockId == 13 ? 0 : static_cast(t % 1000000000ULL); return 0; } if (clockId == 4 || clockId == 5 || clockId == 7 || clockId == 8 || clockId == 11 || clockId == 12) { std::uint64_t nanos = GetMonotonicNanos(); tp->tv_sec = static_cast(nanos / 1000000000ULL); tp->tv_nsec = static_cast(nanos % 1000000000ULL); return 0; } if (clockId == 14 || clockId == 15) { std::uint64_t nanos = 0; if (!(clockId == 14 ? ThreadCpuTimeNanos(&nanos) : ProcessCpuTimeNanos(true, &nanos))) return -1; tp->tv_sec = static_cast(nanos / 1000000000ULL); tp->tv_nsec = static_cast(nanos % 1000000000ULL); return 0; } throw std::runtime_error(std::string("clock_gettime") + ": unsupported clock_id " + std::to_string(clockId)); #else clockid_t nativeId; switch (clockId) { case 0: case 9: nativeId = CLOCK_REALTIME; break; case 10: case 13: #ifdef CLOCK_REALTIME_COARSE nativeId = CLOCK_REALTIME_COARSE; #else nativeId = CLOCK_REALTIME; #endif break; case 4: case 7: case 11: nativeId = CLOCK_MONOTONIC; break; case 5: case 8: case 12: nativeId = CLOCK_MONOTONIC; break; case 14: nativeId = CLOCK_THREAD_CPUTIME_ID; break; case 15: nativeId = CLOCK_PROCESS_CPUTIME_ID; break; default: throw std::runtime_error(std::string("clock_gettime") + ": unsupported clock_id " + std::to_string(clockId)); } #ifdef __APPLE__ if (clockId == 14) { const std::uint64_t nanos = CurrentThreadCpuNanos(); tp->tv_sec = static_cast(nanos / 1000000000ULL); tp->tv_nsec = static_cast(nanos % 1000000000ULL); return 0; } #endif if (nativeId == CLOCK_MONOTONIC) { const std::uint64_t nanos = PausedRawMonotonicNanos(); tp->tv_sec = static_cast(nanos / 1000000000ULL); tp->tv_nsec = static_cast(nanos % 1000000000ULL); return 0; } struct timespec ts{}; if (clock_gettime(nativeId, &ts) != 0) { return -1; } tp->tv_sec = static_cast(ts.tv_sec); tp->tv_nsec = clockId == 13 ? 0 : static_cast(ts.tv_nsec); return 0; #endif } static bool MeasuredInvalidClock(int clockId) { return clockId == 3 || clockId == 6 || (clockId >= 22 && clockId < 32); } static bool MeasuredIoErrorClock(int clockId) { return clockId >= 16 && clockId <= 19; } int APS5_VABI clock_gettime_nid_postfix(int clockId, KernelTimespec* tp) { if (!IsCpuClock(clockId) && (clockId < 0 || clockId >= 32 || MeasuredInvalidClock(clockId))) { *__error_nid_postfix() = GUEST_EINVAL; return -1; } if (MeasuredIoErrorClock(clockId)) { *__error_nid_postfix() = GUEST_EIO; return -1; } KernelTimespec value{}; if (clockId == GUEST_CLOCK_PROCESS_CPUTIME_ID) { const auto elapsed = GetMonotonicNanos() - GetStartNanos(); value.tv_sec = static_cast(elapsed / 1000000000ULL); value.tv_nsec = static_cast(elapsed % 1000000000ULL); } else if (ReadClock(clockId, &value) != 0) { return -1; } if (tp == nullptr) { *__error_nid_postfix() = GUEST_EFAULT; return -1; } *tp = value; return 0; } int APS5_VABI gettimeofday_nid_postfix(KernelTimeval* output, KernelTimezone* zoneOutput) { KernelTimeval current{}; auto* tv = ¤t; KernelTimezone zone{}; #ifdef _WIN32 FILETIME ft{}; GetSystemTimePreciseAsFileTime(&ft); std::uint64_t t = (static_cast(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; t -= 116444736000000000ULL; tv->tv_sec = static_cast(t / 10000000ULL); tv->tv_usec = static_cast((t % 10000000ULL) / 10ULL); #else struct timeval native{}; if (gettimeofday(&native, nullptr) != 0) { return -1; } tv->tv_sec = static_cast(native.tv_sec); tv->tv_usec = static_cast(native.tv_usec); #endif if (output != nullptr && !GuestCopyOut_nid_no_patch(output, ¤t, sizeof(current))) { *__error_nid_postfix() = 14; return -1; } if (zoneOutput != nullptr && !GuestCopyOut_nid_no_patch(zoneOutput, &zone, sizeof(zone))) { *__error_nid_postfix() = 14; return -1; } return 0; } int APS5_VABI clock_getres_nid_postfix(int clockId, KernelTimespec* res) { if (res == nullptr) return 0; if (IsCpuClock(clockId)) clockId = GUEST_CLOCK_THREAD_CPUTIME_ID; switch (clockId) { case 0: case 4: case 5: case 7: case 8: case 9: case 10: case 11: case 12: *res = {0, 81}; return 0; case 1: case 2: *res = {0, 1000000}; return 0; case 13: *res = {1, 0}; return 0; case GUEST_CLOCK_THREAD_CPUTIME_ID: case 21: *res = {0, 1000}; return 0; default: *__error_nid_postfix() = GUEST_EINVAL; return -1; } } int APS5_VABI clock_settime_nid_postfix(int clockId, const KernelTimespec* tp) { KernelTimespec time{}; if (tp == nullptr || !ReadGuestTime(&time, tp, sizeof(time))) { *__error_nid_postfix() = GUEST_EFAULT; return -1; } static_cast(clockId); *__error_nid_postfix() = GUEST_EPERM; return -1; } int SetTimeOfDay_nid_no_patch(const KernelTimeval* tv, const KernelTimezone* tz) { KernelTimeval time{}; KernelTimezone zone{}; if (tv != nullptr && !ReadGuestTime(&time, tv, sizeof(time))) { *__error_nid_postfix() = GUEST_EFAULT; return -1; } if (tz != nullptr && !ReadGuestTime(&zone, tz, sizeof(zone))) { *__error_nid_postfix() = GUEST_EFAULT; return -1; } *__error_nid_postfix() = GUEST_EPERM; return -1; } // --------------------------------------------------------------------------- // Moved as-is (not yet implemented) from the monolithic libkernel/Export.cpp. // --------------------------------------------------------------------------- static constexpr int SceKernelErrorEfault = static_cast(0x8002000e); using HostZone = SonyHostTimeZone; static HostZone HostZoneAt(std::int64_t utcTime) { return SonyHostZoneAt_nid_no_patch(utcTime); } static std::int64_t HostDaylightAmount(std::int64_t utcTime) { return SonyHostDaylightAmount_nid_no_patch(utcTime); } static KernelTimesec ZoneState(std::int64_t time, const HostZone& zone) { return {time, static_cast(zone.standardEast), static_cast(zone.daylight)}; } int APS5_VABI sceKernelClockGetres(KernelClockid clock_id, KernelTimespec* tp) { if (tp == nullptr) return SceKernelErrorEfault; if (clock_getres_nid_postfix(static_cast(clock_id), tp) != 0) return SceKernelError(*__error_nid_postfix()); return 0; } int APS5_VABI sceKernelClockGettime(KernelClockid clock_id, KernelTimespec* tp) { if (tp == nullptr) return SceKernelErrorEfault; if (clock_gettime_nid_postfix(static_cast(clock_id), tp) != 0) return SceKernelError(*__error_nid_postfix()); return 0; } int APS5_VABI sceKernelConvertLocaltimeToUtc(int64_t local_time, int64_t reserved, int64_t* utc_time, KernelTimesec* timezone, int32_t* dst_seconds) { (void)reserved; const HostZone guess = HostZoneAt(local_time); const HostZone zone = HostZoneAt(local_time - guess.standardEast - guess.daylight); if (utc_time != nullptr) { const int64_t converted = local_time - zone.standardEast - zone.daylight; if (!GuestCopyOut_nid_no_patch(utc_time, &converted, sizeof(converted))) return SceKernelErrorEfault; } if (timezone != nullptr) { const KernelTimesec state = ZoneState(local_time, zone); if (!GuestCopyOut_nid_no_patch(timezone, &state, sizeof(state))) return SceKernelErrorEfault; } if (dst_seconds != nullptr) { const int32_t daylight = static_cast(HostDaylightAmount(local_time - zone.standardEast - zone.daylight)); if (!GuestCopyOut_nid_no_patch(dst_seconds, &daylight, sizeof(daylight))) return SceKernelErrorEfault; } return 0; } int APS5_VABI sceKernelConvertUtcToLocaltime(int64_t utc_time, int64_t* local_time, KernelTimesec* st, int32_t* dst_sec) { const HostZone zone = HostZoneAt(utc_time); if (local_time != nullptr) { const int64_t converted = utc_time + zone.standardEast + zone.daylight; if (!GuestCopyOut_nid_no_patch(local_time, &converted, sizeof(converted))) return SceKernelErrorEfault; } if (st != nullptr) { const KernelTimesec state = ZoneState(utc_time, zone); if (!GuestCopyOut_nid_no_patch(st, &state, sizeof(state))) return SceKernelErrorEfault; } if (dst_sec != nullptr) { const int32_t daylight = static_cast(zone.daylight); if (!GuestCopyOut_nid_no_patch(dst_sec, &daylight, sizeof(daylight))) return SceKernelErrorEfault; } return 0; } int APS5_VABI sceKernelGettimeofday(KernelTimeval* tp) { if (tp == nullptr) return SceKernelErrorEfault; const int result = gettimeofday_nid_postfix(tp, nullptr); return result != 0 && *__error_nid_postfix() == 14 ? SceKernelErrorEfault : result; } namespace { std::mutex guestTimezoneMutex; bool guestTimezoneStored = false; KernelTimezone guestTimezone{}; } void SetGuestTimezone_nid_no_patch(std::int32_t minutesWest, std::int32_t daylightTime) { std::lock_guard lock(guestTimezoneMutex); guestTimezone = KernelTimezone{minutesWest, daylightTime}; guestTimezoneStored = true; } void ResetGuestTimezone_nid_no_patch() { std::lock_guard lock(guestTimezoneMutex); guestTimezoneStored = false; guestTimezone = KernelTimezone{}; } int APS5_VABI sceKernelGettimezone(KernelTimezone* tz) { if (tz == nullptr) return 0; KernelTimezone zone{}; bool stored = false; { std::lock_guard lock(guestTimezoneMutex); stored = guestTimezoneStored; zone = guestTimezone; } if (!stored) { const auto now = static_cast(std::time(nullptr)); zone = KernelTimezone{static_cast(HostZoneAt(now).standardEast / 60), static_cast(HostDaylightAmount(now) / 60)}; } return GuestCopyOut_nid_no_patch(tz, &zone, sizeof(zone)) ? 0 : SceKernelErrorEfault; } uint64_t APS5_VABI sceKernelReadTsc(void) { return GuestCpu::ReadTsc(); } std::uint64_t APS5_VABI HostTscFrequency_nid_no_patch() { static const std::uint64_t frequency = [] { const CurrentCpuPin pin; const std::uint64_t startNanos = RawMonotonicNanos(); const std::uint64_t startTicks = GuestCpu::ReadTsc(); TimedWait::SleepNanos(20000000ULL); const std::uint64_t elapsedNanos = RawMonotonicNanos() - startNanos; const std::uint64_t elapsedTicks = GuestCpu::ReadTsc() - startTicks; return static_cast(static_cast(elapsedTicks) * 1000000000.0L / static_cast(elapsedNanos)); }(); return frequency; } uint64_t APS5_VABI sceKernelGetTscFrequency(void) { static const std::uint64_t frequency = static_cast(static_cast(HostTscFrequency_nid_no_patch()) / TimeScale()); return frequency; } std::int64_t APS5_VABI sceKernelGetCpuFrequency(void) { return static_cast(sceKernelGetTscFrequency()); } unsigned int APS5_VABI sceKernelSleep(unsigned int seconds) { SleepUntilComplete(static_cast(seconds) * 1000000000ULL); return 0; } } namespace { const bool clockResolutionRegistered = (RegisterClockGetres_nid_no_patch(&sceKernelClockGetres), true); }