-
Notifications
You must be signed in to change notification settings - Fork 134
/
coffeecatch.c
1418 lines (1263 loc) · 39.6 KB
/
coffeecatch.c
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
1000
/* CoffeeCatch, a tiny native signal handler/catcher for JNI code.
* (especially for Android/Dalvik)
*
* Copyright (c) 2013, Xavier Roche (http://www.httrack.com/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __ANDROID__
#define USE_UNWIND
#define USE_CORKSCREW
#define USE_LIBUNWIND
#endif
/* #undef NO_USE_SIGALTSTACK */
/* #undef USE_SILENT_SIGALTSTACK */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <assert.h>
#include <signal.h>
#include <setjmp.h>
#if defined(__ANDROID__) && !defined(__BIONIC_HAVE_UCONTEXT_T) && \
defined(__arm__) && !defined(__BIONIC_HAVE_STRUCT_SIGCONTEXT)
#include <asm/sigcontext.h>
#endif
#if (defined(USE_UNWIND) && !defined(USE_CORKSCREW))
#include <unwind.h>
#endif
#include <pthread.h>
#include <dlfcn.h>
#include "coffeecatch.h"
/*#define NDK_DEBUG 1*/
#if ( defined(NDK_DEBUG) && ( NDK_DEBUG == 1 ) )
#define DEBUG(A) do { A; } while(0)
#define FD_ERRNO 2
static void print(const char *const s) {
size_t count;
for(count = 0; s[count] != '\0'; count++) ;
/* write() is async-signal-safe. */
(void) write(FD_ERRNO, s, count);
}
#else
#define DEBUG(A)
#endif
/* Alternative stack size. */
#define SIG_STACK_BUFFER_SIZE SIGSTKSZ
#ifdef USE_UNWIND
/* Number of backtraces to get. */
#define BACKTRACE_FRAMES_MAX 32
#endif
/* Signals to be caught. */
#define SIG_CATCH_COUNT 7
static const int native_sig_catch[SIG_CATCH_COUNT + 1]
= { SIGABRT, SIGILL, SIGTRAP, SIGBUS, SIGFPE, SIGSEGV
#ifdef SIGSTKFLT
, SIGSTKFLT
#endif
, 0 };
/* Maximum value of a caught signal. */
#define SIG_NUMBER_MAX 32
#if defined(__ANDROID__)
#ifndef ucontext_h_seen
#define ucontext_h_seen
/* stack_t definition */
#include <asm/signal.h>
#if defined(__arm__)
/* Taken from richard.quirk's header file. (Android does not have it) */
#if !defined(__BIONIC_HAVE_UCONTEXT_T)
typedef struct ucontext {
unsigned long uc_flags;
struct ucontext *uc_link;
stack_t uc_stack;
struct sigcontext uc_mcontext;
unsigned long uc_sigmask;
} ucontext_t;
#endif
#elif defined(__aarch64__)
#elif defined(__i386__)
/* Taken from Google Breakpad. */
/* 80-bit floating-point register */
struct _libc_fpreg {
unsigned short significand[4];
unsigned short exponent;
};
/* Simple floating-point state, see FNSTENV instruction */
struct _libc_fpstate {
unsigned long cw;
unsigned long sw;
unsigned long tag;
unsigned long ipoff;
unsigned long cssel;
unsigned long dataoff;
unsigned long datasel;
struct _libc_fpreg _st[8];
unsigned long status;
};
typedef uint32_t greg_t;
typedef struct {
uint32_t gregs[19];
struct _libc_fpstate* fpregs;
uint32_t oldmask;
uint32_t cr2;
} mcontext_t;
enum {
REG_GS = 0,
REG_FS,
REG_ES,
REG_DS,
REG_EDI,
REG_ESI,
REG_EBP,
REG_ESP,
REG_EBX,
REG_EDX,
REG_ECX,
REG_EAX,
REG_TRAPNO,
REG_ERR,
REG_EIP,
REG_CS,
REG_EFL,
REG_UESP,
REG_SS,
};
#if !defined(__BIONIC_HAVE_UCONTEXT_T)
typedef struct ucontext {
uint32_t uc_flags;
struct ucontext* uc_link;
stack_t uc_stack;
mcontext_t uc_mcontext;
} ucontext_t;
#endif
#elif defined(__mips__)
/* Taken from Google Breakpad. */
typedef struct {
uint32_t regmask;
uint32_t status;
uint64_t pc;
uint64_t gregs[32];
uint64_t fpregs[32];
uint32_t acx;
uint32_t fpc_csr;
uint32_t fpc_eir;
uint32_t used_math;
uint32_t dsp;
uint64_t mdhi;
uint64_t mdlo;
uint32_t hi1;
uint32_t lo1;
uint32_t hi2;
uint32_t lo2;
uint32_t hi3;
uint32_t lo3;
} mcontext_t;
#if !defined(__BIONIC_HAVE_UCONTEXT_T)
typedef struct ucontext {
uint32_t uc_flags;
struct ucontext* uc_link;
stack_t uc_stack;
mcontext_t uc_mcontext;
} ucontext_t;
#endif
#else
#error "Architecture is not supported (unknown ucontext layout)"
#endif
#endif
#ifdef USE_CORKSCREW
typedef struct map_info_t map_info_t;
/* Extracted from Android's include/corkscrew/backtrace.h */
typedef struct {
uintptr_t absolute_pc;
uintptr_t stack_top;
size_t stack_size;
} backtrace_frame_t;
typedef struct {
uintptr_t relative_pc;
uintptr_t relative_symbol_addr;
char* map_name;
char* symbol_name;
char* demangled_name;
} backtrace_symbol_t;
/* Extracted from Android's libcorkscrew/arch-arm/backtrace-arm.c */
typedef ssize_t (*t_unwind_backtrace_signal_arch)
(siginfo_t* si, void* sc, const map_info_t* lst, backtrace_frame_t* bt,
size_t ignore_depth, size_t max_depth);
typedef map_info_t* (*t_acquire_my_map_info_list)();
typedef void (*t_release_my_map_info_list)(map_info_t* milist);
typedef void (*t_get_backtrace_symbols)(const backtrace_frame_t* backtrace,
size_t frames,
backtrace_symbol_t* symbols);
typedef void (*t_free_backtrace_symbols)(backtrace_symbol_t* symbols,
size_t frames);
#endif
#endif
/* Process-wide crash handler structure. */
typedef struct native_code_global_struct {
/* Initialized. */
int initialized;
/* Lock. */
pthread_mutex_t mutex;
/* Backup of sigaction. */
struct sigaction *sa_old;
} native_code_global_struct;
#define NATIVE_CODE_GLOBAL_INITIALIZER { 0, PTHREAD_MUTEX_INITIALIZER, NULL }
/* Thread-specific crash handler structure. */
typedef struct native_code_handler_struct {
/* Restore point context. */
sigjmp_buf ctx;
int ctx_is_set;
int reenter;
/* Alternate stack. */
char *stack_buffer;
size_t stack_buffer_size;
stack_t stack_old;
/* Signal code and info. */
int code;
siginfo_t si;
ucontext_t uc;
/* Uwind context. */
#if (defined(USE_CORKSCREW))
backtrace_frame_t frames[BACKTRACE_FRAMES_MAX];
#elif (defined(USE_UNWIND))
uintptr_t frames[BACKTRACE_FRAMES_MAX];
#endif
#ifdef USE_LIBUNWIND
void* uframes[BACKTRACE_FRAMES_MAX];
#endif
size_t frames_size;
size_t frames_skip;
/* Custom assertion failures. */
const char *expression;
const char *file;
int line;
/* Alarm was fired. */
int alarm;
} native_code_handler_struct;
/* Global crash handler structure. */
static native_code_global_struct native_code_g =
NATIVE_CODE_GLOBAL_INITIALIZER;
/* Thread variable holding context. */
pthread_key_t native_code_thread;
#if (defined(USE_UNWIND) && !defined(USE_CORKSCREW))
/* Unwind callback */
static _Unwind_Reason_Code
coffeecatch_unwind_callback(struct _Unwind_Context* context, void* arg) {
native_code_handler_struct *const s = (native_code_handler_struct*) arg;
const uintptr_t ip = _Unwind_GetIP(context);
DEBUG(print("called unwind callback\n"));
if (ip != 0x0) {
if (s->frames_skip == 0) {
s->frames[s->frames_size] = ip;
s->frames_size++;
} else {
s->frames_skip--;
}
}
if (s->frames_size == BACKTRACE_FRAMES_MAX) {
return _URC_END_OF_STACK;
} else {
DEBUG(print("returned _URC_OK\n"));
return _URC_OK;
}
}
#endif
/* Use libcorkscrew to get a backtrace inside a signal handler.
Will only return a non-zero code on Android >= 4 (with libcorkscrew.so
being shipped) */
#ifdef USE_CORKSCREW
static size_t coffeecatch_backtrace_signal(siginfo_t* si, void* sc,
backtrace_frame_t* frames,
size_t ignore_depth,
size_t max_depth) {
void *const libcorkscrew = dlopen("libcorkscrew.so", RTLD_LAZY | RTLD_LOCAL);
if (libcorkscrew != NULL) {
t_unwind_backtrace_signal_arch unwind_backtrace_signal_arch
= (t_unwind_backtrace_signal_arch)
dlsym(libcorkscrew, "unwind_backtrace_signal_arch");
t_acquire_my_map_info_list acquire_my_map_info_list
= (t_acquire_my_map_info_list)
dlsym(libcorkscrew, "acquire_my_map_info_list");
t_release_my_map_info_list release_my_map_info_list
= (t_release_my_map_info_list)
dlsym(libcorkscrew, "release_my_map_info_list");
if (unwind_backtrace_signal_arch != NULL
&& acquire_my_map_info_list != NULL
&& release_my_map_info_list != NULL) {
map_info_t*const info = acquire_my_map_info_list();
const ssize_t size =
unwind_backtrace_signal_arch(si, sc, info, frames, ignore_depth,
max_depth);
release_my_map_info_list(info);
return size >= 0 ? size : 0;
} else {
DEBUG(print("symbols not found in libcorkscrew.so\n"));
}
dlclose(libcorkscrew);
} else {
DEBUG(print("libcorkscrew.so could not be loaded\n"));
}
return 0;
}
static int coffeecatch_backtrace_symbols(const backtrace_frame_t* backtrace,
size_t frames,
void (*fun)(void *arg,
const backtrace_symbol_t *sym),
void *arg) {
int success = 0;
void *const libcorkscrew = dlopen("libcorkscrew.so", RTLD_LAZY | RTLD_LOCAL);
if (libcorkscrew != NULL) {
t_get_backtrace_symbols get_backtrace_symbols
= (t_get_backtrace_symbols)
dlsym(libcorkscrew, "get_backtrace_symbols");
t_free_backtrace_symbols free_backtrace_symbols
= (t_free_backtrace_symbols)
dlsym(libcorkscrew, "free_backtrace_symbols");
if (get_backtrace_symbols != NULL
&& free_backtrace_symbols != NULL) {
backtrace_symbol_t symbols[BACKTRACE_FRAMES_MAX];
size_t i;
if (frames > BACKTRACE_FRAMES_MAX) {
frames = BACKTRACE_FRAMES_MAX;
}
get_backtrace_symbols(backtrace, frames, symbols);
for(i = 0; i < frames; i++) {
fun(arg, &symbols[i]);
}
free_backtrace_symbols(symbols, frames);
success = 1;
} else {
DEBUG(print("symbols not found in libcorkscrew.so\n"));
}
dlclose(libcorkscrew);
} else {
DEBUG(print("libcorkscrew.so could not be loaded\n"));
}
return success;
}
#endif
/* Use libunwind to get a backtrace inside a signal handler.
Will only return a non-zero code on Android >= 5 (with libunwind.so
being shipped) */
#ifdef USE_LIBUNWIND
static ssize_t coffeecatch_unwind_signal(siginfo_t* si, void* sc,
void** frames,
size_t ignore_depth,
size_t max_depth) {
void *libunwind = dlopen("libunwind.so", RTLD_LAZY | RTLD_LOCAL);
if (libunwind != NULL) {
int (*backtrace)(void **buffer, int size) =
dlsym(libunwind, "unw_backtrace");
if (backtrace != NULL) {
int nb = backtrace(frames, max_depth);
if (nb > 0) {
}
return nb;
} else {
DEBUG(print("symbols not found in libunwind.so\n"));
}
dlclose(libunwind);
} else {
DEBUG(print("libunwind.so could not be loaded\n"));
}
return -1;
}
#endif
/* Call the old handler. */
static void coffeecatch_call_old_signal_handler(const int code, siginfo_t *const si,
void * const sc) {
/* Call the "real" Java handler for JIT and internals. */
if (code >= 0 && code < SIG_NUMBER_MAX) {
if (native_code_g.sa_old[code].sa_sigaction != NULL) {
native_code_g.sa_old[code].sa_sigaction(code, si, sc);
} else if (native_code_g.sa_old[code].sa_handler != NULL) {
native_code_g.sa_old[code].sa_handler(code);
}
}
}
/* Unflag "on stack" */
static void coffeecatch_revert_alternate_stack(void) {
#ifndef NO_USE_SIGALTSTACK
stack_t ss;
if (sigaltstack(NULL, &ss) == 0) {
ss.ss_flags &= ~SS_ONSTACK;
sigaltstack (&ss, NULL);
}
#endif
}
/* Try to jump to userland. */
static void coffeecatch_try_jump_userland(native_code_handler_struct*
const t,
const int code,
siginfo_t *const si,
void * const sc) {
(void) si; /* UNUSED */
(void) sc; /* UNUSED */
/* Valid context ? */
if (t != NULL && t->ctx_is_set) {
DEBUG(print("calling siglongjmp()\n"));
/* Invalidate the context */
t->ctx_is_set = 0;
/* We need to revert the alternate stack before jumping. */
coffeecatch_revert_alternate_stack();
/*
* Note on async-signal-safety of siglongjmp() [POSIX] :
* "Note that longjmp() and siglongjmp() are not in the list of
* async-signal-safe functions. This is because the code executing after
* longjmp() and siglongjmp() can call any unsafe functions with the same
* danger as calling those unsafe functions directly from the signal
* handler. Applications that use longjmp() and siglongjmp() from within
* signal handlers require rigorous protection in order to be portable.
* Many of the other functions that are excluded from the list are
* traditionally implemented using either malloc() or free() functions or
* the standard I/O library, both of which traditionally use data
* structures in a non-async-signal-safe manner. Since any combination of
* different functions using a common data structure can cause
* async-signal-safety problems, this volume of POSIX.1-2008 does not
* define the behavior when any unsafe function is called in a signal
* handler that interrupts an unsafe function."
*/
siglongjmp(t->ctx, code);
}
}
static void coffeecatch_start_alarm(void) {
/* Ensure we do not deadlock. Default of ALRM is to die.
* (signal() and alarm() are signal-safe) */
(void) alarm(30);
}
static void coffeecatch_mark_alarm(native_code_handler_struct *const t) {
t->alarm = 1;
}
/* Copy context infos (signal code, etc.) */
static void coffeecatch_copy_context(native_code_handler_struct *const t,
const int code, siginfo_t *const si,
void *const sc) {
t->code = code;
t->si = *si;
if (sc != NULL) {
ucontext_t *const uc = (ucontext_t*) sc;
t->uc = *uc;
} else {
memset(&t->uc, 0, sizeof(t->uc));
}
#ifdef USE_UNWIND
/* Frame buffer initial position. */
t->frames_size = 0;
/* Skip us and the caller. */
t->frames_skip = 2;
/* Use the corkscrew library to extract the backtrace. */
#ifdef USE_CORKSCREW
t->frames_size = coffeecatch_backtrace_signal(si, sc, t->frames, 0,
BACKTRACE_FRAMES_MAX);
#else
/* Unwind frames (equivalent to backtrace()) */
_Unwind_Backtrace(coffeecatch_unwind_callback, t);
#endif
#ifdef USE_LIBUNWIND
if (t->frames_size == 0) {
size_t i;
t->frames_size = coffeecatch_unwind_signal(si, sc, t->uframes, 0,
BACKTRACE_FRAMES_MAX);
for(i = 0 ; i < t->frames_size ; i++) {
t->frames[i].absolute_pc = (uintptr_t) t->uframes[i];
t->frames[i].stack_top = 0;
t->frames[i].stack_size = 0;
}
}
#endif
if (t->frames_size != 0) {
DEBUG(print("called _Unwind_Backtrace()\n"));
} else {
DEBUG(print("called _Unwind_Backtrace(), but no traces\n"));
}
#endif
}
/* Return the thread-specific native_code_handler_struct structure, or
* @c null if no such structure is available. */
static native_code_handler_struct* coffeecatch_get() {
return (native_code_handler_struct*)
pthread_getspecific(native_code_thread);
}
int coffeecatch_cancel_pending_alarm() {
native_code_handler_struct *const t = coffeecatch_get();
if (t != NULL && t->alarm) {
t->alarm = 0;
/* "If seconds is 0, a pending alarm request, if any, is canceled." */
alarm(0);
return 0;
}
return -1;
}
/* Internal signal pass-through. Allows to peek the "real" crash before
* calling the Java handler. Remember than Java needs many of the signals
* (for the JIT, for test-free NullPointerException handling, etc.)
* We record the siginfo_t context in this function each time it is being
* called, to be able to know what error caused an issue.
*/
static void coffeecatch_signal_pass(const int code, siginfo_t *const si,
void *const sc) {
native_code_handler_struct *t;
DEBUG(print("caught signal\n"));
/* Call the "real" Java handler for JIT and internals. */
coffeecatch_call_old_signal_handler(code, si, sc);
/* Still here ?
* FIXME TODO: This is the Dalvik behavior - but is it the SunJVM one ? */
/* Ensure we do not deadlock. Default of ALRM is to die.
* (signal() and alarm() are signal-safe) */
signal(code, SIG_DFL);
coffeecatch_start_alarm();
/* Available context ? */
t = coffeecatch_get();
if (t != NULL) {
/* An alarm() call was triggered. */
coffeecatch_mark_alarm(t);
/* Take note of the signal. */
coffeecatch_copy_context(t, code, si, sc);
/* Back to the future. */
coffeecatch_try_jump_userland(t, code, si, sc);
}
/* Nope. (abort() is signal-safe) */
DEBUG(print("calling abort()\n"));
signal(SIGABRT, SIG_DFL);
abort();
}
/* Internal crash handler for abort(). Java calls abort() if its signal handler
* could not resolve the signal ; thus calling us through this handler. */
static void coffeecatch_signal_abort(const int code, siginfo_t *const si,
void *const sc) {
native_code_handler_struct *t;
(void) sc; /* UNUSED */
DEBUG(print("caught abort\n"));
/* Ensure we do not deadlock. Default of ALRM is to die.
* (signal() and alarm() are signal-safe) */
signal(code, SIG_DFL);
coffeecatch_start_alarm();
/* Available context ? */
t = coffeecatch_get();
if (t != NULL) {
/* An alarm() call was triggered. */
coffeecatch_mark_alarm(t);
/* Take note (real "abort()") */
coffeecatch_copy_context(t, code, si, sc);
/* Back to the future. */
coffeecatch_try_jump_userland(t, code, si, sc);
}
/* No such restore point, call old signal handler then. */
DEBUG(print("calling old signal handler\n"));
coffeecatch_call_old_signal_handler(code, si, sc);
/* Nope. (abort() is signal-safe) */
DEBUG(print("calling abort()\n"));
abort();
}
/* Internal globals initialization. */
static int coffeecatch_handler_setup_global(void) {
if (native_code_g.initialized++ == 0) {
size_t i;
struct sigaction sa_abort;
struct sigaction sa_pass;
DEBUG(print("installing global signal handlers\n"));
/* Setup handler structure. */
memset(&sa_abort, 0, sizeof(sa_abort));
sigemptyset(&sa_abort.sa_mask);
sa_abort.sa_sigaction = coffeecatch_signal_abort;
sa_abort.sa_flags = SA_SIGINFO | SA_ONSTACK;
memset(&sa_pass, 0, sizeof(sa_pass));
sigemptyset(&sa_pass.sa_mask);
sa_pass.sa_sigaction = coffeecatch_signal_pass;
sa_pass.sa_flags = SA_SIGINFO | SA_ONSTACK;
/* Allocate */
native_code_g.sa_old = calloc(sizeof(struct sigaction), SIG_NUMBER_MAX);
if (native_code_g.sa_old == NULL) {
return -1;
}
/* Setup signal handlers for SIGABRT (Java calls abort()) and others. **/
for (i = 0; native_sig_catch[i] != 0; i++) {
const int sig = native_sig_catch[i];
const struct sigaction * const action =
sig == SIGABRT ? &sa_abort : &sa_pass;
assert(sig < SIG_NUMBER_MAX);
if (sigaction(sig, action, &native_code_g.sa_old[sig]) != 0) {
return -1;
}
}
/* Initialize thread var. */
if (pthread_key_create(&native_code_thread, NULL) != 0) {
return -1;
}
DEBUG(print("installed global signal handlers\n"));
}
/* OK. */
return 0;
}
/**
* Free a native_code_handler_struct structure.
**/
static int coffeecatch_native_code_handler_struct_free(native_code_handler_struct *const t) {
int code = 0;
if (t == NULL) {
return -1;
}
#ifndef NO_USE_SIGALTSTACK
/* Restore previous alternative stack. */
if (t->stack_old.ss_sp != NULL && sigaltstack(&t->stack_old, NULL) != 0) {
#ifndef USE_SILENT_SIGALTSTACK
code = -1;
#endif
}
#endif
/* Free alternative stack */
if (t->stack_buffer != NULL) {
free(t->stack_buffer);
t->stack_buffer = NULL;
t->stack_buffer_size = 0;
}
/* Free structure. */
free(t);
return code;
}
/**
* Create a native_code_handler_struct structure.
**/
static native_code_handler_struct* coffeecatch_native_code_handler_struct_init(void) {
stack_t stack;
native_code_handler_struct *const t =
calloc(sizeof(native_code_handler_struct), 1);
if (t == NULL) {
return NULL;
}
DEBUG(print("installing thread alternative stack\n"));
/* Initialize structure */
t->stack_buffer_size = SIG_STACK_BUFFER_SIZE;
t->stack_buffer = malloc(t->stack_buffer_size);
if (t->stack_buffer == NULL) {
coffeecatch_native_code_handler_struct_free(t);
return NULL;
}
/* Setup alternative stack. */
memset(&stack, 0, sizeof(stack));
stack.ss_sp = t->stack_buffer;
stack.ss_size = t->stack_buffer_size;
stack.ss_flags = 0;
#ifndef NO_USE_SIGALTSTACK
/* Install alternative stack. This is thread-safe */
if (sigaltstack(&stack, &t->stack_old) != 0) {
#ifndef USE_SILENT_SIGALTSTACK
coffeecatch_native_code_handler_struct_free(t);
return NULL;
#endif
}
#endif
return t;
}
/**
* Acquire the crash handler for the current thread.
* The coffeecatch_handler_cleanup() must be called to release allocated
* resources.
**/
static int coffeecatch_handler_setup(int setup_thread) {
int code;
DEBUG(print("setup for a new handler\n"));
/* Initialize globals. */
if (pthread_mutex_lock(&native_code_g.mutex) != 0) {
return -1;
}
code = coffeecatch_handler_setup_global();
if (pthread_mutex_unlock(&native_code_g.mutex) != 0) {
return -1;
}
/* Global initialization failed. */
if (code != 0) {
return -1;
}
/* Initialize locals. */
if (setup_thread && coffeecatch_get() == NULL) {
native_code_handler_struct *const t =
coffeecatch_native_code_handler_struct_init();
if (t == NULL) {
return -1;
}
DEBUG(print("installing thread alternative stack\n"));
/* Set thread-specific value. */
if (pthread_setspecific(native_code_thread, t) != 0) {
coffeecatch_native_code_handler_struct_free(t);
return -1;
}
DEBUG(print("installed thread alternative stack\n"));
}
/* OK. */
return 0;
}
/**
* Release the resources allocated by a previous call to
* coffeecatch_handler_setup().
* This function must be called as many times as
* coffeecatch_handler_setup() was called to fully release allocated
* resources.
**/
static int coffeecatch_handler_cleanup() {
/* Cleanup locals. */
native_code_handler_struct *const t = coffeecatch_get();
if (t != NULL) {
DEBUG(print("removing thread alternative stack\n"));
/* Erase thread-specific value now (detach). */
if (pthread_setspecific(native_code_thread, NULL) != 0) {
assert(! "pthread_setspecific() failed");
}
/* Free handler and reset slternate stack */
if (coffeecatch_native_code_handler_struct_free(t) != 0) {
return -1;
}
DEBUG(print("removed thread alternative stack\n"));
}
/* Cleanup globals. */
if (pthread_mutex_lock(&native_code_g.mutex) != 0) {
assert(! "pthread_mutex_lock() failed");
}
assert(native_code_g.initialized != 0);
if (--native_code_g.initialized == 0) {
size_t i;
DEBUG(print("removing global signal handlers\n"));
/* Restore signal handler. */
for(i = 0; native_sig_catch[i] != 0; i++) {
const int sig = native_sig_catch[i];
assert(sig < SIG_NUMBER_MAX);
if (sigaction(sig, &native_code_g.sa_old[sig], NULL) != 0) {
return -1;
}
}
/* Free old structure. */
free(native_code_g.sa_old);
native_code_g.sa_old = NULL;
/* Delete thread var. */
if (pthread_key_delete(native_code_thread) != 0) {
assert(! "pthread_key_delete() failed");
}
DEBUG(print("removed global signal handlers\n"));
}
if (pthread_mutex_unlock(&native_code_g.mutex) != 0) {
assert(! "pthread_mutex_unlock() failed");
}
return 0;
}
/**
* Get the signal associated with the crash.
*/
int coffeecatch_get_signal() {
const native_code_handler_struct* const t = coffeecatch_get();
if (t != NULL) {
return t->code;
} else {
return -1;
}
}
/* Signal descriptions.
See <http://pubs.opengroup.org/onlinepubs/009696699/basedefs/signal.h.html>
*/
static const char* coffeecatch_desc_sig(int sig, int code) {
switch(sig) {
case SIGILL:
switch(code) {
case ILL_ILLOPC:
return "Illegal opcode";
case ILL_ILLOPN:
return "Illegal operand";
case ILL_ILLADR:
return "Illegal addressing mode";
case ILL_ILLTRP:
return "Illegal trap";
case ILL_PRVOPC:
return "Privileged opcode";
case ILL_PRVREG:
return "Privileged register";
case ILL_COPROC:
return "Coprocessor error";
case ILL_BADSTK:
return "Internal stack error";
default:
return "Illegal operation";
}
break;
case SIGFPE:
switch(code) {
case FPE_INTDIV:
return "Integer divide by zero";
case FPE_INTOVF:
return "Integer overflow";
case FPE_FLTDIV:
return "Floating-point divide by zero";
case FPE_FLTOVF:
return "Floating-point overflow";
case FPE_FLTUND:
return "Floating-point underflow";
case FPE_FLTRES:
return "Floating-point inexact result";
case FPE_FLTINV:
return "Invalid floating-point operation";
case FPE_FLTSUB:
return "Subscript out of range";
default:
return "Floating-point";
}
break;
case SIGSEGV:
switch(code) {
case SEGV_MAPERR:
return "Address not mapped to object";
case SEGV_ACCERR:
return "Invalid permissions for mapped object";
default:
return "Segmentation violation";
}
break;
case SIGBUS:
switch(code) {
case BUS_ADRALN:
return "Invalid address alignment";
case BUS_ADRERR:
return "Nonexistent physical address";
case BUS_OBJERR:
return "Object-specific hardware error";
default:
return "Bus error";
}
break;
case SIGTRAP:
switch(code) {
case TRAP_BRKPT:
return "Process breakpoint";
case TRAP_TRACE:
return "Process trace trap";
default:
return "Trap";
}
break;
case SIGCHLD:
switch(code) {
case CLD_EXITED:
return "Child has exited";
case CLD_KILLED:
return "Child has terminated abnormally and did not create a core file";
case CLD_DUMPED:
return "Child has terminated abnormally and created a core file";
case CLD_TRAPPED:
return "Traced child has trapped";
case CLD_STOPPED:
return "Child has stopped";
case CLD_CONTINUED:
return "Stopped child has continued";
default:
return "Child";