Seregon/ShadPKG

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

C++/47.3 KB/No license
common/signal_context.cpp
ShadPKG / common / signal_context.cpp
1// SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3 
4#include "common/arch.h"
5#include "common/assert.h"
6#include "common/signal_context.h"
7 
8#ifdef _WIN32
9#include <windows.h>
10#else
11#include <sys/ucontext.h>
12#endif
13 
14namespace Common {
15 
16void* GetXmmPointer(void* ctx, u8 index) {
17#if defined(_WIN32)
18#define CASE(index) \
19 case index: \
20 return (void*)(&((EXCEPTION_POINTERS*)ctx)->ContextRecord->Xmm##index.Low)
21#elif defined(__APPLE__)
22#define CASE(index) \
23 case index: \
24 return (void*)(&((ucontext_t*)ctx)->uc_mcontext->__fs.__fpu_xmm##index);
25#else
26#define CASE(index) \
27 case index: \
28 return (void*)(&((ucontext_t*)ctx)->uc_mcontext.fpregs->_xmm[index].element[0])
29#endif
30 switch (index) {
31 CASE(0);
32 CASE(1);
33 CASE(2);
34 CASE(3);
35 CASE(4);
36 CASE(5);
37 CASE(6);
38 CASE(7);
39 CASE(8);
40 CASE(9);
41 CASE(10);
42 CASE(11);
43 CASE(12);
44 CASE(13);
45 CASE(14);
46 CASE(15);
47 default: {
48 UNREACHABLE_MSG("Invalid XMM register index: {}", index);
49 return nullptr;
50 }
51 }
52#undef CASE
53}
54 
55void* GetRip(void* ctx) {
56#if defined(_WIN32)
57 return (void*)((EXCEPTION_POINTERS*)ctx)->ContextRecord->Rip;
58#elif defined(__APPLE__)
59 return (void*)((ucontext_t*)ctx)->uc_mcontext->__ss.__rip;
60#else
61 return (void*)((ucontext_t*)ctx)->uc_mcontext.gregs[REG_RIP];
62#endif
63}
64 
65void IncrementRip(void* ctx, u64 length) {
66#if defined(_WIN32)
67 ((EXCEPTION_POINTERS*)ctx)->ContextRecord->Rip += length;
68#elif defined(__APPLE__)
69 ((ucontext_t*)ctx)->uc_mcontext->__ss.__rip += length;
70#else
71 ((ucontext_t*)ctx)->uc_mcontext.gregs[REG_RIP] += length;
72#endif
73}
74 
75bool IsWriteError(void* ctx) {
76#if defined(_WIN32)
77 return ((EXCEPTION_POINTERS*)ctx)->ExceptionRecord->ExceptionInformation[0] == 1;
78#elif defined(__APPLE__)
79#if defined(ARCH_X86_64)
80 return ((ucontext_t*)ctx)->uc_mcontext->__es.__err & 0x2;
81#elif defined(ARCH_ARM64)
82 return ((ucontext_t*)ctx)->uc_mcontext->__es.__esr & 0x40;
83#endif
84#else
85#if defined(ARCH_X86_64)
86 return ((ucontext_t*)ctx)->uc_mcontext.gregs[REG_ERR] & 0x2;
87#else
88#error "Unsupported architecture"
89#endif
90#endif
91}
92} // namespace Common