CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/MemFault.cpp
Views: 1401
1
// Copyright (C) 2020 PPSSPP Project
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include "ppsspp_config.h"
19
20
#include <cstdint>
21
#include <unordered_set>
22
#include <mutex>
23
#include <sstream>
24
25
#include "Common/StringUtils.h"
26
#include "Common/MachineContext.h"
27
28
#if PPSSPP_ARCH(AMD64) || PPSSPP_ARCH(X86)
29
#include "Common/x64Analyzer.h"
30
31
#elif PPSSPP_ARCH(ARM64)
32
#include "Core/Util/DisArm64.h"
33
#elif PPSSPP_ARCH(ARM)
34
#include "ext/disarm.h"
35
#endif
36
37
#include "Common/Log.h"
38
#include "Core/Config.h"
39
#include "Core/Core.h"
40
#include "Core/MemFault.h"
41
#include "Core/MemMap.h"
42
#include "Core/MIPS/JitCommon/JitCommon.h"
43
#include "Core/Debugger/SymbolMap.h"
44
45
// Stack walking stuff
46
#include "Core/MIPS/MIPSStackWalk.h"
47
#include "Core/MIPS/MIPSDebugInterface.h"
48
#include "Core/HLE/sceKernelThread.h"
49
50
namespace Memory {
51
52
static int64_t g_numReportedBadAccesses = 0;
53
const uint8_t *g_lastCrashAddress;
54
MemoryExceptionType g_lastMemoryExceptionType;
55
static bool inCrashHandler = false;
56
57
std::unordered_set<const uint8_t *> g_ignoredAddresses;
58
59
void MemFault_Init() {
60
g_numReportedBadAccesses = 0;
61
g_lastCrashAddress = nullptr;
62
g_lastMemoryExceptionType = MemoryExceptionType::NONE;
63
g_ignoredAddresses.clear();
64
}
65
66
bool MemFault_MayBeResumable() {
67
return g_lastCrashAddress != nullptr;
68
}
69
70
void MemFault_IgnoreLastCrash() {
71
g_ignoredAddresses.insert(g_lastCrashAddress);
72
}
73
74
#ifdef MACHINE_CONTEXT_SUPPORTED
75
76
static bool DisassembleNativeAt(const uint8_t *codePtr, int instructionSize, std::string *dest) {
77
#if PPSSPP_ARCH(AMD64) || PPSSPP_ARCH(X86)
78
auto lines = DisassembleX86(codePtr, instructionSize);
79
if (!lines.empty()) {
80
*dest = lines[0];
81
return true;
82
}
83
#elif PPSSPP_ARCH(ARM64)
84
auto lines = DisassembleArm64(codePtr, instructionSize);
85
if (!lines.empty()) {
86
*dest = lines[0];
87
return true;
88
}
89
#elif PPSSPP_ARCH(ARM)
90
auto lines = DisassembleArm2(codePtr, instructionSize);
91
if (!lines.empty()) {
92
*dest = lines[0];
93
return true;
94
}
95
#elif PPSSPP_ARCH(RISCV64)
96
auto lines = DisassembleRV64(codePtr, instructionSize);
97
if (!lines.empty()) {
98
*dest = lines[0];
99
return true;
100
}
101
#endif
102
return false;
103
}
104
105
bool HandleFault(uintptr_t hostAddress, void *ctx) {
106
if (inCrashHandler)
107
return false;
108
inCrashHandler = true;
109
110
SContext *context = (SContext *)ctx;
111
const uint8_t *codePtr = (uint8_t *)(context->CTX_PC);
112
113
std::lock_guard<std::recursive_mutex> guard(MIPSComp::jitLock);
114
115
// We set this later if we think it can be resumed from.
116
g_lastCrashAddress = nullptr;
117
118
// TODO: Check that codePtr is within the current JIT space.
119
bool inJitSpace = MIPSComp::jit && MIPSComp::jit->CodeInRange(codePtr);
120
if (!inJitSpace) {
121
// This is a crash in non-jitted code. Not something we want to handle here, ignore.
122
// Actually, we could handle crashes from the IR interpreter here, although recovering the call stack
123
// might be tricky...
124
inCrashHandler = false;
125
return false;
126
}
127
128
uintptr_t baseAddress = (uintptr_t)base;
129
#ifdef MASKED_PSP_MEMORY
130
const uintptr_t addressSpaceSize = 0x40000000ULL;
131
#else
132
const uintptr_t addressSpaceSize = 0x100000000ULL;
133
#endif
134
135
// Check whether hostAddress is within the PSP memory space, which (likely) means it was a guest executable that did the bad access.
136
bool invalidHostAddress = hostAddress == (uintptr_t)0xFFFFFFFFFFFFFFFFULL;
137
if (hostAddress < baseAddress || hostAddress >= baseAddress + addressSpaceSize) {
138
// Host address outside - this was a different kind of crash.
139
if (!invalidHostAddress) {
140
inCrashHandler = false;
141
return false;
142
}
143
}
144
145
// OK, a guest executable did a bad access. Let's handle it.
146
147
uint32_t guestAddress = invalidHostAddress ? 0xFFFFFFFFUL : (uint32_t)(hostAddress - baseAddress);
148
149
// TODO: Share the struct between the various analyzers, that will allow us to share most of
150
// the implementations here.
151
bool success = false;
152
153
MemoryExceptionType type = MemoryExceptionType::NONE;
154
155
int instructionSize = 4;
156
#if PPSSPP_ARCH(AMD64) || PPSSPP_ARCH(X86)
157
// X86, X86-64. Variable instruction size so need to analyze the mov instruction in detail.
158
instructionSize = 15;
159
160
// To ignore the access, we need to disassemble the instruction and modify context->CTX_PC
161
LSInstructionInfo info{};
162
success = X86AnalyzeMOV(codePtr, info);
163
if (success)
164
instructionSize = info.instructionSize;
165
#elif PPSSPP_ARCH(ARM64)
166
uint32_t word;
167
memcpy(&word, codePtr, 4);
168
// To ignore the access, we need to disassemble the instruction and modify context->CTX_PC
169
Arm64LSInstructionInfo info{};
170
success = Arm64AnalyzeLoadStore((uint64_t)codePtr, word, &info);
171
#elif PPSSPP_ARCH(ARM)
172
uint32_t word;
173
memcpy(&word, codePtr, 4);
174
// To ignore the access, we need to disassemble the instruction and modify context->CTX_PC
175
ArmLSInstructionInfo info{};
176
success = ArmAnalyzeLoadStore((uint32_t)codePtr, word, &info);
177
#elif PPSSPP_ARCH(RISCV64)
178
// TODO: Put in a disassembler.
179
struct RiscVLSInstructionInfo {
180
int instructionSize;
181
bool isIntegerLoadStore;
182
bool isFPLoadStore;
183
int size;
184
bool isMemoryWrite;
185
};
186
187
uint32_t word;
188
memcpy(&word, codePtr, 4);
189
190
RiscVLSInstructionInfo info{};
191
// Compressed instructions have low bits 00, 01, or 10.
192
info.instructionSize = (word & 3) == 3 ? 4 : 2;
193
instructionSize = info.instructionSize;
194
195
success = true;
196
switch (word & 0x7F) {
197
case 3:
198
info.isIntegerLoadStore = true;
199
info.size = 1 << ((word >> 12) & 3);
200
break;
201
case 7:
202
info.isFPLoadStore = true;
203
info.size = 1 << ((word >> 12) & 3);
204
break;
205
case 35:
206
info.isIntegerLoadStore = true;
207
info.isMemoryWrite = true;
208
info.size = 1 << ((word >> 12) & 3);
209
break;
210
case 39:
211
info.isFPLoadStore = true;
212
info.isMemoryWrite = true;
213
info.size = 1 << ((word >> 12) & 3);
214
break;
215
default:
216
// Compressed instruction.
217
switch (word & 0x6003) {
218
case 0x4000:
219
case 0x4002:
220
case 0x6000:
221
case 0x6002:
222
info.isIntegerLoadStore = true;
223
info.size = (word & 0x2000) != 0 ? 8 : 4;
224
info.isMemoryWrite = (word & 0x8000) != 0;
225
break;
226
case 0x2000:
227
case 0x2002:
228
info.isFPLoadStore = true;
229
info.size = 8;
230
info.isMemoryWrite = (word & 0x8000) != 0;
231
break;
232
default:
233
// Not a read or a write.
234
success = false;
235
break;
236
}
237
break;
238
}
239
#endif
240
241
if (MIPSComp::jit && MIPSComp::jit->IsAtDispatchFetch(codePtr)) {
242
u32 targetAddr = currentMIPS->pc; // bad approximation
243
// TODO: Do the other archs and platforms.
244
#if PPSSPP_ARCH(AMD64) && PPSSPP_PLATFORM(WINDOWS)
245
// We know which register the address is in, look in Asm.cpp.
246
targetAddr = (uint32_t)context->Rax;
247
#endif
248
Core_ExecException(targetAddr, currentMIPS->pc, ExecExceptionType::JUMP);
249
// Redirect execution to a crash handler that will switch to CoreState::CORE_RUNTIME_ERROR immediately.
250
uintptr_t crashHandler = (uintptr_t)MIPSComp::jit->GetCrashHandler();
251
if (crashHandler != 0) {
252
context->CTX_PC = crashHandler;
253
ERROR_LOG(Log::MemMap, "Bad execution access detected, halting: %08x (last known pc %08x, host: %p)", targetAddr, currentMIPS->pc, (void *)hostAddress);
254
inCrashHandler = false;
255
return true;
256
}
257
258
type = MemoryExceptionType::UNKNOWN;
259
} else if (success) {
260
if (info.isMemoryWrite) {
261
type = MemoryExceptionType::WRITE_WORD;
262
} else {
263
type = MemoryExceptionType::READ_WORD;
264
}
265
} else {
266
type = MemoryExceptionType::UNKNOWN;
267
}
268
269
g_lastMemoryExceptionType = type;
270
271
bool handled = true;
272
if (success && (g_Config.bIgnoreBadMemAccess || g_ignoredAddresses.find(codePtr) != g_ignoredAddresses.end())) {
273
if (!info.isMemoryWrite) {
274
// It was a read. Fill the destination register with 0.
275
// TODO
276
}
277
// Move on to the next instruction. Note that handling bad accesses like this is pretty slow.
278
context->CTX_PC += info.instructionSize;
279
g_numReportedBadAccesses++;
280
if (g_numReportedBadAccesses < 100) {
281
ERROR_LOG(Log::MemMap, "Bad memory access detected and ignored: %08x (%p)", guestAddress, (void *)hostAddress);
282
}
283
} else {
284
std::string infoString = "";
285
std::string temp;
286
if (MIPSComp::jit && MIPSComp::jit->DescribeCodePtr(codePtr, temp)) {
287
infoString += temp + "\n";
288
}
289
temp.clear();
290
if (DisassembleNativeAt(codePtr, instructionSize, &temp)) {
291
infoString += temp + "\n";
292
}
293
294
// Either bIgnoreBadMemAccess is off, or we failed recovery analysis.
295
// We can't ignore this memory access.
296
uint32_t approximatePC = currentMIPS->pc;
297
// TODO: Determine access size from the disassembled native instruction. We have some partial info already,
298
// just need to clean it up.
299
Core_MemoryExceptionInfo(guestAddress, 0, approximatePC, type, infoString, true);
300
301
// There's a small chance we can resume from this type of crash.
302
g_lastCrashAddress = codePtr;
303
304
// Redirect execution to a crash handler that will switch to CoreState::CORE_RUNTIME_ERROR immediately.
305
uintptr_t crashHandler = 0;
306
if (MIPSComp::jit)
307
crashHandler = (uintptr_t)MIPSComp::jit->GetCrashHandler();
308
if (crashHandler != 0)
309
context->CTX_PC = crashHandler;
310
else
311
handled = false;
312
ERROR_LOG(Log::MemMap, "Bad memory access detected! %08x (%p) Stopping emulation. Info:\n%s", guestAddress, (void *)hostAddress, infoString.c_str());
313
}
314
315
inCrashHandler = false;
316
return handled;
317
}
318
319
#else
320
321
bool HandleFault(uintptr_t hostAddress, void *ctx) {
322
ERROR_LOG(Log::MemMap, "Exception handling not supported");
323
return false;
324
}
325
326
#endif
327
328
} // namespace Memory
329
330
std::vector<MIPSStackWalk::StackFrame> WalkCurrentStack(int threadID) {
331
DebugInterface *cpuDebug = currentDebugMIPS;
332
333
auto threads = GetThreadsInfo();
334
uint32_t entry = cpuDebug->GetPC();
335
uint32_t stackTop = 0;
336
for (const DebugThreadInfo &th : threads) {
337
if ((threadID == -1 && th.isCurrent) || th.id == threadID) {
338
entry = th.entrypoint;
339
stackTop = th.initialStack;
340
break;
341
}
342
}
343
344
uint32_t ra = cpuDebug->GetRegValue(0, MIPS_REG_RA);
345
uint32_t sp = cpuDebug->GetRegValue(0, MIPS_REG_SP);
346
return MIPSStackWalk::Walk(cpuDebug->GetPC(), ra, sp, entry, stackTop);
347
}
348
349
std::string FormatStackTrace(const std::vector<MIPSStackWalk::StackFrame> &frames) {
350
std::stringstream str;
351
for (const auto &frame : frames) {
352
std::string desc = g_symbolMap->GetDescription(frame.entry);
353
str << StringFromFormat("%s (%08x+%03x, pc: %08x sp: %08x)\n", desc.c_str(), frame.entry, frame.pc - frame.entry, frame.pc, frame.sp);
354
}
355
return str.str();
356
}
357
358