1 /*
   2  * Copyright (c) 2021, 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 "code/codeCache.hpp"
  29 #include "code/compiledMethod.hpp"
  30 #include "code/nativeInst.hpp"
  31 #include "logging/log.hpp"
  32 #include "runtime/atomic.hpp"
  33 #include "runtime/globals.hpp"
  34 #include "runtime/interfaceSupport.inline.hpp"
  35 #include "runtime/java.hpp"
  36 #include "runtime/os.hpp"
  37 #include "runtime/osThread.hpp"
  38 #include "runtime/semaphore.inline.hpp"
  39 #include "runtime/stubRoutines.hpp"
  40 #include "runtime/thread.hpp"
  41 #include "signals_posix.hpp"
  42 #include "utilities/events.hpp"
  43 #include "utilities/ostream.hpp"
  44 #include "utilities/vmError.hpp"
  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   // Note: it's not uncommon that JNI code uses signal/sigset to install,
 569   // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
 570   // or have a SIGILL handler when detecting CPU type). When that happens,
 571   // this handler might be invoked with junk info/ucVoid. To avoid unnecessary
 572   // crash when libjsig is not preloaded, try handle signals that do not require
 573   // siginfo/ucontext first.
 574 
 575   // Preserve errno value over signal handler.
 576   //  (note: RAII ok here, even with JFR thread crash protection, see below).
 577   ErrnoPreserver ep;
 578 
 579   // Unblock all synchronous error signals (see JDK-8252533)
 580   PosixSignals::unblock_error_signals();
 581 
 582   ucontext_t* const uc = (ucontext_t*) ucVoid;
 583   Thread* const t = Thread::current_or_null_safe();
 584 
 585   // Handle JFR thread crash protection.
 586   //  Note: this may cause us to longjmp away. Do not use any code before this
 587   //  point which really needs any form of epilogue code running, eg RAII objects.
 588   os::ThreadCrashProtection::check_crash_protection(sig, t);
 589 
 590   bool signal_was_handled = false;
 591 
 592   // Handle assertion poison page accesses.
 593 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
 594   if (!signal_was_handled &&
 595       ((sig == SIGSEGV || sig == SIGBUS) && info != NULL && info->si_addr == g_assert_poison)) {
 596     signal_was_handled = handle_assert_poison_fault(ucVoid, info->si_addr);
 597   }
 598 #endif
 599 
 600   if (!signal_was_handled) {
 601     // Handle SafeFetch access.
 602 #ifndef ZERO
 603     if (uc != NULL) {
 604       address pc = os::Posix::ucontext_get_pc(uc);
 605       if (StubRoutines::is_safefetch_fault(pc)) {
 606         os::Posix::ucontext_set_pc(uc, StubRoutines::continuation_for_safefetch_fault(pc));
 607         signal_was_handled = true;
 608       }
 609     }
 610 #else
 611     // See JDK-8076185
 612     if (sig == SIGSEGV || sig == SIGBUS) {
 613       sigjmp_buf* const pjb = get_jmp_buf_for_continuation();
 614       if (pjb) {
 615         siglongjmp(*pjb, 1);
 616       }
 617     }
 618 #endif // ZERO
 619   }
 620 
 621   // Ignore SIGPIPE and SIGXFSZ (4229104, 6499219).
 622   if (!signal_was_handled &&
 623       (sig == SIGPIPE || sig == SIGXFSZ)) {
 624     PosixSignals::chained_handler(sig, info, ucVoid);
 625     signal_was_handled = true; // unconditionally.
 626   }
 627 
 628   // Check for UD trap caused by NOP patching.
 629   // If it is, patch return address to be deopt handler.
 630   if (!signal_was_handled) {
 631     address pc = os::Posix::ucontext_get_pc(uc);
 632     assert (pc != NULL, "");
 633     if (NativeDeoptInstruction::is_deopt_at(pc)) {
 634       CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
 635       if (cb != NULL && cb->is_compiled()) {
 636         CompiledMethod* cm = cb->as_compiled_method();
 637         assert(cm->insts_contains_inclusive(pc), "");
 638         address deopt = cm->is_method_handle_return(pc) ?
 639           cm->deopt_mh_handler_begin() :
 640           cm->deopt_handler_begin();
 641         assert (deopt != NULL, "");
 642 
 643         frame fr = os::fetch_frame_from_context(uc);
 644         cm->set_original_pc(&fr, pc);
 645 
 646         os::Posix::ucontext_set_pc(uc, deopt);
 647         signal_was_handled = true;
 648       }
 649     }
 650   }
 651 
 652   // Call platform dependent signal handler.
 653   if (!signal_was_handled) {
 654     JavaThread* const jt = (t != NULL && t->is_Java_thread()) ? (JavaThread*) t : NULL;
 655     signal_was_handled = PosixSignals::pd_hotspot_signal_handler(sig, info, uc, jt);
 656   }
 657 
 658   // From here on, if the signal had not been handled, it is a fatal error.
 659 
 660   // Give the chained signal handler - should it exist - a shot.
 661   if (!signal_was_handled) {
 662     signal_was_handled = PosixSignals::chained_handler(sig, info, ucVoid);
 663   }
 664 
 665   // Invoke fatal error handling.
 666   if (!signal_was_handled && abort_if_unrecognized) {
 667     // Extract pc from context for the error handler to display.
 668     address pc = NULL;
 669     if (uc != NULL) {
 670       // prepare fault pc address for error reporting.
 671       if (S390_ONLY(sig == SIGILL || sig == SIGFPE) NOT_S390(false)) {
 672         pc = (address)info->si_addr;
 673       } else if (ZERO_ONLY(true) NOT_ZERO(false)) {
 674         // Non-arch-specific Zero code does not really know the pc.
 675         // This can be alleviated by making arch-specific os::Posix::ucontext_get_pc
 676         // available for Zero for known architectures. But for generic Zero
 677         // code, it would still remain unknown.
 678         pc = NULL;
 679       } else {
 680         pc = os::Posix::ucontext_get_pc(uc);
 681       }
 682     }
 683     // For Zero, we ignore the crash context, because:
 684     //  a) The crash would be in C++ interpreter code, so context is not really relevant;
 685     //  b) Generic Zero code would not be able to parse it, so when generic error
 686     //     reporting code asks e.g. about frames on stack, Zero would experience
 687     //     a secondary ShouldNotCallThis() crash.
 688     VMError::report_and_die(t, sig, pc, info, NOT_ZERO(ucVoid) ZERO_ONLY(NULL));
 689     // VMError should not return.
 690     ShouldNotReachHere();
 691   }
 692   return signal_was_handled;
 693 }
 694 
 695 // Entry point for the hotspot signal handler.
 696 static void javaSignalHandler(int sig, siginfo_t* info, void* ucVoid) {
 697   // Do not add any code here!
 698   // Only add code to either JVM_HANDLE_XXX_SIGNAL or PosixSignals::pd_hotspot_signal_handler.
 699   (void)JVM_HANDLE_XXX_SIGNAL(sig, info, ucVoid, true);
 700 }
 701 
 702 static void UserHandler(int sig, void *siginfo, void *context) {
 703 
 704   PosixSignals::unblock_error_signals();
 705 
 706   // Ctrl-C is pressed during error reporting, likely because the error
 707   // handler fails to abort. Let VM die immediately.
 708   if (sig == SIGINT && VMError::is_error_reported()) {
 709     os::die();
 710   }
 711 
 712   os::signal_notify(sig);
 713 }
 714 
 715 static void print_signal_handler_name(outputStream* os, address handler, char* buf, size_t buflen) {
 716   // We demangle, but omit arguments - signal handlers should have always the same prototype.
 717   os::print_function_and_library_name(os, handler, buf, buflen,
 718                                        true, // shorten_path
 719                                        true, // demangle
 720                                        true  // omit arguments
 721                                        );
 722 }
 723 
 724 // Writes one-line description of a combination of sigaction.sa_flags into a user
 725 // provided buffer. Returns that buffer.
 726 static const char* describe_sa_flags(int flags, char* buffer, size_t size) {
 727   char* p = buffer;
 728   size_t remaining = size;
 729   bool first = true;
 730   int idx = 0;
 731 
 732   assert(buffer, "invalid argument");
 733 
 734   if (size == 0) {
 735     return buffer;
 736   }
 737 
 738   strncpy(buffer, "none", size);
 739 
 740   const unsigned int unknown_flag = ~(SA_NOCLDSTOP |
 741                                       SA_ONSTACK   |
 742                                       SA_NOCLDSTOP |
 743                                       SA_RESTART   |
 744                                       SA_SIGINFO   |
 745                                       SA_NOCLDWAIT |
 746                                       SA_NODEFER
 747                                       AIX_ONLY(| SA_OLDSTYLE)
 748                                       );
 749 
 750   const struct {
 751     // NB: i is an unsigned int here because SA_RESETHAND is on some
 752     // systems 0x80000000, which is implicitly unsigned.  Assigning
 753     // it to an int field would be an overflow in unsigned-to-signed
 754     // conversion.
 755     unsigned int i;
 756     const char* s;
 757   } flaginfo [] = {
 758     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
 759     { SA_ONSTACK,   "SA_ONSTACK"   },
 760     { SA_RESETHAND, "SA_RESETHAND" },
 761     { SA_RESTART,   "SA_RESTART"   },
 762     { SA_SIGINFO,   "SA_SIGINFO"   },
 763     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
 764     { SA_NODEFER,   "SA_NODEFER"   },
 765 #if defined(AIX)
 766     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
 767 #endif
 768     { unknown_flag, "NOT USED"     }
 769   };
 770 
 771   for (idx = 0; flaginfo[idx].i != unknown_flag && remaining > 1; idx++) {
 772     if (flags & flaginfo[idx].i) {
 773       if (first) {
 774         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
 775         first = false;
 776       } else {
 777         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
 778       }
 779       const size_t len = strlen(p);
 780       p += len;
 781       remaining -= len;
 782     }
 783   }
 784   unsigned int unknowns = flags & unknown_flag;
 785   if (unknowns != 0) {
 786     jio_snprintf(p, remaining, "|Unknown_flags:%x", unknowns);
 787   }
 788 
 789   buffer[size - 1] = '\0';
 790 
 791   return buffer;
 792 }
 793 
 794 // Prints one-line description of a combination of sigaction.sa_flags.
 795 static void print_sa_flags(outputStream* st, int flags) {
 796   char buffer[0x100];
 797   describe_sa_flags(flags, buffer, sizeof(buffer));
 798   st->print("%s", buffer);
 799 }
 800 
 801 // Implementation may use the same storage for both the sa_sigaction field and the sa_handler field,
 802 // so check for "sigAct.sa_flags == SA_SIGINFO"
 803 static address get_signal_handler(const struct sigaction* action) {
 804   bool siginfo_flag_set = (action->sa_flags & SA_SIGINFO) != 0;
 805   if (siginfo_flag_set) {
 806     return CAST_FROM_FN_PTR(address, action->sa_sigaction);
 807   } else {
 808     return CAST_FROM_FN_PTR(address, action->sa_handler);
 809   }
 810 }
 811 
 812 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
 813 
 814 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context);
 815 
 816 // Semantically compare two sigaction structures. Return true if they are referring to
 817 // the same handler, using the same flags.
 818 static bool are_handlers_equal(const struct sigaction* sa,
 819                                const struct sigaction* expected_sa) {
 820   address this_handler = get_signal_handler(sa);
 821   address expected_handler = get_signal_handler(expected_sa);
 822   const int this_flags = get_sanitized_sa_flags(sa);
 823   const int expected_flags = get_sanitized_sa_flags(expected_sa);
 824   return (this_handler == expected_handler) &&
 825          (this_flags == expected_flags);
 826 }
 827 
 828 // If we installed one of our signal handlers for sig, check that the current
 829 //  setup matches what we originally installed.
 830 static void check_signal_handler(int sig) {
 831   char buf[O_BUFLEN];
 832   bool mismatch = false;
 833 
 834   if (!do_check_signal_periodically[sig]) {
 835     return;
 836   }
 837 
 838   const struct sigaction* expected_act = vm_handlers.get(sig);
 839   assert(expected_act != NULL, "Sanity");
 840 
 841   // Retrieve current signal setup.
 842   struct sigaction act;
 843   static os_sigaction_t os_sigaction = NULL;
 844   if (os_sigaction == NULL) {
 845     // only trust the default sigaction, in case it has been interposed
 846     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
 847     if (os_sigaction == NULL) return;
 848   }
 849 
 850   os_sigaction(sig, (struct sigaction*)NULL, &act);
 851 
 852   // Compare both sigaction structures (intelligently; only the members we care about).
 853   if (!are_handlers_equal(&act, expected_act)) {
 854     tty->print_cr("Warning: %s handler modified!", os::exception_name(sig, buf, sizeof(buf)));
 855     // If we had a mismatch:
 856     // - print all signal handlers. As part of that printout, details will be printed
 857     //   about any modified handlers.
 858     // - Disable any further checks for this signal - we do not want to flood stdout. Though
 859     //   depending on which signal had been overwritten, we may die very soon anyway.
 860     os::print_signal_handlers(tty, buf, O_BUFLEN);
 861     do_check_signal_periodically[sig] = false;
 862     tty->print_cr("Consider using jsig library.");
 863     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
 864     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
 865       tty->print_cr("Note: Running in non-interactive shell, %s handler is replaced by shell",
 866                     os::exception_name(sig, buf, O_BUFLEN));
 867     }
 868   }
 869 }
 870 
 871 void* os::user_handler() {
 872   return CAST_FROM_FN_PTR(void*, UserHandler);
 873 }
 874 
 875 void* os::signal(int signal_number, void* handler) {
 876   struct sigaction sigAct, oldSigAct;
 877 
 878   sigfillset(&(sigAct.sa_mask));
 879   remove_error_signals_from_set(&(sigAct.sa_mask));
 880 
 881   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
 882   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
 883 
 884   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
 885     // -1 means registration failed
 886     return (void *)-1;
 887   }
 888 
 889   return get_signal_handler(&oldSigAct);
 890 }
 891 
 892 void os::signal_raise(int signal_number) {
 893   ::raise(signal_number);
 894 }
 895 
 896 // Will be modified when max signal is changed to be dynamic
 897 int os::sigexitnum_pd() {
 898   return NSIG;
 899 }
 900 
 901 // This method is a periodic task to check for misbehaving JNI applications
 902 // under CheckJNI, we can add any periodic checks here
 903 void os::run_periodic_checks() {
 904 
 905   if (check_signals == false) return;
 906 
 907   // SEGV and BUS if overridden could potentially prevent
 908   // generation of hs*.log in the event of a crash, debugging
 909   // such a case can be very challenging, so we absolutely
 910   // check the following for a good measure:
 911   check_signal_handler(SIGSEGV);
 912   check_signal_handler(SIGILL);
 913   check_signal_handler(SIGFPE);
 914   check_signal_handler(SIGBUS);
 915   check_signal_handler(SIGPIPE);
 916   check_signal_handler(SIGXFSZ);
 917   PPC64_ONLY(check_signal_handler(SIGTRAP);)
 918 
 919   // ReduceSignalUsage allows the user to override these handlers
 920   // see comments at the very top and jvm_md.h
 921   if (!ReduceSignalUsage) {
 922     check_signal_handler(SHUTDOWN1_SIGNAL);
 923     check_signal_handler(SHUTDOWN2_SIGNAL);
 924     check_signal_handler(SHUTDOWN3_SIGNAL);
 925     check_signal_handler(BREAK_SIGNAL);
 926   }
 927 
 928   check_signal_handler(PosixSignals::SR_signum);
 929 }
 930 
 931 // Helper function for PosixSignals::print_siginfo_...():
 932 // return a textual description for signal code.
 933 struct enum_sigcode_desc_t {
 934   const char* s_name;
 935   const char* s_desc;
 936 };
 937 
 938 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
 939 
 940   const struct {
 941     int sig; int code; const char* s_code; const char* s_desc;
 942   } t1 [] = {
 943     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
 944     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
 945     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
 946     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
 947     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
 948     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
 949     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
 950     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
 951 #if defined(IA64) && defined(LINUX)
 952     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
 953     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
 954 #endif
 955     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
 956     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
 957     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
 958     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
 959     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
 960     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
 961     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
 962     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
 963     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
 964     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
 965 #if defined(AIX)
 966     // no explanation found what keyerr would be
 967     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
 968 #endif
 969 #if defined(IA64) && !defined(AIX)
 970     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
 971 #endif
 972     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
 973     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
 974     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
 975     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
 976     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
 977     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
 978     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
 979     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
 980     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
 981     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
 982     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
 983 #ifdef SIGPOLL
 984     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
 985     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
 986     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
 987     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
 988     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
 989 #endif
 990     { -1, -1, NULL, NULL }
 991   };
 992 
 993   // Codes valid in any signal context.
 994   const struct {
 995     int code; const char* s_code; const char* s_desc;
 996   } t2 [] = {
 997     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
 998     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
 999     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
1000     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
1001     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
1002     // Linux specific
1003 #ifdef SI_TKILL
1004     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
1005 #endif
1006 #ifdef SI_DETHREAD
1007     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
1008 #endif
1009 #ifdef SI_KERNEL
1010     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
1011 #endif
1012 #ifdef SI_SIGIO
1013     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
1014 #endif
1015 
1016 #if defined(AIX)
1017     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
1018     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
1019 #endif
1020 
1021     { -1, NULL, NULL }
1022   };
1023 
1024   const char* s_code = NULL;
1025   const char* s_desc = NULL;
1026 
1027   for (int i = 0; t1[i].sig != -1; i ++) {
1028     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
1029       s_code = t1[i].s_code;
1030       s_desc = t1[i].s_desc;
1031       break;
1032     }
1033   }
1034 
1035   if (s_code == NULL) {
1036     for (int i = 0; t2[i].s_code != NULL; i ++) {
1037       if (t2[i].code == si->si_code) {
1038         s_code = t2[i].s_code;
1039         s_desc = t2[i].s_desc;
1040       }
1041     }
1042   }
1043 
1044   if (s_code == NULL) {
1045     out->s_name = "unknown";
1046     out->s_desc = "unknown";
1047     return false;
1048   }
1049 
1050   out->s_name = s_code;
1051   out->s_desc = s_desc;
1052 
1053   return true;
1054 }
1055 
1056 bool os::signal_sent_by_kill(const void* siginfo) {
1057   const siginfo_t* const si = (const siginfo_t*)siginfo;
1058   return si->si_code == SI_USER || si->si_code == SI_QUEUE
1059 #ifdef SI_TKILL
1060          || si->si_code == SI_TKILL
1061 #endif
1062   ;
1063 }
1064 
1065 // Returns true if signal number is valid.
1066 static bool is_valid_signal(int sig) {
1067   // MacOS not really POSIX compliant: sigaddset does not return
1068   // an error for invalid signal numbers. However, MacOS does not
1069   // support real time signals and simply seems to have just 33
1070   // signals with no holes in the signal range.
1071 #if defined(__APPLE__)
1072   return sig >= 1 && sig < NSIG;
1073 #else
1074   // Use sigaddset to check for signal validity.
1075   sigset_t set;
1076   sigemptyset(&set);
1077   if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
1078     return false;
1079   }
1080   return true;
1081 #endif
1082 }
1083 
1084 static const char* get_signal_name(int sig, char* out, size_t outlen) {
1085 
1086   const char* ret = NULL;
1087 
1088 #ifdef SIGRTMIN
1089   if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
1090     if (sig == SIGRTMIN) {
1091       ret = "SIGRTMIN";
1092     } else if (sig == SIGRTMAX) {
1093       ret = "SIGRTMAX";
1094     } else {
1095       jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
1096       return out;
1097     }
1098   }
1099 #endif
1100 
1101   if (sig > 0) {
1102     for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
1103       if (g_signal_info[idx].sig == sig) {
1104         ret = g_signal_info[idx].name;
1105         break;
1106       }
1107     }
1108   }
1109 
1110   if (!ret) {
1111     if (!is_valid_signal(sig)) {
1112       ret = "INVALID";
1113     } else {
1114       ret = "UNKNOWN";
1115     }
1116   }
1117 
1118   if (out && outlen > 0) {
1119     strncpy(out, ret, outlen);
1120     out[outlen - 1] = '\0';
1121   }
1122   return out;
1123 }
1124 
1125 void os::print_siginfo(outputStream* os, const void* si0) {
1126 
1127   const siginfo_t* const si = (const siginfo_t*) si0;
1128 
1129   char buf[20];
1130   os->print("siginfo:");
1131 
1132   if (!si) {
1133     os->print(" <null>");
1134     return;
1135   }
1136 
1137   const int sig = si->si_signo;
1138 
1139   os->print(" si_signo: %d (%s)", sig, get_signal_name(sig, buf, sizeof(buf)));
1140 
1141   enum_sigcode_desc_t ed;
1142   get_signal_code_description(si, &ed);
1143   os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1144 
1145   if (si->si_errno) {
1146     os->print(", si_errno: %d", si->si_errno);
1147   }
1148 
1149   // Output additional information depending on the signal code.
1150 
1151   // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1152   // so it depends on the context which member to use. For synchronous error signals,
1153   // we print si_addr, unless the signal was sent by another process or thread, in
1154   // which case we print out pid or tid of the sender.
1155   if (os::signal_sent_by_kill(si)) {
1156     const pid_t pid = si->si_pid;
1157     os->print(", si_pid: %ld", (long) pid);
1158     if (IS_VALID_PID(pid)) {
1159       const pid_t me = getpid();
1160       if (me == pid) {
1161         os->print(" (current process)");
1162       }
1163     } else {
1164       os->print(" (invalid)");
1165     }
1166     os->print(", si_uid: %ld", (long) si->si_uid);
1167     if (sig == SIGCHLD) {
1168       os->print(", si_status: %d", si->si_status);
1169     }
1170   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1171              sig == SIGTRAP || sig == SIGFPE) {
1172     os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1173 #ifdef SIGPOLL
1174   } else if (sig == SIGPOLL) {
1175     // siginfo_t.si_band is defined as "long", and it is so in most
1176     // implementations. But SPARC64 glibc has a bug: si_band is "int".
1177     // Cast si_band to "long" to prevent format specifier mismatch.
1178     // See: https://sourceware.org/bugzilla/show_bug.cgi?id=23821
1179     os->print(", si_band: %ld", (long) si->si_band);
1180 #endif
1181   }
1182 }
1183 
1184 bool os::signal_thread(Thread* thread, int sig, const char* reason) {
1185   OSThread* osthread = thread->osthread();
1186   if (osthread) {
1187     int status = pthread_kill(osthread->pthread_id(), sig);
1188     if (status == 0) {
1189       Events::log(Thread::current(), "sent signal %d to Thread " INTPTR_FORMAT " because %s.",
1190                   sig, p2i(thread), reason);
1191       return true;
1192     }
1193   }
1194   return false;
1195 }
1196 
1197 // Returns:
1198 // NULL for an invalid signal number
1199 // "SIG<num>" for a valid but unknown signal number
1200 // signal name otherwise.
1201 const char* os::exception_name(int sig, char* buf, size_t size) {
1202   if (!is_valid_signal(sig)) {
1203     return NULL;
1204   }
1205   const char* const name = get_signal_name(sig, buf, size);
1206   if (strcmp(name, "UNKNOWN") == 0) {
1207     jio_snprintf(buf, size, "SIG%d", sig);
1208   }
1209   return buf;
1210 }
1211 
1212 int os::get_signal_number(const char* signal_name) {
1213   char tmp[30];
1214   const char* s = signal_name;
1215   if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
1216     jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
1217     s = tmp;
1218   }
1219   for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
1220     if (strcmp(g_signal_info[idx].name, s) == 0) {
1221       return g_signal_info[idx].sig;
1222     }
1223   }
1224   return -1;
1225 }
1226 
1227 void set_signal_handler(int sig) {
1228   // Check for overwrite.
1229   struct sigaction oldAct;
1230   sigaction(sig, (struct sigaction*)NULL, &oldAct);
1231 
1232   // Query the current signal handler. Needs to be a separate operation
1233   // from installing a new handler since we need to honor AllowUserSignalHandlers.
1234   void* oldhand = get_signal_handler(&oldAct);
1235   if (!HANDLER_IS_IGN_OR_DFL(oldhand) &&
1236       !HANDLER_IS(oldhand, javaSignalHandler)) {
1237     if (AllowUserSignalHandlers) {
1238       // Do not overwrite; user takes responsibility to forward to us.
1239       return;
1240     } else if (UseSignalChaining) {
1241       // save the old handler in jvm
1242       chained_handlers.set(sig, &oldAct);
1243       // libjsig also interposes the sigaction() call below and saves the
1244       // old sigaction on it own.
1245     } else {
1246       fatal("Encountered unexpected pre-existing sigaction handler "
1247             "%#lx for signal %d.", (long)oldhand, sig);
1248     }
1249   }
1250 
1251   struct sigaction sigAct;
1252   sigfillset(&(sigAct.sa_mask));
1253   remove_error_signals_from_set(&(sigAct.sa_mask));
1254   sigAct.sa_sigaction = javaSignalHandler;
1255   sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
1256 #if defined(__APPLE__)
1257   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
1258   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
1259   // if the signal handler declares it will handle it on alternate stack.
1260   // Notice we only declare we will handle it on alt stack, but we are not
1261   // actually going to use real alt stack - this is just a workaround.
1262   // Please see ux_exception.c, method catch_mach_exception_raise for details
1263   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
1264   if (sig == SIGSEGV) {
1265     sigAct.sa_flags |= SA_ONSTACK;
1266   }
1267 #endif
1268 
1269   // Save handler setup for later checking
1270   vm_handlers.set(sig, &sigAct);
1271   do_check_signal_periodically[sig] = true;
1272 
1273   int ret = sigaction(sig, &sigAct, &oldAct);
1274   assert(ret == 0, "check");
1275 
1276   void* oldhand2  = get_signal_handler(&oldAct);
1277   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
1278 }
1279 
1280 // install signal handlers for signals that HotSpot needs to
1281 // handle in order to support Java-level exception handling.
1282 void install_signal_handlers() {
1283   // signal-chaining
1284   typedef void (*signal_setting_t)();
1285   signal_setting_t begin_signal_setting = NULL;
1286   signal_setting_t end_signal_setting = NULL;
1287   begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
1288                                         dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
1289   if (begin_signal_setting != NULL) {
1290     end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
1291                                         dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
1292     get_signal_action = CAST_TO_FN_PTR(get_signal_t,
1293                                        dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
1294     libjsig_is_loaded = true;
1295     assert(UseSignalChaining, "should enable signal-chaining");
1296   }
1297   if (libjsig_is_loaded) {
1298     // Tell libjsig jvm is setting signal handlers
1299     (*begin_signal_setting)();
1300   }
1301 
1302   set_signal_handler(SIGSEGV);
1303   set_signal_handler(SIGPIPE);
1304   set_signal_handler(SIGBUS);
1305   set_signal_handler(SIGILL);
1306   set_signal_handler(SIGFPE);
1307   PPC64_ONLY(set_signal_handler(SIGTRAP);)
1308   set_signal_handler(SIGXFSZ);
1309 
1310 #if defined(__APPLE__)
1311   // lldb (gdb) installs both standard BSD signal handlers, and mach exception
1312   // handlers. By replacing the existing task exception handler, we disable lldb's mach
1313   // exception handling, while leaving the standard BSD signal handlers functional.
1314   //
1315   // EXC_MASK_BAD_ACCESS needed by all architectures for NULL ptr checking
1316   // EXC_MASK_ARITHMETIC needed by all architectures for div by 0 checking
1317   // EXC_MASK_BAD_INSTRUCTION needed by aarch64 to initiate deoptimization
1318   kern_return_t kr;
1319   kr = task_set_exception_ports(mach_task_self(),
1320                                 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC
1321                                   AARCH64_ONLY(| EXC_MASK_BAD_INSTRUCTION),
1322                                 MACH_PORT_NULL,
1323                                 EXCEPTION_STATE_IDENTITY,
1324                                 MACHINE_THREAD_STATE);
1325 
1326   assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
1327 #endif
1328 
1329   if (libjsig_is_loaded) {
1330     // Tell libjsig jvm finishes setting signal handlers
1331     (*end_signal_setting)();
1332   }
1333 
1334   // We don't activate signal checker if libjsig is in place, we trust ourselves
1335   // and if UserSignalHandler is installed all bets are off.
1336   // Log that signal checking is off only if -verbose:jni is specified.
1337   if (CheckJNICalls) {
1338     if (libjsig_is_loaded) {
1339       log_debug(jni, resolve)("Info: libjsig is activated, all active signal checking is disabled");
1340       check_signals = false;
1341     }
1342     if (AllowUserSignalHandlers) {
1343       log_debug(jni, resolve)("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
1344       check_signals = false;
1345     }
1346   }
1347 }
1348 
1349 // Returns one-line short description of a signal set in a user provided buffer.
1350 static const char* describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
1351   assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
1352   // Note: for shortness, just print out the first 32. That should
1353   // cover most of the useful ones, apart from realtime signals.
1354   for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
1355     const int rc = sigismember(set, sig);
1356     if (rc == -1 && errno == EINVAL) {
1357       buffer[sig-1] = '?';
1358     } else {
1359       buffer[sig-1] = rc == 0 ? '0' : '1';
1360     }
1361   }
1362   buffer[NUM_IMPORTANT_SIGS] = 0;
1363   return buffer;
1364 }
1365 
1366 // Prints one-line description of a signal set.
1367 static void print_signal_set_short(outputStream* st, const sigset_t* set) {
1368   char buf[NUM_IMPORTANT_SIGS + 1];
1369   describe_signal_set_short(set, buf, sizeof(buf));
1370   st->print("%s", buf);
1371 }
1372 
1373 static void print_single_signal_handler(outputStream* st,
1374                                         const struct sigaction* act,
1375                                         char* buf, size_t buflen) {
1376 
1377   address handler = get_signal_handler(act);
1378   if (HANDLER_IS_DFL(handler)) {
1379     st->print("SIG_DFL");
1380   } else if (HANDLER_IS_IGN(handler)) {
1381     st->print("SIG_IGN");
1382   } else {
1383     print_signal_handler_name(st, handler, buf, buflen);
1384   }
1385 
1386   st->print(", mask=");
1387   print_signal_set_short(st, &(act->sa_mask));
1388 
1389   st->print(", flags=");
1390   int flags = get_sanitized_sa_flags(act);
1391   print_sa_flags(st, flags);
1392 
1393 }
1394 
1395 // Print established signal handler for this signal.
1396 // - if this signal handler was installed by us and is chained to a pre-established user handler
1397 //    it replaced, print that one too.
1398 // - otherwise, if this signal handler was installed by us and replaced another handler to which we
1399 //    are not chained (e.g. if chaining is off), print that one too.
1400 void PosixSignals::print_signal_handler(outputStream* st, int sig,
1401                                         char* buf, size_t buflen) {
1402 
1403   st->print("%10s: ", os::exception_name(sig, buf, buflen));
1404 
1405   struct sigaction current_act;
1406   sigaction(sig, NULL, &current_act);
1407 
1408   print_single_signal_handler(st, &current_act, buf, buflen);
1409   st->cr();
1410 
1411   // If we expected to see our own hotspot signal handler but found a different one,
1412   //  print a warning (unless the handler replacing it is our own crash handler, which can
1413   //  happen if this function is called during error reporting).
1414   const struct sigaction* expected_act = vm_handlers.get(sig);
1415   if (expected_act != NULL) {
1416     const address current_handler = get_signal_handler(&current_act);
1417     if (!(HANDLER_IS(current_handler, VMError::crash_handler_address))) {
1418       if (!are_handlers_equal(&current_act, expected_act)) {
1419         st->print_cr("  *** Handler was modified!");
1420         st->print   ("  *** Expected: ");
1421         print_single_signal_handler(st, expected_act, buf, buflen);
1422         st->cr();
1423       }
1424     }
1425   }
1426 
1427   // If there is a chained handler waiting behind the current one, print it too.
1428   const struct sigaction* chained_act = get_chained_signal_action(sig);
1429   if (chained_act != NULL) {
1430     st->print("  chained to: ");
1431     print_single_signal_handler(st, &current_act, buf, buflen);
1432     st->cr();
1433   }
1434 }
1435 
1436 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1437   st->print_cr("Signal Handlers:");
1438   PosixSignals::print_signal_handler(st, SIGSEGV, buf, buflen);
1439   PosixSignals::print_signal_handler(st, SIGBUS , buf, buflen);
1440   PosixSignals::print_signal_handler(st, SIGFPE , buf, buflen);
1441   PosixSignals::print_signal_handler(st, SIGPIPE, buf, buflen);
1442   PosixSignals::print_signal_handler(st, SIGXFSZ, buf, buflen);
1443   PosixSignals::print_signal_handler(st, SIGILL , buf, buflen);
1444   PosixSignals::print_signal_handler(st, PosixSignals::SR_signum, buf, buflen);
1445   PosixSignals::print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1446   PosixSignals::print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1447   PosixSignals::print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1448   PosixSignals::print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1449 #if defined(SIGDANGER)
1450   // We also want to know if someone else adds a SIGDANGER handler because
1451   // that will interfere with OOM killling.
1452   PosixSignals::print_signal_handler(st, SIGDANGER, buf, buflen);
1453 #endif
1454 #if defined(SIGTRAP)
1455   PosixSignals::print_signal_handler(st, SIGTRAP, buf, buflen);
1456 #endif
1457 }
1458 
1459 bool PosixSignals::is_sig_ignored(int sig) {
1460   struct sigaction oact;
1461   sigaction(sig, (struct sigaction*)NULL, &oact);
1462   if (HANDLER_IS_IGN(get_signal_handler(&oact))) {
1463     return true;
1464   } else {
1465     return false;
1466   }
1467 }
1468 
1469 static void signal_sets_init() {
1470   sigemptyset(&preinstalled_sigs);
1471 
1472   // Should also have an assertion stating we are still single-threaded.
1473   assert(!signal_sets_initialized, "Already initialized");
1474   // Fill in signals that are necessarily unblocked for all threads in
1475   // the VM. Currently, we unblock the following signals:
1476   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
1477   //                         by -Xrs (=ReduceSignalUsage));
1478   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
1479   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
1480   // the dispositions or masks wrt these signals.
1481   // Programs embedding the VM that want to use the above signals for their
1482   // own purposes must, at this time, use the "-Xrs" option to prevent
1483   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
1484   // (See bug 4345157, and other related bugs).
1485   // In reality, though, unblocking these signals is really a nop, since
1486   // these signals are not blocked by default.
1487   sigemptyset(&unblocked_sigs);
1488   sigaddset(&unblocked_sigs, SIGILL);
1489   sigaddset(&unblocked_sigs, SIGSEGV);
1490   sigaddset(&unblocked_sigs, SIGBUS);
1491   sigaddset(&unblocked_sigs, SIGFPE);
1492   PPC64_ONLY(sigaddset(&unblocked_sigs, SIGTRAP);)
1493   sigaddset(&unblocked_sigs, PosixSignals::SR_signum);
1494 
1495   if (!ReduceSignalUsage) {
1496     if (!PosixSignals::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
1497       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
1498     }
1499     if (!PosixSignals::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
1500       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
1501     }
1502     if (!PosixSignals::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
1503       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
1504     }
1505   }
1506   // Fill in signals that are blocked by all but the VM thread.
1507   sigemptyset(&vm_sigs);
1508   if (!ReduceSignalUsage) {
1509     sigaddset(&vm_sigs, BREAK_SIGNAL);
1510   }
1511   debug_only(signal_sets_initialized = true);
1512 }
1513 
1514 // These are signals that are unblocked while a thread is running Java.
1515 // (For some reason, they get blocked by default.)
1516 static sigset_t* unblocked_signals() {
1517   assert(signal_sets_initialized, "Not initialized");
1518   return &unblocked_sigs;
1519 }
1520 
1521 // These are the signals that are blocked while a (non-VM) thread is
1522 // running Java. Only the VM thread handles these signals.
1523 static sigset_t* vm_signals() {
1524   assert(signal_sets_initialized, "Not initialized");
1525   return &vm_sigs;
1526 }
1527 
1528 void PosixSignals::hotspot_sigmask(Thread* thread) {
1529 
1530   //Save caller's signal mask before setting VM signal mask
1531   sigset_t caller_sigmask;
1532   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
1533 
1534   OSThread* osthread = thread->osthread();
1535   osthread->set_caller_sigmask(caller_sigmask);
1536 
1537   pthread_sigmask(SIG_UNBLOCK, unblocked_signals(), NULL);
1538 
1539   if (!ReduceSignalUsage) {
1540     if (thread->is_VM_thread()) {
1541       // Only the VM thread handles BREAK_SIGNAL ...
1542       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
1543     } else {
1544       // ... all other threads block BREAK_SIGNAL
1545       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
1546     }
1547   }
1548 }
1549 
1550 ////////////////////////////////////////////////////////////////////////////////
1551 // suspend/resume support
1552 
1553 //  The low-level signal-based suspend/resume support is a remnant from the
1554 //  old VM-suspension that used to be for java-suspension, safepoints etc,
1555 //  within hotspot. Currently used by JFR's OSThreadSampler
1556 //
1557 //  The remaining code is greatly simplified from the more general suspension
1558 //  code that used to be used.
1559 //
1560 //  The protocol is quite simple:
1561 //  - suspend:
1562 //      - sends a signal to the target thread
1563 //      - polls the suspend state of the osthread using a yield loop
1564 //      - target thread signal handler (SR_handler) sets suspend state
1565 //        and blocks in sigsuspend until continued
1566 //  - resume:
1567 //      - sets target osthread state to continue
1568 //      - sends signal to end the sigsuspend loop in the SR_handler
1569 //
1570 //  Note that resume_clear_context() and suspend_save_context() are needed
1571 //  by SR_handler(), so that fetch_frame_from_context() works,
1572 //  which in part is used by:
1573 //    - Forte Analyzer: AsyncGetCallTrace()
1574 //    - StackBanging: get_frame_at_stack_banging_point()
1575 
1576 sigset_t SR_sigset;
1577 
1578 static void resume_clear_context(OSThread *osthread) {
1579   osthread->set_ucontext(NULL);
1580   osthread->set_siginfo(NULL);
1581 }
1582 
1583 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
1584   osthread->set_ucontext(context);
1585   osthread->set_siginfo(siginfo);
1586 }
1587 
1588 // Handler function invoked when a thread's execution is suspended or
1589 // resumed. We have to be careful that only async-safe functions are
1590 // called here (Note: most pthread functions are not async safe and
1591 // should be avoided.)
1592 //
1593 // Note: sigwait() is a more natural fit than sigsuspend() from an
1594 // interface point of view, but sigwait() prevents the signal handler
1595 // from being run. libpthread would get very confused by not having
1596 // its signal handlers run and prevents sigwait()'s use with the
1597 // mutex granting signal.
1598 //
1599 // Currently only ever called on the VMThread and JavaThreads (PC sampling)
1600 //
1601 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
1602 
1603   // Save and restore errno to avoid confusing native code with EINTR
1604   // after sigsuspend.
1605   int old_errno = errno;
1606 
1607   PosixSignals::unblock_error_signals();
1608 
1609   Thread* thread = Thread::current_or_null_safe();
1610   assert(thread != NULL, "Missing current thread in SR_handler");
1611 
1612   // On some systems we have seen signal delivery get "stuck" until the signal
1613   // mask is changed as part of thread termination. Check that the current thread
1614   // has not already terminated - else the following assertion
1615   // will fail because the thread is no longer a JavaThread as the ~JavaThread
1616   // destructor has completed.
1617 
1618   if (thread->has_terminated()) {
1619     return;
1620   }
1621 
1622   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
1623 
1624   OSThread* osthread = thread->osthread();
1625 
1626   os::SuspendResume::State current = osthread->sr.state();
1627 
1628   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
1629     suspend_save_context(osthread, siginfo, context);
1630 
1631     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
1632     os::SuspendResume::State state = osthread->sr.suspended();
1633     if (state == os::SuspendResume::SR_SUSPENDED) {
1634       sigset_t suspend_set;  // signals for sigsuspend()
1635       sigemptyset(&suspend_set);
1636 
1637       // get current set of blocked signals and unblock resume signal
1638       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
1639       sigdelset(&suspend_set, PosixSignals::SR_signum);
1640 
1641       sr_semaphore.signal();
1642 
1643       // wait here until we are resumed
1644       while (1) {
1645         sigsuspend(&suspend_set);
1646 
1647         os::SuspendResume::State result = osthread->sr.running();
1648         if (result == os::SuspendResume::SR_RUNNING) {
1649           // double check AIX doesn't need this!
1650           sr_semaphore.signal();
1651           break;
1652         } else if (result != os::SuspendResume::SR_SUSPENDED) {
1653           ShouldNotReachHere();
1654         }
1655       }
1656 
1657     } else if (state == os::SuspendResume::SR_RUNNING) {
1658       // request was cancelled, continue
1659     } else {
1660       ShouldNotReachHere();
1661     }
1662 
1663     resume_clear_context(osthread);
1664   } else if (current == os::SuspendResume::SR_RUNNING) {
1665     // request was cancelled, continue
1666   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
1667     // ignore
1668   } else {
1669     // ignore
1670   }
1671 
1672   errno = old_errno;
1673 }
1674 
1675 int SR_initialize() {
1676   struct sigaction act;
1677   char *s;
1678   // Get signal number to use for suspend/resume
1679   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
1680     int sig = ::strtol(s, 0, 10);
1681     if (sig > MAX2(SIGSEGV, SIGBUS) &&  // See 4355769.
1682         sig < NSIG) {                   // Must be legal signal and fit into sigflags[].
1683       PosixSignals::SR_signum = sig;
1684     } else {
1685       warning("You set _JAVA_SR_SIGNUM=%d. It must be in range [%d, %d]. Using %d instead.",
1686               sig, MAX2(SIGSEGV, SIGBUS)+1, NSIG-1, PosixSignals::SR_signum);
1687     }
1688   }
1689 
1690   assert(PosixSignals::SR_signum > SIGSEGV && PosixSignals::SR_signum > SIGBUS,
1691          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
1692 
1693   sigemptyset(&SR_sigset);
1694   sigaddset(&SR_sigset, PosixSignals::SR_signum);
1695 
1696   // Set up signal handler for suspend/resume
1697   act.sa_flags = SA_RESTART|SA_SIGINFO;
1698   act.sa_handler = (void (*)(int)) SR_handler;
1699 
1700   // SR_signum is blocked by default.
1701   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
1702   remove_error_signals_from_set(&(act.sa_mask));
1703 
1704   if (sigaction(PosixSignals::SR_signum, &act, 0) == -1) {
1705     return -1;
1706   }
1707 
1708   // Save signal setup information for later checking.
1709   vm_handlers.set(PosixSignals::SR_signum, &act);
1710   do_check_signal_periodically[PosixSignals::SR_signum] = true;
1711 
1712   return 0;
1713 }
1714 
1715 static int sr_notify(OSThread* osthread) {
1716   int status = pthread_kill(osthread->pthread_id(), PosixSignals::SR_signum);
1717   assert_status(status == 0, status, "pthread_kill");
1718   return status;
1719 }
1720 
1721 // returns true on success and false on error - really an error is fatal
1722 // but this seems the normal response to library errors
1723 bool PosixSignals::do_suspend(OSThread* osthread) {
1724   assert(osthread->sr.is_running(), "thread should be running");
1725   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
1726 
1727   // mark as suspended and send signal
1728   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
1729     // failed to switch, state wasn't running?
1730     ShouldNotReachHere();
1731     return false;
1732   }
1733 
1734   if (sr_notify(osthread) != 0) {
1735     ShouldNotReachHere();
1736   }
1737 
1738   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
1739   while (true) {
1740     if (sr_semaphore.timedwait(2)) {
1741       break;
1742     } else {
1743       // timeout
1744       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
1745       if (cancelled == os::SuspendResume::SR_RUNNING) {
1746         return false;
1747       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
1748         // make sure that we consume the signal on the semaphore as well
1749         sr_semaphore.wait();
1750         break;
1751       } else {
1752         ShouldNotReachHere();
1753         return false;
1754       }
1755     }
1756   }
1757 
1758   guarantee(osthread->sr.is_suspended(), "Must be suspended");
1759   return true;
1760 }
1761 
1762 void PosixSignals::do_resume(OSThread* osthread) {
1763   assert(osthread->sr.is_suspended(), "thread should be suspended");
1764   assert(!sr_semaphore.trywait(), "invalid semaphore state");
1765 
1766   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
1767     // failed to switch to WAKEUP_REQUEST
1768     ShouldNotReachHere();
1769     return;
1770   }
1771 
1772   while (true) {
1773     if (sr_notify(osthread) == 0) {
1774       if (sr_semaphore.timedwait(2)) {
1775         if (osthread->sr.is_running()) {
1776           return;
1777         }
1778       }
1779     } else {
1780       ShouldNotReachHere();
1781     }
1782   }
1783 
1784   guarantee(osthread->sr.is_running(), "Must be running!");
1785 }
1786 
1787 void os::SuspendedThreadTask::internal_do_task() {
1788   if (PosixSignals::do_suspend(_thread->osthread())) {
1789     os::SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
1790     do_task(context);
1791     PosixSignals::do_resume(_thread->osthread());
1792   }
1793 }
1794 
1795 int PosixSignals::init() {
1796   // initialize suspend/resume support - must do this before signal_sets_init()
1797   if (SR_initialize() != 0) {
1798     vm_exit_during_initialization("SR_initialize failed");
1799     return JNI_ERR;
1800   }
1801 
1802   signal_sets_init();
1803 
1804   install_signal_handlers();
1805 
1806   // Initialize data for jdk.internal.misc.Signal
1807   if (!ReduceSignalUsage) {
1808     jdk_misc_signal_init();
1809   }
1810 
1811   return JNI_OK;
1812 }