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