forked from ppy/osu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrash_handler.cpp
More file actions
665 lines (599 loc) · 25.5 KB
/
Copy pathcrash_handler.cpp
File metadata and controls
665 lines (599 loc) · 25.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
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
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
// Native crash handler for osu!lazer Android.
//
// Why this exists:
// On unrooted Android phones the user typically cannot access logcat or
// /data/tombstones/. Third-party "crash log viewer" apps read only the
// summarised, *unsymbolicated* tombstone the system shows in App Info,
// which gives just `pc=<hex>` and at most two frames — useless for
// diagnosing a SIGSEGV that originated inside libvulkan or another system
// library.
//
// This file installs a SIGSEGV/SIGBUS/SIGILL/SIGFPE/SIGABRT handler that
// captures the signal IN-PROCESS and writes a structured dump to **both**
// logcat (tag `osu!crash`) and a plain text file at a path passed in by
// the C# side (`<external-files-dir>/native_crash.log`). That path is
// reachable by the user via Android's Files app without root or adb.
// After dumping, the previous handler (debuggerd) is invoked so the normal
// Android tombstone is still produced.
//
// The dump contains:
// 1. Signal info (signal/code/fault address/tid/thread name/uptime).
// 2. Full register state.
// 3. The faulting thread's backtrace, walked from the saved ucontext via
// the AArch64 frame-pointer chain. This is the diagnostic that
// actually matters — it shows where the crash happened. We do NOT
// use `_Unwind_Backtrace` for this because that walks the *handler*
// thread's stack (which terminates at the kernel signal trampoline
// in vdso, giving "crashHandler → libsigchain → vdso" — useless).
// 4. /proc/self/maps so any addresses dladdr couldn't symbolicate
// (internal-namespace / stripped-.dynsym frames) can still be matched
// to a library and offset post-mortem.
// 5. The secondary `_Unwind_Backtrace` output for completeness.
//
// Async-signal safety:
// We use only signal-safe primitives in the handler:
// - write(2), open(2), close(2), lseek(2) (all signal-safe)
// - _Unwind_Backtrace (signal-safe in practice;
// used by Crashpad, Breakpad,
// Android's own libdebuggerd)
// - dladdr (uses a process-global rwlock;
// safe in practice for crash
// reporting — same trade-off
// every Android crash reporter
// makes)
// - __android_log_write (single write() to a pipe;
// safe in practice)
// We deliberately avoid: malloc/free, snprintf-style allocators, std::string,
// stdio streams, locale-aware formatting. All formatting is done with our
// own tiny `writeHex` / `writeDec` helpers writing into a stack buffer.
//
// Stack overflow safety:
// We register a sigaltstack so the handler runs even when the crashing
// thread has overflowed its primary stack.
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include <dlfcn.h>
#include <unwind.h>
#include <ucontext.h>
#include <android/log.h>
#include "crash_handler.h"
#define CRASH_LOG_TAG "osu!crash"
namespace {
// Path to write crash dumps to. Set by `nInstallCrashHandler` from C#.
// We hold our own copy so the const char* the C# side passes can be freed
// after the call returns. Maximum path length is bounded — Android paths
// are well below this on real devices.
constexpr size_t kMaxLogPathLen = 1024;
char g_logPath[kMaxLogPathLen] = {};
// Alternate signal stack so the handler runs even on stack overflow.
constexpr size_t kAltStackSize = 64 * 1024; // 64 KB is plenty for our handler
uint8_t g_altStack[kAltStackSize] __attribute__((aligned(16)));
// Saved previous handlers, so we can chain to debuggerd after dumping.
constexpr int kSignals[] = { SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGABRT };
constexpr size_t kNumSignals = sizeof(kSignals) / sizeof(kSignals[0]);
struct sigaction g_prevHandlers[kNumSignals];
// Set to 1 when install completes successfully.
volatile sig_atomic_t g_installed = 0;
// Re-entrancy guard: if the handler itself crashes, fall straight through to
// the previous handler instead of recursing.
volatile sig_atomic_t g_inHandler = 0;
// ----------------------------------------------------------------------------
// Async-signal-safe formatters (no malloc, no stdio, no locale).
// ----------------------------------------------------------------------------
// Write a NUL-terminated string to fd; does nothing if fd < 0.
static void writeStr(int fd, const char* s) {
if (fd < 0 || !s) return;
size_t len = 0;
while (s[len] != '\0') ++len;
ssize_t n = write(fd, s, len);
(void)n; // we intentionally ignore write errors in a crash handler
}
// Write a 64-bit value as zero-padded hex (no "0x" prefix).
static void writeHex64(int fd, uint64_t v, int width = 16) {
if (fd < 0) return;
char buf[17];
static const char digits[] = "0123456789abcdef";
for (int i = 15; i >= 0; --i) {
buf[i] = digits[v & 0xf];
v >>= 4;
}
buf[16] = '\0';
int start = 16 - width;
if (start < 0) start = 0;
ssize_t n = write(fd, buf + start, 16 - start);
(void)n;
}
// Write a signed decimal integer.
static void writeDec(int fd, long long v) {
if (fd < 0) return;
char buf[32];
int pos = (int)sizeof(buf);
bool negative = false;
if (v < 0) { negative = true; v = -v; }
if (v == 0) buf[--pos] = '0';
while (v > 0 && pos > 0) { buf[--pos] = (char)('0' + (v % 10)); v /= 10; }
if (negative && pos > 0) buf[--pos] = '-';
ssize_t n = write(fd, buf + pos, sizeof(buf) - (size_t)pos);
(void)n;
}
// Append-write to logcat with our crash tag.
static void logcatWrite(const char* msg) {
__android_log_write(ANDROID_LOG_ERROR, CRASH_LOG_TAG, msg);
}
// ----------------------------------------------------------------------------
// Backtrace via libgcc/compiler-rt _Unwind_Backtrace.
// ----------------------------------------------------------------------------
struct UnwindState {
int fd;
int frame;
int maxFrames;
};
static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* ctx, void* arg) {
UnwindState* st = static_cast<UnwindState*>(arg);
uintptr_t pc = _Unwind_GetIP(ctx);
if (pc == 0) return _URC_END_OF_STACK;
// Resolve symbol via dladdr.
Dl_info info;
bool resolved = dladdr(reinterpret_cast<void*>(pc), &info) != 0;
// Format: " #NN pc 0xPPPPPPPPPPPPPPPP /path/to/lib.so (sym+0xOFF)"
writeStr(st->fd, " #");
if (st->frame < 10) writeStr(st->fd, "0");
writeDec(st->fd, st->frame);
writeStr(st->fd, " pc 0x");
writeHex64(st->fd, (uint64_t)pc);
if (resolved && info.dli_fname) {
writeStr(st->fd, " ");
writeStr(st->fd, info.dli_fname);
if (info.dli_sname) {
uintptr_t off = pc - (uintptr_t)info.dli_saddr;
writeStr(st->fd, " (");
writeStr(st->fd, info.dli_sname);
writeStr(st->fd, "+0x");
writeHex64(st->fd, (uint64_t)off, 1);
writeStr(st->fd, ")");
} else if (info.dli_fbase) {
uintptr_t off = pc - (uintptr_t)info.dli_fbase;
writeStr(st->fd, " (lib+0x");
writeHex64(st->fd, (uint64_t)off, 1);
writeStr(st->fd, ")");
}
} else {
writeStr(st->fd, " <unresolved>");
}
writeStr(st->fd, "\n");
// Also mirror to logcat (truncated). __android_log_write does its own
// null-terminated bounded write internally.
{
char line[256];
// Build a short line for logcat: "#NN pc=0xHEX <lib|sym>"
int p = 0;
line[p++] = '#';
if (st->frame < 10) line[p++] = '0';
// decimal
long long n = st->frame;
char tmp[12]; int tp = 0;
if (n == 0) tmp[tp++] = '0';
while (n > 0 && tp < 11) { tmp[tp++] = (char)('0' + (n % 10)); n /= 10; }
while (tp > 0 && p < (int)sizeof(line) - 1) line[p++] = tmp[--tp];
const char* sep = " pc=0x";
for (int i = 0; sep[i] && p < (int)sizeof(line) - 1; ++i) line[p++] = sep[i];
// hex pc
static const char hd[] = "0123456789abcdef";
for (int sh = 60; sh >= 0 && p < (int)sizeof(line) - 1; sh -= 4)
line[p++] = hd[(pc >> sh) & 0xf];
if (resolved) {
const char* lib = info.dli_fname ? info.dli_fname : "?";
const char* sym = info.dli_sname ? info.dli_sname : "";
if (p < (int)sizeof(line) - 1) line[p++] = ' ';
for (int i = 0; lib[i] && p < (int)sizeof(line) - 1; ++i) line[p++] = lib[i];
if (sym[0]) {
if (p < (int)sizeof(line) - 1) line[p++] = ' ';
if (p < (int)sizeof(line) - 1) line[p++] = '(';
for (int i = 0; sym[i] && p < (int)sizeof(line) - 2; ++i) line[p++] = sym[i];
if (p < (int)sizeof(line) - 1) line[p++] = ')';
}
}
line[p] = '\0';
logcatWrite(line);
}
st->frame++;
return (st->frame >= st->maxFrames) ? _URC_END_OF_STACK : _URC_NO_REASON;
}
// ----------------------------------------------------------------------------
// Register dump.
// ----------------------------------------------------------------------------
static void dumpRegisters(int fd, void* ucv) {
if (!ucv) return;
auto* uc = static_cast<ucontext_t*>(ucv);
#if defined(__aarch64__)
auto& mc = uc->uc_mcontext;
for (int i = 0; i < 31; i += 4) {
writeStr(fd, " ");
for (int j = 0; j < 4 && (i + j) < 31; ++j) {
writeStr(fd, "x");
writeDec(fd, i + j);
writeStr(fd, "=0x");
writeHex64(fd, (uint64_t)mc.regs[i + j]);
writeStr(fd, " ");
}
writeStr(fd, "\n");
}
writeStr(fd, " sp=0x"); writeHex64(fd, (uint64_t)mc.sp);
writeStr(fd, " pc=0x"); writeHex64(fd, (uint64_t)mc.pc);
writeStr(fd, " pstate=0x"); writeHex64(fd, (uint64_t)mc.pstate);
writeStr(fd, "\n");
#elif defined(__arm__)
auto& mc = uc->uc_mcontext;
writeStr(fd, " r0=0x"); writeHex64(fd, mc.arm_r0, 8);
writeStr(fd, " r1=0x"); writeHex64(fd, mc.arm_r1, 8);
writeStr(fd, " r2=0x"); writeHex64(fd, mc.arm_r2, 8);
writeStr(fd, " r3=0x"); writeHex64(fd, mc.arm_r3, 8);
writeStr(fd, "\n sp=0x"); writeHex64(fd, mc.arm_sp, 8);
writeStr(fd, " lr=0x"); writeHex64(fd, mc.arm_lr, 8);
writeStr(fd, " pc=0x"); writeHex64(fd, mc.arm_pc, 8);
writeStr(fd, "\n");
#else
(void)fd;
#endif
}
// ----------------------------------------------------------------------------
// Symbolicate a single PC and write a " #NN pc=0xHEX /lib (sym+0xOFF)\n" line.
// `tagWhenUnresolved` lets the caller annotate frames whose PC is invalid
// (e.g. NULL function-pointer call → pc == 0).
// Also mirrors a short version to logcat.
// ----------------------------------------------------------------------------
static void writeFrame(int fd, int frameNo, uintptr_t pc, const char* tagWhenUnresolved) {
writeStr(fd, " #");
if (frameNo < 10) writeStr(fd, "0");
writeDec(fd, frameNo);
writeStr(fd, " pc 0x");
writeHex64(fd, (uint64_t)pc);
Dl_info info;
bool resolved = (pc != 0) && (dladdr(reinterpret_cast<void*>(pc), &info) != 0);
if (resolved && info.dli_fname) {
writeStr(fd, " ");
writeStr(fd, info.dli_fname);
if (info.dli_sname) {
uintptr_t off = pc - (uintptr_t)info.dli_saddr;
writeStr(fd, " (");
writeStr(fd, info.dli_sname);
writeStr(fd, "+0x");
writeHex64(fd, (uint64_t)off, 1);
writeStr(fd, ")");
} else if (info.dli_fbase) {
uintptr_t off = pc - (uintptr_t)info.dli_fbase;
writeStr(fd, " (lib+0x");
writeHex64(fd, (uint64_t)off, 1);
writeStr(fd, ")");
}
} else if (tagWhenUnresolved) {
writeStr(fd, " ");
writeStr(fd, tagWhenUnresolved);
} else {
writeStr(fd, " <unresolved>");
}
writeStr(fd, "\n");
// Short logcat mirror.
char line[256];
int p = 0;
line[p++] = '#';
if (frameNo < 10) line[p++] = '0';
long long n = frameNo;
char tmp[12]; int tp = 0;
if (n == 0) tmp[tp++] = '0';
while (n > 0 && tp < 11) { tmp[tp++] = (char)('0' + (n % 10)); n /= 10; }
while (tp > 0 && p < (int)sizeof(line) - 1) line[p++] = tmp[--tp];
const char* sep = " pc=0x";
for (int i = 0; sep[i] && p < (int)sizeof(line) - 1; ++i) line[p++] = sep[i];
static const char hd[] = "0123456789abcdef";
for (int sh = 60; sh >= 0 && p < (int)sizeof(line) - 1; sh -= 4)
line[p++] = hd[(pc >> sh) & 0xf];
if (resolved) {
const char* lib = info.dli_fname ? info.dli_fname : "?";
const char* sym = info.dli_sname ? info.dli_sname : "";
if (p < (int)sizeof(line) - 1) line[p++] = ' ';
for (int i = 0; lib[i] && p < (int)sizeof(line) - 1; ++i) line[p++] = lib[i];
if (sym[0]) {
if (p < (int)sizeof(line) - 1) line[p++] = ' ';
if (p < (int)sizeof(line) - 1) line[p++] = '(';
for (int i = 0; sym[i] && p < (int)sizeof(line) - 2; ++i) line[p++] = sym[i];
if (p < (int)sizeof(line) - 1) line[p++] = ')';
}
}
line[p] = '\0';
logcatWrite(line);
}
// ----------------------------------------------------------------------------
// Walk the *crashing thread's* stack from the saved ucontext.
//
// `_Unwind_Backtrace` (used elsewhere in this file) walks the *current*
// thread's stack — i.e., the stack of the signal handler itself, with the
// libgcc unwinder stopping at the kernel signal trampoline (`__kernel_rt_sigreturn`)
// because there's no CFI across the signal frame. In practice that produces
// only "crashHandler → libsigchain → vdso", which is useless for diagnosing
// the actual fault.
//
// To recover the real backtrace we walk the AArch64 frame-pointer chain
// starting from the saved registers in ucontext:
// - frame[0] is `pc` (or, if pc == 0 because of a NULL function pointer
// call, `lr` — the return address of that call, i.e. the call site).
// - subsequent frames come from following `x29 (fp)` chain:
// prev_fp = *(uintptr_t*)fp
// prev_lr = *(uintptr_t*)(fp + 8)
//
// AArch64 on Android is built with frame pointers preserved (Google ABI
// requirement for Android 10+), so this chain is reliable.
//
// Safety: we validate each `fp` (non-NULL, 16-byte aligned, monotonically
// increasing — the stack grows down so each new fp must be strictly greater
// than the previous) before dereferencing. A bad fp simply terminates the
// walk; the re-entrancy guard catches a SIGSEGV inside the walk and falls
// straight through to the previous handler.
// ----------------------------------------------------------------------------
#if defined(__aarch64__)
static void walkContextStack(int fd, void* ucv) {
if (!ucv) return;
auto* uc = static_cast<ucontext_t*>(ucv);
auto& mc = uc->uc_mcontext;
uintptr_t pc = (uintptr_t)mc.pc;
uintptr_t lr = (uintptr_t)mc.regs[30];
uintptr_t fp = (uintptr_t)mc.regs[29];
int frame = 0;
if (pc == 0) {
// Faulting site is a NULL function pointer call. Emit a synthetic
// frame 0 to make this explicit, then frame 1 is the actual call site
// pointed to by LR.
writeFrame(fd, frame++, 0, "<NULL function pointer call>");
if (lr != 0) {
writeFrame(fd, frame++, lr, "<LR (return address of NULL call)>");
}
} else {
writeFrame(fd, frame++, pc, "<faulting PC>");
// After the leaf frame, LR is the return address (caller). Only emit
// if it differs from PC and looks plausible.
if (lr != 0 && lr != pc) {
writeFrame(fd, frame++, lr, "<LR (caller return address)>");
}
}
// Walk the frame pointer chain. Cap at 32 frames; bail out on any sign
// of a corrupt or non-monotonic chain.
constexpr int kMaxFrames = 32;
uintptr_t lastFp = 0;
while (frame < kMaxFrames && fp != 0) {
// Validate fp: must be 16-byte aligned, non-low-memory, and strictly
// greater than the previous fp (stack grows down → fp moves *up* as
// we walk callers).
if ((fp & 0xf) != 0) break;
if (fp < 0x10000) break;
if (lastFp != 0 && fp <= lastFp) break;
// Read [fp] = saved fp, [fp+8] = saved lr. Best-effort dereference;
// if fp is bogus we'll trip the re-entrancy guard and bail.
uintptr_t prevFp = *reinterpret_cast<volatile uintptr_t*>(fp);
uintptr_t prevLr = *reinterpret_cast<volatile uintptr_t*>(fp + 8);
if (prevLr == 0) break;
writeFrame(fd, frame++, prevLr, nullptr);
lastFp = fp;
fp = prevFp;
}
if (frame == 0) writeStr(fd, " <empty — no recoverable context>\n");
}
#else
static void walkContextStack(int fd, void* /*ucv*/) {
writeStr(fd, " <context-walk only implemented for aarch64>\n");
}
#endif
// ----------------------------------------------------------------------------
// Dump /proc/self/maps to fd so addresses without dladdr symbols can still
// be matched to a library and offset post-mortem. Uses only signal-safe
// primitives (open/read/write).
// ----------------------------------------------------------------------------
static void dumpProcMaps(int fd) {
if (fd < 0) return;
int mapsFd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
if (mapsFd < 0) {
writeStr(fd, " <could not open /proc/self/maps>\n");
return;
}
char buf[4096];
for (;;) {
ssize_t n = read(mapsFd, buf, sizeof(buf));
if (n <= 0) break;
ssize_t off = 0;
while (off < n) {
ssize_t w = write(fd, buf + off, n - off);
if (w <= 0) break;
off += w;
}
}
close(mapsFd);
}
// ----------------------------------------------------------------------------
// Signal name lookup (signal-safe — no strsignal which can allocate).
// ----------------------------------------------------------------------------
static const char* signalName(int sig) {
switch (sig) {
case SIGSEGV: return "SIGSEGV";
case SIGBUS: return "SIGBUS";
case SIGILL: return "SIGILL";
case SIGFPE: return "SIGFPE";
case SIGABRT: return "SIGABRT";
default: return "SIG?";
}
}
static const char* siCodeName(int sig, int code) {
if (sig == SIGSEGV) {
switch (code) {
case SEGV_MAPERR: return "SEGV_MAPERR (address not mapped)";
case SEGV_ACCERR: return "SEGV_ACCERR (invalid permissions)";
default: return "SEGV_?";
}
}
if (sig == SIGBUS) {
switch (code) {
case BUS_ADRALN: return "BUS_ADRALN (alignment)";
case BUS_ADRERR: return "BUS_ADRERR (no physical address)";
case BUS_OBJERR: return "BUS_OBJERR (object-specific HW error)";
default: return "BUS_?";
}
}
return "?";
}
// ----------------------------------------------------------------------------
// The actual handler.
// ----------------------------------------------------------------------------
static void crashHandler(int sig, siginfo_t* info, void* ucontext) {
// Re-entrancy guard. If we crashed inside the handler, jump straight to
// the previous handler.
if (g_inHandler) {
signal(sig, SIG_DFL);
raise(sig);
return;
}
g_inHandler = 1;
// Open the dump file (append). If g_logPath is empty we still log to logcat.
int fd = -1;
if (g_logPath[0] != '\0') {
fd = open(g_logPath, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
}
// Header.
writeStr(fd, "\n=========================================================\n");
writeStr(fd, "[osu!] NATIVE CRASH\n");
writeStr(fd, " signal = ");
writeStr(fd, signalName(sig));
writeStr(fd, " (");
writeDec(fd, sig);
writeStr(fd, ")\n si_code = ");
writeStr(fd, siCodeName(sig, info ? info->si_code : 0));
writeStr(fd, " (");
writeDec(fd, info ? info->si_code : 0);
writeStr(fd, ")\n fault_addr = 0x");
writeHex64(fd, info ? (uint64_t)(uintptr_t)info->si_addr : 0);
writeStr(fd, "\n thread_tid = ");
writeDec(fd, (long long)gettid());
writeStr(fd, "\n pid = ");
writeDec(fd, (long long)getpid());
writeStr(fd, "\n uptime_ns = ");
{
struct timespec ts;
clock_gettime(CLOCK_BOOTTIME, &ts);
writeDec(fd, (long long)ts.tv_sec * 1000000000LL + (long long)ts.tv_nsec);
}
writeStr(fd, "\n thread_name = ");
{
char name[32] = {};
// pthread_getname_np is signal-safe in bionic (it's a thin wrapper
// over a /proc/self/task/<tid>/comm read).
if (pthread_getname_np(pthread_self(), name, sizeof(name)) == 0)
writeStr(fd, name);
else
writeStr(fd, "?");
}
writeStr(fd, "\n");
// Logcat header (so users with logcat access also see something useful).
{
char hdr[160];
// "NATIVE CRASH sig=SIGSEGV(11) code=SEGV_MAPERR(1) addr=0xHEX tid=N"
const char* sname = signalName(sig);
int p = 0;
const char* prefix = "NATIVE CRASH sig=";
for (int i = 0; prefix[i] && p < (int)sizeof(hdr) - 1; ++i) hdr[p++] = prefix[i];
for (int i = 0; sname[i] && p < (int)sizeof(hdr) - 1; ++i) hdr[p++] = sname[i];
if (p < (int)sizeof(hdr) - 1) hdr[p++] = '\0';
logcatWrite(hdr);
}
// Registers.
writeStr(fd, "Registers:\n");
dumpRegisters(fd, ucontext);
// Faulting-thread backtrace, recovered from the saved ucontext. This is
// the *important* one — it shows where the crash actually happened.
// (See walkContextStack for the rationale on why we don't use
// _Unwind_Backtrace for this purpose.)
writeStr(fd, "Backtrace (from signal context):\n");
walkContextStack(fd, ucontext);
if (fd >= 0) fsync(fd);
// Memory map. Lets us correlate any unresolved frames to library+offset
// even when dladdr can't find a symbol (e.g. internal-namespace functions
// or stripped .dynsym entries — both of which produce useless "lib+0xc"
// output above).
writeStr(fd, "Memory map (/proc/self/maps):\n");
dumpProcMaps(fd);
if (fd >= 0) fsync(fd);
// Secondary backtrace via _Unwind_Backtrace. This walks the *handler
// thread's* stack (typically just crashHandler → libsigchain → vdso) and
// is mostly informational; kept for parity with the previous behaviour.
writeStr(fd, "Handler-thread backtrace (_Unwind_Backtrace, for reference):\n");
UnwindState st{ fd, 0, 64 };
_Unwind_Backtrace(&unwindCallback, &st);
if (st.frame == 0) writeStr(fd, " <empty>\n");
writeStr(fd, "=========================================================\n");
if (fd >= 0) {
fsync(fd);
close(fd);
}
// Chain to the previous handler (typically debuggerd) so the system
// tombstone is still produced. Find this signal's slot.
for (size_t i = 0; i < kNumSignals; ++i) {
if (kSignals[i] == sig) {
const struct sigaction& prev = g_prevHandlers[i];
// Restore previous handler so it actually runs (we re-raise below).
sigaction(sig, &prev, nullptr);
break;
}
}
// Re-raise; either the previous handler or default disposition will run.
g_inHandler = 0;
raise(sig);
}
} // namespace
extern "C" {
// Called from C# (P/Invoke) very early in OnCreate, with the absolute path of
// where to write crash dumps (usually `<external-files-dir>/native_crash.log`).
// `logPath` may be NULL or empty — in that case we still install handlers but
// only logcat output is produced.
__attribute__((visibility("default")))
void nInstallCrashHandler(const char* logPath) {
if (g_installed) return;
if (logPath != nullptr) {
size_t i = 0;
while (i < kMaxLogPathLen - 1 && logPath[i] != '\0') {
g_logPath[i] = logPath[i];
++i;
}
g_logPath[i] = '\0';
}
// Install alternate signal stack so we can survive stack overflow in the
// crashing thread. This is per-thread; the JVM/SDL thread we care about
// will inherit it via SA_ONSTACK only if it was set on that thread. In
// practice, the most common "no logs" failure mode is a NULL deref on a
// healthy stack, where the alt stack is unnecessary anyway — but for the
// few cases where it matters (genuine stack overflow), this helps.
stack_t ss{};
ss.ss_sp = g_altStack;
ss.ss_size = kAltStackSize;
ss.ss_flags = 0;
sigaltstack(&ss, nullptr);
struct sigaction sa{};
sa.sa_sigaction = &crashHandler;
sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART;
sigemptyset(&sa.sa_mask);
for (size_t i = 0; i < kNumSignals; ++i) {
sigaction(kSignals[i], &sa, &g_prevHandlers[i]);
}
g_installed = 1;
__android_log_print(ANDROID_LOG_INFO, CRASH_LOG_TAG,
"Crash handler installed (logPath=%s)",
g_logPath[0] ? g_logPath : "<none, logcat only>");
}
} // extern "C"