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
999 lines (914 loc) · 40 KB
/
Copy pathcrash_handler.cpp
File metadata and controls
999 lines (914 loc) · 40 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
// 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. Each frame is symbolicated by
// trying, in order:
// a. dladdr — resolves PCs that fall inside a loaded ELF (.so).
// b. The Mono `--jitmap` perfmap (`<TMPDIR>/perf-<pid>.map`), which
// names managed JIT methods. Enable by setting Mono env vars
// (see `resolveViaPerfmap` comment below).
// c. /proc/self/maps — labels the containing region (e.g. JIT trampoline
// or stripped .so) with offset, so addresses without a symbol still
// produce actionable output instead of "<unresolved>".
// 4. /proc/self/maps so any addresses still without a symbol after (3c)
// can be cross-checked manually against the full process memory layout.
// 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 <sys/mman.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);
}
// ----------------------------------------------------------------------------
// Mapping- and JIT-perfmap-based fallback symbolicators.
//
// Why this exists:
// `dladdr` only resolves PCs that fall inside a loaded ELF (.so) image.
// It cannot resolve:
// a. PCs in Mono's JIT/trampoline regions (anonymous `rwxp` mappings) —
// these are where every `<unresolved>` frame in our existing crash logs
// sits when the crash is in managed C# code or a Mono trampoline.
// b. PCs in stripped libraries with no .dynsym entries, where dladdr at
// best returns the library path with no symbol.
//
// We add two fallbacks below, tried in order whenever dladdr fails:
// 1. `resolveViaPerfmap` — search a Mono `--jitmap` file (if present) for
// the managed method that owns this PC. Mono with `--jitmap` (enabled
// via `MONO_ENV_OPTIONS=--jitmap`) writes one line per JIT method to
// `<TMPDIR>/perf-<pid>.map` in the format
// <hex_start_addr> <hex_size> <method_name>
// which we parse line-by-line.
// 2. `resolveViaProcMaps` — find the `/proc/self/maps` entry containing
// the PC and emit `[perms start-end +offset] /path/to/lib` (or a
// `[Mono JIT/trampoline (anon rwxp)]` tag for anonymous executable
// mappings). This always works and turns "<unresolved>" lines into
// actionable output even when no perfmap is present.
//
// To enable the perfmap output (step 1) for a build:
// - Add an `AndroidEnvironment` text file to the project containing:
// MONO_ENV_OPTIONS=--jitmap
// TMPDIR=/storage/emulated/0/Android/data/<pkg>/files
// so Mono writes the perfmap into the same dir as `native_crash.log`.
// `crash_handler.cpp` searches that dir, plus `/tmp` and `/data/local/tmp`,
// plus the directory containing `g_logPath`.
//
// Async-signal safety:
// - All file I/O uses open/read/close (signal-safe).
// - We do NOT use malloc. The perfmap is mmap'd once on first use into a
// static slot; subsequent frame lookups scan that buffer in-place.
// - The /proc/self/maps lookup uses a fixed-size stack buffer and
// re-opens the file once per crash (it is small — typically <1 MB).
// ----------------------------------------------------------------------------
// Lazily-mapped Mono perfmap. Set on first call to resolveViaPerfmap during
// a crash; never unmapped (we're about to die anyway).
static const char* g_perfmapData = nullptr;
static size_t g_perfmapSize = 0;
static volatile sig_atomic_t g_perfmapTried = 0;
static int hexVal(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return 10 + (c - 'a');
if (c >= 'A' && c <= 'F') return 10 + (c - 'A');
return -1;
}
// Parse "<hex>" up to a non-hex char. Advances *p past the parsed digits.
// Returns the parsed value (0 if no digits parsed).
static uint64_t parseHexAt(const char* s, size_t len, size_t* p) {
uint64_t v = 0;
while (*p < len) {
int d = hexVal(s[*p]);
if (d < 0) break;
v = (v << 4) | (uint64_t)d;
++*p;
}
return v;
}
// Append a NUL-terminated literal to a fixed buffer; advances *bp.
static void appendLit(char* buf, int cap, int* bp, const char* s) {
while (*s && *bp < cap - 1) buf[(*bp)++] = *s++;
}
// Append a length-bounded string (may contain '\n' which we stop at).
static void appendBounded(char* buf, int cap, int* bp, const char* s, int slen) {
for (int i = 0; i < slen && *bp < cap - 1; ++i) {
char c = s[i];
if (c == '\n' || c == '\r') break;
buf[(*bp)++] = c;
}
}
// Try to mmap the Mono perfmap once. Returns true if g_perfmapData is set.
// Searches several plausible locations because Mono's `--jitmap` always
// writes to `<TMPDIR>/perf-<pid>.map` and TMPDIR varies by configuration.
static bool ensurePerfmapLoaded() {
if (g_perfmapTried) return g_perfmapData != nullptr;
g_perfmapTried = 1;
// Build "perf-<pid>.map" once.
char nameBuf[64];
int np = 0;
appendLit(nameBuf, sizeof(nameBuf), &np, "perf-");
{
char tmp[16]; int tp = 0;
long long n = (long long)getpid();
if (n == 0) tmp[tp++] = '0';
while (n > 0 && tp < 15) { tmp[tp++] = (char)('0' + (n % 10)); n /= 10; }
while (tp > 0 && np < (int)sizeof(nameBuf) - 1) nameBuf[np++] = tmp[--tp];
}
appendLit(nameBuf, sizeof(nameBuf), &np, ".map");
nameBuf[np] = '\0';
// Candidate directories, in priority order. The dir containing g_logPath
// is checked first so a build that sets `TMPDIR=<external-files-dir>`
// (the recommended config) finds its perfmap immediately.
const char* tmpEnv = getenv("TMPDIR");
char logDir[kMaxLogPathLen] = {};
if (g_logPath[0] != '\0') {
size_t len = 0;
while (g_logPath[len] != '\0' && len < sizeof(logDir) - 1) {
logDir[len] = g_logPath[len];
++len;
}
// Strip trailing filename component.
while (len > 0 && logDir[len - 1] != '/') { logDir[--len] = '\0'; }
if (len > 1 && logDir[len - 1] == '/') logDir[len - 1] = '\0';
}
const char* dirs[4] = {
logDir[0] ? logDir : nullptr,
tmpEnv,
"/tmp",
"/data/local/tmp",
};
for (int i = 0; i < 4; ++i) {
if (!dirs[i] || dirs[i][0] == '\0') continue;
char path[kMaxLogPathLen + 64];
int p = 0;
for (int k = 0; dirs[i][k] && p < (int)sizeof(path) - 1; ++k) path[p++] = dirs[i][k];
if (p > 0 && path[p - 1] != '/' && p < (int)sizeof(path) - 1) path[p++] = '/';
for (int k = 0; nameBuf[k] && p < (int)sizeof(path) - 1; ++k) path[p++] = nameBuf[k];
path[p] = '\0';
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) continue;
struct stat st;
if (fstat(fd, &st) != 0 || st.st_size <= 0) { close(fd); continue; }
// Cap the mapped size at 64 MB to bound scan time. A perfmap larger
// than that for a single .NET process would be extraordinary.
size_t sz = (size_t)st.st_size;
if (sz > 64u * 1024u * 1024u) sz = 64u * 1024u * 1024u;
void* m = mmap(nullptr, sz, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (m == MAP_FAILED) continue;
g_perfmapData = static_cast<const char*>(m);
g_perfmapSize = sz;
return true;
}
return false;
}
// Linearly scan the perfmap for the entry containing pc. On hit, writes
// " [JIT] <method_name>+0xOFF" to fd and returns true.
static bool resolveViaPerfmap(int fd, uintptr_t pc) {
if (!ensurePerfmapLoaded()) return false;
const char* d = g_perfmapData;
size_t n = g_perfmapSize;
size_t i = 0;
while (i < n) {
// Each line: "<hex_start> <hex_size> <name>\n"
size_t lineStart = i;
size_t p = i;
uint64_t start = parseHexAt(d, n, &p);
// skip space
while (p < n && d[p] == ' ') ++p;
uint64_t size = parseHexAt(d, n, &p);
while (p < n && d[p] == ' ') ++p;
size_t nameStart = p;
while (p < n && d[p] != '\n') ++p;
size_t nameLen = p - nameStart;
if (size != 0 && pc >= start && pc < start + size) {
char buf[320];
int bp = 0;
appendLit(buf, sizeof(buf), &bp, " [JIT] ");
appendBounded(buf, sizeof(buf), &bp, d + nameStart, (int)nameLen);
appendLit(buf, sizeof(buf), &bp, "+0x");
// hex offset
uint64_t off = pc - start;
char hb[17];
static const char hd[] = "0123456789abcdef";
int hp = 0;
if (off == 0) hb[hp++] = '0';
char rev[17]; int rp = 0;
while (off > 0) { rev[rp++] = hd[off & 0xf]; off >>= 4; }
while (rp > 0) hb[hp++] = rev[--rp];
for (int k = 0; k < hp && bp < (int)sizeof(buf) - 1; ++k) buf[bp++] = hb[k];
buf[bp] = '\0';
ssize_t wn = write(fd, buf, bp);
(void)wn;
return true;
}
// advance past newline
if (p < n && d[p] == '\n') ++p;
// safety: if a line is malformed and we didn't advance, force progress
if (p == lineStart) ++p;
i = p;
}
return false;
}
// Scan /proc/self/maps for the entry containing pc. On hit writes
// " [perms start-end +0xOFF] <path-or-tag>" to fd and returns true.
// Reads the file fresh each call (it's small and signal-safe to do so).
static bool resolveViaProcMaps(int fd, uintptr_t pc) {
int mfd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
if (mfd < 0) return false;
// We accumulate a single map line into `line` (max 512 chars; lines on
// Android maps are well below this in practice — long ones are paths to
// /data/app/.../base.apk plus offset, ~280 chars).
char line[512];
int lp = 0;
char chunk[4096];
bool hit = false;
for (;;) {
ssize_t r = read(mfd, chunk, sizeof(chunk));
if (r <= 0) break;
for (ssize_t ci = 0; ci < r; ++ci) {
char c = chunk[ci];
if (c == '\n') {
line[lp] = '\0';
// Parse "start-end perms offset dev inode <path>"
size_t p = 0; size_t lineLen = (size_t)lp;
uint64_t s = parseHexAt(line, lineLen, &p);
if (p < lineLen && line[p] == '-') {
++p;
uint64_t e = parseHexAt(line, lineLen, &p);
if (pc >= s && pc < e) {
// Skip space, capture perms (4 chars).
while (p < lineLen && line[p] == ' ') ++p;
char perms[5] = {};
for (int k = 0; k < 4 && p < lineLen; ++k, ++p) perms[k] = line[p];
// Skip 3 fields (offset dev inode) to reach path.
for (int field = 0; field < 3; ++field) {
while (p < lineLen && line[p] == ' ') ++p;
while (p < lineLen && line[p] != ' ') ++p;
}
while (p < lineLen && line[p] == ' ') ++p;
const char* path = (p < lineLen) ? &line[p] : "";
char outBuf[640];
int bp = 0;
appendLit(outBuf, sizeof(outBuf), &bp, " [");
for (int k = 0; k < 4 && perms[k] && bp < (int)sizeof(outBuf) - 1; ++k)
outBuf[bp++] = perms[k];
appendLit(outBuf, sizeof(outBuf), &bp, " 0x");
// start hex
{
uint64_t v = s;
char hb[17]; int hp = 0;
static const char hd[] = "0123456789abcdef";
if (v == 0) hb[hp++] = '0';
char rev[17]; int rp = 0;
while (v > 0) { rev[rp++] = hd[v & 0xf]; v >>= 4; }
while (rp > 0) hb[hp++] = rev[--rp];
for (int k = 0; k < hp && bp < (int)sizeof(outBuf) - 1; ++k)
outBuf[bp++] = hb[k];
}
appendLit(outBuf, sizeof(outBuf), &bp, "-0x");
{
uint64_t v = e;
char hb[17]; int hp = 0;
static const char hd[] = "0123456789abcdef";
if (v == 0) hb[hp++] = '0';
char rev[17]; int rp = 0;
while (v > 0) { rev[rp++] = hd[v & 0xf]; v >>= 4; }
while (rp > 0) hb[hp++] = rev[--rp];
for (int k = 0; k < hp && bp < (int)sizeof(outBuf) - 1; ++k)
outBuf[bp++] = hb[k];
}
appendLit(outBuf, sizeof(outBuf), &bp, " +0x");
{
uint64_t v = pc - s;
char hb[17]; int hp = 0;
static const char hd[] = "0123456789abcdef";
if (v == 0) hb[hp++] = '0';
char rev[17]; int rp = 0;
while (v > 0) { rev[rp++] = hd[v & 0xf]; v >>= 4; }
while (rp > 0) hb[hp++] = rev[--rp];
for (int k = 0; k < hp && bp < (int)sizeof(outBuf) - 1; ++k)
outBuf[bp++] = hb[k];
}
outBuf[bp < (int)sizeof(outBuf) - 1 ? bp++ : bp] = ']';
if (path[0] != '\0') {
appendLit(outBuf, sizeof(outBuf), &bp, " ");
for (int k = 0; path[k] && bp < (int)sizeof(outBuf) - 1; ++k)
outBuf[bp++] = path[k];
} else if (perms[2] == 'x') {
// Anonymous executable mapping: classic Mono JIT/trampoline region.
appendLit(outBuf, sizeof(outBuf), &bp,
" [Mono JIT/trampoline (anon rwxp)]");
} else {
appendLit(outBuf, sizeof(outBuf), &bp, " [anon]");
}
outBuf[bp] = '\0';
ssize_t wn = write(fd, outBuf, bp);
(void)wn;
hit = true;
}
}
lp = 0;
if (hit) break;
} else if (lp < (int)sizeof(line) - 1) {
line[lp++] = c;
} else {
// overflow: drop until newline
}
}
if (hit) break;
}
close(mfd);
return hit;
}
// Convenience: try perfmap then /proc/self/maps. Writes nothing (and returns
// false) if neither resolves.
static bool resolveUnknownPc(int fd, uintptr_t pc) {
if (pc == 0) return false;
if (resolveViaPerfmap(fd, pc)) return true;
return resolveViaProcMaps(fd, pc);
}
// ----------------------------------------------------------------------------
// 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 if (!resolveUnknownPc(st->fd, pc)) {
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);
// Even when we have a synthetic tag (e.g. "<NULL function pointer call>"
// or "<LR (return address of NULL call)>"), still try to attach a
// perfmap/maps annotation so we know which JIT region or library the
// PC sits in.
resolveUnknownPc(fd, pc);
} else if (!resolveUnknownPc(fd, pc)) {
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"