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