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