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