Repository navigation
Expand file tree
/
Copy pathThread.cpp
More file actions
1437 lines (1322 loc) · 53.6 KB
/
Copy pathThread.cpp
File metadata and controls
1437 lines (1322 loc) · 53.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "prx/libkernel/Pthread/include/ThreadLifecycle.hpp"
#include "prx/libkernel/Pthread/include/Cancel.hpp"
#include "prx/libkernel/include/Api.hpp"
#include "prx/libc/include/Api.hpp"
#include "../include/Pthread.hpp"
#include "../include/ThreadLifecycle.hpp"
#include "../include/WindowsThreadLocal.hpp"
#include "../include/Cancel.hpp"
#include "prx/libkernel/Time/include/Time.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/general/AsmMacros.hpp"
#include "prx/libkernel/KernelErrors.hpp"
#include "prx/libc/include/CpuTopology.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libkernel/DirectMemory/DirectMemory.hpp"
#include <algorithm>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <utility>
#include <vector>
#include <string>
#include <future>
#include <memory>
#include <stdexcept>
#include <thread>
#include <system_error>
#ifndef _WIN32
#include <cerrno>
#include <csetjmp>
#include <csignal>
#include <pthread.h>
#include <sys/mman.h>
#include <unistd.h>
#endif
#ifdef __APPLE__
#include <mach/mach.h>
#endif
#ifdef __linux__
#include <sys/syscall.h>
#else
static const auto initialThreadId = std::this_thread::get_id();
#endif
extern "C" bool IsInitialPthread_nid_no_patch() {
#ifdef __linux__
return ::syscall(SYS_gettid) == ::getpid();
#else
return std::this_thread::get_id() == initialThreadId;
#endif
}
static constexpr int SCE_OK = 0;
static constexpr std::size_t GUEST_THREAD_NAME_CAPACITY = 32;
static constexpr int GUEST_EINVAL = 22;
static constexpr std::size_t HOST_STACK_MARGIN = 1u << 20;
static constexpr int DETACH_DETACHED = 1;
static constexpr std::size_t THREAD_NAME_CAPACITY = 32;
#ifdef _WIN32
#include <windows.h>
#include <process.h>
#include <immintrin.h>
#endif
struct ThreadArgs {
PthreadEntry entry;
void* arg;
PthreadPrivate* self;
#ifndef _WIN32
sigset_t signalMask;
#endif
};
static std::atomic<thread_dtors_func_t> threadDtors{nullptr};
static std::atomic<get_thread_atexit_count_func_t> threadAtexitCount{nullptr};
static std::atomic<thread_atexit_report_func_t> threadAtexitReport{nullptr};
struct GuestThreadState {
PthreadPrivate* current = nullptr;
bool finishing = false;
bool exiting = false;
int cancelState = GUEST_CANCEL_ENABLE;
int cancelType = GUEST_CANCEL_DEFERRED;
CleanupHandler* cleanupHandlers = nullptr;
};
static GuestThreadState& CurrentGuestState() {
#ifdef _WIN32
return WindowsThreadLocal<GuestThreadState>::Get();
#else
static thread_local GuestThreadState state;
return state;
#endif
}
struct StackRegistry {
std::mutex lock;
std::map<PthreadPrivate*, std::pair<std::uintptr_t, std::uintptr_t>> live;
std::map<std::uintptr_t, std::size_t> protectedPages;
};
static StackRegistry& Stacks() {
static auto* registry = new StackRegistry;
return *registry;
}
#if defined(__linux__)
struct GuestStackMapping {
std::uintptr_t mappingEnd;
std::uintptr_t stackStart;
std::uintptr_t stackEnd;
};
static std::mutex guestStackMappingsLock;
static auto& guestStackMappings = *new std::map<std::uintptr_t, GuestStackMapping>();
static void RegisterGuestStackMapping(PthreadPrivate* thread) {
const auto mappingStart = reinterpret_cast<std::uintptr_t>(thread->guestStack);
const auto stackStart = reinterpret_cast<std::uintptr_t>(thread->stackAddress);
std::lock_guard lock(guestStackMappingsLock);
guestStackMappings[mappingStart] = {mappingStart + thread->guestStackBytes, stackStart, stackStart + thread->stackSize};
}
static void UnregisterGuestStackMapping(void* mapping) {
std::lock_guard lock(guestStackMappingsLock);
guestStackMappings.erase(reinterpret_cast<std::uintptr_t>(mapping));
}
#endif
#if defined(__linux__)
static constexpr std::size_t GUEST_STACK_GUARD = PS5_PAGE_SIZE;
struct RetiredStack {
void* address;
std::size_t bytes;
int hostTid;
};
struct FinishedStack {
void* address;
std::size_t bytes;
};
static std::mutex retiredStacksLock;
static std::vector<RetiredStack> retiredStacks;
static std::vector<FinishedStack> spareStacks;
static std::size_t spareStackBytes = 0;
static std::size_t SpareStackLimit() {
static const auto limit = [] {
const auto pages = sysconf(_SC_PHYS_PAGES);
const auto pageSize = sysconf(_SC_PAGESIZE);
if (pages <= 0 || pageSize <= 0) return std::size_t{4u << 20};
const auto total = static_cast<std::uint64_t>(pages) * static_cast<std::uint64_t>(pageSize);
return std::clamp<std::size_t>(static_cast<std::size_t>(total / 1024), 4u << 20, 64u << 20);
}();
return limit;
}
static void ReleaseFinishedStack(const FinishedStack& stack) {
UnregisterGuestStackMapping(stack.address);
DoMunmap(stack.address, stack.bytes);
}
static bool DiscardFinishedStackPages(const FinishedStack& stack) {
auto* usable = static_cast<std::byte*>(stack.address) + GUEST_STACK_GUARD;
const auto bytes = stack.bytes - GUEST_STACK_GUARD;
return madvise(usable, bytes, MADV_DONTNEED) == 0;
}
static void CollectFinishedStack(void* address, std::size_t bytes) {
UnregisterGuestStackMapping(address);
const FinishedStack finished{address, bytes};
if (!DiscardFinishedStackPages(finished)) {
ReleaseFinishedStack(finished);
return;
}
std::vector<FinishedStack> release;
{
std::lock_guard lock(retiredStacksLock);
spareStacks.push_back({address, bytes});
spareStackBytes += bytes;
const auto limit = SpareStackLimit();
while (spareStackBytes > limit && !spareStacks.empty()) {
spareStackBytes -= spareStacks.front().bytes;
release.push_back(spareStacks.front());
spareStacks.erase(spareStacks.begin());
}
}
if (!release.empty()) {
static std::atomic_flag logged = ATOMIC_FLAG_INIT;
if (!logged.test_and_set(std::memory_order_relaxed))
std::fprintf(stderr, "scePthread: spare stack cache reached its host-memory limit; releasing cached mappings\n");
for (const auto& stack : release) ReleaseFinishedStack(stack);
}
}
static bool TakeSpareStack(std::size_t bytes, FinishedStack* stack) {
std::lock_guard lock(retiredStacksLock);
const auto found = std::find_if(spareStacks.begin(), spareStacks.end(), [bytes](const FinishedStack& candidate) { return candidate.bytes == bytes; });
if (found == spareStacks.end()) return false;
*stack = *found;
spareStackBytes -= found->bytes;
spareStacks.erase(found);
return true;
}
static void ReleaseSpareStacks() {
std::vector<FinishedStack> release;
{
std::lock_guard lock(retiredStacksLock);
release.swap(spareStacks);
spareStackBytes = 0;
}
for (const auto& stack : release) ReleaseFinishedStack(stack);
}
static void AllocateGuestStack(PthreadPrivate* thread, std::size_t usableBytes) {
const std::size_t bytes = (usableBytes + PS5_PAGE_SIZE - 1) / PS5_PAGE_SIZE * PS5_PAGE_SIZE + GUEST_STACK_GUARD;
FinishedStack spare{};
if (TakeSpareStack(bytes, &spare)) {
if (DoMprotect(spare.address, spare.bytes, 3) == 0 && DoMprotect(spare.address, GUEST_STACK_GUARD, 0) == 0) {
thread->guestStack = spare.address;
thread->guestStackBytes = spare.bytes;
return;
}
UnregisterGuestStackMapping(spare.address);
DoMunmap(spare.address, spare.bytes);
}
void* stack = nullptr;
if (DoMapAnon(&stack, bytes, 3, 0) != 0) {
ReleaseSpareStacks();
if (DoMapAnon(&stack, bytes, 3, 0) != 0)
throw std::runtime_error("scePthreadCreate: cannot map the guest thread stack");
}
if (DoMprotect(stack, GUEST_STACK_GUARD, 0) != 0) {
DoMunmap(stack, bytes);
throw std::runtime_error("scePthreadCreate: cannot protect the guest thread stack guard");
}
thread->guestStack = stack;
thread->guestStackBytes = bytes;
}
static void FreeGuestStack(PthreadPrivate* thread) {
if (thread->guestStack == nullptr) return;
CollectFinishedStack(thread->guestStack, thread->guestStackBytes);
thread->guestStack = nullptr;
thread->guestStackBytes = 0;
}
static bool HostThreadGone(int hostTid) {
if (hostTid == 0) return false;
char path[48];
std::snprintf(path, sizeof(path), "/proc/self/task/%d", hostTid);
return access(path, F_OK) != 0;
}
static void ReapRetiredStacks() {
std::vector<RetiredStack> ready;
{
std::lock_guard lock(retiredStacksLock);
for (auto it = retiredStacks.begin(); it != retiredStacks.end();) {
if (HostThreadGone(it->hostTid)) {
ready.push_back(*it);
it = retiredStacks.erase(it);
} else {
++it;
}
}
}
for (const auto& stack : ready) CollectFinishedStack(stack.address, stack.bytes);
}
static void RetireGuestStack(PthreadPrivate* thread) {
if (thread->guestStack == nullptr) return;
{
std::lock_guard lock(retiredStacksLock);
retiredStacks.push_back({thread->guestStack, thread->guestStackBytes, thread->hostTid});
}
thread->guestStack = nullptr;
thread->guestStackBytes = 0;
}
#else
static void FreeGuestStack(PthreadPrivate*) {}
static void RetireGuestStack(PthreadPrivate*) {}
#endif
#ifdef _WIN32
static bool CommittedReadWrite(std::uintptr_t begin, std::uintptr_t end) {
for (auto cursor = begin; cursor < end;) {
MEMORY_BASIC_INFORMATION memory{};
if (VirtualQuery(reinterpret_cast<const void*>(cursor), &memory, sizeof(memory)) != sizeof(memory) || memory.RegionSize == 0)
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "Querying the host thread stack");
if (memory.State != MEM_COMMIT || memory.Protect != PAGE_READWRITE) return false;
cursor = reinterpret_cast<std::uintptr_t>(memory.BaseAddress) + memory.RegionSize;
}
return true;
}
static std::uintptr_t PrecommittedStackStart(std::uintptr_t low, std::uintptr_t high) {
SYSTEM_INFO system{};
GetSystemInfo(&system);
const std::uintptr_t start = low + system.dwAllocationGranularity;
return start < high && CommittedReadWrite(start, high) ? start : low;
}
#endif
static bool HostStackLimits(std::uintptr_t* low, std::uintptr_t* high) {
#ifdef _WIN32
ULONG_PTR lowLimit = 0;
ULONG_PTR highLimit = 0;
GetCurrentThreadStackLimits(&lowLimit, &highLimit);
*low = PrecommittedStackStart(lowLimit, highLimit);
*high = highLimit;
#elif defined(__APPLE__)
const pthread_t self = pthread_self();
auto* top = static_cast<std::byte*>(pthread_get_stackaddr_np(self));
const std::size_t size = pthread_get_stacksize_np(self);
if (top == nullptr || size == 0) return false;
*low = reinterpret_cast<std::uintptr_t>(top - size);
*high = reinterpret_cast<std::uintptr_t>(top);
#else
static thread_local std::uintptr_t stackLow = 0;
static thread_local std::uintptr_t stackHigh = 0;
if (stackHigh == 0) {
pthread_attr_t attr;
if (pthread_getattr_np(pthread_self(), &attr) != 0)
return false;
void* address = nullptr;
std::size_t size = 0;
const bool queried = pthread_attr_getstack(&attr, &address, &size) == 0;
pthread_attr_destroy(&attr);
if (!queried || size == 0)
return false;
stackLow = reinterpret_cast<std::uintptr_t>(address);
stackHigh = stackLow + size;
}
*low = stackLow;
*high = stackHigh;
#endif
return *high > *low;
}
static void SetStackFromHost(PthreadPrivate* thread) {
std::uintptr_t low = 0;
std::uintptr_t high = 0;
if (!HostStackLimits(&low, &high)) throw std::runtime_error("Cannot query the host thread stack");
thread->stackAddress = reinterpret_cast<void*>(low);
thread->stackSize = static_cast<std::size_t>(high - low);
}
static bool CurrentStack(std::uintptr_t* low, std::uintptr_t* high) {
if (CurrentGuestState().current && CurrentGuestState().current->stackAddress) {
*low = reinterpret_cast<std::uintptr_t>(CurrentGuestState().current->stackAddress);
*high = *low + CurrentGuestState().current->stackSize;
return true;
}
return HostStackLimits(low, high);
}
static void RegisterStack(PthreadPrivate* self) {
std::uintptr_t low = 0;
std::uintptr_t high = 0;
if (!CurrentStack(&low, &high))
throw std::runtime_error("Cannot query guest thread stack");
auto& stacks = Stacks();
std::lock_guard lock(stacks.lock);
stacks.live[self] = {low, high};
}
static void RestoreStackPages(std::uintptr_t start, std::size_t bytes) noexcept {
#ifdef _WIN32
DWORD previous = 0;
const bool restored = VirtualAlloc(reinterpret_cast<void*>(start), bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr &&
VirtualProtect(reinterpret_cast<void*>(start), bytes, PAGE_READWRITE, &previous) != 0;
#else
const bool restored = ::mprotect(reinterpret_cast<void*>(start), bytes, PROT_READ | PROT_WRITE) == 0;
#endif
if (!restored) std::fprintf(stderr, "[thread] cannot restore the protection of guest stack pages 0x%llx+0x%zx at thread exit\n", static_cast<unsigned long long>(start), bytes);
GuestAllocations::GuestAllocationsInvalidate_nid_postfix(start, bytes);
}
static void ReplaceStackProtection(std::map<std::uintptr_t, std::size_t>& ranges, std::uintptr_t start, std::size_t bytes, bool readWrite) {
const auto end = start + bytes;
auto it = ranges.upper_bound(start);
if (it != ranges.begin() && std::prev(it)->first + std::prev(it)->second > start) --it;
while (it != ranges.end() && it->first < end) {
const auto previousStart = it->first;
const auto previousEnd = previousStart + it->second;
it = ranges.erase(it);
if (previousStart < start) ranges.emplace(previousStart, start - previousStart);
if (previousEnd > end) {
ranges.emplace(end, previousEnd - end);
break;
}
}
if (!readWrite) ranges[start] = bytes;
}
void NoteGuestStackProtection(std::uintptr_t start, std::size_t bytes, bool readWrite) {
auto& stacks = Stacks();
std::lock_guard lock(stacks.lock);
auto replacement = stacks.protectedPages;
ReplaceStackProtection(replacement, start, bytes, readWrite);
stacks.protectedPages.swap(replacement);
}
#ifdef _WIN32
bool ReplaceGuestThreadStack(std::uintptr_t start, std::size_t bytes, bool readWrite, const std::function<bool()>& replace) {
if (bytes == 0 || bytes > std::numeric_limits<std::uintptr_t>::max() - start) return false;
std::uintptr_t low = 0;
std::uintptr_t high = 0;
const bool current = CurrentStack(&low, &high) && start >= low && start + bytes <= high;
constexpr std::uintptr_t HostFrameReserve = 64 * 1024;
const auto frame = reinterpret_cast<std::uintptr_t>(&low);
if (current && (frame < HostFrameReserve || start + bytes > frame - HostFrameReserve)) return false;
auto& stacks = Stacks();
std::lock_guard lock(stacks.lock);
if (!current && std::none_of(stacks.live.begin(), stacks.live.end(), [&](const auto& entry) {
return start >= entry.second.first && start + bytes <= entry.second.second;
})) return false;
auto replacement = stacks.protectedPages;
ReplaceStackProtection(replacement, start, bytes, readWrite);
auto failure = stacks.protectedPages;
ReplaceStackProtection(failure, start, bytes, false);
try {
if (!replace()) return false;
} catch (...) {
stacks.protectedPages.swap(failure);
throw;
}
stacks.protectedPages.swap(replacement);
return true;
}
#endif
static void UnregisterStack(PthreadPrivate* self) {
auto& stacks = Stacks();
std::lock_guard lock(stacks.lock);
if (const auto found = stacks.live.find(self); found != stacks.live.end()) {
const auto [low, high] = found->second;
for (auto it = stacks.protectedPages.begin(); it != stacks.protectedPages.end();) {
if (it->first < high && it->first + it->second > low) {
RestoreStackPages(it->first, it->second);
it = stacks.protectedPages.erase(it);
} else {
++it;
}
}
}
stacks.live.erase(self);
}
bool GuestThreadStack(std::uintptr_t address, std::uintptr_t* start, std::uintptr_t* end) {
std::uintptr_t low = 0;
std::uintptr_t high = 0;
if (CurrentStack(&low, &high) && address >= low && address < high) {
*start = low;
*end = high;
return true;
}
auto& stacks = Stacks();
std::lock_guard lock(stacks.lock);
for (const auto& [thread, range] : stacks.live) {
if (address >= range.first && address < range.second) {
*start = range.first;
*end = range.second;
return true;
}
}
return false;
}
bool GuestThreadStackHostRangeOverlaps(std::uintptr_t start, std::uintptr_t end) {
#if defined(__linux__)
std::lock_guard lock(guestStackMappingsLock);
auto it = guestStackMappings.upper_bound(start);
if (it != guestStackMappings.begin()) --it;
for (; it != guestStackMappings.end() && it->first < end; ++it) {
const auto mappingStart = it->first;
const auto& stack = it->second;
if (start < stack.stackStart && end > mappingStart) return true;
if (start < stack.mappingEnd && end > stack.stackEnd) return true;
}
#else
(void)start;
(void)end;
#endif
return false;
}
struct CpuClockRegistry {
std::mutex lock;
std::map<int, PthreadPrivate*> threads;
int nextThread = 100000;
KernelCpumask processAffinity = DEFAULT_THREAD_AFFINITY;
};
static CpuClockRegistry& CpuClocks() {
static auto* registry = new CpuClockRegistry();
return *registry;
}
PthreadPrivate::PthreadPrivate(const PthreadAttrPrivate* attr) : _finished(false), _retval(nullptr), _detached(false), _adopted(false), _handleStorage(nullptr), _joined(false) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
const auto* parent = CurrentGuestState().current;
const KernelCpumask inherited = parent ? parent->affinity.load(std::memory_order_relaxed) : registry.processAffinity;
affinity.store(attr && attr->_affinityExplicit ? attr->_affinity : inherited, std::memory_order_relaxed);
constexpr int ExplicitSched = 0;
const bool explicitSched = attr && attr->_inheritsched == ExplicitSched;
if (attr) inheritSched = attr->_inheritsched;
const int inheritedPolicy = parent ? parent->schedPolicy.load(std::memory_order_relaxed) : schedPolicy.load(std::memory_order_relaxed);
schedPolicy.store(explicitSched ? attr->_schedpolicy : inheritedPolicy, std::memory_order_relaxed);
const int attrPriority = attr ? attr->_schedpriority : DEFAULT_THREAD_PRIORITY;
priority.store(explicitSched || !parent ? attrPriority : parent->priority.load(std::memory_order_relaxed), std::memory_order_relaxed);
if (registry.nextThread > static_cast<int>(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;
#elif defined(__APPLE__)
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
self->hostMachThread = pthread_mach_thread_np(pthread_self());
self->hostCpuClockBound = true;
#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<int>(CPU_CLOCK_BIT | static_cast<std::uint32_t>(thread->cpuClockThread));
}
void SetLiveGuestThreadsAffinity(KernelCpumask mask) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
registry.processAffinity = mask;
for (const auto& [id, thread] : registry.threads) {
if (!thread->_finished.load(std::memory_order_acquire)) thread->affinity.store(mask, std::memory_order_relaxed);
}
}
KernelCpumask LiveGuestThreadsAffinity() {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
KernelCpumask mask = 0;
for (const auto& [id, thread] : registry.threads) {
if (!thread->_finished.load(std::memory_order_acquire)) mask |= thread->affinity.load(std::memory_order_relaxed);
}
return mask;
}
std::unique_lock<std::mutex> LockLiveGuestThread(const PthreadPrivate* thread) {
auto& registry = CpuClocks();
std::unique_lock lock(registry.lock);
for (const auto& [id, live] : registry.threads) {
if (live == thread && !live->_finished.load(std::memory_order_acquire)) return lock;
}
return {};
}
bool GuestThreadIsLive(const PthreadPrivate* thread) {
return LockLiveGuestThread(thread).owns_lock();
}
extern "C" int ResumeGuestThread_nid_no_patch(PthreadPrivate* thread) {
constexpr int GuestEsrch = 3;
const auto live = LockLiveGuestThread(thread);
if (!live.owns_lock()) return GuestEsrch;
thread->suspended.store(false, std::memory_order_release);
thread->suspended.notify_all();
return 0;
}
extern "C" void ResumeAllGuestThreads_nid_no_patch() {
const auto* self = CurrentGuestState().current;
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
for (const auto& [id, thread] : registry.threads) {
if (thread == self) continue;
thread->suspended.store(false, std::memory_order_release);
thread->suspended.notify_all();
}
}
bool GetLiveGuestThreadAffinity_nid_no_patch(std::int64_t tid, KernelCpumask& mask) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
for (const auto& [id, thread] : registry.threads) {
if (thread->tid != tid || thread->_finished.load(std::memory_order_acquire)) continue;
mask = thread->affinity.load(std::memory_order_relaxed);
return true;
}
return false;
}
bool GetLiveGuestThreadSched_nid_no_patch(std::int64_t tid, int& policy, int& priority) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
for (const auto& [id, thread] : registry.threads) {
if (thread->tid != tid || thread->_finished.load(std::memory_order_acquire)) continue;
policy = thread->schedPolicy.load(std::memory_order_relaxed);
priority = thread->priority.load(std::memory_order_relaxed);
return true;
}
return false;
}
bool SetLiveGuestThreadAffinity_nid_no_patch(std::int64_t tid, KernelCpumask mask) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
for (const auto& [id, thread] : registry.threads) {
if (thread->tid != tid || thread->_finished.load(std::memory_order_acquire)) continue;
thread->affinity.store(mask, std::memory_order_relaxed);
return true;
}
return false;
}
bool LiveGuestThreadExists(std::int64_t tid) {
auto& registry = CpuClocks();
std::lock_guard lock(registry.lock);
for (const auto& [id, thread] : registry.threads) {
if (!thread->_finished.load(std::memory_order_acquire) && thread->tid == tid) return true;
}
return false;
}
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<std::uint64_t>(time.dwHighDateTime) << 32) | time.dwLowDateTime;
};
*nanos = (toTicks(user) + toTicks(kernel)) * 100ULL;
#elif defined(__APPLE__)
if (!thread->hostCpuClockBound) {
*nanos = 0;
return true;
}
thread_basic_info_data_t info{};
mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
if (thread_info(thread->hostMachThread, THREAD_BASIC_INFO, reinterpret_cast<thread_info_t>(&info), &count) != KERN_SUCCESS)
return false;
const auto micros = (static_cast<std::uint64_t>(info.user_time.seconds) + static_cast<std::uint64_t>(info.system_time.seconds)) * 1000000ULL +
static_cast<std::uint64_t>(info.user_time.microseconds) + static_cast<std::uint64_t>(info.system_time.microseconds);
*nanos = micros * 1000ULL;
#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<std::uint64_t>(time.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(time.tv_nsec);
#endif
return true;
}
#ifndef _WIN32
static thread_local std::unique_ptr<PthreadPrivate> adoptedThread;
// pthread_exit force-unwinds through guest frames, whose personality resolves to
// libc.prx's __gxx_personality_v0; that routine cannot read libgcc's unwind context
// and aborts. scePthreadExit instead jumps back to the thread start routine, which,
// like _endthreadex on Windows, skips the guest frames without unwinding them.
static thread_local std::jmp_buf* threadExitJump = nullptr;
static void* MeasureStackReserve(void* reserve) {
std::uintptr_t low = 0;
std::uintptr_t high = 0;
if (HostStackLimits(&low, &high))
*static_cast<std::size_t*>(reserve) = high - reinterpret_cast<std::uintptr_t>(__builtin_frame_address(0));
return nullptr;
}
static std::size_t HostStackReserve() {
static const std::size_t reserve = [] {
std::size_t measured = 0;
pthread_t probe{};
if (const int result = pthread_create(&probe, nullptr, MeasureStackReserve, &measured); result != 0)
throw std::system_error(result, std::generic_category(), "Measuring the host thread stack reserve");
if (const int result = pthread_join(probe, nullptr); result != 0)
throw std::system_error(result, std::generic_category(), "Measuring the host thread stack reserve");
if (measured == 0)
throw std::runtime_error("Cannot measure the host thread stack reserve");
return measured;
}();
return reserve;
}
#endif
void ThreadLifecycle::SetThreadDtors(thread_dtors_func_t callback) {
if (!callback)
throw std::runtime_error("Thread destructor callback is null");
thread_dtors_func_t expected = nullptr;
if (!threadDtors.compare_exchange_strong(expected, callback))
throw std::runtime_error("Thread destructor callback is already registered");
}
void ThreadLifecycle::SetThreadAtexitCount(get_thread_atexit_count_func_t callback) {
if (!callback)
throw std::runtime_error("Thread atexit count callback is null");
get_thread_atexit_count_func_t expected = nullptr;
if (!threadAtexitCount.compare_exchange_strong(expected, callback))
throw std::runtime_error("Thread atexit count callback is already registered");
}
void ThreadLifecycle::SetThreadAtexitReport(thread_atexit_report_func_t callback) {
if (!callback)
throw std::runtime_error("Thread atexit report callback is null");
thread_atexit_report_func_t expected = nullptr;
if (!threadAtexitReport.compare_exchange_strong(expected, callback))
throw std::runtime_error("Thread atexit report callback is already registered");
}
static void finishThread(PthreadPrivate* self, void* retval) {
if (!self || self != CurrentGuestState().current)
throw std::runtime_error("Finishing an unregistered guest thread");
if (CurrentGuestState().finishing)
throw std::runtime_error("Guest thread is already finishing");
CurrentGuestState().finishing = true;
CurrentGuestState().exiting = true;
UnregisterStack(self);
if (const auto callback = threadDtors.load())
callback();
ThreadLifecycle::RunKeyDtors();
{
std::unique_lock<std::mutex> lk(self->_join_mtx);
self->_retval = retval;
self->_finished.store(true, std::memory_order_release);
}
self->_join_cv.NotifyAll();
}
bool ThreadCancel::Requested() {
return CurrentGuestState().current && !CurrentGuestState().exiting && CurrentGuestState().cancelState == GUEST_CANCEL_ENABLE && CurrentGuestState().current->cancelPending.load();
}
void ThreadCancel::Check() {
if (Requested()) scePthreadExit(GUEST_CANCELED);
}
void* ThreadCancel::CleanupMark() {
return CurrentGuestState().cleanupHandlers;
}
void ThreadCancel::CleanupRestore(void* mark) {
CurrentGuestState().cleanupHandlers = static_cast<CleanupHandler*>(mark);
}
void ThreadCancel::BeginWait(TimedWait::Condition* condition) {
if (!CurrentGuestState().current) return;
std::lock_guard lock(CurrentGuestState().current->cancelLock);
CurrentGuestState().current->cancelWait = condition;
}
void ThreadCancel::EndWait() {
BeginWait(nullptr);
}
extern "C" void* APS5_VABI Aps5CallGuestEntry_nid_no_patch(PthreadEntry entry, void* arg);
asm(".text\n"
APS5_ASM_FUNCTION("Aps5CallGuestEntry_nid_no_patch") R"(
.cfi_startproc
push %rbp
.cfi_adjust_cfa_offset 8
.cfi_rel_offset %rbp, 0
push $0
.cfi_adjust_cfa_offset 8
push $0
.cfi_adjust_cfa_offset 8
mov %rsp, %rbp
mov %rdi, %rax
mov %rsi, %rdi
call *%rax
add $16, %rsp
.cfi_adjust_cfa_offset -16
pop %rbp
.cfi_adjust_cfa_offset -8
.cfi_restore %rbp
ret
.cfi_endproc
)" APS5_ASM_FUNCTION_END("Aps5CallGuestEntry_nid_no_patch"));
static void RunThread(std::unique_ptr<ThreadArgs> args) {
APS5_LOG_OUT("RunThread entry=0x%llx arg=%p self=%p", static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(args->entry)), args->arg, static_cast<void*>(args->self));
const auto entry = args->entry;
void* arg = args->arg;
PthreadPrivate* self = args->self;
BindHostCpuClock(self);
TimedWait::BindThreadWaitState(&self->waitCount);
CurrentGuestState().current = self;
RegisterStack(self);
#ifndef _WIN32
const sigset_t signalMask = args->signalMask;
#endif
args.reset();
self->suspended.wait(true, std::memory_order_acquire);
#ifndef _WIN32
pthread_sigmask(SIG_SETMASK, &signalMask, nullptr);
#endif
finishThread(self, Aps5CallGuestEntry_nid_no_patch(entry, arg));
CurrentGuestState().current = nullptr;
}
static void ReleaseThread(PthreadPrivate* thread) {
if (thread->_adopted)
return;
if (thread->references.fetch_sub(1, std::memory_order_acq_rel) != 1)
return;
#ifdef _WIN32
if (thread->wakeEvent)
CloseHandle(static_cast<HANDLE>(thread->wakeEvent));
if (!CloseHandle(thread->nativeHandle))
throw std::system_error(GetLastError(), std::system_category(), "Closing guest thread handle");
#endif
delete thread;
}
static std::mutex joinedLock;
static std::map<Pthread*, PthreadPrivate*> joinedThreads;
static void RetainJoinedThread(PthreadPrivate* thread) {
std::lock_guard lock(joinedLock);
Pthread* const storage = thread->_handleStorage;
const auto found = joinedThreads.find(storage);
if (found != joinedThreads.end() && found->second != thread) ReleaseThread(found->second);
joinedThreads[storage] = thread;
}
static void RecycleJoinedThread(Pthread* storage) {
std::lock_guard lock(joinedLock);
const auto found = joinedThreads.find(storage);
if (found == joinedThreads.end()) return;
PthreadPrivate* joined = found->second;
joinedThreads.erase(found);
ReleaseThread(joined);
}
#ifdef _WIN32
// The title's job workers ("BPE JobWorkerThread CPU0".."CPU12") spin at full load on one core each.
// Pinning them to the efficiency cores of a hybrid CPU (APS5_JOB_AFFINITY=1, with the driver's
// worker pinning) measured 0 to -9 % at the video stage, so the default leaves them free;
// APS5_JOB_AFFINITY_MASK=<hex> picks the cores.
static constexpr const char* JOB_WORKER_PREFIX = "BPE JobWorkerThread";
static std::uint64_t JobWorkerMask() {
static const std::uint64_t mask = [] {
if (std::getenv("APS5_NO_JOB_AFFINITY") != nullptr) return std::uint64_t{0};
const auto requested = CpuTopology::MaskFromEnvironment("APS5_JOB_AFFINITY_MASK");
if (requested != 0) return requested;
if (std::getenv("APS5_JOB_AFFINITY") == nullptr) return std::uint64_t{0};
const auto& layout = CpuTopology::Get();
return layout.hybrid ? layout.efficient : std::uint64_t{0};
}();
return mask;
}
static void ApplyJobAffinity(PthreadPrivate& thread, void* handle) {
if (thread.name.compare(0, std::strlen(JOB_WORKER_PREFIX), JOB_WORKER_PREFIX) != 0) return;
const auto mask = JobWorkerMask();
if (mask == 0) return;
static std::once_flag summary;
std::call_once(summary, [mask] {
const auto& layout = CpuTopology::Get();
std::fprintf(stderr, "[affinity] job worker threads -> 0x%llx (hybrid=%d efficient=0x%llx performant=0x%llx process=0x%llx)\n", static_cast<unsigned long long>(mask), layout.hybrid ? 1 : 0, static_cast<unsigned long long>(layout.efficient), static_cast<unsigned long long>(layout.performant), static_cast<unsigned long long>(layout.process));
});
CpuTopology::PinTraced(thread.name.c_str(), handle, mask);
}
#endif
struct NativeThreadArgs {
std::unique_ptr<ThreadArgs> guest;
std::future<bool> start;
std::promise<void> initialized;
};
#ifdef _WIN32
static unsigned __stdcall StartNativeThread(void* opaque) {
std::unique_ptr<NativeThreadArgs> args(static_cast<NativeThreadArgs*>(opaque));
auto* self = args->guest->self;
try {
ULONG_PTR low = 0;
ULONG_PTR high = 0;
GetCurrentThreadStackLimits(&low, &high);
if (high <= low || high - low < self->stackSize)
throw std::runtime_error("Cannot query guest thread stack");
self->stackAddress = reinterpret_cast<void*>(high - self->stackSize);
if (!CommittedReadWrite(high - self->stackSize, high))
throw std::runtime_error("Guest thread stack is not fully committed");
self->threadId = std::this_thread::get_id();
CurrentGuestState().current = self;
if (!self->name.empty()) {
const std::wstring description(self->name.begin(), self->name.end());
SetThreadDescription(GetCurrentThread(), description.c_str());
ApplyJobAffinity(*self, nullptr);
}
args->initialized.set_value();
} catch (...) {
args->initialized.set_exception(std::current_exception());
return 0;
}
if (!args->start.get())
return 0;
auto guest = std::move(args->guest);
args.reset();
RunThread(std::move(guest));
CurrentGuestState().current = nullptr;
ReleaseThread(self);
return 0;
}
#else
static void* StartNativeThread(void* opaque) {
std::unique_ptr<NativeThreadArgs> args(static_cast<NativeThreadArgs*>(opaque));
auto* self = args->guest->self;
try {
std::uintptr_t low = 0;
std::uintptr_t high = 0;
const auto reserve = HostStackReserve();
if (!HostStackLimits(&low, &high) || high - low < reserve + self->stackSize)
throw std::runtime_error("Cannot query guest thread stack");
self->stackAddress = reinterpret_cast<void*>(high - reserve - self->stackSize);
self->threadId = std::this_thread::get_id();
#if defined(__linux__)
self->hostTid = static_cast<int>(gettid());
RegisterGuestStackMapping(self);
#endif
args->initialized.set_value();
} catch (...) {
args->initialized.set_exception(std::current_exception());
return nullptr;
}
if (!args->start.get())
return nullptr;
auto* guest = args->guest.release();
args.reset();
struct ThreadGuard {
PthreadPrivate* self;
~ThreadGuard() {
CurrentGuestState().current = nullptr;
ReleaseThread(self);
}
} guard{self};
std::jmp_buf exitJump;
if (setjmp(exitJump) == 0) {
threadExitJump = &exitJump;
RunThread(std::unique_ptr<ThreadArgs>(guest));
}
threadExitJump = nullptr;
return nullptr;
}
#endif
extern "C" {
int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name) {
if (!thread || !entry) throw std::runtime_error("scePthreadCreate: null arg");