1 /*
   2  * Copyright (c) 1999, 2017, 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/macros.hpp"
  32 #include "utilities/vmError.hpp"
  33 
  34 #include <dlfcn.h>
  35 #include <pthread.h>
  36 #include <semaphore.h>
  37 #include <signal.h>
  38 #include <sys/resource.h>
  39 #include <sys/utsname.h>
  40 #include <time.h>
  41 #include <unistd.h>
  42 
  43 // Todo: provide a os::get_max_process_id() or similar. Number of processes
  44 // may have been configured, can be read more accurately from proc fs etc.
  45 #ifndef MAX_PID
  46 #define MAX_PID INT_MAX
  47 #endif
  48 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
  49 
  50 // Check core dump limit and report possible place where core can be found
  51 void os::check_dump_limit(char* buffer, size_t bufferSize) {
  52   if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) {
  53     jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line");
  54     VMError::record_coredump_status(buffer, false);
  55     return;
  56   }
  57 
  58   int n;
  59   struct rlimit rlim;
  60   bool success;
  61 
  62   char core_path[PATH_MAX];
  63   n = get_core_path(core_path, PATH_MAX);
  64 
  65   if (n <= 0) {
  66     jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
  67     success = true;
  68 #ifdef LINUX
  69   } else if (core_path[0] == '"') { // redirect to user process
  70     jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
  71     success = true;
  72 #endif
  73   } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
  74     jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
  75     success = true;
  76   } else {
  77     switch(rlim.rlim_cur) {
  78       case RLIM_INFINITY:
  79         jio_snprintf(buffer, bufferSize, "%s", core_path);
  80         success = true;
  81         break;
  82       case 0:
  83         jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
  84         success = false;
  85         break;
  86       default:
  87         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));
  88         success = true;
  89         break;
  90     }
  91   }
  92 
  93   VMError::record_coredump_status(buffer, success);
  94 }
  95 
  96 int os::get_native_stack(address* stack, int frames, int toSkip) {
  97   int frame_idx = 0;
  98   int num_of_frames;  // number of frames captured
  99   frame fr = os::current_frame();
 100   while (fr.pc() && frame_idx < frames) {
 101     if (toSkip > 0) {
 102       toSkip --;
 103     } else {
 104       stack[frame_idx ++] = fr.pc();
 105     }
 106     if (fr.fp() == NULL || fr.cb() != NULL ||
 107         fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
 108 
 109     if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
 110       fr = os::get_sender_for_C_frame(&fr);
 111     } else {
 112       break;
 113     }
 114   }
 115   num_of_frames = frame_idx;
 116   for (; frame_idx < frames; frame_idx ++) {
 117     stack[frame_idx] = NULL;
 118   }
 119 
 120   return num_of_frames;
 121 }
 122 
 123 
 124 bool os::unsetenv(const char* name) {
 125   assert(name != NULL, "Null pointer");
 126   return (::unsetenv(name) == 0);
 127 }
 128 
 129 int os::get_last_error() {
 130   return errno;
 131 }
 132 
 133 bool os::is_debugger_attached() {
 134   // not implemented
 135   return false;
 136 }
 137 
 138 void os::wait_for_keypress_at_exit(void) {
 139   // don't do anything on posix platforms
 140   return;
 141 }
 142 
 143 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
 144 // so on posix, unmap the section at the start and at the end of the chunk that we mapped
 145 // rather than unmapping and remapping the whole chunk to get requested alignment.
 146 char* os::reserve_memory_aligned(size_t size, size_t alignment) {
 147   assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
 148       "Alignment must be a multiple of allocation granularity (page size)");
 149   assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
 150 
 151   size_t extra_size = size + alignment;
 152   assert(extra_size >= size, "overflow, size is too large to allow alignment");
 153 
 154   char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
 155 
 156   if (extra_base == NULL) {
 157     return NULL;
 158   }
 159 
 160   // Do manual alignment
 161   char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
 162 
 163   // [  |                                       |  ]
 164   // ^ extra_base
 165   //    ^ extra_base + begin_offset == aligned_base
 166   //     extra_base + begin_offset + size       ^
 167   //                       extra_base + extra_size ^
 168   // |<>| == begin_offset
 169   //                              end_offset == |<>|
 170   size_t begin_offset = aligned_base - extra_base;
 171   size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
 172 
 173   if (begin_offset > 0) {
 174       os::release_memory(extra_base, begin_offset);
 175   }
 176 
 177   if (end_offset > 0) {
 178       os::release_memory(extra_base + begin_offset + size, end_offset);
 179   }
 180 
 181   return aligned_base;
 182 }
 183 
 184 int os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
 185     return vsnprintf(buf, len, fmt, args);
 186 }
 187 
 188 int os::get_fileno(FILE* fp) {
 189   return NOT_AIX(::)fileno(fp);
 190 }
 191 
 192 struct tm* os::gmtime_pd(const time_t* clock, struct tm*  res) {
 193   return gmtime_r(clock, res);
 194 }
 195 
 196 void os::Posix::print_load_average(outputStream* st) {
 197   st->print("load average:");
 198   double loadavg[3];
 199   os::loadavg(loadavg, 3);
 200   st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
 201   st->cr();
 202 }
 203 
 204 void os::Posix::print_rlimit_info(outputStream* st) {
 205   st->print("rlimit:");
 206   struct rlimit rlim;
 207 
 208   st->print(" STACK ");
 209   getrlimit(RLIMIT_STACK, &rlim);
 210   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 211   else st->print("%luk", rlim.rlim_cur >> 10);
 212 
 213   st->print(", CORE ");
 214   getrlimit(RLIMIT_CORE, &rlim);
 215   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 216   else st->print("%luk", rlim.rlim_cur >> 10);
 217 
 218   // Isn't there on solaris
 219 #if !defined(SOLARIS) && !defined(AIX)
 220   st->print(", NPROC ");
 221   getrlimit(RLIMIT_NPROC, &rlim);
 222   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 223   else st->print("%lu", rlim.rlim_cur);
 224 #endif
 225 
 226   st->print(", NOFILE ");
 227   getrlimit(RLIMIT_NOFILE, &rlim);
 228   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 229   else st->print("%lu", rlim.rlim_cur);
 230 
 231   st->print(", AS ");
 232   getrlimit(RLIMIT_AS, &rlim);
 233   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 234   else st->print("%luk", rlim.rlim_cur >> 10);
 235   st->cr();
 236 }
 237 
 238 void os::Posix::print_uname_info(outputStream* st) {
 239   // kernel
 240   st->print("uname:");
 241   struct utsname name;
 242   uname(&name);
 243   st->print("%s ", name.sysname);
 244 #ifdef ASSERT
 245   st->print("%s ", name.nodename);
 246 #endif
 247   st->print("%s ", name.release);
 248   st->print("%s ", name.version);
 249   st->print("%s", name.machine);
 250   st->cr();
 251 }
 252 
 253 bool os::get_host_name(char* buf, size_t buflen) {
 254   struct utsname name;
 255   uname(&name);
 256   jio_snprintf(buf, buflen, "%s", name.nodename);
 257   return true;
 258 }
 259 
 260 bool os::has_allocatable_memory_limit(julong* limit) {
 261   struct rlimit rlim;
 262   int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
 263   // if there was an error when calling getrlimit, assume that there is no limitation
 264   // on virtual memory.
 265   bool result;
 266   if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
 267     result = false;
 268   } else {
 269     *limit = (julong)rlim.rlim_cur;
 270     result = true;
 271   }
 272 #ifdef _LP64
 273   return result;
 274 #else
 275   // arbitrary virtual space limit for 32 bit Unices found by testing. If
 276   // getrlimit above returned a limit, bound it with this limit. Otherwise
 277   // directly use it.
 278   const julong max_virtual_limit = (julong)3800*M;
 279   if (result) {
 280     *limit = MIN2(*limit, max_virtual_limit);
 281   } else {
 282     *limit = max_virtual_limit;
 283   }
 284 
 285   // bound by actually allocatable memory. The algorithm uses two bounds, an
 286   // upper and a lower limit. The upper limit is the current highest amount of
 287   // memory that could not be allocated, the lower limit is the current highest
 288   // amount of memory that could be allocated.
 289   // The algorithm iteratively refines the result by halving the difference
 290   // between these limits, updating either the upper limit (if that value could
 291   // not be allocated) or the lower limit (if the that value could be allocated)
 292   // until the difference between these limits is "small".
 293 
 294   // the minimum amount of memory we care about allocating.
 295   const julong min_allocation_size = M;
 296 
 297   julong upper_limit = *limit;
 298 
 299   // first check a few trivial cases
 300   if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
 301     *limit = upper_limit;
 302   } else if (!is_allocatable(min_allocation_size)) {
 303     // we found that not even min_allocation_size is allocatable. Return it
 304     // anyway. There is no point to search for a better value any more.
 305     *limit = min_allocation_size;
 306   } else {
 307     // perform the binary search.
 308     julong lower_limit = min_allocation_size;
 309     while ((upper_limit - lower_limit) > min_allocation_size) {
 310       julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
 311       temp_limit = align_size_down_(temp_limit, min_allocation_size);
 312       if (is_allocatable(temp_limit)) {
 313         lower_limit = temp_limit;
 314       } else {
 315         upper_limit = temp_limit;
 316       }
 317     }
 318     *limit = lower_limit;
 319   }
 320   return true;
 321 #endif
 322 }
 323 
 324 const char* os::get_current_directory(char *buf, size_t buflen) {
 325   return getcwd(buf, buflen);
 326 }
 327 
 328 FILE* os::open(int fd, const char* mode) {
 329   return ::fdopen(fd, mode);
 330 }
 331 
 332 void os::flockfile(FILE* fp) {
 333   ::flockfile(fp);
 334 }
 335 
 336 void os::funlockfile(FILE* fp) {
 337   ::funlockfile(fp);
 338 }
 339 
 340 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
 341 // which is used to find statically linked in agents.
 342 // Parameters:
 343 //            sym_name: Symbol in library we are looking for
 344 //            lib_name: Name of library to look in, NULL for shared libs.
 345 //            is_absolute_path == true if lib_name is absolute path to agent
 346 //                                     such as "/a/b/libL.so"
 347 //            == false if only the base name of the library is passed in
 348 //               such as "L"
 349 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
 350                                     bool is_absolute_path) {
 351   char *agent_entry_name;
 352   size_t len;
 353   size_t name_len;
 354   size_t prefix_len = strlen(JNI_LIB_PREFIX);
 355   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
 356   const char *start;
 357 
 358   if (lib_name != NULL) {
 359     name_len = strlen(lib_name);
 360     if (is_absolute_path) {
 361       // Need to strip path, prefix and suffix
 362       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
 363         lib_name = ++start;
 364       }
 365       if (strlen(lib_name) <= (prefix_len + suffix_len)) {
 366         return NULL;
 367       }
 368       lib_name += prefix_len;
 369       name_len = strlen(lib_name) - suffix_len;
 370     }
 371   }
 372   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
 373   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
 374   if (agent_entry_name == NULL) {
 375     return NULL;
 376   }
 377   strcpy(agent_entry_name, sym_name);
 378   if (lib_name != NULL) {
 379     strcat(agent_entry_name, "_");
 380     strncat(agent_entry_name, lib_name, name_len);
 381   }
 382   return agent_entry_name;
 383 }
 384 
 385 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
 386   assert(thread == Thread::current(),  "thread consistency check");
 387 
 388   ParkEvent * const slp = thread->_SleepEvent ;
 389   slp->reset() ;
 390   OrderAccess::fence() ;
 391 
 392   if (interruptible) {
 393     jlong prevtime = javaTimeNanos();
 394 
 395     for (;;) {
 396       if (os::is_interrupted(thread, true)) {
 397         return OS_INTRPT;
 398       }
 399 
 400       jlong newtime = javaTimeNanos();
 401 
 402       if (newtime - prevtime < 0) {
 403         // time moving backwards, should only happen if no monotonic clock
 404         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 405         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
 406       } else {
 407         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 408       }
 409 
 410       if (millis <= 0) {
 411         return OS_OK;
 412       }
 413 
 414       prevtime = newtime;
 415 
 416       {
 417         assert(thread->is_Java_thread(), "sanity check");
 418         JavaThread *jt = (JavaThread *) thread;
 419         ThreadBlockInVM tbivm(jt);
 420         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
 421 
 422         jt->set_suspend_equivalent();
 423         // cleared by handle_special_suspend_equivalent_condition() or
 424         // java_suspend_self() via check_and_wait_while_suspended()
 425 
 426         slp->park(millis);
 427 
 428         // were we externally suspended while we were waiting?
 429         jt->check_and_wait_while_suspended();
 430       }
 431     }
 432   } else {
 433     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
 434     jlong prevtime = javaTimeNanos();
 435 
 436     for (;;) {
 437       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
 438       // the 1st iteration ...
 439       jlong newtime = javaTimeNanos();
 440 
 441       if (newtime - prevtime < 0) {
 442         // time moving backwards, should only happen if no monotonic clock
 443         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 444         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
 445       } else {
 446         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 447       }
 448 
 449       if (millis <= 0) break ;
 450 
 451       prevtime = newtime;
 452       slp->park(millis);
 453     }
 454     return OS_OK ;
 455   }
 456 }
 457 
 458 ////////////////////////////////////////////////////////////////////////////////
 459 // interrupt support
 460 
 461 void os::interrupt(Thread* thread) {
 462   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 463     "possibility of dangling Thread pointer");
 464 
 465   OSThread* osthread = thread->osthread();
 466 
 467   if (!osthread->interrupted()) {
 468     osthread->set_interrupted(true);
 469     // More than one thread can get here with the same value of osthread,
 470     // resulting in multiple notifications.  We do, however, want the store
 471     // to interrupted() to be visible to other threads before we execute unpark().
 472     OrderAccess::fence();
 473     ParkEvent * const slp = thread->_SleepEvent ;
 474     if (slp != NULL) slp->unpark() ;
 475   }
 476 
 477   // For JSR166. Unpark even if interrupt status already was set
 478   if (thread->is_Java_thread())
 479     ((JavaThread*)thread)->parker()->unpark();
 480 
 481   ParkEvent * ev = thread->_ParkEvent ;
 482   if (ev != NULL) ev->unpark() ;
 483 
 484 }
 485 
 486 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
 487   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 488     "possibility of dangling Thread pointer");
 489 
 490   OSThread* osthread = thread->osthread();
 491 
 492   bool interrupted = osthread->interrupted();
 493 
 494   // NOTE that since there is no "lock" around the interrupt and
 495   // is_interrupted operations, there is the possibility that the
 496   // interrupted flag (in osThread) will be "false" but that the
 497   // low-level events will be in the signaled state. This is
 498   // intentional. The effect of this is that Object.wait() and
 499   // LockSupport.park() will appear to have a spurious wakeup, which
 500   // is allowed and not harmful, and the possibility is so rare that
 501   // it is not worth the added complexity to add yet another lock.
 502   // For the sleep event an explicit reset is performed on entry
 503   // to os::sleep, so there is no early return. It has also been
 504   // recommended not to put the interrupted flag into the "event"
 505   // structure because it hides the issue.
 506   if (interrupted && clear_interrupted) {
 507     osthread->set_interrupted(false);
 508     // consider thread->_SleepEvent->reset() ... optional optimization
 509   }
 510 
 511   return interrupted;
 512 }
 513 
 514 
 515 
 516 static const struct {
 517   int sig; const char* name;
 518 }
 519  g_signal_info[] =
 520   {
 521   {  SIGABRT,     "SIGABRT" },
 522 #ifdef SIGAIO
 523   {  SIGAIO,      "SIGAIO" },
 524 #endif
 525   {  SIGALRM,     "SIGALRM" },
 526 #ifdef SIGALRM1
 527   {  SIGALRM1,    "SIGALRM1" },
 528 #endif
 529   {  SIGBUS,      "SIGBUS" },
 530 #ifdef SIGCANCEL
 531   {  SIGCANCEL,   "SIGCANCEL" },
 532 #endif
 533   {  SIGCHLD,     "SIGCHLD" },
 534 #ifdef SIGCLD
 535   {  SIGCLD,      "SIGCLD" },
 536 #endif
 537   {  SIGCONT,     "SIGCONT" },
 538 #ifdef SIGCPUFAIL
 539   {  SIGCPUFAIL,  "SIGCPUFAIL" },
 540 #endif
 541 #ifdef SIGDANGER
 542   {  SIGDANGER,   "SIGDANGER" },
 543 #endif
 544 #ifdef SIGDIL
 545   {  SIGDIL,      "SIGDIL" },
 546 #endif
 547 #ifdef SIGEMT
 548   {  SIGEMT,      "SIGEMT" },
 549 #endif
 550   {  SIGFPE,      "SIGFPE" },
 551 #ifdef SIGFREEZE
 552   {  SIGFREEZE,   "SIGFREEZE" },
 553 #endif
 554 #ifdef SIGGFAULT
 555   {  SIGGFAULT,   "SIGGFAULT" },
 556 #endif
 557 #ifdef SIGGRANT
 558   {  SIGGRANT,    "SIGGRANT" },
 559 #endif
 560   {  SIGHUP,      "SIGHUP" },
 561   {  SIGILL,      "SIGILL" },
 562   {  SIGINT,      "SIGINT" },
 563 #ifdef SIGIO
 564   {  SIGIO,       "SIGIO" },
 565 #endif
 566 #ifdef SIGIOINT
 567   {  SIGIOINT,    "SIGIOINT" },
 568 #endif
 569 #ifdef SIGIOT
 570 // SIGIOT is there for BSD compatibility, but on most Unices just a
 571 // synonym for SIGABRT. The result should be "SIGABRT", not
 572 // "SIGIOT".
 573 #if (SIGIOT != SIGABRT )
 574   {  SIGIOT,      "SIGIOT" },
 575 #endif
 576 #endif
 577 #ifdef SIGKAP
 578   {  SIGKAP,      "SIGKAP" },
 579 #endif
 580   {  SIGKILL,     "SIGKILL" },
 581 #ifdef SIGLOST
 582   {  SIGLOST,     "SIGLOST" },
 583 #endif
 584 #ifdef SIGLWP
 585   {  SIGLWP,      "SIGLWP" },
 586 #endif
 587 #ifdef SIGLWPTIMER
 588   {  SIGLWPTIMER, "SIGLWPTIMER" },
 589 #endif
 590 #ifdef SIGMIGRATE
 591   {  SIGMIGRATE,  "SIGMIGRATE" },
 592 #endif
 593 #ifdef SIGMSG
 594   {  SIGMSG,      "SIGMSG" },
 595 #endif
 596   {  SIGPIPE,     "SIGPIPE" },
 597 #ifdef SIGPOLL
 598   {  SIGPOLL,     "SIGPOLL" },
 599 #endif
 600 #ifdef SIGPRE
 601   {  SIGPRE,      "SIGPRE" },
 602 #endif
 603   {  SIGPROF,     "SIGPROF" },
 604 #ifdef SIGPTY
 605   {  SIGPTY,      "SIGPTY" },
 606 #endif
 607 #ifdef SIGPWR
 608   {  SIGPWR,      "SIGPWR" },
 609 #endif
 610   {  SIGQUIT,     "SIGQUIT" },
 611 #ifdef SIGRECONFIG
 612   {  SIGRECONFIG, "SIGRECONFIG" },
 613 #endif
 614 #ifdef SIGRECOVERY
 615   {  SIGRECOVERY, "SIGRECOVERY" },
 616 #endif
 617 #ifdef SIGRESERVE
 618   {  SIGRESERVE,  "SIGRESERVE" },
 619 #endif
 620 #ifdef SIGRETRACT
 621   {  SIGRETRACT,  "SIGRETRACT" },
 622 #endif
 623 #ifdef SIGSAK
 624   {  SIGSAK,      "SIGSAK" },
 625 #endif
 626   {  SIGSEGV,     "SIGSEGV" },
 627 #ifdef SIGSOUND
 628   {  SIGSOUND,    "SIGSOUND" },
 629 #endif
 630 #ifdef SIGSTKFLT
 631   {  SIGSTKFLT,    "SIGSTKFLT" },
 632 #endif
 633   {  SIGSTOP,     "SIGSTOP" },
 634   {  SIGSYS,      "SIGSYS" },
 635 #ifdef SIGSYSERROR
 636   {  SIGSYSERROR, "SIGSYSERROR" },
 637 #endif
 638 #ifdef SIGTALRM
 639   {  SIGTALRM,    "SIGTALRM" },
 640 #endif
 641   {  SIGTERM,     "SIGTERM" },
 642 #ifdef SIGTHAW
 643   {  SIGTHAW,     "SIGTHAW" },
 644 #endif
 645   {  SIGTRAP,     "SIGTRAP" },
 646 #ifdef SIGTSTP
 647   {  SIGTSTP,     "SIGTSTP" },
 648 #endif
 649   {  SIGTTIN,     "SIGTTIN" },
 650   {  SIGTTOU,     "SIGTTOU" },
 651 #ifdef SIGURG
 652   {  SIGURG,      "SIGURG" },
 653 #endif
 654   {  SIGUSR1,     "SIGUSR1" },
 655   {  SIGUSR2,     "SIGUSR2" },
 656 #ifdef SIGVIRT
 657   {  SIGVIRT,     "SIGVIRT" },
 658 #endif
 659   {  SIGVTALRM,   "SIGVTALRM" },
 660 #ifdef SIGWAITING
 661   {  SIGWAITING,  "SIGWAITING" },
 662 #endif
 663 #ifdef SIGWINCH
 664   {  SIGWINCH,    "SIGWINCH" },
 665 #endif
 666 #ifdef SIGWINDOW
 667   {  SIGWINDOW,   "SIGWINDOW" },
 668 #endif
 669   {  SIGXCPU,     "SIGXCPU" },
 670   {  SIGXFSZ,     "SIGXFSZ" },
 671 #ifdef SIGXRES
 672   {  SIGXRES,     "SIGXRES" },
 673 #endif
 674   { -1, NULL }
 675 };
 676 
 677 // Returned string is a constant. For unknown signals "UNKNOWN" is returned.
 678 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
 679 
 680   const char* ret = NULL;
 681 
 682 #ifdef SIGRTMIN
 683   if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
 684     if (sig == SIGRTMIN) {
 685       ret = "SIGRTMIN";
 686     } else if (sig == SIGRTMAX) {
 687       ret = "SIGRTMAX";
 688     } else {
 689       jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
 690       return out;
 691     }
 692   }
 693 #endif
 694 
 695   if (sig > 0) {
 696     for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
 697       if (g_signal_info[idx].sig == sig) {
 698         ret = g_signal_info[idx].name;
 699         break;
 700       }
 701     }
 702   }
 703 
 704   if (!ret) {
 705     if (!is_valid_signal(sig)) {
 706       ret = "INVALID";
 707     } else {
 708       ret = "UNKNOWN";
 709     }
 710   }
 711 
 712   if (out && outlen > 0) {
 713     strncpy(out, ret, outlen);
 714     out[outlen - 1] = '\0';
 715   }
 716   return out;
 717 }
 718 
 719 int os::Posix::get_signal_number(const char* signal_name) {
 720   char tmp[30];
 721   const char* s = signal_name;
 722   if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
 723     jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
 724     s = tmp;
 725   }
 726   for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
 727     if (strcmp(g_signal_info[idx].name, s) == 0) {
 728       return g_signal_info[idx].sig;
 729     }
 730   }
 731   return -1;
 732 }
 733 
 734 int os::get_signal_number(const char* signal_name) {
 735   return os::Posix::get_signal_number(signal_name);
 736 }
 737 
 738 // Returns true if signal number is valid.
 739 bool os::Posix::is_valid_signal(int sig) {
 740   // MacOS not really POSIX compliant: sigaddset does not return
 741   // an error for invalid signal numbers. However, MacOS does not
 742   // support real time signals and simply seems to have just 33
 743   // signals with no holes in the signal range.
 744 #ifdef __APPLE__
 745   return sig >= 1 && sig < NSIG;
 746 #else
 747   // Use sigaddset to check for signal validity.
 748   sigset_t set;
 749   if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
 750     return false;
 751   }
 752   return true;
 753 #endif
 754 }
 755 
 756 // Returns:
 757 // NULL for an invalid signal number
 758 // "SIG<num>" for a valid but unknown signal number
 759 // signal name otherwise.
 760 const char* os::exception_name(int sig, char* buf, size_t size) {
 761   if (!os::Posix::is_valid_signal(sig)) {
 762     return NULL;
 763   }
 764   const char* const name = os::Posix::get_signal_name(sig, buf, size);
 765   if (strcmp(name, "UNKNOWN") == 0) {
 766     jio_snprintf(buf, size, "SIG%d", sig);
 767   }
 768   return buf;
 769 }
 770 
 771 #define NUM_IMPORTANT_SIGS 32
 772 // Returns one-line short description of a signal set in a user provided buffer.
 773 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
 774   assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
 775   // Note: for shortness, just print out the first 32. That should
 776   // cover most of the useful ones, apart from realtime signals.
 777   for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
 778     const int rc = sigismember(set, sig);
 779     if (rc == -1 && errno == EINVAL) {
 780       buffer[sig-1] = '?';
 781     } else {
 782       buffer[sig-1] = rc == 0 ? '0' : '1';
 783     }
 784   }
 785   buffer[NUM_IMPORTANT_SIGS] = 0;
 786   return buffer;
 787 }
 788 
 789 // Prints one-line description of a signal set.
 790 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
 791   char buf[NUM_IMPORTANT_SIGS + 1];
 792   os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
 793   st->print("%s", buf);
 794 }
 795 
 796 // Writes one-line description of a combination of sigaction.sa_flags into a user
 797 // provided buffer. Returns that buffer.
 798 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
 799   char* p = buffer;
 800   size_t remaining = size;
 801   bool first = true;
 802   int idx = 0;
 803 
 804   assert(buffer, "invalid argument");
 805 
 806   if (size == 0) {
 807     return buffer;
 808   }
 809 
 810   strncpy(buffer, "none", size);
 811 
 812   const struct {
 813     // NB: i is an unsigned int here because SA_RESETHAND is on some
 814     // systems 0x80000000, which is implicitly unsigned.  Assignining
 815     // it to an int field would be an overflow in unsigned-to-signed
 816     // conversion.
 817     unsigned int i;
 818     const char* s;
 819   } flaginfo [] = {
 820     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
 821     { SA_ONSTACK,   "SA_ONSTACK"   },
 822     { SA_RESETHAND, "SA_RESETHAND" },
 823     { SA_RESTART,   "SA_RESTART"   },
 824     { SA_SIGINFO,   "SA_SIGINFO"   },
 825     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
 826     { SA_NODEFER,   "SA_NODEFER"   },
 827 #ifdef AIX
 828     { SA_ONSTACK,   "SA_ONSTACK"   },
 829     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
 830 #endif
 831     { 0, NULL }
 832   };
 833 
 834   for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
 835     if (flags & flaginfo[idx].i) {
 836       if (first) {
 837         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
 838         first = false;
 839       } else {
 840         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
 841       }
 842       const size_t len = strlen(p);
 843       p += len;
 844       remaining -= len;
 845     }
 846   }
 847 
 848   buffer[size - 1] = '\0';
 849 
 850   return buffer;
 851 }
 852 
 853 // Prints one-line description of a combination of sigaction.sa_flags.
 854 void os::Posix::print_sa_flags(outputStream* st, int flags) {
 855   char buffer[0x100];
 856   os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
 857   st->print("%s", buffer);
 858 }
 859 
 860 // Helper function for os::Posix::print_siginfo_...():
 861 // return a textual description for signal code.
 862 struct enum_sigcode_desc_t {
 863   const char* s_name;
 864   const char* s_desc;
 865 };
 866 
 867 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
 868 
 869   const struct {
 870     int sig; int code; const char* s_code; const char* s_desc;
 871   } t1 [] = {
 872     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
 873     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
 874     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
 875     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
 876     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
 877     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
 878     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
 879     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
 880 #if defined(IA64) && defined(LINUX)
 881     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
 882     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
 883 #endif
 884     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
 885     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
 886     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
 887     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
 888     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
 889     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
 890     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
 891     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
 892     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
 893     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
 894 #ifdef AIX
 895     // no explanation found what keyerr would be
 896     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
 897 #endif
 898 #if defined(IA64) && !defined(AIX)
 899     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
 900 #endif
 901 #if defined(__sparc) && defined(SOLARIS)
 902 // define Solaris Sparc M7 ADI SEGV signals
 903 #if !defined(SEGV_ACCADI)
 904 #define SEGV_ACCADI 3
 905 #endif
 906     { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
 907 #if !defined(SEGV_ACCDERR)
 908 #define SEGV_ACCDERR 4
 909 #endif
 910     { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
 911 #if !defined(SEGV_ACCPERR)
 912 #define SEGV_ACCPERR 5
 913 #endif
 914     { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
 915 #endif // defined(__sparc) && defined(SOLARIS)
 916     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
 917     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
 918     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
 919     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
 920     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
 921     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
 922     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
 923     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
 924     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
 925     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
 926     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
 927 #ifdef SIGPOLL
 928     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
 929     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
 930     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
 931     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
 932     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
 933 #endif
 934     { -1, -1, NULL, NULL }
 935   };
 936 
 937   // Codes valid in any signal context.
 938   const struct {
 939     int code; const char* s_code; const char* s_desc;
 940   } t2 [] = {
 941     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
 942     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
 943     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
 944     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
 945     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
 946     // Linux specific
 947 #ifdef SI_TKILL
 948     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
 949 #endif
 950 #ifdef SI_DETHREAD
 951     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
 952 #endif
 953 #ifdef SI_KERNEL
 954     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
 955 #endif
 956 #ifdef SI_SIGIO
 957     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
 958 #endif
 959 
 960 #ifdef AIX
 961     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
 962     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
 963 #endif
 964 
 965 #ifdef __sun
 966     { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
 967     { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
 968     { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
 969 #endif
 970 
 971     { -1, NULL, NULL }
 972   };
 973 
 974   const char* s_code = NULL;
 975   const char* s_desc = NULL;
 976 
 977   for (int i = 0; t1[i].sig != -1; i ++) {
 978     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
 979       s_code = t1[i].s_code;
 980       s_desc = t1[i].s_desc;
 981       break;
 982     }
 983   }
 984 
 985   if (s_code == NULL) {
 986     for (int i = 0; t2[i].s_code != NULL; i ++) {
 987       if (t2[i].code == si->si_code) {
 988         s_code = t2[i].s_code;
 989         s_desc = t2[i].s_desc;
 990       }
 991     }
 992   }
 993 
 994   if (s_code == NULL) {
 995     out->s_name = "unknown";
 996     out->s_desc = "unknown";
 997     return false;
 998   }
 999 
1000   out->s_name = s_code;
1001   out->s_desc = s_desc;
1002 
1003   return true;
1004 }
1005 
1006 void os::print_siginfo(outputStream* os, const void* si0) {
1007 
1008   const siginfo_t* const si = (const siginfo_t*) si0;
1009 
1010   char buf[20];
1011   os->print("siginfo:");
1012 
1013   if (!si) {
1014     os->print(" <null>");
1015     return;
1016   }
1017 
1018   const int sig = si->si_signo;
1019 
1020   os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
1021 
1022   enum_sigcode_desc_t ed;
1023   get_signal_code_description(si, &ed);
1024   os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1025 
1026   if (si->si_errno) {
1027     os->print(", si_errno: %d", si->si_errno);
1028   }
1029 
1030   // Output additional information depending on the signal code.
1031 
1032   // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1033   // so it depends on the context which member to use. For synchronous error signals,
1034   // we print si_addr, unless the signal was sent by another process or thread, in
1035   // which case we print out pid or tid of the sender.
1036   if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
1037     const pid_t pid = si->si_pid;
1038     os->print(", si_pid: %ld", (long) pid);
1039     if (IS_VALID_PID(pid)) {
1040       const pid_t me = getpid();
1041       if (me == pid) {
1042         os->print(" (current process)");
1043       }
1044     } else {
1045       os->print(" (invalid)");
1046     }
1047     os->print(", si_uid: %ld", (long) si->si_uid);
1048     if (sig == SIGCHLD) {
1049       os->print(", si_status: %d", si->si_status);
1050     }
1051   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1052              sig == SIGTRAP || sig == SIGFPE) {
1053     os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1054 #ifdef SIGPOLL
1055   } else if (sig == SIGPOLL) {
1056     os->print(", si_band: %ld", si->si_band);
1057 #endif
1058   }
1059 
1060 }
1061 
1062 int os::Posix::unblock_thread_signal_mask(const sigset_t *set) {
1063   return pthread_sigmask(SIG_UNBLOCK, set, NULL);
1064 }
1065 
1066 address os::Posix::ucontext_get_pc(const ucontext_t* ctx) {
1067 #if defined(AIX)
1068    return Aix::ucontext_get_pc(ctx);
1069 #elif defined(BSD)
1070    return Bsd::ucontext_get_pc(ctx);
1071 #elif defined(LINUX)
1072    return Linux::ucontext_get_pc(ctx);
1073 #elif defined(SOLARIS)
1074    return Solaris::ucontext_get_pc(ctx);
1075 #else
1076    VMError::report_and_die("unimplemented ucontext_get_pc");
1077 #endif
1078 }
1079 
1080 void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) {
1081 #if defined(AIX)
1082    Aix::ucontext_set_pc(ctx, pc);
1083 #elif defined(BSD)
1084    Bsd::ucontext_set_pc(ctx, pc);
1085 #elif defined(LINUX)
1086    Linux::ucontext_set_pc(ctx, pc);
1087 #elif defined(SOLARIS)
1088    Solaris::ucontext_set_pc(ctx, pc);
1089 #else
1090    VMError::report_and_die("unimplemented ucontext_get_pc");
1091 #endif
1092 }
1093 
1094 char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) {
1095   size_t stack_size = 0;
1096   size_t guard_size = 0;
1097   int detachstate = 0;
1098   pthread_attr_getstacksize(attr, &stack_size);
1099   pthread_attr_getguardsize(attr, &guard_size);
1100   // Work around linux NPTL implementation error, see also os::create_thread() in os_linux.cpp.
1101   LINUX_ONLY(stack_size -= guard_size);
1102   pthread_attr_getdetachstate(attr, &detachstate);
1103   jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s",
1104     stack_size / 1024, guard_size / 1024,
1105     (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable"));
1106   return buf;
1107 }
1108 
1109 char* os::Posix::realpath(const char* filename, char* outbuf, size_t outbuflen) {
1110 
1111   if (filename == NULL || outbuf == NULL || outbuflen < 1) {
1112     assert(false, "os::Posix::realpath: invalid arguments.");
1113     errno = EINVAL;
1114     return NULL;
1115   }
1116 
1117   char* result = NULL;
1118 
1119   // This assumes platform realpath() is implemented according to POSIX.1-2008.
1120   // POSIX.1-2008 allows to specify NULL for the output buffer, in which case
1121   // output buffer is dynamically allocated and must be ::free()'d by the caller.
1122   char* p = ::realpath(filename, NULL);
1123   if (p != NULL) {
1124     if (strlen(p) < outbuflen) {
1125       strcpy(outbuf, p);
1126       result = outbuf;
1127     } else {
1128       errno = ENAMETOOLONG;
1129     }
1130     ::free(p); // *not* os::free
1131   } else {
1132     // Fallback for platforms struggling with modern Posix standards (AIX 5.3, 6.1). If realpath
1133     // returns EINVAL, this may indicate that realpath is not POSIX.1-2008 compatible and
1134     // that it complains about the NULL we handed down as user buffer.
1135     // In this case, use the user provided buffer but at least check whether realpath caused
1136     // a memory overwrite.
1137     if (errno == EINVAL) {
1138       outbuf[outbuflen - 1] = '\0';
1139       p = ::realpath(filename, outbuf);
1140       if (p != NULL) {
1141         guarantee(outbuf[outbuflen - 1] == '\0', "realpath buffer overwrite detected.");
1142         result = p;
1143       }
1144     }
1145   }
1146   return result;
1147 
1148 }
1149 
1150 
1151 // Check minimum allowable stack sizes for thread creation and to initialize
1152 // the java system classes, including StackOverflowError - depends on page
1153 // size.
1154 // The space needed for frames during startup is platform dependent. It
1155 // depends on word size, platform calling conventions, C frame layout and
1156 // interpreter/C1/C2 design decisions. Therefore this is given in a
1157 // platform (os/cpu) dependent constant.
1158 // To this, space for guard mechanisms is added, which depends on the
1159 // page size which again depends on the concrete system the VM is running
1160 // on. Space for libc guard pages is not included in this size.
1161 jint os::Posix::set_minimum_stack_sizes() {
1162   size_t os_min_stack_allowed = SOLARIS_ONLY(thr_min_stack()) NOT_SOLARIS(PTHREAD_STACK_MIN);
1163 
1164   _java_thread_min_stack_allowed = _java_thread_min_stack_allowed +
1165                                    JavaThread::stack_guard_zone_size() +
1166                                    JavaThread::stack_shadow_zone_size();
1167 
1168   _java_thread_min_stack_allowed = align_size_up(_java_thread_min_stack_allowed, vm_page_size());
1169   _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed, os_min_stack_allowed);
1170 
1171   size_t stack_size_in_bytes = ThreadStackSize * K;
1172   if (stack_size_in_bytes != 0 &&
1173       stack_size_in_bytes < _java_thread_min_stack_allowed) {
1174     // The '-Xss' and '-XX:ThreadStackSize=N' options both set
1175     // ThreadStackSize so we go with "Java thread stack size" instead
1176     // of "ThreadStackSize" to be more friendly.
1177     tty->print_cr("\nThe Java thread stack size specified is too small. "
1178                   "Specify at least " SIZE_FORMAT "k",
1179                   _java_thread_min_stack_allowed / K);
1180     return JNI_ERR;
1181   }
1182 
1183   // Make the stack size a multiple of the page size so that
1184   // the yellow/red zones can be guarded.
1185   JavaThread::set_stack_size_at_create(round_to(stack_size_in_bytes, vm_page_size()));
1186 
1187   // Reminder: a compiler thread is a Java thread.
1188   _compiler_thread_min_stack_allowed = _compiler_thread_min_stack_allowed +
1189                                        JavaThread::stack_guard_zone_size() +
1190                                        JavaThread::stack_shadow_zone_size();
1191 
1192   _compiler_thread_min_stack_allowed = align_size_up(_compiler_thread_min_stack_allowed, vm_page_size());
1193   _compiler_thread_min_stack_allowed = MAX2(_compiler_thread_min_stack_allowed, os_min_stack_allowed);
1194 
1195   stack_size_in_bytes = CompilerThreadStackSize * K;
1196   if (stack_size_in_bytes != 0 &&
1197       stack_size_in_bytes < _compiler_thread_min_stack_allowed) {
1198     tty->print_cr("\nThe CompilerThreadStackSize specified is too small. "
1199                   "Specify at least " SIZE_FORMAT "k",
1200                   _compiler_thread_min_stack_allowed / K);
1201     return JNI_ERR;
1202   }
1203 
1204   _vm_internal_thread_min_stack_allowed = align_size_up(_vm_internal_thread_min_stack_allowed, vm_page_size());
1205   _vm_internal_thread_min_stack_allowed = MAX2(_vm_internal_thread_min_stack_allowed, os_min_stack_allowed);
1206 
1207   stack_size_in_bytes = VMThreadStackSize * K;
1208   if (stack_size_in_bytes != 0 &&
1209       stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) {
1210     tty->print_cr("\nThe VMThreadStackSize specified is too small. "
1211                   "Specify at least " SIZE_FORMAT "k",
1212                   _vm_internal_thread_min_stack_allowed / K);
1213     return JNI_ERR;
1214   }
1215   return JNI_OK;
1216 }
1217 
1218 // Called when creating the thread.  The minimum stack sizes have already been calculated
1219 size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) {
1220   size_t stack_size;
1221   if (req_stack_size == 0) {
1222     stack_size = default_stack_size(thr_type);
1223   } else {
1224     stack_size = req_stack_size;
1225   }
1226 
1227   switch (thr_type) {
1228   case os::java_thread:
1229     // Java threads use ThreadStackSize which default value can be
1230     // changed with the flag -Xss
1231     if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) {
1232       // no requested size and we have a more specific default value
1233       stack_size = JavaThread::stack_size_at_create();
1234     }
1235     stack_size = MAX2(stack_size,
1236                       _java_thread_min_stack_allowed);
1237     break;
1238   case os::compiler_thread:
1239     if (req_stack_size == 0 && CompilerThreadStackSize > 0) {
1240       // no requested size and we have a more specific default value
1241       stack_size = (size_t)(CompilerThreadStackSize * K);
1242     }
1243     stack_size = MAX2(stack_size,
1244                       _compiler_thread_min_stack_allowed);
1245     break;
1246   case os::vm_thread:
1247   case os::pgc_thread:
1248   case os::cgc_thread:
1249   case os::watcher_thread:
1250   default:  // presume the unknown thr_type is a VM internal
1251     if (req_stack_size == 0 && VMThreadStackSize > 0) {
1252       // no requested size and we have a more specific default value
1253       stack_size = (size_t)(VMThreadStackSize * K);
1254     }
1255 
1256     stack_size = MAX2(stack_size,
1257                       _vm_internal_thread_min_stack_allowed);
1258     break;
1259   }
1260 
1261   // pthread_attr_setstacksize() may require that the size be rounded up to the OS page size.
1262   // Be careful not to round up to 0. Align down in that case.
1263   if (stack_size <= SIZE_MAX - vm_page_size()) {
1264     stack_size = align_size_up(stack_size, vm_page_size());
1265   } else {
1266     stack_size = align_size_down(stack_size, vm_page_size());
1267   }
1268 
1269   return stack_size;
1270 }
1271 
1272 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
1273   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
1274 }
1275 
1276 /*
1277  * See the caveats for this class in os_posix.hpp
1278  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
1279  * method and returns false. If none of the signals are raised, returns true.
1280  * The callback is supposed to provide the method that should be protected.
1281  */
1282 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
1283   sigset_t saved_sig_mask;
1284 
1285   assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
1286   assert(!WatcherThread::watcher_thread()->has_crash_protection(),
1287       "crash_protection already set?");
1288 
1289   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
1290   // since on at least some systems (OS X) siglongjmp will restore the mask
1291   // for the process, not the thread
1292   pthread_sigmask(0, NULL, &saved_sig_mask);
1293   if (sigsetjmp(_jmpbuf, 0) == 0) {
1294     // make sure we can see in the signal handler that we have crash protection
1295     // installed
1296     WatcherThread::watcher_thread()->set_crash_protection(this);
1297     cb.call();
1298     // and clear the crash protection
1299     WatcherThread::watcher_thread()->set_crash_protection(NULL);
1300     return true;
1301   }
1302   // this happens when we siglongjmp() back
1303   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1304   WatcherThread::watcher_thread()->set_crash_protection(NULL);
1305   return false;
1306 }
1307 
1308 void os::WatcherThreadCrashProtection::restore() {
1309   assert(WatcherThread::watcher_thread()->has_crash_protection(),
1310       "must have crash protection");
1311 
1312   siglongjmp(_jmpbuf, 1);
1313 }
1314 
1315 void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
1316     Thread* thread) {
1317 
1318   if (thread != NULL &&
1319       thread->is_Watcher_thread() &&
1320       WatcherThread::watcher_thread()->has_crash_protection()) {
1321 
1322     if (sig == SIGSEGV || sig == SIGBUS) {
1323       WatcherThread::watcher_thread()->crash_protection()->restore();
1324     }
1325   }
1326 }
1327 
1328 #define check_with_errno(check_type, cond, msg)                             \
1329   do {                                                                      \
1330     int err = errno;                                                        \
1331     check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
1332                os::errno_name(err));                                        \
1333 } while (false)
1334 
1335 #define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
1336 #define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
1337 
1338 // POSIX unamed semaphores are not supported on OS X.
1339 #ifndef __APPLE__
1340 
1341 PosixSemaphore::PosixSemaphore(uint value) {
1342   int ret = sem_init(&_semaphore, 0, value);
1343 
1344   guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
1345 }
1346 
1347 PosixSemaphore::~PosixSemaphore() {
1348   sem_destroy(&_semaphore);
1349 }
1350 
1351 void PosixSemaphore::signal(uint count) {
1352   for (uint i = 0; i < count; i++) {
1353     int ret = sem_post(&_semaphore);
1354 
1355     assert_with_errno(ret == 0, "sem_post failed");
1356   }
1357 }
1358 
1359 void PosixSemaphore::wait() {
1360   int ret;
1361 
1362   do {
1363     ret = sem_wait(&_semaphore);
1364   } while (ret != 0 && errno == EINTR);
1365 
1366   assert_with_errno(ret == 0, "sem_wait failed");
1367 }
1368 
1369 bool PosixSemaphore::trywait() {
1370   int ret;
1371 
1372   do {
1373     ret = sem_trywait(&_semaphore);
1374   } while (ret != 0 && errno == EINTR);
1375 
1376   assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
1377 
1378   return ret == 0;
1379 }
1380 
1381 bool PosixSemaphore::timedwait(struct timespec ts) {
1382   while (true) {
1383     int result = sem_timedwait(&_semaphore, &ts);
1384     if (result == 0) {
1385       return true;
1386     } else if (errno == EINTR) {
1387       continue;
1388     } else if (errno == ETIMEDOUT) {
1389       return false;
1390     } else {
1391       assert_with_errno(false, "timedwait failed");
1392       return false;
1393     }
1394   }
1395 }
1396 
1397 #endif // __APPLE__
1398 
1399 
1400 // Shared pthread_mutex/cond based PlatformEvent implementation.
1401 // Not currently usable by Solaris
1402 
1403 #ifndef SOLARIS
1404 
1405 // Shared condattr object for use with relative timed-waits. Will be associated
1406 // with CLOCK_MONOTONIC if available to avoid issues with time-of-day changes,
1407 // but otherwise whatever default is used by the platform - generally the
1408 // time-of-day clock
1409 static pthread_condattr_t _condAttr[1];
1410 
1411 // Shared mutexattr to explicitly set the type to PTHREAD_MUTEX_NORMAL as not
1412 // all systems (e.g. FreeBSD) map the default to "normal".
1413 static pthread_mutexattr_t _mutexAttr[1];
1414 
1415 // common basic initialization that is always supported
1416 static void pthread_init_common(void) {
1417   int status;
1418   if ((status = pthread_condattr_init(_condAttr)) != 0) {
1419     fatal("pthread_condattr_init: %s", os::strerror(status));
1420   }
1421   if ((status = pthread_mutexattr_init(_mutexAttr)) != 0) {
1422     fatal("pthread_mutexattr_init: %s", os::strerror(status));
1423   }
1424   if ((status = pthread_mutexattr_settype(_mutexAttr, PTHREAD_MUTEX_NORMAL)) != 0) {
1425     fatal("pthread_mutexattr_settype: %s", os::strerror(status));
1426   }
1427 }
1428 
1429 // Not all POSIX types and API's are available on all notionally "posix"
1430 // platforms. If we have build-time support then we will check for actual
1431 // runtime support via dlopen/dlsym lookup. This allows for running on an
1432 // older OS version compared to the build platform. But if there is no
1433 // build time support then there can not be any runtime support as we do not
1434 // know what the runtime types would be (for example clockid_t might be an
1435 // int or int64_t.
1436 //
1437 #ifdef SUPPORTS_CLOCK_MONOTONIC
1438 
1439 // This means we have clockid_t, clock_gettime et al and CLOCK_MONOTONIC
1440 
1441 static int (*_clock_gettime)(clockid_t, struct timespec *);
1442 static int (*_pthread_condattr_setclock)(pthread_condattr_t *, clockid_t);
1443 
1444 static bool _use_clock_monotonic_condattr;
1445 
1446 // determine what POSIX API's are present and do appropriate
1447 // configuration
1448 void os::Posix::init(void) {
1449 
1450   // NOTE: no logging available when this is called. Put logging
1451   // statements in init_2().
1452 
1453   // copied from os::Linux::clock_init(). The duplication is temporary.
1454 
1455   // 1. Check for CLOCK_MONOTONIC support
1456 
1457   void* handle = NULL;
1458 
1459   // For linux we need librt, for other OS we can find
1460   // this function in regular libc
1461 #ifdef NEEDS_LIBRT
1462   // we do dlopen's in this particular order due to bug in linux
1463   // dynamical loader (see 6348968) leading to crash on exit
1464   handle = dlopen("librt.so.1", RTLD_LAZY);
1465   if (handle == NULL) {
1466     handle = dlopen("librt.so", RTLD_LAZY);
1467   }
1468 #endif
1469 
1470   if (handle == NULL) {
1471     handle = RTLD_DEFAULT;
1472   }
1473 
1474   _clock_gettime = NULL;
1475 
1476   int (*clock_getres_func)(clockid_t, struct timespec*) =
1477     (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
1478   int (*clock_gettime_func)(clockid_t, struct timespec*) =
1479     (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
1480   if (clock_getres_func != NULL && clock_gettime_func != NULL) {
1481     // we assume that if both clock_gettime and clock_getres support
1482     // CLOCK_MONOTONIC then the OS provides true high-res monotonic clock
1483     struct timespec res;
1484     struct timespec tp;
1485     if (clock_getres_func(CLOCK_MONOTONIC, &res) == 0 &&
1486         clock_gettime_func(CLOCK_MONOTONIC, &tp)  == 0) {
1487       // yes, monotonic clock is supported
1488       _clock_gettime = clock_gettime_func;
1489     } else {
1490 #ifdef NEEDS_LIBRT
1491       // close librt if there is no monotonic clock
1492       if (handle != RTLD_DEFAULT) {
1493         dlclose(handle);
1494       }
1495 #endif
1496     }
1497   }
1498   
1499   // 2. Check for pthread_condattr_setclock support
1500   
1501   _pthread_condattr_setclock = NULL;
1502 
1503   // libpthread is already loaded
1504   int (*condattr_setclock_func)(pthread_condattr_t*, clockid_t) =
1505     (int (*)(pthread_condattr_t*, clockid_t))dlsym(RTLD_DEFAULT,
1506                                                    "pthread_condattr_setclock");
1507   if (condattr_setclock_func != NULL) {
1508     _pthread_condattr_setclock = condattr_setclock_func;
1509   }
1510 
1511   // Now do general initialization
1512 
1513   pthread_init_common();
1514 
1515   int status;
1516   if (_pthread_condattr_setclock != NULL &&
1517       _clock_gettime != NULL) {
1518     _use_clock_monotonic_condattr = true;
1519 
1520     if ((status = _pthread_condattr_setclock(_condAttr, CLOCK_MONOTONIC)) != 0) {
1521       if (status == EINVAL) {
1522         _use_clock_monotonic_condattr = false;
1523         warning("Unable to use monotonic clock with relative timed-waits" \
1524                 " - changes to the time-of-day clock may have adverse affects");
1525       } else {
1526         fatal("pthread_condattr_setclock: %s", os::strerror(status));
1527       }
1528     }
1529   }
1530   else {
1531     _use_clock_monotonic_condattr = false;
1532   }
1533 }
1534 
1535 void os::Posix::init_2(void) {
1536   log_info(os)("Use of CLOCK_MONOTONIC is%s supported",
1537                (_clock_gettime != NULL ? "" : " not"));
1538   log_info(os)("Use of pthread_condattr_setclock is%s supported",
1539                (_pthread_condattr_setclock != NULL ? "" : " not"));
1540   log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with %s",
1541                _use_clock_monotonic_condattr ? "CLOCK_MONOTONIC" : "the default clock");
1542 }
1543 
1544 #else // !SUPPORTS_CLOCK_MONOTONIC
1545 
1546 void os::Posix::init(void) {
1547   pthread_init_common();
1548 }
1549 
1550 void os::Posix::init_2(void) {
1551   log_info(os)("Use of CLOCK_MONOTONIC is not supported");
1552   log_info(os)("Use of pthread_condattr_setclock is not supported");
1553   log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with the default clock");
1554 }
1555 
1556 #endif // SUPPORTS_CLOCK_MONOTONIC
1557 
1558 os::PlatformEvent::PlatformEvent() {
1559   int status = pthread_cond_init(_cond, _condAttr);
1560   assert_status(status == 0, status, "cond_init");
1561   status = pthread_mutex_init(_mutex, _mutexAttr);
1562   assert_status(status == 0, status, "mutex_init");
1563   _event   = 0;
1564   _nParked = 0;
1565 }
1566 
1567 // Utility to convert the given timeout to an absolute timespec
1568 // (based on the appropriate clock) to use with pthread_cond_timewait.
1569 // The clock queried here must be the clock used to manage the 
1570 // timeout of the condition variable.
1571 //
1572 // The passed in timeout value is either a relative time in nanoseconds
1573 // or an absolute time in milliseconds. A relative timeout will be
1574 // associated with CLOCK_MONOTONIC if available; otherwise, or if absolute,
1575 // the default time-of-day clock will be used.
1576 
1577 // Given time is a 64-bit value and the time_t used in the timespec is
1578 // sometimes a signed-32-bit value we have to watch for overflow if times
1579 // way in the future are given. Further on Solaris versions
1580 // prior to 10 there is a restriction (see cond_timedwait) that the specified
1581 // number of seconds, in abstime, is less than current_time + 100,000,000.
1582 // As it will be over 20 years before "now + 100000000" will overflow we can
1583 // ignore overflow and just impose a hard-limit on seconds using the value
1584 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
1585 // years from "now".
1586 //
1587 #define MAX_SECS 100000000
1588 
1589 static void to_abstime(timespec* abstime, jlong timeout, bool isAbsolute) {
1590 
1591   if (timeout < 0)
1592     timeout = 0;
1593 
1594   time_t max_secs = 0;
1595 
1596 #ifdef SUPPORTS_CLOCK_MONOTONIC
1597 
1598   if (_use_clock_monotonic_condattr && !isAbsolute) {
1599     // relative timeout in nanoseconds
1600     jlong seconds = timeout / NANOUNITS;
1601     timeout %= NANOUNITS; // remaining nanos
1602 
1603     struct timespec now;
1604     int status = _clock_gettime(CLOCK_MONOTONIC, &now);
1605     assert_status(status == 0, status, "clock_gettime");
1606 
1607     max_secs = now.tv_sec + MAX_SECS;
1608     if (seconds >= MAX_SECS) {
1609       // More seconds than we can add, so pin to max_secs
1610       abstime->tv_sec = max_secs;
1611       abstime->tv_nsec = 0;
1612     }
1613     else {
1614       abstime->tv_sec = now.tv_sec  + seconds;
1615       long nsecs = now.tv_nsec + timeout;
1616       if (nsecs >= NANOUNITS) { // overflow
1617         abstime->tv_sec += 1;
1618         nsecs -= NANOUNITS;
1619       }
1620       abstime->tv_nsec = nsecs;
1621     }
1622   }
1623   else {
1624 
1625 #else
1626 
1627   { // match the block scope
1628 
1629 #endif // SUPPORTS_CLOCK_MONOTONIC
1630 
1631     // time-of-day clock is all we can reliably use
1632     struct timeval now;
1633     int status = gettimeofday(&now, NULL);
1634     assert(status == 0, "gettimeofday");
1635     max_secs = now.tv_sec + MAX_SECS;
1636 
1637     if (isAbsolute) {
1638       // absolute timeout in milliseconds
1639       jlong seconds = timeout / MILLIUNITS;
1640       timeout %= MILLIUNITS; // remaining millis
1641 
1642       if (seconds >= max_secs) {
1643         // Absolue seconds exceeds allow max, so pin to max_secs
1644         abstime->tv_sec = max_secs;
1645         abstime->tv_nsec = 0;
1646       }
1647       else {
1648         abstime->tv_sec = seconds;
1649         abstime->tv_nsec = timeout * (NANOUNITS/MILLIUNITS);
1650       }
1651     }
1652     else {
1653       // relative timeout in nanoseconds
1654       jlong seconds = timeout / NANOUNITS;
1655       timeout %= NANOUNITS; // remaining nanos
1656 
1657       if (seconds >= MAX_SECS) {
1658         // More seconds than we can add, so pin to max_secs
1659         abstime->tv_sec = max_secs;
1660         abstime->tv_nsec = 0;
1661       }        
1662       else {
1663         abstime->tv_sec = now.tv_sec + seconds;
1664         jlong micros_left = timeout / (NANOUNITS/MICROUNITS);
1665         long usec = now.tv_usec + micros_left;
1666         if (usec >= MICROUNITS) { // overflow
1667           abstime->tv_sec += 1;
1668           usec -= MICROUNITS;
1669         }
1670         abstime->tv_nsec = usec * (NANOUNITS/MICROUNITS);
1671       }
1672     }
1673   }
1674 
1675   assert(abstime->tv_sec >= 0, "tv_sec < 0");
1676   assert(abstime->tv_sec <= max_secs, "tv_sec > max_secs");
1677   assert(abstime->tv_nsec >= 0, "tv_nsec < 0");
1678   assert(abstime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
1679   
1680 }
1681 
1682 // PlatformEvent
1683 //
1684 // Assumption:
1685 //    Only one parker can exist on an event, which is why we allocate
1686 //    them per-thread. Multiple unparkers can coexist.
1687 //
1688 // _event serves as a restricted-range semaphore.
1689 //   -1 : thread is blocked, i.e. there is a waiter
1690 //    0 : neutral: thread is running or ready,
1691 //        could have been signaled after a wait started
1692 //    1 : signaled - thread is running or ready
1693 //
1694 //    Having three states allows for some detection of bad usage - see
1695 //    comments on unpark().
1696 
1697 void os::PlatformEvent::park() {       // AKA "down()"
1698   // Transitions for _event:
1699   //   -1 => -1 : illegal
1700   //    1 =>  0 : pass - return immediately
1701   //    0 => -1 : block; then set _event to 0 before returning
1702 
1703   // Invariant: Only the thread associated with the PlatformEvent
1704   // may call park().
1705   assert(_nParked == 0, "invariant");
1706 
1707   int v;
1708 
1709   // atomically decrement _event
1710   for (;;) {
1711     v = _event;
1712     if (Atomic::cmpxchg(v-1, &_event, v) == v) break;
1713   }
1714   guarantee(v >= 0, "invariant");
1715 
1716   if (v == 0) { // Do this the hard way by blocking ...
1717     int status = pthread_mutex_lock(_mutex);
1718     assert_status(status == 0, status, "mutex_lock");
1719     guarantee(_nParked == 0, "invariant");
1720     ++_nParked;
1721     while (_event < 0) {
1722       // OS-level "spurious wakeups" are ignored
1723       status = pthread_cond_wait(_cond, _mutex);
1724       assert_status(status == 0, status, "cond_wait");
1725     }
1726     --_nParked;
1727 
1728     _event = 0;
1729     status = pthread_mutex_unlock(_mutex);
1730     assert_status(status == 0, status, "mutex_unlock");
1731     // Paranoia to ensure our locked and lock-free paths interact
1732     // correctly with each other.
1733     OrderAccess::fence();
1734   }
1735   guarantee(_event >= 0, "invariant");
1736 }
1737 
1738 int os::PlatformEvent::park(jlong millis) {
1739   // Transitions for _event:
1740   //   -1 => -1 : illegal
1741   //    1 =>  0 : pass - return immediately
1742   //    0 => -1 : block; then set _event to 0 before returning
1743 
1744   // Invariant: Only the thread associated with the Event/PlatformEvent
1745   // may call park().
1746   assert(_nParked == 0, "invariant");
1747 
1748   int v;
1749   // atomically decrement _event
1750   for (;;) {
1751     v = _event;
1752     if (Atomic::cmpxchg(v-1, &_event, v) == v) break;
1753   }
1754   guarantee(v >= 0, "invariant");
1755 
1756   if (v == 0) { // Do this the hard way by blocking ...
1757     struct timespec abst;
1758     to_abstime(&abst, millis * (NANOUNITS/MILLIUNITS), false);
1759 
1760     int ret = OS_TIMEOUT;
1761     int status = pthread_mutex_lock(_mutex);
1762     assert_status(status == 0, status, "mutex_lock");
1763     guarantee(_nParked == 0, "invariant");
1764     ++_nParked;
1765 
1766     while (_event < 0) {
1767       status = pthread_cond_timedwait(_cond, _mutex, &abst);
1768       assert_status(status == 0 || status == ETIMEDOUT,
1769                     status, "cond_timedwait");
1770       // OS-level "spurious wakeups" are ignored unless the archaic
1771       // FilterSpuriousWakeups is set false. That flag should be obsoleted.
1772       if (!FilterSpuriousWakeups) break;
1773       if (status == ETIMEDOUT) break;
1774     }
1775     --_nParked;
1776 
1777     if (_event >= 0) {
1778       ret = OS_OK;
1779     }
1780 
1781     _event = 0;
1782     status = pthread_mutex_unlock(_mutex);
1783     assert_status(status == 0, status, "mutex_unlock");
1784     // Paranoia to ensure our locked and lock-free paths interact
1785     // correctly with each other.
1786     OrderAccess::fence();
1787     return ret;
1788   }
1789   return OS_OK;
1790 }
1791 
1792 void os::PlatformEvent::unpark() {
1793   // Transitions for _event:
1794   //    0 => 1 : just return
1795   //    1 => 1 : just return
1796   //   -1 => either 0 or 1; must signal target thread
1797   //         That is, we can safely transition _event from -1 to either
1798   //         0 or 1.
1799   // See also: "Semaphores in Plan 9" by Mullender & Cox
1800   //
1801   // Note: Forcing a transition from "-1" to "1" on an unpark() means
1802   // that it will take two back-to-back park() calls for the owning
1803   // thread to block. This has the benefit of forcing a spurious return
1804   // from the first park() call after an unpark() call which will help
1805   // shake out uses of park() and unpark() without checking state conditions
1806   // properly. This spurious return doesn't manifest itself in any user code
1807   // but only in the correctly written condition checking loops of ObjectMonitor,
1808   // Mutex/Monitor, Thread::muxAcquire and os::sleep
1809 
1810   if (Atomic::xchg(1, &_event) >= 0) return;
1811 
1812   int status = pthread_mutex_lock(_mutex);
1813   assert_status(status == 0, status, "mutex_lock");
1814   int anyWaiters = _nParked;
1815   assert(anyWaiters == 0 || anyWaiters == 1, "invariant");
1816   status = pthread_mutex_unlock(_mutex);
1817   assert_status(status == 0, status, "mutex_unlock");
1818 
1819   // Note that we signal() *after* dropping the lock for "immortal" Events.
1820   // This is safe and avoids a common class of futile wakeups.  In rare
1821   // circumstances this can cause a thread to return prematurely from
1822   // cond_{timed}wait() but the spurious wakeup is benign and the victim
1823   // will simply re-test the condition and re-park itself.
1824   // This provides particular benefit if the underlying platform does not
1825   // provide wait morphing.
1826 
1827   if (anyWaiters != 0) {
1828     status = pthread_cond_signal(_cond);
1829     assert_status(status == 0, status, "cond_signal");
1830   }
1831 }
1832 
1833 // JSR166 support
1834 
1835  os::PlatformParker::PlatformParker() {
1836   int status;
1837   status = pthread_cond_init(&_cond[REL_INDEX], _condAttr);
1838   assert_status(status == 0, status, "cond_init rel");
1839   status = pthread_cond_init(&_cond[ABS_INDEX], NULL);
1840   assert_status(status == 0, status, "cond_init abs");
1841   status = pthread_mutex_init(_mutex, _mutexAttr);
1842   assert_status(status == 0, status, "mutex_init");
1843   _cur_index = -1; // mark as unused
1844 }
1845 
1846 // Parker::park decrements count if > 0, else does a condvar wait.  Unpark
1847 // sets count to 1 and signals condvar.  Only one thread ever waits
1848 // on the condvar. Contention seen when trying to park implies that someone
1849 // is unparking you, so don't wait. And spurious returns are fine, so there
1850 // is no need to track notifications.
1851 
1852 void Parker::park(bool isAbsolute, jlong time) {
1853 
1854   // Optional fast-path check:
1855   // Return immediately if a permit is available.
1856   // We depend on Atomic::xchg() having full barrier semantics
1857   // since we are doing a lock-free update to _counter.
1858   if (Atomic::xchg(0, &_counter) > 0) return;
1859 
1860   Thread* thread = Thread::current();
1861   assert(thread->is_Java_thread(), "Must be JavaThread");
1862   JavaThread *jt = (JavaThread *)thread;
1863 
1864   // Optional optimization -- avoid state transitions if there's 
1865   // an interrupt pending.
1866   if (Thread::is_interrupted(thread, false)) {
1867     return;
1868   }
1869 
1870   // Next, demultiplex/decode time arguments
1871   struct timespec absTime;
1872   if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
1873     return;
1874   }
1875   if (time > 0) {
1876     to_abstime(&absTime, time, isAbsolute);
1877   }
1878 
1879   // Enter safepoint region
1880   // Beware of deadlocks such as 6317397.
1881   // The per-thread Parker:: mutex is a classic leaf-lock.
1882   // In particular a thread must never block on the Threads_lock while
1883   // holding the Parker:: mutex.  If safepoints are pending both the
1884   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
1885   ThreadBlockInVM tbivm(jt);
1886 
1887   // Don't wait if cannot get lock since interference arises from
1888   // unparking. Also re-check interrupt before trying wait.
1889   if (Thread::is_interrupted(thread, false) || 
1890       pthread_mutex_trylock(_mutex) != 0) {
1891     return;
1892   }
1893 
1894   int status;
1895   if (_counter > 0)  { // no wait needed
1896     _counter = 0;
1897     status = pthread_mutex_unlock(_mutex);
1898     assert_status(status == 0, status, "invariant");
1899     // Paranoia to ensure our locked and lock-free paths interact
1900     // correctly with each other and Java-level accesses.
1901     OrderAccess::fence();
1902     return;
1903   }
1904 
1905   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
1906   jt->set_suspend_equivalent();
1907   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
1908 
1909   assert(_cur_index == -1, "invariant");
1910   if (time == 0) {
1911     _cur_index = REL_INDEX; // arbitrary choice when not timed
1912     status = pthread_cond_wait(&_cond[_cur_index], _mutex);
1913     assert_status(status == 0, status, "cond_timedwait");
1914   } 
1915   else {
1916     _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX;
1917     status = pthread_cond_timedwait(&_cond[_cur_index], _mutex, &absTime);
1918     assert_status(status == 0 || status == ETIMEDOUT,
1919                   status, "cond_timedwait");
1920   }
1921   _cur_index = -1;
1922 
1923   _counter = 0;
1924   status = pthread_mutex_unlock(_mutex);
1925   assert_status(status == 0, status, "invariant");
1926   // Paranoia to ensure our locked and lock-free paths interact
1927   // correctly with each other and Java-level accesses.
1928   OrderAccess::fence();
1929 
1930   // If externally suspended while waiting, re-suspend
1931   if (jt->handle_special_suspend_equivalent_condition()) {
1932     jt->java_suspend_self();
1933   }
1934 }
1935 
1936 void Parker::unpark() {
1937   int status = pthread_mutex_lock(_mutex);
1938   assert_status(status == 0, status, "invariant");
1939   const int s = _counter;
1940   _counter = 1;
1941   // must capture correct index before unlocking
1942   int index = _cur_index;
1943   status = pthread_mutex_unlock(_mutex);
1944   assert_status(status == 0, status, "invariant");
1945 
1946   // Note that we signal() *after* dropping the lock for "immortal" Events.
1947   // This is safe and avoids a common class of futile wakeups.  In rare
1948   // circumstances this can cause a thread to return prematurely from
1949   // cond_{timed}wait() but the spurious wakeup is benign and the victim
1950   // will simply re-test the condition and re-park itself.
1951   // This provides particular benefit if the underlying platform does not
1952   // provide wait morphing.
1953 
1954   if (s < 1 && index != -1) {
1955     // thread is definitely parked
1956     status = pthread_cond_signal(&_cond[index]);
1957     assert_status(status == 0, status, "invariant");
1958   }
1959 }
1960 
1961 
1962 #endif // !SOLARIS