/
signals_posix.cpp
1861 lines (1635 loc) · 63.3 KB
/
signals_posix.cpp
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
/*
* Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "code/codeCache.hpp"
#include "code/compiledMethod.hpp"
#include "code/nativeInst.hpp"
#include "jvm.h"
#include "logging/log.hpp"
#include "os_posix.hpp"
#include "runtime/atomic.hpp"
#include "runtime/globals.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/javaThread.hpp"
#include "runtime/os.hpp"
#include "runtime/osThread.hpp"
#include "runtime/safefetch.hpp"
#include "runtime/semaphore.inline.hpp"
#include "runtime/suspendedThreadTask.hpp"
#include "runtime/threadCrashProtection.hpp"
#include "signals_posix.hpp"
#include "suspendResume_posix.hpp"
#include "utilities/checkedCast.hpp"
#include "utilities/events.hpp"
#include "utilities/ostream.hpp"
#include "utilities/parseInteger.hpp"
#include "utilities/vmError.hpp"
#include <signal.h>
static const char* get_signal_name(int sig, char* out, size_t outlen);
// Returns address of a handler associated with the given sigaction
static address get_signal_handler(const struct sigaction* action);
#define HANDLER_IS(handler, address) ((handler) == CAST_FROM_FN_PTR(void*, (address)))
#define HANDLER_IS_IGN(handler) (HANDLER_IS(handler, SIG_IGN))
#define HANDLER_IS_DFL(handler) (HANDLER_IS(handler, SIG_DFL))
#define HANDLER_IS_IGN_OR_DFL(handler) (HANDLER_IS_IGN(handler) || HANDLER_IS_DFL(handler))
// Various signal related mechanism are laid out in the following order:
//
// sun.misc.Signal
// signal chaining
// signal handling (except suspend/resume)
// suspend/resume
// Helper function to strip any flags from a sigaction sa_flag
// which are not needed for semantic comparison (see remarks below
// about SA_RESTORER on Linux).
// Also to work around the fact that not all platforms define sa_flags
// as signed int (looking at you, zlinux).
static int get_sanitized_sa_flags(const struct sigaction* sa) {
int f = (int) sa->sa_flags;
#ifdef LINUX
// Glibc on Linux uses the SA_RESTORER flag to indicate
// the use of a "signal trampoline". We have no interest
// in this flag and need to ignore it when checking our
// own flag settings.
// Note: SA_RESTORER is not exposed through signal.h so we
// have to hardcode its 0x04000000 value here.
const int sa_restorer_flag = 0x04000000;
f &= ~sa_restorer_flag;
#endif // LINUX
return f;
}
// Todo: provide a os::get_max_process_id() or similar. Number of processes
// may have been configured, can be read more accurately from proc fs etc.
#ifndef MAX_PID
#define MAX_PID INT_MAX
#endif
#define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
#define NUM_IMPORTANT_SIGS 32
// At various places we store handler information for each installed handler.
// SavedSignalHandlers is a helper class for those cases, keeping an array of sigaction
// structures.
class SavedSignalHandlers {
// Note: NSIG can be largish, depending on platform, and this array is expected
// to be sparsely populated. To save space the contained structures are
// C-heap allocated. Since they only get added outside of signal handling
// this is no problem.
struct sigaction* _sa[NSIG];
bool check_signal_number(int sig) const {
assert(sig > 0 && sig < NSIG, "invalid signal number %d", sig);
return sig > 0 && sig < NSIG;
}
public:
SavedSignalHandlers() {
::memset(_sa, 0, sizeof(_sa));
}
~SavedSignalHandlers() {
for (int i = 0; i < NSIG; i ++) {
FREE_C_HEAP_OBJ(_sa[i]);
}
}
void set(int sig, const struct sigaction* act) {
if (check_signal_number(sig)) {
assert(_sa[sig] == nullptr, "Overwriting signal handler?");
_sa[sig] = NEW_C_HEAP_OBJ(struct sigaction, mtInternal);
*_sa[sig] = *act;
}
}
const struct sigaction* get(int sig) const {
if (check_signal_number(sig)) {
return _sa[sig];
}
return nullptr;
}
};
debug_only(static bool signal_sets_initialized = false);
static sigset_t unblocked_sigs, vm_sigs, preinstalled_sigs;
// Our own signal handlers should never ever get replaced by a third party one.
// To check that, and to aid with diagnostics, store a copy of the handler setup
// and compare it periodically against reality (see os::run_periodic_checks()).
static bool check_signals = true;
static SavedSignalHandlers vm_handlers;
static bool do_check_signal_periodically[NSIG] = { 0 };
// For signal-chaining:
// if chaining is active, chained_handlers contains all handlers which we
// replaced with our own and to which we must delegate.
static SavedSignalHandlers chained_handlers;
static bool libjsig_is_loaded = false;
typedef struct sigaction *(*get_signal_t)(int);
static get_signal_t get_signal_action = nullptr;
// suspend/resume support
#if defined(__APPLE__)
static OSXSemaphore sr_semaphore;
#else
static PosixSemaphore sr_semaphore;
#endif
// Signal number used to suspend/resume a thread
// do not use any signal number less than SIGSEGV, see 4355769
int PosixSignals::SR_signum = SIGUSR2;
// sun.misc.Signal support
static Semaphore* sig_semaphore = nullptr;
// a counter for each possible signal value
static volatile jint pending_signals[NSIG+1] = { 0 };
static const struct {
int sig; const char* name;
} g_signal_info[] = {
{ SIGABRT, "SIGABRT" },
#ifdef SIGAIO
{ SIGAIO, "SIGAIO" },
#endif
{ SIGALRM, "SIGALRM" },
#ifdef SIGALRM1
{ SIGALRM1, "SIGALRM1" },
#endif
{ SIGBUS, "SIGBUS" },
#ifdef SIGCANCEL
{ SIGCANCEL, "SIGCANCEL" },
#endif
{ SIGCHLD, "SIGCHLD" },
#ifdef SIGCLD
{ SIGCLD, "SIGCLD" },
#endif
{ SIGCONT, "SIGCONT" },
#ifdef SIGCPUFAIL
{ SIGCPUFAIL, "SIGCPUFAIL" },
#endif
#ifdef SIGDANGER
{ SIGDANGER, "SIGDANGER" },
#endif
#ifdef SIGDIL
{ SIGDIL, "SIGDIL" },
#endif
#ifdef SIGEMT
{ SIGEMT, "SIGEMT" },
#endif
{ SIGFPE, "SIGFPE" },
#ifdef SIGFREEZE
{ SIGFREEZE, "SIGFREEZE" },
#endif
#ifdef SIGGFAULT
{ SIGGFAULT, "SIGGFAULT" },
#endif
#ifdef SIGGRANT
{ SIGGRANT, "SIGGRANT" },
#endif
{ SIGHUP, "SIGHUP" },
{ SIGILL, "SIGILL" },
#ifdef SIGINFO
{ SIGINFO, "SIGINFO" },
#endif
{ SIGINT, "SIGINT" },
#ifdef SIGIO
{ SIGIO, "SIGIO" },
#endif
#ifdef SIGIOINT
{ SIGIOINT, "SIGIOINT" },
#endif
#ifdef SIGIOT
// SIGIOT is there for BSD compatibility, but on most Unices just a
// synonym for SIGABRT. The result should be "SIGABRT", not
// "SIGIOT".
#if (SIGIOT != SIGABRT )
{ SIGIOT, "SIGIOT" },
#endif
#endif
#ifdef SIGKAP
{ SIGKAP, "SIGKAP" },
#endif
{ SIGKILL, "SIGKILL" },
#ifdef SIGLOST
{ SIGLOST, "SIGLOST" },
#endif
#ifdef SIGLWP
{ SIGLWP, "SIGLWP" },
#endif
#ifdef SIGLWPTIMER
{ SIGLWPTIMER, "SIGLWPTIMER" },
#endif
#ifdef SIGMIGRATE
{ SIGMIGRATE, "SIGMIGRATE" },
#endif
#ifdef SIGMSG
{ SIGMSG, "SIGMSG" },
#endif
{ SIGPIPE, "SIGPIPE" },
#ifdef SIGPOLL
{ SIGPOLL, "SIGPOLL" },
#endif
#ifdef SIGPRE
{ SIGPRE, "SIGPRE" },
#endif
{ SIGPROF, "SIGPROF" },
#ifdef SIGPTY
{ SIGPTY, "SIGPTY" },
#endif
#ifdef SIGPWR
{ SIGPWR, "SIGPWR" },
#endif
{ SIGQUIT, "SIGQUIT" },
#ifdef SIGRECONFIG
{ SIGRECONFIG, "SIGRECONFIG" },
#endif
#ifdef SIGRECOVERY
{ SIGRECOVERY, "SIGRECOVERY" },
#endif
#ifdef SIGRESERVE
{ SIGRESERVE, "SIGRESERVE" },
#endif
#ifdef SIGRETRACT
{ SIGRETRACT, "SIGRETRACT" },
#endif
#ifdef SIGSAK
{ SIGSAK, "SIGSAK" },
#endif
{ SIGSEGV, "SIGSEGV" },
#ifdef SIGSOUND
{ SIGSOUND, "SIGSOUND" },
#endif
#ifdef SIGSTKFLT
{ SIGSTKFLT, "SIGSTKFLT" },
#endif
{ SIGSTOP, "SIGSTOP" },
{ SIGSYS, "SIGSYS" },
#ifdef SIGSYSERROR
{ SIGSYSERROR, "SIGSYSERROR" },
#endif
#ifdef SIGTALRM
{ SIGTALRM, "SIGTALRM" },
#endif
{ SIGTERM, "SIGTERM" },
#ifdef SIGTHAW
{ SIGTHAW, "SIGTHAW" },
#endif
{ SIGTRAP, "SIGTRAP" },
#ifdef SIGTSTP
{ SIGTSTP, "SIGTSTP" },
#endif
{ SIGTTIN, "SIGTTIN" },
{ SIGTTOU, "SIGTTOU" },
#ifdef SIGURG
{ SIGURG, "SIGURG" },
#endif
{ SIGUSR1, "SIGUSR1" },
{ SIGUSR2, "SIGUSR2" },
#ifdef SIGVIRT
{ SIGVIRT, "SIGVIRT" },
#endif
{ SIGVTALRM, "SIGVTALRM" },
#ifdef SIGWAITING
{ SIGWAITING, "SIGWAITING" },
#endif
#ifdef SIGWINCH
{ SIGWINCH, "SIGWINCH" },
#endif
#ifdef SIGWINDOW
{ SIGWINDOW, "SIGWINDOW" },
#endif
{ SIGXCPU, "SIGXCPU" },
{ SIGXFSZ, "SIGXFSZ" },
#ifdef SIGXRES
{ SIGXRES, "SIGXRES" },
#endif
{ -1, nullptr }
};
////////////////////////////////////////////////////////////////////////////////
// sun.misc.Signal and BREAK_SIGNAL support
static void jdk_misc_signal_init() {
// Initialize signal structures
::memset((void*)pending_signals, 0, sizeof(pending_signals));
// Initialize signal semaphore
sig_semaphore = new Semaphore();
}
void os::signal_notify(int sig) {
if (sig_semaphore != nullptr) {
Atomic::inc(&pending_signals[sig]);
sig_semaphore->signal();
} else {
// Signal thread is not created with ReduceSignalUsage and jdk_misc_signal_init
// initialization isn't called.
assert(ReduceSignalUsage, "signal semaphore should be created");
}
}
static int check_pending_signals() {
for (;;) {
for (int i = 0; i < NSIG + 1; i++) {
jint n = pending_signals[i];
if (n > 0 && n == Atomic::cmpxchg(&pending_signals[i], n, n - 1)) {
return i;
}
}
sig_semaphore->wait_with_safepoint_check(JavaThread::current());
}
ShouldNotReachHere();
return 0; // Satisfy compiler
}
int os::signal_wait() {
return check_pending_signals();
}
////////////////////////////////////////////////////////////////////////////////
// signal chaining support
static struct sigaction* get_chained_signal_action(int sig) {
struct sigaction *actp = nullptr;
if (libjsig_is_loaded) {
// Retrieve the old signal handler from libjsig
actp = (*get_signal_action)(sig);
}
if (actp == nullptr) {
// Retrieve the preinstalled signal handler from jvm
actp = const_cast<struct sigaction*>(chained_handlers.get(sig));
}
return actp;
}
static bool call_chained_handler(struct sigaction *actp, int sig,
siginfo_t *siginfo, void *context) {
// Call the old signal handler
if (actp->sa_handler == SIG_DFL) {
// It's more reasonable to let jvm treat it as an unexpected exception
// instead of taking the default action.
return false;
} else if (actp->sa_handler != SIG_IGN) {
if ((actp->sa_flags & SA_NODEFER) == 0) {
// automatically block the signal
sigaddset(&(actp->sa_mask), sig);
}
sa_handler_t hand = nullptr;
sa_sigaction_t sa = nullptr;
bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
// retrieve the chained handler
if (siginfo_flag_set) {
sa = actp->sa_sigaction;
} else {
hand = actp->sa_handler;
}
if ((actp->sa_flags & SA_RESETHAND) != 0) {
actp->sa_handler = SIG_DFL;
}
// try to honor the signal mask
sigset_t oset;
sigemptyset(&oset);
pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
// call into the chained handler
if (siginfo_flag_set) {
(*sa)(sig, siginfo, context);
} else {
(*hand)(sig);
}
// restore the signal mask
pthread_sigmask(SIG_SETMASK, &oset, nullptr);
}
// Tell jvm's signal handler the signal is taken care of.
return true;
}
bool PosixSignals::chained_handler(int sig, siginfo_t* siginfo, void* context) {
bool chained = false;
// signal-chaining
if (UseSignalChaining) {
struct sigaction *actp = get_chained_signal_action(sig);
if (actp != nullptr) {
chained = call_chained_handler(actp, sig, siginfo, context);
}
}
return chained;
}
///// Synchronous (non-deferrable) error signals (ILL, SEGV, FPE, BUS, TRAP):
// These signals are special because they cannot be deferred and, if they
// happen while delivery is blocked for the receiving thread, will cause UB
// (in practice typically resulting in sudden process deaths or hangs, see
// JDK-8252533). So we must take care never to block them when we cannot be
// absolutely sure they won't happen. In practice, this is always.
//
// Relevant Posix quote:
// "The behavior of a process is undefined after it ignores a SIGFPE, SIGILL,
// SIGSEGV, or SIGBUS signal that was not generated by kill(), sigqueue(), or
// raise()."
//
// We also include SIGTRAP in that list of never-to-block-signals. While not
// mentioned by the Posix documentation, in our (SAPs) experience blocking it
// causes similar problems. Beside, during normal operation - outside of error
// handling - SIGTRAP may be used for implicit null checking, so it makes sense
// to never block it.
//
// We deal with those signals in two ways:
// - we just never explicitly block them, which includes not accidentally blocking
// them via sa_mask when establishing signal handlers.
// - as an additional safety measure, at the entrance of a signal handler, we
// unblock them explicitly.
static void add_error_signals_to_set(sigset_t* set) {
sigaddset(set, SIGILL);
sigaddset(set, SIGBUS);
sigaddset(set, SIGFPE);
sigaddset(set, SIGSEGV);
sigaddset(set, SIGTRAP);
}
static void remove_error_signals_from_set(sigset_t* set) {
sigdelset(set, SIGILL);
sigdelset(set, SIGBUS);
sigdelset(set, SIGFPE);
sigdelset(set, SIGSEGV);
sigdelset(set, SIGTRAP);
}
// Unblock all signals whose delivery cannot be deferred and which, if they happen
// while delivery is blocked, would cause crashes or hangs (JDK-8252533).
void PosixSignals::unblock_error_signals() {
sigset_t set;
sigemptyset(&set);
add_error_signals_to_set(&set);
::pthread_sigmask(SIG_UNBLOCK, &set, nullptr);
}
class ErrnoPreserver: public StackObj {
const int _saved;
public:
ErrnoPreserver() : _saved(errno) {}
~ErrnoPreserver() { errno = _saved; }
};
////////////////////////////////////////////////////////////////////////////////
// JVM_handle_(linux|aix|bsd)_signal()
// This routine is the shared part of the central hotspot signal handler. It can
// also be called by a user application, if a user application prefers to do
// signal handling itself - in that case it needs to pass signals the VM
// internally uses on to the VM first.
//
// The user-defined signal handler must pass unrecognized signals to this
// routine, and if it returns true (non-zero), then the signal handler must
// return immediately. If the flag "abort_if_unrecognized" is true, then this
// routine will never return false (zero), but instead will execute a VM panic
// routine to kill the process.
//
// If this routine returns false, it is OK to call it again. This allows
// the user-defined signal handler to perform checks either before or after
// the VM performs its own checks. Naturally, the user code would be making
// a serious error if it tried to handle an exception (such as a null check
// or breakpoint) that the VM was generating for its own correct operation.
//
// This routine may recognize any of the following kinds of signals:
// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
// It should be consulted by handlers for any of those signals.
//
// The caller of this routine must pass in the three arguments supplied
// to the function referred to in the "sa_sigaction" (not the "sa_handler")
// field of the structure passed to sigaction(). This routine assumes that
// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
//
// Note that the VM will print warnings if it detects conflicting signal
// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
//
#if defined(BSD)
#define JVM_HANDLE_XXX_SIGNAL JVM_handle_bsd_signal
#elif defined(AIX)
#define JVM_HANDLE_XXX_SIGNAL JVM_handle_aix_signal
#elif defined(LINUX)
#define JVM_HANDLE_XXX_SIGNAL JVM_handle_linux_signal
#else
#error who are you?
#endif
extern "C" JNIEXPORT
int JVM_HANDLE_XXX_SIGNAL(int sig, siginfo_t* info,
void* ucVoid, int abort_if_unrecognized)
{
assert(info != nullptr && ucVoid != nullptr, "sanity");
// Note: it's not uncommon that JNI code uses signal/sigset to install,
// then restore certain signal handler (e.g. to temporarily block SIGPIPE,
// or have a SIGILL handler when detecting CPU type). When that happens,
// this handler might be invoked with junk info/ucVoid. To avoid unnecessary
// crash when libjsig is not preloaded, try handle signals that do not require
// siginfo/ucontext first.
// Preserve errno value over signal handler.
// (note: RAII ok here, even with JFR thread crash protection, see below).
ErrnoPreserver ep;
// Unblock all synchronous error signals (see JDK-8252533)
PosixSignals::unblock_error_signals();
ucontext_t* const uc = (ucontext_t*) ucVoid;
Thread* const t = Thread::current_or_null_safe();
// Handle JFR thread crash protection.
// Note: this may cause us to longjmp away. Do not use any code before this
// point which really needs any form of epilogue code running, eg RAII objects.
ThreadCrashProtection::check_crash_protection(sig, t);
bool signal_was_handled = false;
// Handle assertion poison page accesses.
#ifdef CAN_SHOW_REGISTERS_ON_ASSERT
if (!signal_was_handled &&
((sig == SIGSEGV || sig == SIGBUS) && info != nullptr && info->si_addr == g_assert_poison)) {
signal_was_handled = handle_assert_poison_fault(ucVoid, info->si_addr);
}
#endif
// Extract pc from context. Note that for certain signals and certain
// architectures the pc in ucontext_t will point *after* the offending
// instruction. In those cases, use siginfo si_addr instead.
address pc = nullptr;
if (uc != nullptr) {
if (S390_ONLY(sig == SIGILL || sig == SIGFPE) NOT_S390(false)) {
pc = (address)info->si_addr;
} else {
pc = os::Posix::ucontext_get_pc(uc);
}
}
if (!signal_was_handled) {
signal_was_handled = handle_safefetch(sig, pc, uc);
}
// Ignore SIGPIPE and SIGXFSZ (4229104, 6499219).
if (!signal_was_handled &&
(sig == SIGPIPE || sig == SIGXFSZ)) {
PosixSignals::chained_handler(sig, info, ucVoid);
signal_was_handled = true; // unconditionally.
}
#ifndef ZERO
// Check for UD trap caused by NOP patching.
// If it is, patch return address to be deopt handler.
if (!signal_was_handled && pc != nullptr && os::is_readable_pointer(pc)) {
if (NativeDeoptInstruction::is_deopt_at(pc)) {
CodeBlob* cb = CodeCache::find_blob(pc);
if (cb != nullptr && cb->is_compiled()) {
MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, t);) // can call PcDescCache::add_pc_desc
CompiledMethod* cm = cb->as_compiled_method();
assert(cm->insts_contains_inclusive(pc), "");
address deopt = cm->is_method_handle_return(pc) ?
cm->deopt_mh_handler_begin() :
cm->deopt_handler_begin();
assert(deopt != nullptr, "");
frame fr = os::fetch_frame_from_context(uc);
cm->set_original_pc(&fr, pc);
os::Posix::ucontext_set_pc(uc, deopt);
signal_was_handled = true;
}
}
}
#endif // !ZERO
// Call platform dependent signal handler.
if (!signal_was_handled) {
JavaThread* const jt = (t != nullptr && t->is_Java_thread()) ? JavaThread::cast(t) : nullptr;
signal_was_handled = PosixSignals::pd_hotspot_signal_handler(sig, info, uc, jt);
}
// From here on, if the signal had not been handled, it is a fatal error.
// Give the chained signal handler - should it exist - a shot.
if (!signal_was_handled) {
signal_was_handled = PosixSignals::chained_handler(sig, info, ucVoid);
}
// Invoke fatal error handling.
if (!signal_was_handled && abort_if_unrecognized) {
VMError::report_and_die(t, sig, pc, info, ucVoid);
// VMError should not return.
ShouldNotReachHere();
}
return signal_was_handled;
}
// Entry point for the hotspot signal handler.
static void javaSignalHandler(int sig, siginfo_t* info, void* context) {
// Do not add any code here!
// Only add code to either JVM_HANDLE_XXX_SIGNAL or PosixSignals::pd_hotspot_signal_handler.
(void)JVM_HANDLE_XXX_SIGNAL(sig, info, context, true);
}
static void UserHandler(int sig, siginfo_t* siginfo, void* context) {
PosixSignals::unblock_error_signals();
// Ctrl-C is pressed during error reporting, likely because the error
// handler fails to abort. Let VM die immediately.
if (sig == SIGINT && VMError::is_error_reported()) {
os::die();
}
os::signal_notify(sig);
}
static void print_signal_handler_name(outputStream* os, address handler, char* buf, size_t buflen) {
// We demangle, but omit arguments - signal handlers should have always the same prototype.
os::print_function_and_library_name(os, handler, buf, checked_cast<int>(buflen),
true, // shorten_path
true, // demangle
true // omit arguments
);
}
// Writes one-line description of a combination of sigaction.sa_flags into a user
// provided buffer. Returns that buffer.
static const char* describe_sa_flags(int flags, char* buffer, size_t size) {
char* p = buffer;
size_t remaining = size;
bool first = true;
int idx = 0;
assert(buffer, "invalid argument");
if (size == 0) {
return buffer;
}
strncpy(buffer, "none", size);
const unsigned int unknown_flag = ~(SA_NOCLDSTOP |
SA_ONSTACK |
SA_NOCLDSTOP |
SA_RESTART |
SA_SIGINFO |
SA_NOCLDWAIT |
SA_NODEFER
AIX_ONLY(| SA_OLDSTYLE)
);
const struct {
// NB: i is an unsigned int here because SA_RESETHAND is on some
// systems 0x80000000, which is implicitly unsigned. Assigning
// it to an int field would be an overflow in unsigned-to-signed
// conversion.
unsigned int i;
const char* s;
} flaginfo [] = {
{ SA_NOCLDSTOP, "SA_NOCLDSTOP" },
{ SA_ONSTACK, "SA_ONSTACK" },
{ SA_RESETHAND, "SA_RESETHAND" },
{ SA_RESTART, "SA_RESTART" },
{ SA_SIGINFO, "SA_SIGINFO" },
{ SA_NOCLDWAIT, "SA_NOCLDWAIT" },
{ SA_NODEFER, "SA_NODEFER" },
#if defined(AIX)
{ SA_OLDSTYLE, "SA_OLDSTYLE" },
#endif
{ unknown_flag, "NOT USED" }
};
for (idx = 0; flaginfo[idx].i != unknown_flag && remaining > 1; idx++) {
if (flags & flaginfo[idx].i) {
if (first) {
jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
first = false;
} else {
jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
}
const size_t len = strlen(p);
p += len;
remaining -= len;
}
}
unsigned int unknowns = flags & unknown_flag;
if (unknowns != 0) {
jio_snprintf(p, remaining, "|Unknown_flags:%x", unknowns);
}
buffer[size - 1] = '\0';
return buffer;
}
// Prints one-line description of a combination of sigaction.sa_flags.
static void print_sa_flags(outputStream* st, int flags) {
char buffer[0x100];
describe_sa_flags(flags, buffer, sizeof(buffer));
st->print("%s", buffer);
}
// Implementation may use the same storage for both the sa_sigaction field and the sa_handler field,
// so check for "sigAct.sa_flags == SA_SIGINFO"
static address get_signal_handler(const struct sigaction* action) {
bool siginfo_flag_set = (action->sa_flags & SA_SIGINFO) != 0;
if (siginfo_flag_set) {
return CAST_FROM_FN_PTR(address, action->sa_sigaction);
} else {
return CAST_FROM_FN_PTR(address, action->sa_handler);
}
}
typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
static void SR_handler(int sig, siginfo_t* siginfo, void* context);
// Semantically compare two sigaction structures. Return true if they are referring to
// the same handler, using the same flags.
static bool are_actions_equal(const struct sigaction* sa,
const struct sigaction* expected_sa) {
address this_handler = get_signal_handler(sa);
address expected_handler = get_signal_handler(expected_sa);
const int this_flags = get_sanitized_sa_flags(sa);
const int expected_flags = get_sanitized_sa_flags(expected_sa);
return (this_handler == expected_handler) &&
(this_flags == expected_flags);
}
// If we installed one of our signal handlers for sig, check that the current
// setup matches what we originally installed. Return true if signal handler
// is different. Otherwise, return false;
static bool check_signal_handler(int sig) {
char buf[O_BUFLEN];
bool mismatch = false;
if (!do_check_signal_periodically[sig]) {
return false;
}
const struct sigaction* expected_act = vm_handlers.get(sig);
assert(expected_act != nullptr, "Sanity");
// Retrieve current signal setup.
struct sigaction act;
static os_sigaction_t os_sigaction = nullptr;
if (os_sigaction == nullptr) {
// only trust the default sigaction, in case it has been interposed
os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
if (os_sigaction == nullptr) return false;
}
os_sigaction(sig, (struct sigaction*)nullptr, &act);
// Compare both sigaction structures (intelligently; only the members we care about).
// Ignore if the handler is our own crash handler.
if (!are_actions_equal(&act, expected_act) &&
!(HANDLER_IS(get_signal_handler(&act), VMError::crash_handler_address))) {
tty->print_cr("Warning: %s handler modified!", os::exception_name(sig, buf, sizeof(buf)));
// If we had a mismatch:
// - Disable any further checks for this signal - we do not want to flood stdout. Though
// depending on which signal had been overwritten, we may die very soon anyway.
do_check_signal_periodically[sig] = false;
// Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
tty->print_cr("Note: Running in non-interactive shell, %s handler is replaced by shell",
os::exception_name(sig, buf, O_BUFLEN));
}
return true;
}
return false;
}
void* PosixSignals::user_handler() {
return CAST_FROM_FN_PTR(void*, UserHandler);
}
// Used by JVM_RegisterSignal to install a signal handler.
// The allowed set of signals is restricted by the caller.
// The incoming handler is one of:
// - psuedo-handler: SIG_IGN or SIG_DFL
// - the VM's UserHandler of type sa_sigaction_t
// - unknown signal handling function which we assume is also
// of type sa_sigaction_t - this is a bug - see JDK-8295702
// Returns the currently installed handler.
void* PosixSignals::install_generic_signal_handler(int sig, void* handler) {
struct sigaction sigAct, oldSigAct;
sigfillset(&(sigAct.sa_mask));
remove_error_signals_from_set(&(sigAct.sa_mask));
sigAct.sa_flags = SA_RESTART;
if (HANDLER_IS_IGN_OR_DFL(handler)) {
sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
} else {
sigAct.sa_flags |= SA_SIGINFO;
sigAct.sa_sigaction = CAST_TO_FN_PTR(sa_sigaction_t, handler);
}
if (sigaction(sig, &sigAct, &oldSigAct)) {
// -1 means registration failed
return (void *)-1;
}
return get_signal_handler(&oldSigAct);
}
// Installs the given sigaction handler for the given signal.
// - sigAct: the new struct sigaction to be filled in and used
// for this signal. The caller must provide this as it
// may need to be stored/accessed by that caller.
// - oldSigAct: the old struct sigaction that was associated with
// this signal
// Returns 0 on success and -1 on error.
int PosixSignals::install_sigaction_signal_handler(struct sigaction* sigAct,
struct sigaction* oldSigAct,
int sig,
sa_sigaction_t handler) {
sigfillset(&sigAct->sa_mask);
remove_error_signals_from_set(&sigAct->sa_mask);
sigAct->sa_sigaction = handler;
sigAct->sa_flags = SA_SIGINFO|SA_RESTART;
#if defined(__APPLE__)
// Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
// (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
// if the signal handler declares it will handle it on alternate stack.
// Notice we only declare we will handle it on alt stack, but we are not
// actually going to use real alt stack - this is just a workaround.
// Please see ux_exception.c, method catch_mach_exception_raise for details
// link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
if (sig == SIGSEGV) {
sigAct->sa_flags |= SA_ONSTACK;
}
#endif
return sigaction(sig, sigAct, oldSigAct);
}
// Will be modified when max signal is changed to be dynamic
int os::sigexitnum_pd() {
return NSIG;
}
// This method is a periodic task to check for misbehaving JNI applications
// under CheckJNI, we can add any periodic checks here
void os::run_periodic_checks(outputStream* st) {
if (check_signals == false) return;
// SEGV and BUS if overridden could potentially prevent
// generation of hs*.log in the event of a crash, debugging
// such a case can be very challenging, so we absolutely
// check the following for a good measure:
bool print_handlers = false;
print_handlers |= check_signal_handler(SIGSEGV);
print_handlers |= check_signal_handler(SIGILL);
print_handlers |= check_signal_handler(SIGFPE);
print_handlers |= check_signal_handler(SIGBUS);
PPC64_ONLY(print_handlers |= check_signal_handler(SIGTRAP);)
// ReduceSignalUsage allows the user to override these handlers
// see comments at the very top and jvm_md.h
if (!ReduceSignalUsage) {
print_handlers |= check_signal_handler(SHUTDOWN1_SIGNAL);
print_handlers |= check_signal_handler(SHUTDOWN2_SIGNAL);
print_handlers |= check_signal_handler(SHUTDOWN3_SIGNAL);
print_handlers |= check_signal_handler(BREAK_SIGNAL);
}
print_handlers |= check_signal_handler(PosixSignals::SR_signum);
// As we ignore SIGPIPE and SIGXFSZ, and expect other code to potentially
// install handlers for them, we don't bother checking them here.
if (print_handlers) {
// If we had a mismatch:
// - print all signal handlers. As part of that printout, details will be printed
// about any modified handlers.
char buf[O_BUFLEN];
os::print_signal_handlers(st, buf, O_BUFLEN);
st->print_cr("Consider using jsig library.");
}
}
// Helper function for PosixSignals::print_siginfo_...():
// return a textual description for signal code.
struct enum_sigcode_desc_t {
const char* s_name;
const char* s_desc;
};
static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
const struct {
int sig; int code; const char* s_code; const char* s_desc;
} t1 [] = {
{ SIGILL, ILL_ILLOPC, "ILL_ILLOPC", "Illegal opcode." },
{ SIGILL, ILL_ILLOPN, "ILL_ILLOPN", "Illegal operand." },
{ SIGILL, ILL_ILLADR, "ILL_ILLADR", "Illegal addressing mode." },
{ SIGILL, ILL_ILLTRP, "ILL_ILLTRP", "Illegal trap." },
{ SIGILL, ILL_PRVOPC, "ILL_PRVOPC", "Privileged opcode." },
{ SIGILL, ILL_PRVREG, "ILL_PRVREG", "Privileged register." },
{ SIGILL, ILL_COPROC, "ILL_COPROC", "Coprocessor error." },
{ SIGILL, ILL_BADSTK, "ILL_BADSTK", "Internal stack error." },
#if defined(IA64) && defined(LINUX)
{ SIGILL, ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
{ SIGILL, ILL_BREAK, "ILL_BREAK", "Application Break instruction" },
#endif
{ SIGFPE, FPE_INTDIV, "FPE_INTDIV", "Integer divide by zero." },
{ SIGFPE, FPE_INTOVF, "FPE_INTOVF", "Integer overflow." },
{ SIGFPE, FPE_FLTDIV, "FPE_FLTDIV", "Floating-point divide by zero." },
{ SIGFPE, FPE_FLTOVF, "FPE_FLTOVF", "Floating-point overflow." },
{ SIGFPE, FPE_FLTUND, "FPE_FLTUND", "Floating-point underflow." },
{ SIGFPE, FPE_FLTRES, "FPE_FLTRES", "Floating-point inexact result." },
{ SIGFPE, FPE_FLTINV, "FPE_FLTINV", "Invalid floating-point operation." },
{ SIGFPE, FPE_FLTSUB, "FPE_FLTSUB", "Subscript out of range." },
{ SIGSEGV, SEGV_MAPERR, "SEGV_MAPERR", "Address not mapped to object." },
{ SIGSEGV, SEGV_ACCERR, "SEGV_ACCERR", "Invalid permissions for mapped object." },
#if defined(AIX)
// no explanation found what keyerr would be
{ SIGSEGV, SEGV_KEYERR, "SEGV_KEYERR", "key error" },
#endif
#if defined(IA64) && !defined(AIX)
{ SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
#endif
{ SIGBUS, BUS_ADRALN, "BUS_ADRALN", "Invalid address alignment." },
{ SIGBUS, BUS_ADRERR, "BUS_ADRERR", "Nonexistent physical address." },
{ SIGBUS, BUS_OBJERR, "BUS_OBJERR", "Object-specific hardware error." },
{ SIGTRAP, TRAP_BRKPT, "TRAP_BRKPT", "Process breakpoint." },
{ SIGTRAP, TRAP_TRACE, "TRAP_TRACE", "Process trace trap." },
{ SIGCHLD, CLD_EXITED, "CLD_EXITED", "Child has exited." },
{ SIGCHLD, CLD_KILLED, "CLD_KILLED", "Child has terminated abnormally and did not create a core file." },
{ SIGCHLD, CLD_DUMPED, "CLD_DUMPED", "Child has terminated abnormally and created a core file." },