-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathcrashlog.cpp
More file actions
479 lines (397 loc) · 15.5 KB
/
crashlog.cpp
File metadata and controls
479 lines (397 loc) · 15.5 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
// this is mostly copied from macos
#include <crashlog.hpp>
#include <crashlogUnix.hpp>
#include <Geode/utils/string.hpp>
#include <Geode/utils/ZStringView.hpp>
#include <tulip/TulipHook.hpp>
#include <thread>
#include <dlfcn.h>
#include <cxxabi.h>
#include <sys/ucontext.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <link.h>
#include <unwind.h>
#include <unwindstack/Maps.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/Unwinder.h>
using namespace geode::prelude;
using namespace crashlog;
using namespace unwindstack;
static constexpr auto crashIndicatorFilename = "lastSessionDidCrash";
static int s_signal = 0;
static std::atomic<int> s_reentrancy{0};
static std::atomic<bool> s_skipSymbols{false};
static siginfo_t* s_siginfo = nullptr;
static ucontext_t* s_context = nullptr;
static struct sigaction s_oldAbort;
static crashlog::CrashContext g_context;
static std::unique_ptr<Maps> g_maps;
static std::shared_ptr<Memory> g_memory;
static int s_pipe[2];
static std::string nameForMap(MapInfo& map) {
auto elf = map.GetElf(g_memory, Regs::CurrentArch());
std::string name = map.name();
if (elf) {
auto soname = elf->GetSoname();
if (!soname.empty()) {
name = soname;
}
}
return name;
}
std::vector<Image> CrashContext::getImages() {
std::vector<Image> images;
images.reserve(256); // on my device it was around 200, with mods it can be much higher
if (!g_maps || s_skipSymbols.load()) return images;
Image current{};
std::string currentName;
auto commit = [&] {
if (current.address != 0) {
images.push_back(std::move(current));
current = Image{};
currentName.clear();
}
};
for (auto& map : *g_maps) {
std::string_view n = map->name();
// ignore very uninteresting ones
if (
n.empty()
|| n == "[page size compat]"
|| n.starts_with("/dev/mali")
|| n.starts_with("/mali")
|| n.starts_with("[anon:")
|| n.starts_with("/dev/__properties__")
|| n.starts_with("/dev/ashmem")
|| n.starts_with("/metadata")
|| n.starts_with("/system/fonts")
|| n.starts_with("/system/usr")
|| n.starts_with("/dmabuf")
|| n.starts_with("/data/user_de/0/com.geode.launcher/cache")
) {
continue;
}
if (map->name() != currentName) {
// new image, commit the previous one
commit();
currentName = map->name();
}
// get the human name, base and size if applicable
// note that current.name is NOT what we have in currentName,
// currentName will be raw name in maps e.g. split_config.apk,
// while the current.name() will be the soname if available
if (current.name_.empty()) {
current.name_ = nameForMap(*map);
}
if (current.address == 0) {
current.address = map->start();
}
current.size = std::max<size_t>(current.size, map->end() - current.address);
}
commit();
// __android_log_print(ANDROID_LOG_DEBUG, "Geode", "Images: %zu", images.size());
// for (auto& img : images) {
// __android_log_print(ANDROID_LOG_DEBUG, "Geode", "Image: %s at %p (size 0x%zx)", img.name().data(), (void*)img.address, img.size);
// }
return images;
}
class GeodeUnwinder : public Unwinder {
public:
GeodeUnwinder(Maps* maps, Regs* regs, std::shared_ptr<Memory> process_memory)
: Unwinder(CrashContext::MAX_FRAMES, maps, regs, process_memory) {}
bool Step(Elf* elf, uint64_t rel_pc, Regs* regs_, Memory* memory, bool* finished, bool* is_signal_frame) override {
// check if it's a tulip function
auto tinfo = tulip::hook::getFunctionInformation((void*)regs_->pc());
if (!tinfo) {
return elf->Step(rel_pc, regs_, memory, finished, is_signal_frame);
}
#ifdef GEODE_IS_ANDROID64
auto regs = static_cast<RegsArm64*>(regs_);
uint64_t sp = regs->sp();
// Compute CFA
uint64_t cfa = sp + 0xc0;
// Read saved registers from stack
uint64_t new_fp, new_pc;
memory->Read64(cfa - 16, &new_fp); // X29
memory->Read64(cfa - 8, &new_pc); // X30
// Apply unwind
regs->set_sp(cfa);
regs->set_pc(new_pc);
(*regs)[29] = new_fp;
#else
auto regs = static_cast<RegsArm*>(regs_);
uint32_t sp = regs->sp();
uint32_t cfa = sp + 0x80;
uint32_t new_fp, new_pc;
memory->Read32(cfa - 4, &new_fp);
memory->Read32(cfa - 8, &new_pc);
// Thumb fix
new_pc |= 1;
// Apply unwind
regs->set_sp(cfa);
regs->set_pc(new_pc);
(*regs)[11] = new_fp; // R11
#endif
return true;
}
};
std::vector<StackFrame> CrashContext::getStacktrace() {
std::vector<StackFrame> frames;
auto jit = CreateJitDebug(Regs::CurrentArch(), g_memory);
auto dex = CreateDexFiles(Regs::CurrentArch(), g_memory);
GeodeUnwinder unwinder(
g_maps.get(),
Regs::CreateFromUcontext(Regs::CurrentArch(), s_context),
g_memory
);
unwinder.SetArch(Regs::CurrentArch());
unwinder.SetResolveNames(!s_skipSymbols);
unwinder.SetJitDebug(jit.get());
unwinder.SetDexFiles(dex.get());
unwinder.Unwind();
for (int i = 0; i < unwinder.NumFrames(); ++i) {
__android_log_print(ANDROID_LOG_DEBUG, "Geode", "Unwinder frame %d: %s", i, unwinder.FormatFrame(i).c_str());
auto& frame = unwinder.frames()[i];
std::string symbol;
uintptr_t offset = 0;
if (!frame.function_name.empty()) {
offset = frame.function_offset;
int status;
auto demangle = abi::__cxa_demangle(frame.function_name.c_str(), 0, 0, &status);
if (status == 0) {
symbol = demangle;
} else {
symbol = frame.function_name;
}
free(demangle);
}
StackFrame sframe {
.address = (uintptr_t)frame.pc,
.symbol = std::move(symbol),
.offset = offset
};
if (frame.map_info) {
// try to find the image using map info, more reliable
std::string name = nameForMap(*frame.map_info);
if (!s_skipSymbols.load()) {
auto it = std::find_if(g_context.images.begin(), g_context.images.end(), [&name](const Image& img) {
return img.name() == name;
});
if (it != g_context.images.end()) {
sframe.image = &*it;
}
} else {
// if skip symbols is set to true, we have no images in g_context, so mark the image name as description
uintptr_t offset = sframe.address - frame.map_info->start();
sframe.description = fmt::format("{} + 0x{:x}", name, offset);
}
// if there is no map info, it is likely a hook handler and will be handled by the common handler
}
frames.push_back(std::move(sframe));
}
return frames;
}
std::vector<Register> CrashContext::getRegisters() {
std::vector<Register> registers;
auto& ss = s_context->uc_mcontext;
#ifdef GEODE_IS_ANDROID64
registers.push_back({ "x0", ss.regs[0] });
registers.push_back({ "x1", ss.regs[1] });
registers.push_back({ "x2", ss.regs[2] });
registers.push_back({ "x3", ss.regs[3] });
registers.push_back({ "x4", ss.regs[4] });
registers.push_back({ "x5", ss.regs[5] });
registers.push_back({ "x6", ss.regs[6] });
registers.push_back({ "x7", ss.regs[7] });
registers.push_back({ "x8", ss.regs[8] });
registers.push_back({ "x9", ss.regs[9] });
registers.push_back({ "x10", ss.regs[10] });
registers.push_back({ "x11", ss.regs[11] });
registers.push_back({ "x12", ss.regs[12] });
registers.push_back({ "x13", ss.regs[13] });
registers.push_back({ "x14", ss.regs[14] });
registers.push_back({ "x15", ss.regs[15] });
registers.push_back({ "x16", ss.regs[16] });
registers.push_back({ "x17", ss.regs[17] });
registers.push_back({ "x18", ss.regs[18] });
registers.push_back({ "x19", ss.regs[19] });
registers.push_back({ "x20", ss.regs[20] });
registers.push_back({ "x21", ss.regs[21] });
registers.push_back({ "x22", ss.regs[22] });
registers.push_back({ "x23", ss.regs[23] });
registers.push_back({ "x24", ss.regs[24] });
registers.push_back({ "x25", ss.regs[25] });
registers.push_back({ "x26", ss.regs[26] });
registers.push_back({ "x27", ss.regs[27] });
registers.push_back({ "x28", ss.regs[28] });
registers.push_back({ "fp", ss.regs[29] });
registers.push_back({ "lr", ss.regs[30] });
registers.push_back({ "sp", ss.sp });
registers.push_back({ "pc", ss.pc });
registers.push_back({ "cpsr", ss.pstate });
#else
registers.push_back({ "r0", ss.arm_r0 });
registers.push_back({ "r1", ss.arm_r1 });
registers.push_back({ "r2", ss.arm_r2 });
registers.push_back({ "r3", ss.arm_r3 });
registers.push_back({ "r4", ss.arm_r4 });
registers.push_back({ "r5", ss.arm_r5 });
registers.push_back({ "r6", ss.arm_r6 });
registers.push_back({ "r7", ss.arm_r7 });
registers.push_back({ "r8", ss.arm_r8 });
registers.push_back({ "r9", ss.arm_r9 });
registers.push_back({ "r10", ss.arm_r10 });
registers.push_back({ "r11", ss.arm_fp });
registers.push_back({ "r12", ss.arm_ip });
registers.push_back({ "sp", ss.arm_sp });
registers.push_back({ "lr", ss.arm_lr });
registers.push_back({ "pc", ss.arm_pc });
registers.push_back({ "cpsr", ss.arm_cpsr });
#endif
return registers;
}
std::string_view CrashContext::getGeodeBinaryName() {
return "Geode.so";
}
/// Source: https://cs.android.com/android/platform/superproject/main/+/main:bionic/libc/bionic/android_set_abort_message.cpp
struct abort_message_t {
uint64_t magic1;
uint64_t magic2;
size_t size;
char msg[0];
};
static std::string getAbortMessage() {
if (s_signal != SIGABRT) {
return "";
}
for (size_t i = 0; i < g_maps->Total(); i++) {
auto map = g_maps->Get(i);
if (map->name() != "[anon:abort message]") continue;
auto start = (abort_message_t const*)map->start();
if (start->magic1 != 0xb18e40886ac388f0ULL || start->magic2 != 0xc6dfba755a1de0b5ULL) {
continue;
}
return std::string(start->msg);
}
return "";
}
void CrashContext::writeInfo(Buffer& stream) {
auto image = this->imageFromAddress(crashAddr);
stream.append("Faulty Lib: {}\n", image ? image->name() : "<Unknown>");
stream.append("Faulty Mod: {} ({})\n", faultyMod ? faultyMod->getID() : "<Unknown>", faultyMod ? faultyMod->getHash() : "N/A");
stream.append("Instruction Address: ");
this->formatAddress(crashAddr, infoStream);
stream.append("\nSignal: {}, code {} ({})\n", s_siginfo->si_signo, s_siginfo->si_code, getSignalCodeString(s_signal, s_siginfo));
if (hasSignalDetail(s_signal)) {
stream.append("Signal Detail: ");
writeSignalDetail(stream, g_context, s_signal, s_siginfo);
stream.append('\n');
}
auto abortMsg = getAbortMessage();
if (!abortMsg.empty()) {
stream.append("Abort message: {}\n", abortMsg);
}
int reentrancy = s_reentrancy.load();
if (reentrancy > 1) {
stream.append("Note: The crash handler crashed while processing the real crash, so this log does not cover the real crash.\n"
"Please report this to the Geode Team. (reentrancy: {})\n",
reentrancy
);
}
}
extern "C" void signalHandler(int signal, siginfo_t* signalInfo, void* vcontext) {
__android_log_print(ANDROID_LOG_ERROR, "Geode", "Signal handler called with signal %d", signal);
int reentrancy = s_reentrancy.fetch_add(1) + 1;
if (reentrancy > 3) {
// crash handler crashed 3 times, give up and die
__android_log_print(ANDROID_LOG_ERROR, "Geode", "Signal handler reentrancy level %d, giving up", reentrancy);
std::_Exit(EXIT_FAILURE);
}
// if the crash handler itself has already crashed processing its own crash, skip extra processing to try and avoid another crash
s_skipSymbols = reentrancy > 2;
s_signal = signal;
s_siginfo = signalInfo;
s_context = reinterpret_cast<ucontext_t*>(vcontext);
write(s_pipe[1], "1", 1);
// wait for the death to come
while (true) {
usleep(100000);
}
}
static void handlerThread() {
// no more mutex deadlocker
char buf;
while (read(s_pipe[0], &buf, 1) != 0) {
#ifdef GEODE_IS_ANDROID64
auto signalAddress = reinterpret_cast<void*>(s_context->uc_mcontext.pc);
#else
auto signalAddress = reinterpret_cast<void*>(s_context->uc_mcontext.arm_pc);
#endif
int signal = s_signal;
__android_log_print(ANDROID_LOG_ERROR, "Geode", "Picked up signal %d at %p", signal, signalAddress);
// initialize maps & memory early
g_memory = Memory::CreateProcessMemoryCached(getpid());
g_maps = std::make_unique<LocalMaps>();
if (!g_maps->Parse()) {
__android_log_print(ANDROID_LOG_ERROR, "Geode", "Failed to parse memory maps");
}
g_context.initialize(signalAddress);
g_maps.reset();
g_memory.reset();
crashlog::writeCrashlog(g_context);
// if this was an abort, call the previous handler, otherwise just exit immediately
// this means that if other interceptors are active (like hwasan), they will get to handle the crash as well
// if none are active, the game will simply exit
if (signal == SIGABRT && (s_oldAbort.sa_sigaction || s_oldAbort.sa_handler)) {
// unblock the signal just in case
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGABRT);
pthread_sigmask(SIG_UNBLOCK, &set, nullptr);
sigaction(SIGABRT, &s_oldAbort, nullptr);
raise(SIGABRT);
} else {
std::_Exit(EXIT_FAILURE);
}
}
}
static bool s_lastLaunchCrashed;
bool crashlog::setupPlatformHandler() {
// for whatever reason, i can't just do int*
if (pipe(s_pipe) != 0) return false;
fcntl(s_pipe[0], F_SETFD, FD_CLOEXEC);
fcntl(s_pipe[1], F_SETFD, FD_CLOEXEC);
struct sigaction action;
action.sa_sigaction = &signalHandler;
action.sa_flags = SA_SIGINFO;
sigemptyset(&action.sa_mask);
sigaction(SIGSEGV, &action, nullptr);
// I'd rather not track interrupt lol
// sigaction(SIGINT, &action, nullptr);
sigaction(SIGFPE, &action, nullptr);
sigaction(SIGILL, &action, nullptr);
sigaction(SIGTERM, &action, nullptr);
sigaction(SIGABRT, &action, &s_oldAbort);
sigaction(SIGBUS, &action, nullptr);
sigaction(SIGTRAP, &action, nullptr);
// spawn multiple to handle reentrant crashes, cases where one handler thread died
for (size_t i = 0; i < 3; i++) {
std::thread(&handlerThread).detach();
}
auto crashIndicatorPath = crashlog::getCrashLogDirectory() / crashIndicatorFilename;
if (std::filesystem::exists(crashIndicatorPath)) {
s_lastLaunchCrashed = true;
std::filesystem::remove(crashIndicatorPath);
}
return true;
}
void crashlog::setupPlatformHandlerPost() {}
bool crashlog::didLastLaunchCrash() {
return s_lastLaunchCrashed;
}
std::filesystem::path crashlog::getCrashLogDirectory() {
return dirs::getGeodeDir() / "crashlogs";
}