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