Seregon/ShadPKG

A tool for deriving PKG packet encryption keys for ps4 written in c++

C++/47.3 KB/No license
common/thread.cpp
ShadPKG / common / thread.cpp
1// SPDX-FileCopyrightText: 2013 Dolphin Emulator Project
2// SPDX-FileCopyrightText: 2014 Citra Emulator Project
3// SPDX-License-Identifier: GPL-2.0-or-later
4 
5#include <string>
6#include <thread>
7 
8#include "common/error.h"
9#include "common/logging/log.h"
10#include "common/thread.h"
11#include "ntapi.h"
12#ifdef __APPLE__
13#include <mach/mach.h>
14#include <mach/mach_time.h>
15#include <pthread.h>
16#elif defined(_WIN32)
17#include <windows.h>
18#include "common/string_util.h"
19#else
20#if defined(__Bitrig__) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__OpenBSD__)
21#include <pthread_np.h>
22#else
23#include <pthread.h>
24#endif
25#include <sched.h>
26#endif
27#ifndef _WIN32
28#include <unistd.h>
29#endif
30 
31#ifdef __FreeBSD__
32#define cpu_set_t cpuset_t
33#endif
34 
35namespace Common {
36 
37#ifdef __APPLE__
38 
39void SetCurrentThreadRealtime(const std::chrono::nanoseconds period_ns) {
40 // CPU time to grant.
41 const std::chrono::nanoseconds computation_ns = period_ns / 2;
42 
43 // Determine the timebase for converting time to ticks.
44 struct mach_timebase_info timebase {};
45 mach_timebase_info(&timebase);
46 const auto ticks_per_ns =
47 static_cast<double>(timebase.denom) / static_cast<double>(timebase.numer);
48 
49 const auto period_ticks =
50 static_cast<u32>(static_cast<double>(period_ns.count()) * ticks_per_ns);
51 const auto computation_ticks =
52 static_cast<u32>(static_cast<double>(computation_ns.count()) * ticks_per_ns);
53 
54 thread_time_constraint_policy policy = {
55 .period = period_ticks,
56 .computation = computation_ticks,
57 // Should not matter since preemptible is false, but needs to be >= computation regardless.
58 .constraint = computation_ticks,
59 .preemptible = false,
60 };
61 
62 int ret = thread_policy_set(
63 pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY,
64 reinterpret_cast<thread_policy_t>(&policy), THREAD_TIME_CONSTRAINT_POLICY_COUNT);
65 if (ret != KERN_SUCCESS) {
66 LOG_ERROR(Common, "Could not set thread to real-time with period {} ns: {}",
67 period_ns.count(), ret);
68 }
69}
70 
71#else
72 
73void SetCurrentThreadRealtime(const std::chrono::nanoseconds period_ns) {
74 // Not implemented
75}
76 
77#endif
78 
79#ifdef _WIN32
80 
81void SetCurrentThreadPriority(ThreadPriority new_priority) {
82 auto handle = GetCurrentThread();
83 int windows_priority = 0;
84 switch (new_priority) {
85 case ThreadPriority::Low:
86 windows_priority = THREAD_PRIORITY_BELOW_NORMAL;
87 break;
88 case ThreadPriority::Normal:
89 windows_priority = THREAD_PRIORITY_NORMAL;
90 break;
91 case ThreadPriority::High:
92 windows_priority = THREAD_PRIORITY_ABOVE_NORMAL;
93 break;
94 case ThreadPriority::VeryHigh:
95 windows_priority = THREAD_PRIORITY_HIGHEST;
96 break;
97 case ThreadPriority::Critical:
98 windows_priority = THREAD_PRIORITY_TIME_CRITICAL;
99 break;
100 default:
101 windows_priority = THREAD_PRIORITY_NORMAL;
102 break;
103 }
104 SetThreadPriority(handle, windows_priority);
105}
106 
107static void AccurateSleep(std::chrono::nanoseconds duration) {
108 LARGE_INTEGER interval{
109 .QuadPart = -1 * (duration.count() / 100u),
110 };
111 HANDLE timer = ::CreateWaitableTimer(NULL, TRUE, NULL);
112 SetWaitableTimer(timer, &interval, 0, NULL, NULL, 0);
113 WaitForSingleObject(timer, INFINITE);
114 ::CloseHandle(timer);
115}
116 
117#else
118 
119void SetCurrentThreadPriority(ThreadPriority new_priority) {
120 pthread_t this_thread = pthread_self();
121 
122 const auto scheduling_type = SCHED_OTHER;
123 s32 max_prio = sched_get_priority_max(scheduling_type);
124 s32 min_prio = sched_get_priority_min(scheduling_type);
125 u32 level = std::max(static_cast<u32>(new_priority) + 1, 4U);
126 
127 struct sched_param params;
128 if (max_prio > min_prio) {
129 params.sched_priority = min_prio + ((max_prio - min_prio) * level) / 4;
130 } else {
131 params.sched_priority = min_prio - ((min_prio - max_prio) * level) / 4;
132 }
133 
134 pthread_setschedparam(this_thread, scheduling_type, &params);
135}
136 
137static void AccurateSleep(std::chrono::nanoseconds duration) {
138 std::this_thread::sleep_for(duration);
139}
140 
141#endif
142 
143#ifdef _MSC_VER
144 
145// Sets the debugger-visible name of the current thread.
146void SetCurrentThreadName(const char* name) {
147 SetThreadDescription(GetCurrentThread(), UTF8ToUTF16W(name).data());
148}
149 
150void SetThreadName(void* thread, const char* name) {
151 SetThreadDescription(thread, UTF8ToUTF16W(name).data());
152}
153 
154#else // !MSVC_VER, so must be POSIX threads
155 
156// MinGW with the POSIX threading model does not support pthread_setname_np
157#if !defined(_WIN32) || defined(_MSC_VER)
158void SetCurrentThreadName(const char* name) {
159#ifdef __APPLE__
160 pthread_setname_np(name);
161#elif defined(__Bitrig__) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__OpenBSD__)
162 pthread_set_name_np(pthread_self(), name);
163#elif defined(__NetBSD__)
164 pthread_setname_np(pthread_self(), "%s", (void*)name);
165#elif defined(__linux__)
166 // Linux limits thread names to 15 characters and will outright reject any
167 // attempt to set a longer name with ERANGE.
168 std::string truncated(name, std::min(strlen(name), static_cast<std::size_t>(15)));
169 if (int e = pthread_setname_np(pthread_self(), truncated.c_str())) {
170 errno = e;
171 LOG_ERROR(Common, "Failed to set thread name to '{}': {}", truncated, GetLastErrorMsg());
172 }
173#else
174 pthread_setname_np(pthread_self(), name);
175#endif
176}
177 
178void SetThreadName(void* thread, const char* name) {
179 // TODO
180}
181#endif
182 
183#if defined(_WIN32)
184void SetCurrentThreadName(const char*) {
185 // Do Nothing on MinGW
186}
187 
188void SetThreadName(void* thread, const char* name) {
189 // Do Nothing on MinGW
190}
191#endif
192 
193#endif
194 
195AccurateTimer::AccurateTimer(std::chrono::nanoseconds target_interval)
196 : target_interval(target_interval) {}
197 
198void AccurateTimer::Start() {
199 auto begin_sleep = std::chrono::high_resolution_clock::now();
200 if (total_wait.count() > 0) {
201 AccurateSleep(total_wait);
202 }
203 start_time = std::chrono::high_resolution_clock::now();
204 total_wait -= std::chrono::duration_cast<std::chrono::nanoseconds>(start_time - begin_sleep);
205}
206 
207void AccurateTimer::End() {
208 auto now = std::chrono::high_resolution_clock::now();
209 total_wait +=
210 target_interval - std::chrono::duration_cast<std::chrono::nanoseconds>(now - start_time);
211}
212 
213} // namespace Common
214