1 /*
   2  * Copyright (c) 1999, 2016, 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 "utilities/globalDefinitions.hpp"
  26 #include "prims/jvm.h"
  27 #include "semaphore_posix.hpp"
  28 #include "runtime/frame.inline.hpp"
  29 #include "runtime/interfaceSupport.hpp"
  30 #include "runtime/os.hpp"
  31 #include "utilities/vmError.hpp"
  32 
  33 #include <signal.h>
  34 #include <unistd.h>
  35 #include <sys/resource.h>
  36 #include <sys/utsname.h>
  37 #include <pthread.h>
  38 #include <semaphore.h>
  39 #include <signal.h>
  40 
  41 // Todo: provide a os::get_max_process_id() or similar. Number of processes
  42 // may have been configured, can be read more accurately from proc fs etc.
  43 #ifndef MAX_PID
  44 #define MAX_PID INT_MAX
  45 #endif
  46 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
  47 
  48 // Check core dump limit and report possible place where core can be found
  49 void os::check_dump_limit(char* buffer, size_t bufferSize) {
  50   if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) {
  51     jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line");
  52     VMError::record_coredump_status(buffer, false);
  53     return;
  54   }
  55 
  56   int n;
  57   struct rlimit rlim;
  58   bool success;
  59 
  60   char core_path[PATH_MAX];
  61   n = get_core_path(core_path, PATH_MAX);
  62 
  63   if (n <= 0) {
  64     jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
  65     success = true;
  66 #ifdef LINUX
  67   } else if (core_path[0] == '"') { // redirect to user process
  68     jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
  69     success = true;
  70 #endif
  71   } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
  72     jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
  73     success = true;
  74   } else {
  75     switch(rlim.rlim_cur) {
  76       case RLIM_INFINITY:
  77         jio_snprintf(buffer, bufferSize, "%s", core_path);
  78         success = true;
  79         break;
  80       case 0:
  81         jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
  82         success = false;
  83         break;
  84       default:
  85         jio_snprintf(buffer, bufferSize, "%s (max size %lu kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, (unsigned long)(rlim.rlim_cur >> 10));
  86         success = true;
  87         break;
  88     }
  89   }
  90 
  91   VMError::record_coredump_status(buffer, success);
  92 }
  93 
  94 int os::get_native_stack(address* stack, int frames, int toSkip) {
  95 #ifdef _NMT_NOINLINE_
  96   toSkip++;
  97 #endif
  98 
  99   int frame_idx = 0;
 100   int num_of_frames;  // number of frames captured
 101   frame fr = os::current_frame();
 102   while (fr.pc() && frame_idx < frames) {
 103     if (toSkip > 0) {
 104       toSkip --;
 105     } else {
 106       stack[frame_idx ++] = fr.pc();
 107     }
 108     if (fr.fp() == NULL || fr.cb() != NULL ||
 109         fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
 110 
 111     if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
 112       fr = os::get_sender_for_C_frame(&fr);
 113     } else {
 114       break;
 115     }
 116   }
 117   num_of_frames = frame_idx;
 118   for (; frame_idx < frames; frame_idx ++) {
 119     stack[frame_idx] = NULL;
 120   }
 121 
 122   return num_of_frames;
 123 }
 124 
 125 
 126 bool os::unsetenv(const char* name) {
 127   assert(name != NULL, "Null pointer");
 128   return (::unsetenv(name) == 0);
 129 }
 130 
 131 int os::get_last_error() {
 132   return errno;
 133 }
 134 
 135 bool os::is_debugger_attached() {
 136   // not implemented
 137   return false;
 138 }
 139 
 140 void os::wait_for_keypress_at_exit(void) {
 141   // don't do anything on posix platforms
 142   return;
 143 }
 144 
 145 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
 146 // so on posix, unmap the section at the start and at the end of the chunk that we mapped
 147 // rather than unmapping and remapping the whole chunk to get requested alignment.
 148 char* os::reserve_memory_aligned(size_t size, size_t alignment) {
 149   assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
 150       "Alignment must be a multiple of allocation granularity (page size)");
 151   assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
 152 
 153   size_t extra_size = size + alignment;
 154   assert(extra_size >= size, "overflow, size is too large to allow alignment");
 155 
 156   char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
 157 
 158   if (extra_base == NULL) {
 159     return NULL;
 160   }
 161 
 162   // Do manual alignment
 163   char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
 164 
 165   // [  |                                       |  ]
 166   // ^ extra_base
 167   //    ^ extra_base + begin_offset == aligned_base
 168   //     extra_base + begin_offset + size       ^
 169   //                       extra_base + extra_size ^
 170   // |<>| == begin_offset
 171   //                              end_offset == |<>|
 172   size_t begin_offset = aligned_base - extra_base;
 173   size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
 174 
 175   if (begin_offset > 0) {
 176       os::release_memory(extra_base, begin_offset);
 177   }
 178 
 179   if (end_offset > 0) {
 180       os::release_memory(extra_base + begin_offset + size, end_offset);
 181   }
 182 
 183   return aligned_base;
 184 }
 185 
 186 int os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
 187     return vsnprintf(buf, len, fmt, args);
 188 }
 189 
 190 int os::get_fileno(FILE* fp) {
 191   return NOT_AIX(::)fileno(fp);
 192 }
 193 
 194 void os::Posix::print_load_average(outputStream* st) {
 195   st->print("load average:");
 196   double loadavg[3];
 197   os::loadavg(loadavg, 3);
 198   st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
 199   st->cr();
 200 }
 201 
 202 void os::Posix::print_rlimit_info(outputStream* st) {
 203   st->print("rlimit:");
 204   struct rlimit rlim;
 205 
 206   st->print(" STACK ");
 207   getrlimit(RLIMIT_STACK, &rlim);
 208   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 209   else st->print("%luk", rlim.rlim_cur >> 10);
 210 
 211   st->print(", CORE ");
 212   getrlimit(RLIMIT_CORE, &rlim);
 213   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 214   else st->print("%luk", rlim.rlim_cur >> 10);
 215 
 216   // Isn't there on solaris
 217 #if !defined(TARGET_OS_FAMILY_solaris) && !defined(TARGET_OS_FAMILY_aix)
 218   st->print(", NPROC ");
 219   getrlimit(RLIMIT_NPROC, &rlim);
 220   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 221   else st->print("%lu", rlim.rlim_cur);
 222 #endif
 223 
 224   st->print(", NOFILE ");
 225   getrlimit(RLIMIT_NOFILE, &rlim);
 226   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 227   else st->print("%lu", rlim.rlim_cur);
 228 
 229   st->print(", AS ");
 230   getrlimit(RLIMIT_AS, &rlim);
 231   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 232   else st->print("%luk", rlim.rlim_cur >> 10);
 233   st->cr();
 234 }
 235 
 236 void os::Posix::print_uname_info(outputStream* st) {
 237   // kernel
 238   st->print("uname:");
 239   struct utsname name;
 240   uname(&name);
 241   st->print("%s ", name.sysname);
 242 #ifdef ASSERT
 243   st->print("%s ", name.nodename);
 244 #endif
 245   st->print("%s ", name.release);
 246   st->print("%s ", name.version);
 247   st->print("%s", name.machine);
 248   st->cr();
 249 }
 250 
 251 bool os::get_host_name(char* buf, size_t buflen) {
 252   struct utsname name;
 253   uname(&name);
 254   jio_snprintf(buf, buflen, "%s", name.nodename);
 255   return true;
 256 }
 257 
 258 bool os::has_allocatable_memory_limit(julong* limit) {
 259   struct rlimit rlim;
 260   int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
 261   // if there was an error when calling getrlimit, assume that there is no limitation
 262   // on virtual memory.
 263   bool result;
 264   if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
 265     result = false;
 266   } else {
 267     *limit = (julong)rlim.rlim_cur;
 268     result = true;
 269   }
 270 #ifdef _LP64
 271   return result;
 272 #else
 273   // arbitrary virtual space limit for 32 bit Unices found by testing. If
 274   // getrlimit above returned a limit, bound it with this limit. Otherwise
 275   // directly use it.
 276   const julong max_virtual_limit = (julong)3800*M;
 277   if (result) {
 278     *limit = MIN2(*limit, max_virtual_limit);
 279   } else {
 280     *limit = max_virtual_limit;
 281   }
 282 
 283   // bound by actually allocatable memory. The algorithm uses two bounds, an
 284   // upper and a lower limit. The upper limit is the current highest amount of
 285   // memory that could not be allocated, the lower limit is the current highest
 286   // amount of memory that could be allocated.
 287   // The algorithm iteratively refines the result by halving the difference
 288   // between these limits, updating either the upper limit (if that value could
 289   // not be allocated) or the lower limit (if the that value could be allocated)
 290   // until the difference between these limits is "small".
 291 
 292   // the minimum amount of memory we care about allocating.
 293   const julong min_allocation_size = M;
 294 
 295   julong upper_limit = *limit;
 296 
 297   // first check a few trivial cases
 298   if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
 299     *limit = upper_limit;
 300   } else if (!is_allocatable(min_allocation_size)) {
 301     // we found that not even min_allocation_size is allocatable. Return it
 302     // anyway. There is no point to search for a better value any more.
 303     *limit = min_allocation_size;
 304   } else {
 305     // perform the binary search.
 306     julong lower_limit = min_allocation_size;
 307     while ((upper_limit - lower_limit) > min_allocation_size) {
 308       julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
 309       temp_limit = align_size_down_(temp_limit, min_allocation_size);
 310       if (is_allocatable(temp_limit)) {
 311         lower_limit = temp_limit;
 312       } else {
 313         upper_limit = temp_limit;
 314       }
 315     }
 316     *limit = lower_limit;
 317   }
 318   return true;
 319 #endif
 320 }
 321 
 322 const char* os::get_current_directory(char *buf, size_t buflen) {
 323   return getcwd(buf, buflen);
 324 }
 325 
 326 FILE* os::open(int fd, const char* mode) {
 327   return ::fdopen(fd, mode);
 328 }
 329 
 330 void os::flockfile(FILE* fp) {
 331   ::flockfile(fp);
 332 }
 333 
 334 void os::funlockfile(FILE* fp) {
 335   ::funlockfile(fp);
 336 }
 337 
 338 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
 339 // which is used to find statically linked in agents.
 340 // Parameters:
 341 //            sym_name: Symbol in library we are looking for
 342 //            lib_name: Name of library to look in, NULL for shared libs.
 343 //            is_absolute_path == true if lib_name is absolute path to agent
 344 //                                     such as "/a/b/libL.so"
 345 //            == false if only the base name of the library is passed in
 346 //               such as "L"
 347 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
 348                                     bool is_absolute_path) {
 349   char *agent_entry_name;
 350   size_t len;
 351   size_t name_len;
 352   size_t prefix_len = strlen(JNI_LIB_PREFIX);
 353   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
 354   const char *start;
 355 
 356   if (lib_name != NULL) {
 357     name_len = strlen(lib_name);
 358     if (is_absolute_path) {
 359       // Need to strip path, prefix and suffix
 360       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
 361         lib_name = ++start;
 362       }
 363       if (strlen(lib_name) <= (prefix_len + suffix_len)) {
 364         return NULL;
 365       }
 366       lib_name += prefix_len;
 367       name_len = strlen(lib_name) - suffix_len;
 368     }
 369   }
 370   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
 371   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
 372   if (agent_entry_name == NULL) {
 373     return NULL;
 374   }
 375   strcpy(agent_entry_name, sym_name);
 376   if (lib_name != NULL) {
 377     strcat(agent_entry_name, "_");
 378     strncat(agent_entry_name, lib_name, name_len);
 379   }
 380   return agent_entry_name;
 381 }
 382 
 383 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
 384   assert(thread == Thread::current(),  "thread consistency check");
 385 
 386   ParkEvent * const slp = thread->_SleepEvent ;
 387   slp->reset() ;
 388   OrderAccess::fence() ;
 389 
 390   if (interruptible) {
 391     jlong prevtime = javaTimeNanos();
 392 
 393     for (;;) {
 394       if (os::is_interrupted(thread, true)) {
 395         return OS_INTRPT;
 396       }
 397 
 398       jlong newtime = javaTimeNanos();
 399 
 400       if (newtime - prevtime < 0) {
 401         // time moving backwards, should only happen if no monotonic clock
 402         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 403         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
 404       } else {
 405         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 406       }
 407 
 408       if (millis <= 0) {
 409         return OS_OK;
 410       }
 411 
 412       prevtime = newtime;
 413 
 414       {
 415         assert(thread->is_Java_thread(), "sanity check");
 416         JavaThread *jt = (JavaThread *) thread;
 417         ThreadBlockInVM tbivm(jt);
 418         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
 419 
 420         jt->set_suspend_equivalent();
 421         // cleared by handle_special_suspend_equivalent_condition() or
 422         // java_suspend_self() via check_and_wait_while_suspended()
 423 
 424         slp->park(millis);
 425 
 426         // were we externally suspended while we were waiting?
 427         jt->check_and_wait_while_suspended();
 428       }
 429     }
 430   } else {
 431     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
 432     jlong prevtime = javaTimeNanos();
 433 
 434     for (;;) {
 435       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
 436       // the 1st iteration ...
 437       jlong newtime = javaTimeNanos();
 438 
 439       if (newtime - prevtime < 0) {
 440         // time moving backwards, should only happen if no monotonic clock
 441         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 442         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
 443       } else {
 444         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 445       }
 446 
 447       if (millis <= 0) break ;
 448 
 449       prevtime = newtime;
 450       slp->park(millis);
 451     }
 452     return OS_OK ;
 453   }
 454 }
 455 
 456 ////////////////////////////////////////////////////////////////////////////////
 457 // interrupt support
 458 
 459 void os::interrupt(Thread* thread) {
 460   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 461     "possibility of dangling Thread pointer");
 462 
 463   OSThread* osthread = thread->osthread();
 464 
 465   if (!osthread->interrupted()) {
 466     osthread->set_interrupted(true);
 467     // More than one thread can get here with the same value of osthread,
 468     // resulting in multiple notifications.  We do, however, want the store
 469     // to interrupted() to be visible to other threads before we execute unpark().
 470     OrderAccess::fence();
 471     ParkEvent * const slp = thread->_SleepEvent ;
 472     if (slp != NULL) slp->unpark() ;
 473   }
 474 
 475   // For JSR166. Unpark even if interrupt status already was set
 476   if (thread->is_Java_thread())
 477     ((JavaThread*)thread)->parker()->unpark();
 478 
 479   ParkEvent * ev = thread->_ParkEvent ;
 480   if (ev != NULL) ev->unpark() ;
 481 
 482 }
 483 
 484 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
 485   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 486     "possibility of dangling Thread pointer");
 487 
 488   OSThread* osthread = thread->osthread();
 489 
 490   bool interrupted = osthread->interrupted();
 491 
 492   // NOTE that since there is no "lock" around the interrupt and
 493   // is_interrupted operations, there is the possibility that the
 494   // interrupted flag (in osThread) will be "false" but that the
 495   // low-level events will be in the signaled state. This is
 496   // intentional. The effect of this is that Object.wait() and
 497   // LockSupport.park() will appear to have a spurious wakeup, which
 498   // is allowed and not harmful, and the possibility is so rare that
 499   // it is not worth the added complexity to add yet another lock.
 500   // For the sleep event an explicit reset is performed on entry
 501   // to os::sleep, so there is no early return. It has also been
 502   // recommended not to put the interrupted flag into the "event"
 503   // structure because it hides the issue.
 504   if (interrupted && clear_interrupted) {
 505     osthread->set_interrupted(false);
 506     // consider thread->_SleepEvent->reset() ... optional optimization
 507   }
 508 
 509   return interrupted;
 510 }
 511 
 512 
 513 
 514 static const struct {
 515   int sig; const char* name;
 516 }
 517  g_signal_info[] =
 518   {
 519   {  SIGABRT,     "SIGABRT" },
 520 #ifdef SIGAIO
 521   {  SIGAIO,      "SIGAIO" },
 522 #endif
 523   {  SIGALRM,     "SIGALRM" },
 524 #ifdef SIGALRM1
 525   {  SIGALRM1,    "SIGALRM1" },
 526 #endif
 527   {  SIGBUS,      "SIGBUS" },
 528 #ifdef SIGCANCEL
 529   {  SIGCANCEL,   "SIGCANCEL" },
 530 #endif
 531   {  SIGCHLD,     "SIGCHLD" },
 532 #ifdef SIGCLD
 533   {  SIGCLD,      "SIGCLD" },
 534 #endif
 535   {  SIGCONT,     "SIGCONT" },
 536 #ifdef SIGCPUFAIL
 537   {  SIGCPUFAIL,  "SIGCPUFAIL" },
 538 #endif
 539 #ifdef SIGDANGER
 540   {  SIGDANGER,   "SIGDANGER" },
 541 #endif
 542 #ifdef SIGDIL
 543   {  SIGDIL,      "SIGDIL" },
 544 #endif
 545 #ifdef SIGEMT
 546   {  SIGEMT,      "SIGEMT" },
 547 #endif
 548   {  SIGFPE,      "SIGFPE" },
 549 #ifdef SIGFREEZE
 550   {  SIGFREEZE,   "SIGFREEZE" },
 551 #endif
 552 #ifdef SIGGFAULT
 553   {  SIGGFAULT,   "SIGGFAULT" },
 554 #endif
 555 #ifdef SIGGRANT
 556   {  SIGGRANT,    "SIGGRANT" },
 557 #endif
 558   {  SIGHUP,      "SIGHUP" },
 559   {  SIGILL,      "SIGILL" },
 560   {  SIGINT,      "SIGINT" },
 561 #ifdef SIGIO
 562   {  SIGIO,       "SIGIO" },
 563 #endif
 564 #ifdef SIGIOINT
 565   {  SIGIOINT,    "SIGIOINT" },
 566 #endif
 567 #ifdef SIGIOT
 568 // SIGIOT is there for BSD compatibility, but on most Unices just a
 569 // synonym for SIGABRT. The result should be "SIGABRT", not
 570 // "SIGIOT".
 571 #if (SIGIOT != SIGABRT )
 572   {  SIGIOT,      "SIGIOT" },
 573 #endif
 574 #endif
 575 #ifdef SIGKAP
 576   {  SIGKAP,      "SIGKAP" },
 577 #endif
 578   {  SIGKILL,     "SIGKILL" },
 579 #ifdef SIGLOST
 580   {  SIGLOST,     "SIGLOST" },
 581 #endif
 582 #ifdef SIGLWP
 583   {  SIGLWP,      "SIGLWP" },
 584 #endif
 585 #ifdef SIGLWPTIMER
 586   {  SIGLWPTIMER, "SIGLWPTIMER" },
 587 #endif
 588 #ifdef SIGMIGRATE
 589   {  SIGMIGRATE,  "SIGMIGRATE" },
 590 #endif
 591 #ifdef SIGMSG
 592   {  SIGMSG,      "SIGMSG" },
 593 #endif
 594   {  SIGPIPE,     "SIGPIPE" },
 595 #ifdef SIGPOLL
 596   {  SIGPOLL,     "SIGPOLL" },
 597 #endif
 598 #ifdef SIGPRE
 599   {  SIGPRE,      "SIGPRE" },
 600 #endif
 601   {  SIGPROF,     "SIGPROF" },
 602 #ifdef SIGPTY
 603   {  SIGPTY,      "SIGPTY" },
 604 #endif
 605 #ifdef SIGPWR
 606   {  SIGPWR,      "SIGPWR" },
 607 #endif
 608   {  SIGQUIT,     "SIGQUIT" },
 609 #ifdef SIGRECONFIG
 610   {  SIGRECONFIG, "SIGRECONFIG" },
 611 #endif
 612 #ifdef SIGRECOVERY
 613   {  SIGRECOVERY, "SIGRECOVERY" },
 614 #endif
 615 #ifdef SIGRESERVE
 616   {  SIGRESERVE,  "SIGRESERVE" },
 617 #endif
 618 #ifdef SIGRETRACT
 619   {  SIGRETRACT,  "SIGRETRACT" },
 620 #endif
 621 #ifdef SIGSAK
 622   {  SIGSAK,      "SIGSAK" },
 623 #endif
 624   {  SIGSEGV,     "SIGSEGV" },
 625 #ifdef SIGSOUND
 626   {  SIGSOUND,    "SIGSOUND" },
 627 #endif
 628 #ifdef SIGSTKFLT
 629   {  SIGSTKFLT,    "SIGSTKFLT" },
 630 #endif
 631   {  SIGSTOP,     "SIGSTOP" },
 632   {  SIGSYS,      "SIGSYS" },
 633 #ifdef SIGSYSERROR
 634   {  SIGSYSERROR, "SIGSYSERROR" },
 635 #endif
 636 #ifdef SIGTALRM
 637   {  SIGTALRM,    "SIGTALRM" },
 638 #endif
 639   {  SIGTERM,     "SIGTERM" },
 640 #ifdef SIGTHAW
 641   {  SIGTHAW,     "SIGTHAW" },
 642 #endif
 643   {  SIGTRAP,     "SIGTRAP" },
 644 #ifdef SIGTSTP
 645   {  SIGTSTP,     "SIGTSTP" },
 646 #endif
 647   {  SIGTTIN,     "SIGTTIN" },
 648   {  SIGTTOU,     "SIGTTOU" },
 649 #ifdef SIGURG
 650   {  SIGURG,      "SIGURG" },
 651 #endif
 652   {  SIGUSR1,     "SIGUSR1" },
 653   {  SIGUSR2,     "SIGUSR2" },
 654 #ifdef SIGVIRT
 655   {  SIGVIRT,     "SIGVIRT" },
 656 #endif
 657   {  SIGVTALRM,   "SIGVTALRM" },
 658 #ifdef SIGWAITING
 659   {  SIGWAITING,  "SIGWAITING" },
 660 #endif
 661 #ifdef SIGWINCH
 662   {  SIGWINCH,    "SIGWINCH" },
 663 #endif
 664 #ifdef SIGWINDOW
 665   {  SIGWINDOW,   "SIGWINDOW" },
 666 #endif
 667   {  SIGXCPU,     "SIGXCPU" },
 668   {  SIGXFSZ,     "SIGXFSZ" },
 669 #ifdef SIGXRES
 670   {  SIGXRES,     "SIGXRES" },
 671 #endif
 672   { -1, NULL }
 673 };
 674 
 675 // Returned string is a constant. For unknown signals "UNKNOWN" is returned.
 676 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
 677 
 678   const char* ret = NULL;
 679 
 680 #ifdef SIGRTMIN
 681   if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
 682     if (sig == SIGRTMIN) {
 683       ret = "SIGRTMIN";
 684     } else if (sig == SIGRTMAX) {
 685       ret = "SIGRTMAX";
 686     } else {
 687       jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
 688       return out;
 689     }
 690   }
 691 #endif
 692 
 693   if (sig > 0) {
 694     for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
 695       if (g_signal_info[idx].sig == sig) {
 696         ret = g_signal_info[idx].name;
 697         break;
 698       }
 699     }
 700   }
 701 
 702   if (!ret) {
 703     if (!is_valid_signal(sig)) {
 704       ret = "INVALID";
 705     } else {
 706       ret = "UNKNOWN";
 707     }
 708   }
 709 
 710   if (out && outlen > 0) {
 711     strncpy(out, ret, outlen);
 712     out[outlen - 1] = '\0';
 713   }
 714   return out;
 715 }
 716 
 717 int os::Posix::get_signal_number(const char* signal_name) {
 718   char tmp[30];
 719   const char* s = signal_name;
 720   if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
 721     jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
 722     s = tmp;
 723   }
 724   for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
 725     if (strcmp(g_signal_info[idx].name, s) == 0) {
 726       return g_signal_info[idx].sig;
 727     }
 728   }
 729   return -1;
 730 }
 731 
 732 int os::get_signal_number(const char* signal_name) {
 733   return os::Posix::get_signal_number(signal_name);
 734 }
 735 
 736 // Returns true if signal number is valid.
 737 bool os::Posix::is_valid_signal(int sig) {
 738   // MacOS not really POSIX compliant: sigaddset does not return
 739   // an error for invalid signal numbers. However, MacOS does not
 740   // support real time signals and simply seems to have just 33
 741   // signals with no holes in the signal range.
 742 #ifdef __APPLE__
 743   return sig >= 1 && sig < NSIG;
 744 #else
 745   // Use sigaddset to check for signal validity.
 746   sigset_t set;
 747   if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
 748     return false;
 749   }
 750   return true;
 751 #endif
 752 }
 753 
 754 // Returns:
 755 // NULL for an invalid signal number
 756 // "SIG<num>" for a valid but unknown signal number
 757 // signal name otherwise.
 758 const char* os::exception_name(int sig, char* buf, size_t size) {
 759   if (!os::Posix::is_valid_signal(sig)) {
 760     return NULL;
 761   }
 762   const char* const name = os::Posix::get_signal_name(sig, buf, size);
 763   if (strcmp(name, "UNKNOWN") == 0) {
 764     jio_snprintf(buf, size, "SIG%d", sig);
 765   }
 766   return buf;
 767 }
 768 
 769 #define NUM_IMPORTANT_SIGS 32
 770 // Returns one-line short description of a signal set in a user provided buffer.
 771 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
 772   assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
 773   // Note: for shortness, just print out the first 32. That should
 774   // cover most of the useful ones, apart from realtime signals.
 775   for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
 776     const int rc = sigismember(set, sig);
 777     if (rc == -1 && errno == EINVAL) {
 778       buffer[sig-1] = '?';
 779     } else {
 780       buffer[sig-1] = rc == 0 ? '0' : '1';
 781     }
 782   }
 783   buffer[NUM_IMPORTANT_SIGS] = 0;
 784   return buffer;
 785 }
 786 
 787 // Prints one-line description of a signal set.
 788 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
 789   char buf[NUM_IMPORTANT_SIGS + 1];
 790   os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
 791   st->print("%s", buf);
 792 }
 793 
 794 // Writes one-line description of a combination of sigaction.sa_flags into a user
 795 // provided buffer. Returns that buffer.
 796 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
 797   char* p = buffer;
 798   size_t remaining = size;
 799   bool first = true;
 800   int idx = 0;
 801 
 802   assert(buffer, "invalid argument");
 803 
 804   if (size == 0) {
 805     return buffer;
 806   }
 807 
 808   strncpy(buffer, "none", size);
 809 
 810   const struct {
 811     // NB: i is an unsigned int here because SA_RESETHAND is on some
 812     // systems 0x80000000, which is implicitly unsigned.  Assignining
 813     // it to an int field would be an overflow in unsigned-to-signed
 814     // conversion.
 815     unsigned int i;
 816     const char* s;
 817   } flaginfo [] = {
 818     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
 819     { SA_ONSTACK,   "SA_ONSTACK"   },
 820     { SA_RESETHAND, "SA_RESETHAND" },
 821     { SA_RESTART,   "SA_RESTART"   },
 822     { SA_SIGINFO,   "SA_SIGINFO"   },
 823     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
 824     { SA_NODEFER,   "SA_NODEFER"   },
 825 #ifdef AIX
 826     { SA_ONSTACK,   "SA_ONSTACK"   },
 827     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
 828 #endif
 829     { 0, NULL }
 830   };
 831 
 832   for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
 833     if (flags & flaginfo[idx].i) {
 834       if (first) {
 835         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
 836         first = false;
 837       } else {
 838         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
 839       }
 840       const size_t len = strlen(p);
 841       p += len;
 842       remaining -= len;
 843     }
 844   }
 845 
 846   buffer[size - 1] = '\0';
 847 
 848   return buffer;
 849 }
 850 
 851 // Prints one-line description of a combination of sigaction.sa_flags.
 852 void os::Posix::print_sa_flags(outputStream* st, int flags) {
 853   char buffer[0x100];
 854   os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
 855   st->print("%s", buffer);
 856 }
 857 
 858 // Helper function for os::Posix::print_siginfo_...():
 859 // return a textual description for signal code.
 860 struct enum_sigcode_desc_t {
 861   const char* s_name;
 862   const char* s_desc;
 863 };
 864 
 865 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
 866 
 867   const struct {
 868     int sig; int code; const char* s_code; const char* s_desc;
 869   } t1 [] = {
 870     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
 871     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
 872     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
 873     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
 874     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
 875     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
 876     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
 877     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
 878 #if defined(IA64) && defined(LINUX)
 879     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
 880     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
 881 #endif
 882     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
 883     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
 884     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
 885     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
 886     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
 887     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
 888     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
 889     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
 890     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
 891     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
 892 #ifdef AIX
 893     // no explanation found what keyerr would be
 894     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
 895 #endif
 896 #if defined(IA64) && !defined(AIX)
 897     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
 898 #endif
 899 #if defined(__sparc) && defined(SOLARIS)
 900 // define Solaris Sparc M7 ADI SEGV signals
 901 #if !defined(SEGV_ACCADI)
 902 #define SEGV_ACCADI 3
 903 #endif
 904     { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
 905 #if !defined(SEGV_ACCDERR)
 906 #define SEGV_ACCDERR 4
 907 #endif
 908     { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
 909 #if !defined(SEGV_ACCPERR)
 910 #define SEGV_ACCPERR 5
 911 #endif
 912     { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
 913 #endif // defined(__sparc) && defined(SOLARIS)
 914     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
 915     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
 916     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
 917     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
 918     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
 919     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
 920     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
 921     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
 922     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
 923     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
 924     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
 925 #ifdef SIGPOLL
 926     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
 927     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
 928     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
 929     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
 930     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
 931 #endif
 932     { -1, -1, NULL, NULL }
 933   };
 934 
 935   // Codes valid in any signal context.
 936   const struct {
 937     int code; const char* s_code; const char* s_desc;
 938   } t2 [] = {
 939     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
 940     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
 941     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
 942     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
 943     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
 944     // Linux specific
 945 #ifdef SI_TKILL
 946     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
 947 #endif
 948 #ifdef SI_DETHREAD
 949     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
 950 #endif
 951 #ifdef SI_KERNEL
 952     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
 953 #endif
 954 #ifdef SI_SIGIO
 955     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
 956 #endif
 957 
 958 #ifdef AIX
 959     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
 960     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
 961 #endif
 962 
 963 #ifdef __sun
 964     { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
 965     { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
 966     { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
 967 #endif
 968 
 969     { -1, NULL, NULL }
 970   };
 971 
 972   const char* s_code = NULL;
 973   const char* s_desc = NULL;
 974 
 975   for (int i = 0; t1[i].sig != -1; i ++) {
 976     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
 977       s_code = t1[i].s_code;
 978       s_desc = t1[i].s_desc;
 979       break;
 980     }
 981   }
 982 
 983   if (s_code == NULL) {
 984     for (int i = 0; t2[i].s_code != NULL; i ++) {
 985       if (t2[i].code == si->si_code) {
 986         s_code = t2[i].s_code;
 987         s_desc = t2[i].s_desc;
 988       }
 989     }
 990   }
 991 
 992   if (s_code == NULL) {
 993     out->s_name = "unknown";
 994     out->s_desc = "unknown";
 995     return false;
 996   }
 997 
 998   out->s_name = s_code;
 999   out->s_desc = s_desc;
1000 
1001   return true;
1002 }
1003 
1004 void os::print_siginfo(outputStream* os, const void* si0) {
1005 
1006   const siginfo_t* const si = (const siginfo_t*) si0;
1007 
1008   char buf[20];
1009   os->print("siginfo:");
1010 
1011   if (!si) {
1012     os->print(" <null>");
1013     return;
1014   }
1015 
1016   const int sig = si->si_signo;
1017 
1018   os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
1019 
1020   enum_sigcode_desc_t ed;
1021   get_signal_code_description(si, &ed);
1022   os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1023 
1024   if (si->si_errno) {
1025     os->print(", si_errno: %d", si->si_errno);
1026   }
1027 
1028   // Output additional information depending on the signal code.
1029 
1030   // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1031   // so it depends on the context which member to use. For synchronous error signals,
1032   // we print si_addr, unless the signal was sent by another process or thread, in
1033   // which case we print out pid or tid of the sender.
1034   if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
1035     const pid_t pid = si->si_pid;
1036     os->print(", si_pid: %ld", (long) pid);
1037     if (IS_VALID_PID(pid)) {
1038       const pid_t me = getpid();
1039       if (me == pid) {
1040         os->print(" (current process)");
1041       }
1042     } else {
1043       os->print(" (invalid)");
1044     }
1045     os->print(", si_uid: %ld", (long) si->si_uid);
1046     if (sig == SIGCHLD) {
1047       os->print(", si_status: %d", si->si_status);
1048     }
1049   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1050              sig == SIGTRAP || sig == SIGFPE) {
1051     os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1052 #ifdef SIGPOLL
1053   } else if (sig == SIGPOLL) {
1054     os->print(", si_band: %ld", si->si_band);
1055 #endif
1056   }
1057 
1058 }
1059 
1060 int os::Posix::unblock_thread_signal_mask(const sigset_t *set) {
1061   return pthread_sigmask(SIG_UNBLOCK, set, NULL);
1062 }
1063 
1064 address os::Posix::ucontext_get_pc(const ucontext_t* ctx) {
1065 #ifdef TARGET_OS_FAMILY_linux
1066    return Linux::ucontext_get_pc(ctx);
1067 #elif defined(TARGET_OS_FAMILY_solaris)
1068    return Solaris::ucontext_get_pc(ctx);
1069 #elif defined(TARGET_OS_FAMILY_aix)
1070    return Aix::ucontext_get_pc(ctx);
1071 #elif defined(TARGET_OS_FAMILY_bsd)
1072    return Bsd::ucontext_get_pc(ctx);
1073 #else
1074    VMError::report_and_die("unimplemented ucontext_get_pc");
1075 #endif
1076 }
1077 
1078 void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) {
1079 #ifdef TARGET_OS_FAMILY_linux
1080    Linux::ucontext_set_pc(ctx, pc);
1081 #elif defined(TARGET_OS_FAMILY_solaris)
1082    Solaris::ucontext_set_pc(ctx, pc);
1083 #elif defined(TARGET_OS_FAMILY_aix)
1084    Aix::ucontext_set_pc(ctx, pc);
1085 #elif defined(TARGET_OS_FAMILY_bsd)
1086    Bsd::ucontext_set_pc(ctx, pc);
1087 #else
1088    VMError::report_and_die("unimplemented ucontext_get_pc");
1089 #endif
1090 }
1091 
1092 char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) {
1093   size_t stack_size = 0;
1094   size_t guard_size = 0;
1095   int detachstate = 0;
1096   pthread_attr_getstacksize(attr, &stack_size);
1097   pthread_attr_getguardsize(attr, &guard_size);
1098   pthread_attr_getdetachstate(attr, &detachstate);
1099   jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s",
1100     stack_size / 1024, guard_size / 1024,
1101     (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable"));
1102   return buf;
1103 }
1104 
1105 
1106 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
1107   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
1108 }
1109 
1110 /*
1111  * See the caveats for this class in os_posix.hpp
1112  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
1113  * method and returns false. If none of the signals are raised, returns true.
1114  * The callback is supposed to provide the method that should be protected.
1115  */
1116 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
1117   sigset_t saved_sig_mask;
1118 
1119   assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
1120   assert(!WatcherThread::watcher_thread()->has_crash_protection(),
1121       "crash_protection already set?");
1122 
1123   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
1124   // since on at least some systems (OS X) siglongjmp will restore the mask
1125   // for the process, not the thread
1126   pthread_sigmask(0, NULL, &saved_sig_mask);
1127   if (sigsetjmp(_jmpbuf, 0) == 0) {
1128     // make sure we can see in the signal handler that we have crash protection
1129     // installed
1130     WatcherThread::watcher_thread()->set_crash_protection(this);
1131     cb.call();
1132     // and clear the crash protection
1133     WatcherThread::watcher_thread()->set_crash_protection(NULL);
1134     return true;
1135   }
1136   // this happens when we siglongjmp() back
1137   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1138   WatcherThread::watcher_thread()->set_crash_protection(NULL);
1139   return false;
1140 }
1141 
1142 void os::WatcherThreadCrashProtection::restore() {
1143   assert(WatcherThread::watcher_thread()->has_crash_protection(),
1144       "must have crash protection");
1145 
1146   siglongjmp(_jmpbuf, 1);
1147 }
1148 
1149 void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
1150     Thread* thread) {
1151 
1152   if (thread != NULL &&
1153       thread->is_Watcher_thread() &&
1154       WatcherThread::watcher_thread()->has_crash_protection()) {
1155 
1156     if (sig == SIGSEGV || sig == SIGBUS) {
1157       WatcherThread::watcher_thread()->crash_protection()->restore();
1158     }
1159   }
1160 }
1161 
1162 #define check_with_errno(check_type, cond, msg)                             \
1163   do {                                                                      \
1164     int err = errno;                                                        \
1165     check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
1166                os::errno_name(err));                                        \
1167 } while (false)
1168 
1169 #define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
1170 #define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
1171 
1172 // POSIX unamed semaphores are not supported on OS X.
1173 #ifndef __APPLE__
1174 
1175 PosixSemaphore::PosixSemaphore(uint value) {
1176   int ret = sem_init(&_semaphore, 0, value);
1177 
1178   guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
1179 }
1180 
1181 PosixSemaphore::~PosixSemaphore() {
1182   sem_destroy(&_semaphore);
1183 }
1184 
1185 void PosixSemaphore::signal(uint count) {
1186   for (uint i = 0; i < count; i++) {
1187     int ret = sem_post(&_semaphore);
1188 
1189     assert_with_errno(ret == 0, "sem_post failed");
1190   }
1191 }
1192 
1193 void PosixSemaphore::wait() {
1194   int ret;
1195 
1196   do {
1197     ret = sem_wait(&_semaphore);
1198   } while (ret != 0 && errno == EINTR);
1199 
1200   assert_with_errno(ret == 0, "sem_wait failed");
1201 }
1202 
1203 bool PosixSemaphore::trywait() {
1204   int ret;
1205 
1206   do {
1207     ret = sem_trywait(&_semaphore);
1208   } while (ret != 0 && errno == EINTR);
1209 
1210   assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
1211 
1212   return ret == 0;
1213 }
1214 
1215 bool PosixSemaphore::timedwait(struct timespec ts) {
1216   while (true) {
1217     int result = sem_timedwait(&_semaphore, &ts);
1218     if (result == 0) {
1219       return true;
1220     } else if (errno == EINTR) {
1221       continue;
1222     } else if (errno == ETIMEDOUT) {
1223       return false;
1224     } else {
1225       assert_with_errno(false, "timedwait failed");
1226       return false;
1227     }
1228   }
1229 }
1230 
1231 #endif // __APPLE__