Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/hotspot/os/posix/signals_posix.cpp
64440 views
1
/*
2
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*
23
*/
24
25
#include "precompiled.hpp"
26
27
#include "jvm.h"
28
#include "logging/log.hpp"
29
#include "runtime/atomic.hpp"
30
#include "runtime/globals.hpp"
31
#include "runtime/interfaceSupport.inline.hpp"
32
#include "runtime/java.hpp"
33
#include "runtime/os.hpp"
34
#include "runtime/osThread.hpp"
35
#include "runtime/semaphore.inline.hpp"
36
#include "runtime/stubRoutines.hpp"
37
#include "runtime/thread.hpp"
38
#include "signals_posix.hpp"
39
#include "utilities/events.hpp"
40
#include "utilities/ostream.hpp"
41
#include "utilities/vmError.hpp"
42
43
#include "code/codeCache.hpp"
44
#include <sys/mman.h>
45
46
#ifdef ZERO
47
// See stubGenerator_zero.cpp
48
#include <setjmp.h>
49
extern sigjmp_buf* get_jmp_buf_for_continuation();
50
#endif
51
52
#include <signal.h>
53
54
55
static const char* get_signal_name(int sig, char* out, size_t outlen);
56
57
// Returns address of a handler associated with the given sigaction
58
static address get_signal_handler(const struct sigaction* action);
59
60
#define HANDLER_IS(handler, address) ((handler) == CAST_FROM_FN_PTR(void*, (address)))
61
#define HANDLER_IS_IGN(handler) (HANDLER_IS(handler, SIG_IGN))
62
#define HANDLER_IS_DFL(handler) (HANDLER_IS(handler, SIG_DFL))
63
#define HANDLER_IS_IGN_OR_DFL(handler) (HANDLER_IS_IGN(handler) || HANDLER_IS_DFL(handler))
64
65
// Various signal related mechanism are laid out in the following order:
66
//
67
// sun.misc.Signal
68
// signal chaining
69
// signal handling (except suspend/resume)
70
// suspend/resume
71
72
// Helper function to strip any flags from a sigaction sa_flag
73
// which are not needed for semantic comparison (see remarks below
74
// about SA_RESTORER on Linux).
75
// Also to work around the fact that not all platforms define sa_flags
76
// as signed int (looking at you, zlinux).
77
static int get_sanitized_sa_flags(const struct sigaction* sa) {
78
int f = (int) sa->sa_flags;
79
#ifdef LINUX
80
// Glibc on Linux uses the SA_RESTORER flag to indicate
81
// the use of a "signal trampoline". We have no interest
82
// in this flag and need to ignore it when checking our
83
// own flag settings.
84
// Note: SA_RESTORER is not exposed through signal.h so we
85
// have to hardcode its 0x04000000 value here.
86
const int sa_restorer_flag = 0x04000000;
87
f &= ~sa_restorer_flag;
88
#endif // LINUX
89
return f;
90
}
91
92
// Todo: provide a os::get_max_process_id() or similar. Number of processes
93
// may have been configured, can be read more accurately from proc fs etc.
94
#ifndef MAX_PID
95
#define MAX_PID INT_MAX
96
#endif
97
#define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
98
99
#define NUM_IMPORTANT_SIGS 32
100
101
extern "C" {
102
typedef void (*sa_handler_t)(int);
103
typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
104
}
105
106
// At various places we store handler information for each installed handler.
107
// SavedSignalHandlers is a helper class for those cases, keeping an array of sigaction
108
// structures.
109
class SavedSignalHandlers {
110
// Note: NSIG can be largish, depending on platform, and this array is expected
111
// to be sparsely populated. To save space the contained structures are
112
// C-heap allocated. Since they only get added outside of signal handling
113
// this is no problem.
114
struct sigaction* _sa[NSIG];
115
116
bool check_signal_number(int sig) const {
117
assert(sig > 0 && sig < NSIG, "invalid signal number %d", sig);
118
return sig > 0 && sig < NSIG;
119
}
120
121
public:
122
123
SavedSignalHandlers() {
124
::memset(_sa, 0, sizeof(_sa));
125
}
126
127
~SavedSignalHandlers() {
128
for (int i = 0; i < NSIG; i ++) {
129
FREE_C_HEAP_OBJ(_sa[i]);
130
}
131
}
132
133
void set(int sig, const struct sigaction* act) {
134
if (check_signal_number(sig)) {
135
assert(_sa[sig] == NULL, "Overwriting signal handler?");
136
_sa[sig] = NEW_C_HEAP_OBJ(struct sigaction, mtInternal);
137
*_sa[sig] = *act;
138
}
139
}
140
141
const struct sigaction* get(int sig) const {
142
if (check_signal_number(sig)) {
143
return _sa[sig];
144
}
145
return NULL;
146
}
147
};
148
149
150
debug_only(static bool signal_sets_initialized = false);
151
static sigset_t unblocked_sigs, vm_sigs, preinstalled_sigs;
152
153
// Our own signal handlers should never ever get replaced by a third party one.
154
// To check that, and to aid with diagnostics, store a copy of the handler setup
155
// and compare it periodically against reality (see os::run_periodic_checks()).
156
static bool check_signals = true;
157
static SavedSignalHandlers vm_handlers;
158
static bool do_check_signal_periodically[NSIG] = { 0 };
159
160
// For signal-chaining:
161
// if chaining is active, chained_handlers contains all handlers which we
162
// replaced with our own and to which we must delegate.
163
static SavedSignalHandlers chained_handlers;
164
static bool libjsig_is_loaded = false;
165
typedef struct sigaction *(*get_signal_t)(int);
166
static get_signal_t get_signal_action = NULL;
167
168
// suspend/resume support
169
#if defined(__APPLE__)
170
static OSXSemaphore sr_semaphore;
171
#else
172
static PosixSemaphore sr_semaphore;
173
#endif
174
175
// Signal number used to suspend/resume a thread
176
// do not use any signal number less than SIGSEGV, see 4355769
177
int PosixSignals::SR_signum = SIGUSR2;
178
179
// sun.misc.Signal support
180
static Semaphore* sig_semaphore = NULL;
181
// a counter for each possible signal value
182
static volatile jint pending_signals[NSIG+1] = { 0 };
183
184
static const struct {
185
int sig; const char* name;
186
} g_signal_info[] = {
187
{ SIGABRT, "SIGABRT" },
188
#ifdef SIGAIO
189
{ SIGAIO, "SIGAIO" },
190
#endif
191
{ SIGALRM, "SIGALRM" },
192
#ifdef SIGALRM1
193
{ SIGALRM1, "SIGALRM1" },
194
#endif
195
{ SIGBUS, "SIGBUS" },
196
#ifdef SIGCANCEL
197
{ SIGCANCEL, "SIGCANCEL" },
198
#endif
199
{ SIGCHLD, "SIGCHLD" },
200
#ifdef SIGCLD
201
{ SIGCLD, "SIGCLD" },
202
#endif
203
{ SIGCONT, "SIGCONT" },
204
#ifdef SIGCPUFAIL
205
{ SIGCPUFAIL, "SIGCPUFAIL" },
206
#endif
207
#ifdef SIGDANGER
208
{ SIGDANGER, "SIGDANGER" },
209
#endif
210
#ifdef SIGDIL
211
{ SIGDIL, "SIGDIL" },
212
#endif
213
#ifdef SIGEMT
214
{ SIGEMT, "SIGEMT" },
215
#endif
216
{ SIGFPE, "SIGFPE" },
217
#ifdef SIGFREEZE
218
{ SIGFREEZE, "SIGFREEZE" },
219
#endif
220
#ifdef SIGGFAULT
221
{ SIGGFAULT, "SIGGFAULT" },
222
#endif
223
#ifdef SIGGRANT
224
{ SIGGRANT, "SIGGRANT" },
225
#endif
226
{ SIGHUP, "SIGHUP" },
227
{ SIGILL, "SIGILL" },
228
#ifdef SIGINFO
229
{ SIGINFO, "SIGINFO" },
230
#endif
231
{ SIGINT, "SIGINT" },
232
#ifdef SIGIO
233
{ SIGIO, "SIGIO" },
234
#endif
235
#ifdef SIGIOINT
236
{ SIGIOINT, "SIGIOINT" },
237
#endif
238
#ifdef SIGIOT
239
// SIGIOT is there for BSD compatibility, but on most Unices just a
240
// synonym for SIGABRT. The result should be "SIGABRT", not
241
// "SIGIOT".
242
#if (SIGIOT != SIGABRT )
243
{ SIGIOT, "SIGIOT" },
244
#endif
245
#endif
246
#ifdef SIGKAP
247
{ SIGKAP, "SIGKAP" },
248
#endif
249
{ SIGKILL, "SIGKILL" },
250
#ifdef SIGLOST
251
{ SIGLOST, "SIGLOST" },
252
#endif
253
#ifdef SIGLWP
254
{ SIGLWP, "SIGLWP" },
255
#endif
256
#ifdef SIGLWPTIMER
257
{ SIGLWPTIMER, "SIGLWPTIMER" },
258
#endif
259
#ifdef SIGMIGRATE
260
{ SIGMIGRATE, "SIGMIGRATE" },
261
#endif
262
#ifdef SIGMSG
263
{ SIGMSG, "SIGMSG" },
264
#endif
265
{ SIGPIPE, "SIGPIPE" },
266
#ifdef SIGPOLL
267
{ SIGPOLL, "SIGPOLL" },
268
#endif
269
#ifdef SIGPRE
270
{ SIGPRE, "SIGPRE" },
271
#endif
272
{ SIGPROF, "SIGPROF" },
273
#ifdef SIGPTY
274
{ SIGPTY, "SIGPTY" },
275
#endif
276
#ifdef SIGPWR
277
{ SIGPWR, "SIGPWR" },
278
#endif
279
{ SIGQUIT, "SIGQUIT" },
280
#ifdef SIGRECONFIG
281
{ SIGRECONFIG, "SIGRECONFIG" },
282
#endif
283
#ifdef SIGRECOVERY
284
{ SIGRECOVERY, "SIGRECOVERY" },
285
#endif
286
#ifdef SIGRESERVE
287
{ SIGRESERVE, "SIGRESERVE" },
288
#endif
289
#ifdef SIGRETRACT
290
{ SIGRETRACT, "SIGRETRACT" },
291
#endif
292
#ifdef SIGSAK
293
{ SIGSAK, "SIGSAK" },
294
#endif
295
{ SIGSEGV, "SIGSEGV" },
296
#ifdef SIGSOUND
297
{ SIGSOUND, "SIGSOUND" },
298
#endif
299
#ifdef SIGSTKFLT
300
{ SIGSTKFLT, "SIGSTKFLT" },
301
#endif
302
{ SIGSTOP, "SIGSTOP" },
303
{ SIGSYS, "SIGSYS" },
304
#ifdef SIGSYSERROR
305
{ SIGSYSERROR, "SIGSYSERROR" },
306
#endif
307
#ifdef SIGTALRM
308
{ SIGTALRM, "SIGTALRM" },
309
#endif
310
{ SIGTERM, "SIGTERM" },
311
#ifdef SIGTHAW
312
{ SIGTHAW, "SIGTHAW" },
313
#endif
314
{ SIGTRAP, "SIGTRAP" },
315
#ifdef SIGTSTP
316
{ SIGTSTP, "SIGTSTP" },
317
#endif
318
{ SIGTTIN, "SIGTTIN" },
319
{ SIGTTOU, "SIGTTOU" },
320
#ifdef SIGURG
321
{ SIGURG, "SIGURG" },
322
#endif
323
{ SIGUSR1, "SIGUSR1" },
324
{ SIGUSR2, "SIGUSR2" },
325
#ifdef SIGVIRT
326
{ SIGVIRT, "SIGVIRT" },
327
#endif
328
{ SIGVTALRM, "SIGVTALRM" },
329
#ifdef SIGWAITING
330
{ SIGWAITING, "SIGWAITING" },
331
#endif
332
#ifdef SIGWINCH
333
{ SIGWINCH, "SIGWINCH" },
334
#endif
335
#ifdef SIGWINDOW
336
{ SIGWINDOW, "SIGWINDOW" },
337
#endif
338
{ SIGXCPU, "SIGXCPU" },
339
{ SIGXFSZ, "SIGXFSZ" },
340
#ifdef SIGXRES
341
{ SIGXRES, "SIGXRES" },
342
#endif
343
{ -1, NULL }
344
};
345
346
////////////////////////////////////////////////////////////////////////////////
347
// sun.misc.Signal support
348
349
void jdk_misc_signal_init() {
350
// Initialize signal structures
351
::memset((void*)pending_signals, 0, sizeof(pending_signals));
352
353
// Initialize signal semaphore
354
sig_semaphore = new Semaphore();
355
}
356
357
void os::signal_notify(int sig) {
358
if (sig_semaphore != NULL) {
359
Atomic::inc(&pending_signals[sig]);
360
sig_semaphore->signal();
361
} else {
362
// Signal thread is not created with ReduceSignalUsage and jdk_misc_signal_init
363
// initialization isn't called.
364
assert(ReduceSignalUsage, "signal semaphore should be created");
365
}
366
}
367
368
static int check_pending_signals() {
369
for (;;) {
370
for (int i = 0; i < NSIG + 1; i++) {
371
jint n = pending_signals[i];
372
if (n > 0 && n == Atomic::cmpxchg(&pending_signals[i], n, n - 1)) {
373
return i;
374
}
375
}
376
sig_semaphore->wait_with_safepoint_check(JavaThread::current());
377
}
378
ShouldNotReachHere();
379
return 0; // Satisfy compiler
380
}
381
382
int os::signal_wait() {
383
return check_pending_signals();
384
}
385
386
////////////////////////////////////////////////////////////////////////////////
387
// signal chaining support
388
389
struct sigaction* get_chained_signal_action(int sig) {
390
struct sigaction *actp = NULL;
391
392
if (libjsig_is_loaded) {
393
// Retrieve the old signal handler from libjsig
394
actp = (*get_signal_action)(sig);
395
}
396
if (actp == NULL) {
397
// Retrieve the preinstalled signal handler from jvm
398
actp = const_cast<struct sigaction*>(chained_handlers.get(sig));
399
}
400
401
return actp;
402
}
403
404
static bool call_chained_handler(struct sigaction *actp, int sig,
405
siginfo_t *siginfo, void *context) {
406
// Call the old signal handler
407
if (actp->sa_handler == SIG_DFL) {
408
// It's more reasonable to let jvm treat it as an unexpected exception
409
// instead of taking the default action.
410
return false;
411
} else if (actp->sa_handler != SIG_IGN) {
412
if ((actp->sa_flags & SA_NODEFER) == 0) {
413
// automaticlly block the signal
414
sigaddset(&(actp->sa_mask), sig);
415
}
416
417
sa_handler_t hand = NULL;
418
sa_sigaction_t sa = NULL;
419
bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
420
// retrieve the chained handler
421
if (siginfo_flag_set) {
422
sa = actp->sa_sigaction;
423
} else {
424
hand = actp->sa_handler;
425
}
426
427
if ((actp->sa_flags & SA_RESETHAND) != 0) {
428
actp->sa_handler = SIG_DFL;
429
}
430
431
// try to honor the signal mask
432
sigset_t oset;
433
sigemptyset(&oset);
434
pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
435
436
// call into the chained handler
437
if (siginfo_flag_set) {
438
(*sa)(sig, siginfo, context);
439
} else {
440
(*hand)(sig);
441
}
442
443
// restore the signal mask
444
pthread_sigmask(SIG_SETMASK, &oset, NULL);
445
}
446
// Tell jvm's signal handler the signal is taken care of.
447
return true;
448
}
449
450
bool PosixSignals::chained_handler(int sig, siginfo_t* siginfo, void* context) {
451
bool chained = false;
452
// signal-chaining
453
if (UseSignalChaining) {
454
struct sigaction *actp = get_chained_signal_action(sig);
455
if (actp != NULL) {
456
chained = call_chained_handler(actp, sig, siginfo, context);
457
}
458
}
459
return chained;
460
}
461
462
///// Synchronous (non-deferrable) error signals (ILL, SEGV, FPE, BUS, TRAP):
463
464
// These signals are special because they cannot be deferred and, if they
465
// happen while delivery is blocked for the receiving thread, will cause UB
466
// (in practice typically resulting in sudden process deaths or hangs, see
467
// JDK-8252533). So we must take care never to block them when we cannot be
468
// absolutely sure they won't happen. In practice, this is always.
469
//
470
// Relevant Posix quote:
471
// "The behavior of a process is undefined after it ignores a SIGFPE, SIGILL,
472
// SIGSEGV, or SIGBUS signal that was not generated by kill(), sigqueue(), or
473
// raise()."
474
//
475
// We also include SIGTRAP in that list of never-to-block-signals. While not
476
// mentioned by the Posix documentation, in our (SAPs) experience blocking it
477
// causes similar problems. Beside, during normal operation - outside of error
478
// handling - SIGTRAP may be used for implicit NULL checking, so it makes sense
479
// to never block it.
480
//
481
// We deal with those signals in two ways:
482
// - we just never explicitly block them, which includes not accidentally blocking
483
// them via sa_mask when establishing signal handlers.
484
// - as an additional safety measure, at the entrance of a signal handler, we
485
// unblock them explicitly.
486
487
static void add_error_signals_to_set(sigset_t* set) {
488
sigaddset(set, SIGILL);
489
sigaddset(set, SIGBUS);
490
sigaddset(set, SIGFPE);
491
sigaddset(set, SIGSEGV);
492
sigaddset(set, SIGTRAP);
493
}
494
495
static void remove_error_signals_from_set(sigset_t* set) {
496
sigdelset(set, SIGILL);
497
sigdelset(set, SIGBUS);
498
sigdelset(set, SIGFPE);
499
sigdelset(set, SIGSEGV);
500
sigdelset(set, SIGTRAP);
501
}
502
503
// Unblock all signals whose delivery cannot be deferred and which, if they happen
504
// while delivery is blocked, would cause crashes or hangs (JDK-8252533).
505
void PosixSignals::unblock_error_signals() {
506
sigset_t set;
507
sigemptyset(&set);
508
add_error_signals_to_set(&set);
509
::pthread_sigmask(SIG_UNBLOCK, &set, NULL);
510
}
511
512
class ErrnoPreserver: public StackObj {
513
const int _saved;
514
public:
515
ErrnoPreserver() : _saved(errno) {}
516
~ErrnoPreserver() { errno = _saved; }
517
};
518
519
////////////////////////////////////////////////////////////////////////////////
520
// JVM_handle_(linux|aix|bsd)_signal()
521
522
// This routine is the shared part of the central hotspot signal handler. It can
523
// also be called by a user application, if a user application prefers to do
524
// signal handling itself - in that case it needs to pass signals the VM
525
// internally uses on to the VM first.
526
//
527
// The user-defined signal handler must pass unrecognized signals to this
528
// routine, and if it returns true (non-zero), then the signal handler must
529
// return immediately. If the flag "abort_if_unrecognized" is true, then this
530
// routine will never return false (zero), but instead will execute a VM panic
531
// routine to kill the process.
532
//
533
// If this routine returns false, it is OK to call it again. This allows
534
// the user-defined signal handler to perform checks either before or after
535
// the VM performs its own checks. Naturally, the user code would be making
536
// a serious error if it tried to handle an exception (such as a null check
537
// or breakpoint) that the VM was generating for its own correct operation.
538
//
539
// This routine may recognize any of the following kinds of signals:
540
// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
541
// It should be consulted by handlers for any of those signals.
542
//
543
// The caller of this routine must pass in the three arguments supplied
544
// to the function referred to in the "sa_sigaction" (not the "sa_handler")
545
// field of the structure passed to sigaction(). This routine assumes that
546
// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
547
//
548
// Note that the VM will print warnings if it detects conflicting signal
549
// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
550
//
551
552
#if defined(BSD)
553
#define JVM_HANDLE_XXX_SIGNAL JVM_handle_bsd_signal
554
#elif defined(AIX)
555
#define JVM_HANDLE_XXX_SIGNAL JVM_handle_aix_signal
556
#elif defined(LINUX)
557
#define JVM_HANDLE_XXX_SIGNAL JVM_handle_linux_signal
558
#else
559
#error who are you?
560
#endif
561
562
extern "C" JNIEXPORT
563
int JVM_HANDLE_XXX_SIGNAL(int sig, siginfo_t* info,
564
void* ucVoid, int abort_if_unrecognized)
565
{
566
assert(info != NULL && ucVoid != NULL, "sanity");
567
568
if (sig == BREAK_SIGNAL) {
569
assert(!ReduceSignalUsage, "Should not happen with -Xrs/-XX:+ReduceSignalUsage");
570
return true; // ignore it
571
}
572
573
// Note: it's not uncommon that JNI code uses signal/sigset to install,
574
// then restore certain signal handler (e.g. to temporarily block SIGPIPE,
575
// or have a SIGILL handler when detecting CPU type). When that happens,
576
// this handler might be invoked with junk info/ucVoid. To avoid unnecessary
577
// crash when libjsig is not preloaded, try handle signals that do not require
578
// siginfo/ucontext first.
579
580
// Preserve errno value over signal handler.
581
// (note: RAII ok here, even with JFR thread crash protection, see below).
582
ErrnoPreserver ep;
583
584
// Unblock all synchronous error signals (see JDK-8252533)
585
PosixSignals::unblock_error_signals();
586
587
ucontext_t* const uc = (ucontext_t*) ucVoid;
588
Thread* const t = Thread::current_or_null_safe();
589
590
// Hopefully placing W^X handing here is safe enough, maybe check repeat?
591
if (!os::Bsd::isRWXJITAvailable() && sig == SIGBUS) {
592
address pc = (address) os::Posix::ucontext_get_pc(uc);
593
//static address last_pc, last_si_addr;
594
if (pc == info->si_addr) { //(pc >= CodeCache::low_bound() && pc < CodeCache::high_bound()) {
595
//(CodeCache::contains(pc) || thread->thread_state() == _thread_in_Java) {
596
//if (last_pc != pc) {
597
// last_pc = pc;
598
bool handled = !mprotect((address) ((uintptr_t)pc & -PAGE_SIZE), PAGE_SIZE, PROT_READ | PROT_EXEC);
599
if (handled) return true;
600
//}
601
} else if (info->si_addr >= CodeCache::low_bound() && info->si_addr < CodeCache::high_bound()) {
602
//(CodeCache::contains(info->si_addr)) { // && last_si_addr != info->si_addr) {
603
//last_si_addr = (address) info->si_addr;
604
bool handled = !mprotect((address) ((uintptr_t)info->si_addr & -PAGE_SIZE), PAGE_SIZE, PROT_READ | PROT_WRITE);
605
if (handled) return true;
606
}
607
}
608
609
610
// Handle JFR thread crash protection.
611
// Note: this may cause us to longjmp away. Do not use any code before this
612
// point which really needs any form of epilogue code running, eg RAII objects.
613
os::ThreadCrashProtection::check_crash_protection(sig, t);
614
615
bool signal_was_handled = false;
616
617
// Handle assertion poison page accesses.
618
#ifdef CAN_SHOW_REGISTERS_ON_ASSERT
619
if (!signal_was_handled &&
620
((sig == SIGSEGV || sig == SIGBUS) && info != NULL && info->si_addr == g_assert_poison)) {
621
signal_was_handled = handle_assert_poison_fault(ucVoid, info->si_addr);
622
}
623
#endif
624
625
if (!signal_was_handled) {
626
// Handle SafeFetch access.
627
#ifndef ZERO
628
if (uc != NULL) {
629
address pc = os::Posix::ucontext_get_pc(uc);
630
if (StubRoutines::is_safefetch_fault(pc)) {
631
os::Posix::ucontext_set_pc(uc, StubRoutines::continuation_for_safefetch_fault(pc));
632
signal_was_handled = true;
633
}
634
}
635
#else
636
// See JDK-8076185
637
if (sig == SIGSEGV || sig == SIGBUS) {
638
sigjmp_buf* const pjb = get_jmp_buf_for_continuation();
639
if (pjb) {
640
siglongjmp(*pjb, 1);
641
}
642
}
643
#endif // ZERO
644
}
645
646
// Ignore SIGPIPE and SIGXFSZ (4229104, 6499219).
647
if (!signal_was_handled &&
648
(sig == SIGPIPE || sig == SIGXFSZ)) {
649
PosixSignals::chained_handler(sig, info, ucVoid);
650
signal_was_handled = true; // unconditionally.
651
}
652
653
// Call platform dependent signal handler.
654
if (!signal_was_handled) {
655
JavaThread* const jt = (t != NULL && t->is_Java_thread()) ? (JavaThread*) t : NULL;
656
signal_was_handled = PosixSignals::pd_hotspot_signal_handler(sig, info, uc, jt);
657
}
658
659
// From here on, if the signal had not been handled, it is a fatal error.
660
661
// Give the chained signal handler - should it exist - a shot.
662
if (!signal_was_handled) {
663
signal_was_handled = PosixSignals::chained_handler(sig, info, ucVoid);
664
}
665
666
// Invoke fatal error handling.
667
if (!signal_was_handled && abort_if_unrecognized) {
668
// Extract pc from context for the error handler to display.
669
address pc = NULL;
670
if (uc != NULL) {
671
// prepare fault pc address for error reporting.
672
if (S390_ONLY(sig == SIGILL || sig == SIGFPE) NOT_S390(false)) {
673
pc = (address)info->si_addr;
674
} else if (ZERO_ONLY(true) NOT_ZERO(false)) {
675
// Non-arch-specific Zero code does not really know the pc.
676
// This can be alleviated by making arch-specific os::Posix::ucontext_get_pc
677
// available for Zero for known architectures. But for generic Zero
678
// code, it would still remain unknown.
679
pc = NULL;
680
} else {
681
pc = os::Posix::ucontext_get_pc(uc);
682
}
683
}
684
// For Zero, we ignore the crash context, because:
685
// a) The crash would be in C++ interpreter code, so context is not really relevant;
686
// b) Generic Zero code would not be able to parse it, so when generic error
687
// reporting code asks e.g. about frames on stack, Zero would experience
688
// a secondary ShouldNotCallThis() crash.
689
VMError::report_and_die(t, sig, pc, info, NOT_ZERO(ucVoid) ZERO_ONLY(NULL));
690
// VMError should not return.
691
ShouldNotReachHere();
692
}
693
return signal_was_handled;
694
}
695
696
// Entry point for the hotspot signal handler.
697
static void javaSignalHandler(int sig, siginfo_t* info, void* ucVoid) {
698
// Do not add any code here!
699
// Only add code to either JVM_HANDLE_XXX_SIGNAL or PosixSignals::pd_hotspot_signal_handler.
700
(void)JVM_HANDLE_XXX_SIGNAL(sig, info, ucVoid, true);
701
}
702
703
static void UserHandler(int sig, void *siginfo, void *context) {
704
705
PosixSignals::unblock_error_signals();
706
707
// Ctrl-C is pressed during error reporting, likely because the error
708
// handler fails to abort. Let VM die immediately.
709
if (sig == SIGINT && VMError::is_error_reported()) {
710
os::die();
711
}
712
713
os::signal_notify(sig);
714
}
715
716
static void print_signal_handler_name(outputStream* os, address handler, char* buf, size_t buflen) {
717
// We demangle, but omit arguments - signal handlers should have always the same prototype.
718
os::print_function_and_library_name(os, handler, buf, buflen,
719
true, // shorten_path
720
true, // demangle
721
true // omit arguments
722
);
723
}
724
725
// Writes one-line description of a combination of sigaction.sa_flags into a user
726
// provided buffer. Returns that buffer.
727
static const char* describe_sa_flags(int flags, char* buffer, size_t size) {
728
char* p = buffer;
729
size_t remaining = size;
730
bool first = true;
731
int idx = 0;
732
733
assert(buffer, "invalid argument");
734
735
if (size == 0) {
736
return buffer;
737
}
738
739
strncpy(buffer, "none", size);
740
741
const unsigned int unknown_flag = ~(SA_NOCLDSTOP |
742
SA_ONSTACK |
743
SA_NOCLDSTOP |
744
SA_RESTART |
745
SA_SIGINFO |
746
SA_NOCLDWAIT |
747
SA_NODEFER
748
AIX_ONLY(| SA_OLDSTYLE)
749
);
750
751
const struct {
752
// NB: i is an unsigned int here because SA_RESETHAND is on some
753
// systems 0x80000000, which is implicitly unsigned. Assigning
754
// it to an int field would be an overflow in unsigned-to-signed
755
// conversion.
756
unsigned int i;
757
const char* s;
758
} flaginfo [] = {
759
{ SA_NOCLDSTOP, "SA_NOCLDSTOP" },
760
{ SA_ONSTACK, "SA_ONSTACK" },
761
{ SA_RESETHAND, "SA_RESETHAND" },
762
{ SA_RESTART, "SA_RESTART" },
763
{ SA_SIGINFO, "SA_SIGINFO" },
764
{ SA_NOCLDWAIT, "SA_NOCLDWAIT" },
765
{ SA_NODEFER, "SA_NODEFER" },
766
#if defined(AIX)
767
{ SA_OLDSTYLE, "SA_OLDSTYLE" },
768
#endif
769
{ unknown_flag, "NOT USED" }
770
};
771
772
for (idx = 0; flaginfo[idx].i != unknown_flag && remaining > 1; idx++) {
773
if (flags & flaginfo[idx].i) {
774
if (first) {
775
jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
776
first = false;
777
} else {
778
jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
779
}
780
const size_t len = strlen(p);
781
p += len;
782
remaining -= len;
783
}
784
}
785
unsigned int unknowns = flags & unknown_flag;
786
if (unknowns != 0) {
787
jio_snprintf(p, remaining, "|Unknown_flags:%x", unknowns);
788
}
789
790
buffer[size - 1] = '\0';
791
792
return buffer;
793
}
794
795
// Prints one-line description of a combination of sigaction.sa_flags.
796
static void print_sa_flags(outputStream* st, int flags) {
797
char buffer[0x100];
798
describe_sa_flags(flags, buffer, sizeof(buffer));
799
st->print("%s", buffer);
800
}
801
802
// Implementation may use the same storage for both the sa_sigaction field and the sa_handler field,
803
// so check for "sigAct.sa_flags == SA_SIGINFO"
804
static address get_signal_handler(const struct sigaction* action) {
805
bool siginfo_flag_set = (action->sa_flags & SA_SIGINFO) != 0;
806
if (siginfo_flag_set) {
807
return CAST_FROM_FN_PTR(address, action->sa_sigaction);
808
} else {
809
return CAST_FROM_FN_PTR(address, action->sa_handler);
810
}
811
}
812
813
typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
814
815
static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context);
816
817
// Semantically compare two sigaction structures. Return true if they are referring to
818
// the same handler, using the same flags.
819
static bool are_handlers_equal(const struct sigaction* sa,
820
const struct sigaction* expected_sa) {
821
address this_handler = get_signal_handler(sa);
822
address expected_handler = get_signal_handler(expected_sa);
823
const int this_flags = get_sanitized_sa_flags(sa);
824
const int expected_flags = get_sanitized_sa_flags(expected_sa);
825
return (this_handler == expected_handler) &&
826
(this_flags == expected_flags);
827
}
828
829
// If we installed one of our signal handlers for sig, check that the current
830
// setup matches what we originally installed.
831
static void check_signal_handler(int sig) {
832
char buf[O_BUFLEN];
833
bool mismatch = false;
834
835
if (!do_check_signal_periodically[sig]) {
836
return;
837
}
838
839
const struct sigaction* expected_act = vm_handlers.get(sig);
840
assert(expected_act != NULL, "Sanity");
841
842
// Retrieve current signal setup.
843
struct sigaction act;
844
static os_sigaction_t os_sigaction = NULL;
845
if (os_sigaction == NULL) {
846
// only trust the default sigaction, in case it has been interposed
847
os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
848
if (os_sigaction == NULL) return;
849
}
850
851
os_sigaction(sig, (struct sigaction*)NULL, &act);
852
853
// Compare both sigaction structures (intelligently; only the members we care about).
854
if (!are_handlers_equal(&act, expected_act)) {
855
tty->print_cr("Warning: %s handler modified!", os::exception_name(sig, buf, sizeof(buf)));
856
// If we had a mismatch:
857
// - print all signal handlers. As part of that printout, details will be printed
858
// about any modified handlers.
859
// - Disable any further checks for this signal - we do not want to flood stdout. Though
860
// depending on which signal had been overwritten, we may die very soon anyway.
861
os::print_signal_handlers(tty, buf, O_BUFLEN);
862
do_check_signal_periodically[sig] = false;
863
tty->print_cr("Consider using jsig library.");
864
// Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
865
if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
866
tty->print_cr("Note: Running in non-interactive shell, %s handler is replaced by shell",
867
os::exception_name(sig, buf, O_BUFLEN));
868
}
869
}
870
}
871
872
void* os::user_handler() {
873
return CAST_FROM_FN_PTR(void*, UserHandler);
874
}
875
876
void* os::signal(int signal_number, void* handler) {
877
struct sigaction sigAct, oldSigAct;
878
879
sigfillset(&(sigAct.sa_mask));
880
remove_error_signals_from_set(&(sigAct.sa_mask));
881
882
sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
883
sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
884
885
if (sigaction(signal_number, &sigAct, &oldSigAct)) {
886
// -1 means registration failed
887
return (void *)-1;
888
}
889
890
return get_signal_handler(&oldSigAct);
891
}
892
893
void os::signal_raise(int signal_number) {
894
::raise(signal_number);
895
}
896
897
// Will be modified when max signal is changed to be dynamic
898
int os::sigexitnum_pd() {
899
return NSIG;
900
}
901
902
// This method is a periodic task to check for misbehaving JNI applications
903
// under CheckJNI, we can add any periodic checks here
904
void os::run_periodic_checks() {
905
906
if (check_signals == false) return;
907
908
// SEGV and BUS if overridden could potentially prevent
909
// generation of hs*.log in the event of a crash, debugging
910
// such a case can be very challenging, so we absolutely
911
// check the following for a good measure:
912
check_signal_handler(SIGSEGV);
913
check_signal_handler(SIGILL);
914
check_signal_handler(SIGFPE);
915
check_signal_handler(SIGBUS);
916
check_signal_handler(SIGPIPE);
917
check_signal_handler(SIGXFSZ);
918
PPC64_ONLY(check_signal_handler(SIGTRAP);)
919
920
// ReduceSignalUsage allows the user to override these handlers
921
// see comments at the very top and jvm_md.h
922
if (!ReduceSignalUsage) {
923
check_signal_handler(SHUTDOWN1_SIGNAL);
924
check_signal_handler(SHUTDOWN2_SIGNAL);
925
check_signal_handler(SHUTDOWN3_SIGNAL);
926
check_signal_handler(BREAK_SIGNAL);
927
}
928
929
check_signal_handler(PosixSignals::SR_signum);
930
}
931
932
// Helper function for PosixSignals::print_siginfo_...():
933
// return a textual description for signal code.
934
struct enum_sigcode_desc_t {
935
const char* s_name;
936
const char* s_desc;
937
};
938
939
static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
940
941
const struct {
942
int sig; int code; const char* s_code; const char* s_desc;
943
} t1 [] = {
944
{ SIGILL, ILL_ILLOPC, "ILL_ILLOPC", "Illegal opcode." },
945
{ SIGILL, ILL_ILLOPN, "ILL_ILLOPN", "Illegal operand." },
946
{ SIGILL, ILL_ILLADR, "ILL_ILLADR", "Illegal addressing mode." },
947
{ SIGILL, ILL_ILLTRP, "ILL_ILLTRP", "Illegal trap." },
948
{ SIGILL, ILL_PRVOPC, "ILL_PRVOPC", "Privileged opcode." },
949
{ SIGILL, ILL_PRVREG, "ILL_PRVREG", "Privileged register." },
950
{ SIGILL, ILL_COPROC, "ILL_COPROC", "Coprocessor error." },
951
{ SIGILL, ILL_BADSTK, "ILL_BADSTK", "Internal stack error." },
952
#if defined(IA64) && defined(LINUX)
953
{ SIGILL, ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
954
{ SIGILL, ILL_BREAK, "ILL_BREAK", "Application Break instruction" },
955
#endif
956
{ SIGFPE, FPE_INTDIV, "FPE_INTDIV", "Integer divide by zero." },
957
{ SIGFPE, FPE_INTOVF, "FPE_INTOVF", "Integer overflow." },
958
{ SIGFPE, FPE_FLTDIV, "FPE_FLTDIV", "Floating-point divide by zero." },
959
{ SIGFPE, FPE_FLTOVF, "FPE_FLTOVF", "Floating-point overflow." },
960
{ SIGFPE, FPE_FLTUND, "FPE_FLTUND", "Floating-point underflow." },
961
{ SIGFPE, FPE_FLTRES, "FPE_FLTRES", "Floating-point inexact result." },
962
{ SIGFPE, FPE_FLTINV, "FPE_FLTINV", "Invalid floating-point operation." },
963
{ SIGFPE, FPE_FLTSUB, "FPE_FLTSUB", "Subscript out of range." },
964
{ SIGSEGV, SEGV_MAPERR, "SEGV_MAPERR", "Address not mapped to object." },
965
{ SIGSEGV, SEGV_ACCERR, "SEGV_ACCERR", "Invalid permissions for mapped object." },
966
#if defined(AIX)
967
// no explanation found what keyerr would be
968
{ SIGSEGV, SEGV_KEYERR, "SEGV_KEYERR", "key error" },
969
#endif
970
#if defined(IA64) && !defined(AIX)
971
{ SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
972
#endif
973
{ SIGBUS, BUS_ADRALN, "BUS_ADRALN", "Invalid address alignment." },
974
{ SIGBUS, BUS_ADRERR, "BUS_ADRERR", "Nonexistent physical address." },
975
{ SIGBUS, BUS_OBJERR, "BUS_OBJERR", "Object-specific hardware error." },
976
{ SIGTRAP, TRAP_BRKPT, "TRAP_BRKPT", "Process breakpoint." },
977
{ SIGTRAP, TRAP_TRACE, "TRAP_TRACE", "Process trace trap." },
978
{ SIGCHLD, CLD_EXITED, "CLD_EXITED", "Child has exited." },
979
{ SIGCHLD, CLD_KILLED, "CLD_KILLED", "Child has terminated abnormally and did not create a core file." },
980
{ SIGCHLD, CLD_DUMPED, "CLD_DUMPED", "Child has terminated abnormally and created a core file." },
981
{ SIGCHLD, CLD_TRAPPED, "CLD_TRAPPED", "Traced child has trapped." },
982
{ SIGCHLD, CLD_STOPPED, "CLD_STOPPED", "Child has stopped." },
983
{ SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
984
#ifdef SIGPOLL
985
{ SIGPOLL, POLL_OUT, "POLL_OUT", "Output buffers available." },
986
{ SIGPOLL, POLL_MSG, "POLL_MSG", "Input message available." },
987
{ SIGPOLL, POLL_ERR, "POLL_ERR", "I/O error." },
988
{ SIGPOLL, POLL_PRI, "POLL_PRI", "High priority input available." },
989
{ SIGPOLL, POLL_HUP, "POLL_HUP", "Device disconnected. [Option End]" },
990
#endif
991
{ -1, -1, NULL, NULL }
992
};
993
994
// Codes valid in any signal context.
995
const struct {
996
int code; const char* s_code; const char* s_desc;
997
} t2 [] = {
998
{ SI_USER, "SI_USER", "Signal sent by kill()." },
999
{ SI_QUEUE, "SI_QUEUE", "Signal sent by the sigqueue()." },
1000
{ SI_TIMER, "SI_TIMER", "Signal generated by expiration of a timer set by timer_settime()." },
1001
{ SI_ASYNCIO, "SI_ASYNCIO", "Signal generated by completion of an asynchronous I/O request." },
1002
{ SI_MESGQ, "SI_MESGQ", "Signal generated by arrival of a message on an empty message queue." },
1003
// Linux specific
1004
#ifdef SI_TKILL
1005
{ SI_TKILL, "SI_TKILL", "Signal sent by tkill (pthread_kill)" },
1006
#endif
1007
#ifdef SI_DETHREAD
1008
{ SI_DETHREAD, "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
1009
#endif
1010
#ifdef SI_KERNEL
1011
{ SI_KERNEL, "SI_KERNEL", "Signal sent by kernel." },
1012
#endif
1013
#ifdef SI_SIGIO
1014
{ SI_SIGIO, "SI_SIGIO", "Signal sent by queued SIGIO" },
1015
#endif
1016
1017
#if defined(AIX)
1018
{ SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
1019
{ SI_EMPTY, "SI_EMPTY", "siginfo contains no useful information" },
1020
#endif
1021
1022
{ -1, NULL, NULL }
1023
};
1024
1025
const char* s_code = NULL;
1026
const char* s_desc = NULL;
1027
1028
for (int i = 0; t1[i].sig != -1; i ++) {
1029
if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
1030
s_code = t1[i].s_code;
1031
s_desc = t1[i].s_desc;
1032
break;
1033
}
1034
}
1035
1036
if (s_code == NULL) {
1037
for (int i = 0; t2[i].s_code != NULL; i ++) {
1038
if (t2[i].code == si->si_code) {
1039
s_code = t2[i].s_code;
1040
s_desc = t2[i].s_desc;
1041
}
1042
}
1043
}
1044
1045
if (s_code == NULL) {
1046
out->s_name = "unknown";
1047
out->s_desc = "unknown";
1048
return false;
1049
}
1050
1051
out->s_name = s_code;
1052
out->s_desc = s_desc;
1053
1054
return true;
1055
}
1056
1057
bool os::signal_sent_by_kill(const void* siginfo) {
1058
const siginfo_t* const si = (const siginfo_t*)siginfo;
1059
return si->si_code == SI_USER || si->si_code == SI_QUEUE
1060
#ifdef SI_TKILL
1061
|| si->si_code == SI_TKILL
1062
#endif
1063
;
1064
}
1065
1066
// Returns true if signal number is valid.
1067
static bool is_valid_signal(int sig) {
1068
// MacOS not really POSIX compliant: sigaddset does not return
1069
// an error for invalid signal numbers. However, MacOS does not
1070
// support real time signals and simply seems to have just 33
1071
// signals with no holes in the signal range.
1072
#if defined(__APPLE__)
1073
return sig >= 1 && sig < NSIG;
1074
#else
1075
// Use sigaddset to check for signal validity.
1076
sigset_t set;
1077
sigemptyset(&set);
1078
if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
1079
return false;
1080
}
1081
return true;
1082
#endif
1083
}
1084
1085
static const char* get_signal_name(int sig, char* out, size_t outlen) {
1086
1087
const char* ret = NULL;
1088
1089
#ifdef SIGRTMIN
1090
if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
1091
if (sig == SIGRTMIN) {
1092
ret = "SIGRTMIN";
1093
} else if (sig == SIGRTMAX) {
1094
ret = "SIGRTMAX";
1095
} else {
1096
jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
1097
return out;
1098
}
1099
}
1100
#endif
1101
1102
if (sig > 0) {
1103
for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
1104
if (g_signal_info[idx].sig == sig) {
1105
ret = g_signal_info[idx].name;
1106
break;
1107
}
1108
}
1109
}
1110
1111
if (!ret) {
1112
if (!is_valid_signal(sig)) {
1113
ret = "INVALID";
1114
} else {
1115
ret = "UNKNOWN";
1116
}
1117
}
1118
1119
if (out && outlen > 0) {
1120
strncpy(out, ret, outlen);
1121
out[outlen - 1] = '\0';
1122
}
1123
return out;
1124
}
1125
1126
void os::print_siginfo(outputStream* os, const void* si0) {
1127
1128
const siginfo_t* const si = (const siginfo_t*) si0;
1129
1130
char buf[20];
1131
os->print("siginfo:");
1132
1133
if (!si) {
1134
os->print(" <null>");
1135
return;
1136
}
1137
1138
const int sig = si->si_signo;
1139
1140
os->print(" si_signo: %d (%s)", sig, get_signal_name(sig, buf, sizeof(buf)));
1141
1142
enum_sigcode_desc_t ed;
1143
get_signal_code_description(si, &ed);
1144
os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1145
1146
if (si->si_errno) {
1147
os->print(", si_errno: %d", si->si_errno);
1148
}
1149
1150
// Output additional information depending on the signal code.
1151
1152
// Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1153
// so it depends on the context which member to use. For synchronous error signals,
1154
// we print si_addr, unless the signal was sent by another process or thread, in
1155
// which case we print out pid or tid of the sender.
1156
if (os::signal_sent_by_kill(si)) {
1157
const pid_t pid = si->si_pid;
1158
os->print(", si_pid: %ld", (long) pid);
1159
if (IS_VALID_PID(pid)) {
1160
const pid_t me = getpid();
1161
if (me == pid) {
1162
os->print(" (current process)");
1163
}
1164
} else {
1165
os->print(" (invalid)");
1166
}
1167
os->print(", si_uid: %ld", (long) si->si_uid);
1168
if (sig == SIGCHLD) {
1169
os->print(", si_status: %d", si->si_status);
1170
}
1171
} else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1172
sig == SIGTRAP || sig == SIGFPE) {
1173
os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1174
#ifdef SIGPOLL
1175
} else if (sig == SIGPOLL) {
1176
// siginfo_t.si_band is defined as "long", and it is so in most
1177
// implementations. But SPARC64 glibc has a bug: si_band is "int".
1178
// Cast si_band to "long" to prevent format specifier mismatch.
1179
// See: https://sourceware.org/bugzilla/show_bug.cgi?id=23821
1180
os->print(", si_band: %ld", (long) si->si_band);
1181
#endif
1182
}
1183
}
1184
1185
bool os::signal_thread(Thread* thread, int sig, const char* reason) {
1186
OSThread* osthread = thread->osthread();
1187
if (osthread) {
1188
int status = pthread_kill(osthread->pthread_id(), sig);
1189
if (status == 0) {
1190
Events::log(Thread::current(), "sent signal %d to Thread " INTPTR_FORMAT " because %s.",
1191
sig, p2i(thread), reason);
1192
return true;
1193
}
1194
}
1195
return false;
1196
}
1197
1198
// Returns:
1199
// NULL for an invalid signal number
1200
// "SIG<num>" for a valid but unknown signal number
1201
// signal name otherwise.
1202
const char* os::exception_name(int sig, char* buf, size_t size) {
1203
if (!is_valid_signal(sig)) {
1204
return NULL;
1205
}
1206
const char* const name = get_signal_name(sig, buf, size);
1207
if (strcmp(name, "UNKNOWN") == 0) {
1208
jio_snprintf(buf, size, "SIG%d", sig);
1209
}
1210
return buf;
1211
}
1212
1213
int os::get_signal_number(const char* signal_name) {
1214
char tmp[30];
1215
const char* s = signal_name;
1216
if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
1217
jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
1218
s = tmp;
1219
}
1220
for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
1221
if (strcmp(g_signal_info[idx].name, s) == 0) {
1222
return g_signal_info[idx].sig;
1223
}
1224
}
1225
return -1;
1226
}
1227
1228
void set_signal_handler(int sig, bool do_check = true) {
1229
// Check for overwrite.
1230
struct sigaction oldAct;
1231
sigaction(sig, (struct sigaction*)NULL, &oldAct);
1232
1233
// Query the current signal handler. Needs to be a separate operation
1234
// from installing a new handler since we need to honor AllowUserSignalHandlers.
1235
void* oldhand = get_signal_handler(&oldAct);
1236
if (!HANDLER_IS_IGN_OR_DFL(oldhand) &&
1237
!HANDLER_IS(oldhand, javaSignalHandler)) {
1238
if (AllowUserSignalHandlers) {
1239
// Do not overwrite; user takes responsibility to forward to us.
1240
return;
1241
} else if (UseSignalChaining) {
1242
// save the old handler in jvm
1243
chained_handlers.set(sig, &oldAct);
1244
// libjsig also interposes the sigaction() call below and saves the
1245
// old sigaction on it own.
1246
} else {
1247
fatal("Encountered unexpected pre-existing sigaction handler "
1248
"%#lx for signal %d.", (long)oldhand, sig);
1249
}
1250
}
1251
1252
struct sigaction sigAct;
1253
sigfillset(&(sigAct.sa_mask));
1254
remove_error_signals_from_set(&(sigAct.sa_mask));
1255
sigAct.sa_sigaction = javaSignalHandler;
1256
sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
1257
#if defined(__APPLE__)
1258
// Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
1259
// (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
1260
// if the signal handler declares it will handle it on alternate stack.
1261
// Notice we only declare we will handle it on alt stack, but we are not
1262
// actually going to use real alt stack - this is just a workaround.
1263
// Please see ux_exception.c, method catch_mach_exception_raise for details
1264
// link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
1265
if (sig == SIGSEGV) {
1266
sigAct.sa_flags |= SA_ONSTACK;
1267
}
1268
#endif
1269
1270
// Save handler setup for later checking
1271
vm_handlers.set(sig, &sigAct);
1272
do_check_signal_periodically[sig] = do_check;
1273
1274
int ret = sigaction(sig, &sigAct, &oldAct);
1275
assert(ret == 0, "check");
1276
1277
void* oldhand2 = get_signal_handler(&oldAct);
1278
assert(oldhand2 == oldhand, "no concurrent signal handler installation");
1279
}
1280
1281
// install signal handlers for signals that HotSpot needs to
1282
// handle in order to support Java-level exception handling.
1283
void install_signal_handlers() {
1284
// signal-chaining
1285
typedef void (*signal_setting_t)();
1286
signal_setting_t begin_signal_setting = NULL;
1287
signal_setting_t end_signal_setting = NULL;
1288
begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
1289
dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
1290
if (begin_signal_setting != NULL) {
1291
end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
1292
dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
1293
get_signal_action = CAST_TO_FN_PTR(get_signal_t,
1294
dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
1295
libjsig_is_loaded = true;
1296
assert(UseSignalChaining, "should enable signal-chaining");
1297
}
1298
if (libjsig_is_loaded) {
1299
// Tell libjsig jvm is setting signal handlers
1300
(*begin_signal_setting)();
1301
}
1302
1303
set_signal_handler(SIGSEGV);
1304
set_signal_handler(SIGPIPE);
1305
set_signal_handler(SIGBUS);
1306
set_signal_handler(SIGILL);
1307
set_signal_handler(SIGFPE);
1308
PPC64_ONLY(set_signal_handler(SIGTRAP);)
1309
set_signal_handler(SIGXFSZ);
1310
if (!ReduceSignalUsage) {
1311
// This is just for early initialization phase. Intercepting the signal here reduces the risk
1312
// that an attach client accidentally forces HotSpot to quit prematurely. We skip the periodic
1313
// check because late initialization will overwrite it to UserHandler.
1314
set_signal_handler(BREAK_SIGNAL, false);
1315
}
1316
#if defined(__APPLE__)
1317
// lldb (gdb) installs both standard BSD signal handlers, and mach exception
1318
// handlers. By replacing the existing task exception handler, we disable lldb's mach
1319
// exception handling, while leaving the standard BSD signal handlers functional.
1320
//
1321
// EXC_MASK_BAD_ACCESS needed by all architectures for NULL ptr checking
1322
// EXC_MASK_ARITHMETIC needed by all architectures for div by 0 checking
1323
// EXC_MASK_BAD_INSTRUCTION needed by aarch64 to initiate deoptimization
1324
kern_return_t kr;
1325
kr = task_set_exception_ports(mach_task_self(),
1326
EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC
1327
AARCH64_ONLY(| EXC_MASK_BAD_INSTRUCTION),
1328
MACH_PORT_NULL,
1329
EXCEPTION_STATE_IDENTITY,
1330
MACHINE_THREAD_STATE);
1331
1332
assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
1333
#endif
1334
1335
if (libjsig_is_loaded) {
1336
// Tell libjsig jvm finishes setting signal handlers
1337
(*end_signal_setting)();
1338
}
1339
1340
// We don't activate signal checker if libjsig is in place, we trust ourselves
1341
// and if UserSignalHandler is installed all bets are off.
1342
// Log that signal checking is off only if -verbose:jni is specified.
1343
if (CheckJNICalls) {
1344
if (libjsig_is_loaded) {
1345
log_debug(jni, resolve)("Info: libjsig is activated, all active signal checking is disabled");
1346
check_signals = false;
1347
}
1348
if (AllowUserSignalHandlers) {
1349
log_debug(jni, resolve)("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
1350
check_signals = false;
1351
}
1352
}
1353
}
1354
1355
// Returns one-line short description of a signal set in a user provided buffer.
1356
static const char* describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
1357
assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
1358
// Note: for shortness, just print out the first 32. That should
1359
// cover most of the useful ones, apart from realtime signals.
1360
for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
1361
const int rc = sigismember(set, sig);
1362
if (rc == -1 && errno == EINVAL) {
1363
buffer[sig-1] = '?';
1364
} else {
1365
buffer[sig-1] = rc == 0 ? '0' : '1';
1366
}
1367
}
1368
buffer[NUM_IMPORTANT_SIGS] = 0;
1369
return buffer;
1370
}
1371
1372
// Prints one-line description of a signal set.
1373
static void print_signal_set_short(outputStream* st, const sigset_t* set) {
1374
char buf[NUM_IMPORTANT_SIGS + 1];
1375
describe_signal_set_short(set, buf, sizeof(buf));
1376
st->print("%s", buf);
1377
}
1378
1379
static void print_single_signal_handler(outputStream* st,
1380
const struct sigaction* act,
1381
char* buf, size_t buflen) {
1382
1383
address handler = get_signal_handler(act);
1384
if (HANDLER_IS_DFL(handler)) {
1385
st->print("SIG_DFL");
1386
} else if (HANDLER_IS_IGN(handler)) {
1387
st->print("SIG_IGN");
1388
} else {
1389
print_signal_handler_name(st, handler, buf, buflen);
1390
}
1391
1392
st->print(", mask=");
1393
print_signal_set_short(st, &(act->sa_mask));
1394
1395
st->print(", flags=");
1396
int flags = get_sanitized_sa_flags(act);
1397
print_sa_flags(st, flags);
1398
1399
}
1400
1401
// Print established signal handler for this signal.
1402
// - if this signal handler was installed by us and is chained to a pre-established user handler
1403
// it replaced, print that one too.
1404
// - otherwise, if this signal handler was installed by us and replaced another handler to which we
1405
// are not chained (e.g. if chaining is off), print that one too.
1406
void PosixSignals::print_signal_handler(outputStream* st, int sig,
1407
char* buf, size_t buflen) {
1408
1409
st->print("%10s: ", os::exception_name(sig, buf, buflen));
1410
1411
struct sigaction current_act;
1412
sigaction(sig, NULL, &current_act);
1413
1414
print_single_signal_handler(st, &current_act, buf, buflen);
1415
st->cr();
1416
1417
// If we expected to see our own hotspot signal handler but found a different one,
1418
// print a warning (unless the handler replacing it is our own crash handler, which can
1419
// happen if this function is called during error reporting).
1420
const struct sigaction* expected_act = vm_handlers.get(sig);
1421
if (expected_act != NULL) {
1422
const address current_handler = get_signal_handler(&current_act);
1423
if (!(HANDLER_IS(current_handler, VMError::crash_handler_address))) {
1424
if (!are_handlers_equal(&current_act, expected_act)) {
1425
st->print_cr(" *** Handler was modified!");
1426
st->print (" *** Expected: ");
1427
print_single_signal_handler(st, expected_act, buf, buflen);
1428
st->cr();
1429
}
1430
}
1431
}
1432
1433
// If there is a chained handler waiting behind the current one, print it too.
1434
const struct sigaction* chained_act = get_chained_signal_action(sig);
1435
if (chained_act != NULL) {
1436
st->print(" chained to: ");
1437
print_single_signal_handler(st, &current_act, buf, buflen);
1438
st->cr();
1439
}
1440
}
1441
1442
void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1443
st->print_cr("Signal Handlers:");
1444
PosixSignals::print_signal_handler(st, SIGSEGV, buf, buflen);
1445
PosixSignals::print_signal_handler(st, SIGBUS , buf, buflen);
1446
PosixSignals::print_signal_handler(st, SIGFPE , buf, buflen);
1447
PosixSignals::print_signal_handler(st, SIGPIPE, buf, buflen);
1448
PosixSignals::print_signal_handler(st, SIGXFSZ, buf, buflen);
1449
PosixSignals::print_signal_handler(st, SIGILL , buf, buflen);
1450
PosixSignals::print_signal_handler(st, PosixSignals::SR_signum, buf, buflen);
1451
PosixSignals::print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1452
PosixSignals::print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1453
PosixSignals::print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1454
PosixSignals::print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1455
#if defined(SIGDANGER)
1456
// We also want to know if someone else adds a SIGDANGER handler because
1457
// that will interfere with OOM killling.
1458
PosixSignals::print_signal_handler(st, SIGDANGER, buf, buflen);
1459
#endif
1460
#if defined(SIGTRAP)
1461
PosixSignals::print_signal_handler(st, SIGTRAP, buf, buflen);
1462
#endif
1463
}
1464
1465
bool PosixSignals::is_sig_ignored(int sig) {
1466
struct sigaction oact;
1467
sigaction(sig, (struct sigaction*)NULL, &oact);
1468
if (HANDLER_IS_IGN(get_signal_handler(&oact))) {
1469
return true;
1470
} else {
1471
return false;
1472
}
1473
}
1474
1475
static void signal_sets_init() {
1476
sigemptyset(&preinstalled_sigs);
1477
1478
// Should also have an assertion stating we are still single-threaded.
1479
assert(!signal_sets_initialized, "Already initialized");
1480
// Fill in signals that are necessarily unblocked for all threads in
1481
// the VM. Currently, we unblock the following signals:
1482
// SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
1483
// by -Xrs (=ReduceSignalUsage));
1484
// BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
1485
// other threads. The "ReduceSignalUsage" boolean tells us not to alter
1486
// the dispositions or masks wrt these signals.
1487
// Programs embedding the VM that want to use the above signals for their
1488
// own purposes must, at this time, use the "-Xrs" option to prevent
1489
// interference with shutdown hooks and BREAK_SIGNAL thread dumping.
1490
// (See bug 4345157, and other related bugs).
1491
// In reality, though, unblocking these signals is really a nop, since
1492
// these signals are not blocked by default.
1493
sigemptyset(&unblocked_sigs);
1494
sigaddset(&unblocked_sigs, SIGILL);
1495
sigaddset(&unblocked_sigs, SIGSEGV);
1496
sigaddset(&unblocked_sigs, SIGBUS);
1497
sigaddset(&unblocked_sigs, SIGFPE);
1498
PPC64_ONLY(sigaddset(&unblocked_sigs, SIGTRAP);)
1499
sigaddset(&unblocked_sigs, PosixSignals::SR_signum);
1500
1501
if (!ReduceSignalUsage) {
1502
if (!PosixSignals::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
1503
sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
1504
}
1505
if (!PosixSignals::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
1506
sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
1507
}
1508
if (!PosixSignals::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
1509
sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
1510
}
1511
}
1512
// Fill in signals that are blocked by all but the VM thread.
1513
sigemptyset(&vm_sigs);
1514
if (!ReduceSignalUsage) {
1515
sigaddset(&vm_sigs, BREAK_SIGNAL);
1516
}
1517
debug_only(signal_sets_initialized = true);
1518
}
1519
1520
// These are signals that are unblocked while a thread is running Java.
1521
// (For some reason, they get blocked by default.)
1522
static sigset_t* unblocked_signals() {
1523
assert(signal_sets_initialized, "Not initialized");
1524
return &unblocked_sigs;
1525
}
1526
1527
// These are the signals that are blocked while a (non-VM) thread is
1528
// running Java. Only the VM thread handles these signals.
1529
static sigset_t* vm_signals() {
1530
assert(signal_sets_initialized, "Not initialized");
1531
return &vm_sigs;
1532
}
1533
1534
void PosixSignals::hotspot_sigmask(Thread* thread) {
1535
1536
//Save caller's signal mask before setting VM signal mask
1537
sigset_t caller_sigmask;
1538
pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
1539
1540
OSThread* osthread = thread->osthread();
1541
osthread->set_caller_sigmask(caller_sigmask);
1542
1543
pthread_sigmask(SIG_UNBLOCK, unblocked_signals(), NULL);
1544
1545
if (!ReduceSignalUsage) {
1546
if (thread->is_VM_thread()) {
1547
// Only the VM thread handles BREAK_SIGNAL ...
1548
pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
1549
} else {
1550
// ... all other threads block BREAK_SIGNAL
1551
pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
1552
}
1553
}
1554
}
1555
1556
////////////////////////////////////////////////////////////////////////////////
1557
// suspend/resume support
1558
1559
// The low-level signal-based suspend/resume support is a remnant from the
1560
// old VM-suspension that used to be for java-suspension, safepoints etc,
1561
// within hotspot. Currently used by JFR's OSThreadSampler
1562
//
1563
// The remaining code is greatly simplified from the more general suspension
1564
// code that used to be used.
1565
//
1566
// The protocol is quite simple:
1567
// - suspend:
1568
// - sends a signal to the target thread
1569
// - polls the suspend state of the osthread using a yield loop
1570
// - target thread signal handler (SR_handler) sets suspend state
1571
// and blocks in sigsuspend until continued
1572
// - resume:
1573
// - sets target osthread state to continue
1574
// - sends signal to end the sigsuspend loop in the SR_handler
1575
//
1576
// Note that resume_clear_context() and suspend_save_context() are needed
1577
// by SR_handler(), so that fetch_frame_from_context() works,
1578
// which in part is used by:
1579
// - Forte Analyzer: AsyncGetCallTrace()
1580
// - StackBanging: get_frame_at_stack_banging_point()
1581
1582
sigset_t SR_sigset;
1583
1584
static void resume_clear_context(OSThread *osthread) {
1585
osthread->set_ucontext(NULL);
1586
osthread->set_siginfo(NULL);
1587
}
1588
1589
static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
1590
osthread->set_ucontext(context);
1591
osthread->set_siginfo(siginfo);
1592
}
1593
1594
// Handler function invoked when a thread's execution is suspended or
1595
// resumed. We have to be careful that only async-safe functions are
1596
// called here (Note: most pthread functions are not async safe and
1597
// should be avoided.)
1598
//
1599
// Note: sigwait() is a more natural fit than sigsuspend() from an
1600
// interface point of view, but sigwait() prevents the signal handler
1601
// from being run. libpthread would get very confused by not having
1602
// its signal handlers run and prevents sigwait()'s use with the
1603
// mutex granting signal.
1604
//
1605
// Currently only ever called on the VMThread and JavaThreads (PC sampling)
1606
//
1607
static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
1608
1609
// Save and restore errno to avoid confusing native code with EINTR
1610
// after sigsuspend.
1611
int old_errno = errno;
1612
1613
PosixSignals::unblock_error_signals();
1614
1615
Thread* thread = Thread::current_or_null_safe();
1616
assert(thread != NULL, "Missing current thread in SR_handler");
1617
1618
// On some systems we have seen signal delivery get "stuck" until the signal
1619
// mask is changed as part of thread termination. Check that the current thread
1620
// has not already terminated - else the following assertion
1621
// will fail because the thread is no longer a JavaThread as the ~JavaThread
1622
// destructor has completed.
1623
1624
if (thread->has_terminated()) {
1625
return;
1626
}
1627
1628
assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
1629
1630
OSThread* osthread = thread->osthread();
1631
1632
os::SuspendResume::State current = osthread->sr.state();
1633
1634
if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
1635
suspend_save_context(osthread, siginfo, context);
1636
1637
// attempt to switch the state, we assume we had a SUSPEND_REQUEST
1638
os::SuspendResume::State state = osthread->sr.suspended();
1639
if (state == os::SuspendResume::SR_SUSPENDED) {
1640
sigset_t suspend_set; // signals for sigsuspend()
1641
sigemptyset(&suspend_set);
1642
1643
// get current set of blocked signals and unblock resume signal
1644
pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
1645
sigdelset(&suspend_set, PosixSignals::SR_signum);
1646
1647
sr_semaphore.signal();
1648
1649
// wait here until we are resumed
1650
while (1) {
1651
sigsuspend(&suspend_set);
1652
1653
os::SuspendResume::State result = osthread->sr.running();
1654
if (result == os::SuspendResume::SR_RUNNING) {
1655
// double check AIX doesn't need this!
1656
sr_semaphore.signal();
1657
break;
1658
} else if (result != os::SuspendResume::SR_SUSPENDED) {
1659
ShouldNotReachHere();
1660
}
1661
}
1662
1663
} else if (state == os::SuspendResume::SR_RUNNING) {
1664
// request was cancelled, continue
1665
} else {
1666
ShouldNotReachHere();
1667
}
1668
1669
resume_clear_context(osthread);
1670
} else if (current == os::SuspendResume::SR_RUNNING) {
1671
// request was cancelled, continue
1672
} else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
1673
// ignore
1674
} else {
1675
// ignore
1676
}
1677
1678
errno = old_errno;
1679
}
1680
1681
int SR_initialize() {
1682
struct sigaction act;
1683
char *s;
1684
// Get signal number to use for suspend/resume
1685
if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
1686
int sig = ::strtol(s, 0, 10);
1687
if (sig > MAX2(SIGSEGV, SIGBUS) && // See 4355769.
1688
sig < NSIG) { // Must be legal signal and fit into sigflags[].
1689
PosixSignals::SR_signum = sig;
1690
} else {
1691
warning("You set _JAVA_SR_SIGNUM=%d. It must be in range [%d, %d]. Using %d instead.",
1692
sig, MAX2(SIGSEGV, SIGBUS)+1, NSIG-1, PosixSignals::SR_signum);
1693
}
1694
}
1695
1696
assert(PosixSignals::SR_signum > SIGSEGV && PosixSignals::SR_signum > SIGBUS,
1697
"SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
1698
1699
sigemptyset(&SR_sigset);
1700
sigaddset(&SR_sigset, PosixSignals::SR_signum);
1701
1702
// Set up signal handler for suspend/resume
1703
act.sa_flags = SA_RESTART|SA_SIGINFO;
1704
act.sa_handler = (void (*)(int)) SR_handler;
1705
1706
// SR_signum is blocked by default.
1707
pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
1708
remove_error_signals_from_set(&(act.sa_mask));
1709
1710
if (sigaction(PosixSignals::SR_signum, &act, 0) == -1) {
1711
return -1;
1712
}
1713
1714
// Save signal setup information for later checking.
1715
vm_handlers.set(PosixSignals::SR_signum, &act);
1716
do_check_signal_periodically[PosixSignals::SR_signum] = true;
1717
1718
return 0;
1719
}
1720
1721
static int sr_notify(OSThread* osthread) {
1722
int status = pthread_kill(osthread->pthread_id(), PosixSignals::SR_signum);
1723
assert_status(status == 0, status, "pthread_kill");
1724
return status;
1725
}
1726
1727
// returns true on success and false on error - really an error is fatal
1728
// but this seems the normal response to library errors
1729
bool PosixSignals::do_suspend(OSThread* osthread) {
1730
assert(osthread->sr.is_running(), "thread should be running");
1731
assert(!sr_semaphore.trywait(), "semaphore has invalid state");
1732
1733
// mark as suspended and send signal
1734
if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
1735
// failed to switch, state wasn't running?
1736
ShouldNotReachHere();
1737
return false;
1738
}
1739
1740
if (sr_notify(osthread) != 0) {
1741
ShouldNotReachHere();
1742
}
1743
1744
// managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
1745
while (true) {
1746
if (sr_semaphore.timedwait(2)) {
1747
break;
1748
} else {
1749
// timeout
1750
os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
1751
if (cancelled == os::SuspendResume::SR_RUNNING) {
1752
return false;
1753
} else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
1754
// make sure that we consume the signal on the semaphore as well
1755
sr_semaphore.wait();
1756
break;
1757
} else {
1758
ShouldNotReachHere();
1759
return false;
1760
}
1761
}
1762
}
1763
1764
guarantee(osthread->sr.is_suspended(), "Must be suspended");
1765
return true;
1766
}
1767
1768
void PosixSignals::do_resume(OSThread* osthread) {
1769
assert(osthread->sr.is_suspended(), "thread should be suspended");
1770
assert(!sr_semaphore.trywait(), "invalid semaphore state");
1771
1772
if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
1773
// failed to switch to WAKEUP_REQUEST
1774
ShouldNotReachHere();
1775
return;
1776
}
1777
1778
while (true) {
1779
if (sr_notify(osthread) == 0) {
1780
if (sr_semaphore.timedwait(2)) {
1781
if (osthread->sr.is_running()) {
1782
return;
1783
}
1784
}
1785
} else {
1786
ShouldNotReachHere();
1787
}
1788
}
1789
1790
guarantee(osthread->sr.is_running(), "Must be running!");
1791
}
1792
1793
void os::SuspendedThreadTask::internal_do_task() {
1794
if (PosixSignals::do_suspend(_thread->osthread())) {
1795
os::SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
1796
do_task(context);
1797
PosixSignals::do_resume(_thread->osthread());
1798
}
1799
}
1800
1801
int PosixSignals::init() {
1802
// initialize suspend/resume support - must do this before signal_sets_init()
1803
if (SR_initialize() != 0) {
1804
vm_exit_during_initialization("SR_initialize failed");
1805
return JNI_ERR;
1806
}
1807
1808
signal_sets_init();
1809
1810
install_signal_handlers();
1811
1812
// Initialize data for jdk.internal.misc.Signal
1813
if (!ReduceSignalUsage) {
1814
jdk_misc_signal_init();
1815
}
1816
1817
return JNI_OK;
1818
}
1819
1820