1 /*
   2  * Copyright (c) 1999, 2021, 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 
  26 #include "jvm.h"
  27 #ifdef LINUX
  28 #include "classfile/classLoader.hpp"
  29 #endif
  30 #include "jvmtifiles/jvmti.h"
  31 #include "logging/log.hpp"
  32 #include "memory/allocation.inline.hpp"
  33 #include "os_posix.inline.hpp"
  34 #include "runtime/globals_extension.hpp"
  35 #include "runtime/osThread.hpp"
  36 #include "utilities/globalDefinitions.hpp"
  37 #include "runtime/frame.inline.hpp"
  38 #include "runtime/interfaceSupport.inline.hpp"
  39 #include "runtime/sharedRuntime.hpp"
  40 #include "services/attachListener.hpp"
  41 #include "services/memTracker.hpp"
  42 #include "runtime/arguments.hpp"
  43 #include "runtime/atomic.hpp"
  44 #include "runtime/java.hpp"
  45 #include "runtime/orderAccess.hpp"
  46 #include "runtime/perfMemory.hpp"
  47 #include "utilities/align.hpp"
  48 #include "utilities/events.hpp"
  49 #include "utilities/formatBuffer.hpp"
  50 #include "utilities/macros.hpp"
  51 #include "utilities/vmError.hpp"
  52 
  53 #include <dirent.h>
  54 #include <dlfcn.h>
  55 #include <grp.h>
  56 #include <netdb.h>
  57 #include <pwd.h>
  58 #include <pthread.h>
  59 #include <signal.h>
  60 #include <sys/mman.h>
  61 #include <sys/resource.h>
  62 #include <sys/socket.h>
  63 #include <sys/time.h>
  64 #include <sys/times.h>
  65 #include <sys/types.h>
  66 #include <sys/utsname.h>
  67 #include <sys/wait.h>
  68 #include <time.h>
  69 #include <unistd.h>
  70 #include <utmpx.h>
  71 
  72 #ifdef __APPLE__
  73   #include <crt_externs.h>
  74 #endif
  75 
  76 #define ROOT_UID 0
  77 
  78 #ifndef MAP_ANONYMOUS
  79   #define MAP_ANONYMOUS MAP_ANON
  80 #endif
  81 
  82 #define check_with_errno(check_type, cond, msg)                             \
  83   do {                                                                      \
  84     int err = errno;                                                        \
  85     check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
  86                os::errno_name(err));                                        \
  87 } while (false)
  88 
  89 #define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
  90 #define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
  91 
  92 static jlong initial_time_count = 0;
  93 
  94 static int clock_tics_per_sec = 100;
  95 
  96 // Check core dump limit and report possible place where core can be found
  97 void os::check_dump_limit(char* buffer, size_t bufferSize) {
  98   if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) {
  99     jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line");
 100     VMError::record_coredump_status(buffer, false);
 101     return;
 102   }
 103 
 104   int n;
 105   struct rlimit rlim;
 106   bool success;
 107 
 108   char core_path[PATH_MAX];
 109   n = get_core_path(core_path, PATH_MAX);
 110 
 111   if (n <= 0) {
 112     jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
 113     success = true;
 114 #ifdef LINUX
 115   } else if (core_path[0] == '"') { // redirect to user process
 116     jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
 117     success = true;
 118 #endif
 119   } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
 120     jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
 121     success = true;
 122   } else {
 123     switch(rlim.rlim_cur) {
 124       case RLIM_INFINITY:
 125         jio_snprintf(buffer, bufferSize, "%s", core_path);
 126         success = true;
 127         break;
 128       case 0:
 129         jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
 130         success = false;
 131         break;
 132       default:
 133         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);
 134         success = true;
 135         break;
 136     }
 137   }
 138 
 139   VMError::record_coredump_status(buffer, success);
 140 }
 141 
 142 int os::get_native_stack(address* stack, int frames, int toSkip) {
 143   int frame_idx = 0;
 144   int num_of_frames;  // number of frames captured
 145   frame fr = os::current_frame();
 146   while (fr.pc() && frame_idx < frames) {
 147     if (toSkip > 0) {
 148       toSkip --;
 149     } else {
 150       stack[frame_idx ++] = fr.pc();
 151     }
 152     if (fr.fp() == NULL || fr.cb() != NULL ||
 153         fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
 154 
 155     if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
 156       fr = os::get_sender_for_C_frame(&fr);
 157     } else {
 158       break;
 159     }
 160   }
 161   num_of_frames = frame_idx;
 162   for (; frame_idx < frames; frame_idx ++) {
 163     stack[frame_idx] = NULL;
 164   }
 165 
 166   return num_of_frames;
 167 }
 168 
 169 int os::get_last_error() {
 170   return errno;
 171 }
 172 
 173 size_t os::lasterror(char *buf, size_t len) {
 174   if (errno == 0)  return 0;
 175 
 176   const char *s = os::strerror(errno);
 177   size_t n = ::strlen(s);
 178   if (n >= len) {
 179     n = len - 1;
 180   }
 181   ::strncpy(buf, s, n);
 182   buf[n] = '\0';
 183   return n;
 184 }
 185 
 186 // Return true if user is running as root.
 187 bool os::have_special_privileges() {
 188   static bool privileges = (getuid() != geteuid()) || (getgid() != getegid());
 189   return privileges;
 190 }
 191 
 192 void os::wait_for_keypress_at_exit(void) {
 193   // don't do anything on posix platforms
 194   return;
 195 }
 196 
 197 int os::create_file_for_heap(const char* dir) {
 198   int fd;
 199 
 200 #if defined(LINUX) && defined(O_TMPFILE)
 201   char* native_dir = os::strdup(dir);
 202   if (native_dir == NULL) {
 203     vm_exit_during_initialization(err_msg("strdup failed during creation of backing file for heap (%s)", os::strerror(errno)));
 204     return -1;
 205   }
 206   os::native_path(native_dir);
 207   fd = os::open(dir, O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
 208   os::free(native_dir);
 209 
 210   if (fd == -1)
 211 #endif
 212   {
 213     const char name_template[] = "/jvmheap.XXXXXX";
 214 
 215     size_t fullname_len = strlen(dir) + strlen(name_template);
 216     char *fullname = (char*)os::malloc(fullname_len + 1, mtInternal);
 217     if (fullname == NULL) {
 218       vm_exit_during_initialization(err_msg("Malloc failed during creation of backing file for heap (%s)", os::strerror(errno)));
 219       return -1;
 220     }
 221     int n = snprintf(fullname, fullname_len + 1, "%s%s", dir, name_template);
 222     assert((size_t)n == fullname_len, "Unexpected number of characters in string");
 223 
 224     os::native_path(fullname);
 225 
 226     // create a new file.
 227     fd = mkstemp(fullname);
 228 
 229     if (fd < 0) {
 230       warning("Could not create file for heap with template %s", fullname);
 231       os::free(fullname);
 232       return -1;
 233     } else {
 234       // delete the name from the filesystem. When 'fd' is closed, the file (and space) will be deleted.
 235       int ret = unlink(fullname);
 236       assert_with_errno(ret == 0, "unlink returned error");
 237     }
 238 
 239     os::free(fullname);
 240   }
 241 
 242   return fd;
 243 }
 244 
 245 static char* reserve_mmapped_memory(size_t bytes, char* requested_addr) {
 246   char * addr;
 247   int flags = MAP_PRIVATE NOT_AIX( | MAP_NORESERVE ) | MAP_ANONYMOUS;
 248   if (requested_addr != NULL) {
 249     assert((uintptr_t)requested_addr % os::vm_page_size() == 0, "Requested address should be aligned to OS page size");
 250     flags |= MAP_FIXED;
 251   }
 252 
 253   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
 254   // touch an uncommitted page. Otherwise, the read/write might
 255   // succeed if we have enough swap space to back the physical page.
 256   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
 257                        flags, -1, 0);
 258 
 259   if (addr != MAP_FAILED) {
 260     MemTracker::record_virtual_memory_reserve((address)addr, bytes, CALLER_PC);
 261     return addr;
 262   }
 263   return NULL;
 264 }
 265 
 266 static int util_posix_fallocate(int fd, off_t offset, off_t len) {
 267 #ifdef __APPLE__
 268   fstore_t store = { F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, len };
 269   // First we try to get a continuous chunk of disk space
 270   int ret = fcntl(fd, F_PREALLOCATE, &store);
 271   if (ret == -1) {
 272     // Maybe we are too fragmented, try to allocate non-continuous range
 273     store.fst_flags = F_ALLOCATEALL;
 274     ret = fcntl(fd, F_PREALLOCATE, &store);
 275   }
 276   if(ret != -1) {
 277     return ftruncate(fd, len);
 278   }
 279   return -1;
 280 #else
 281   return posix_fallocate(fd, offset, len);
 282 #endif
 283 }
 284 
 285 // Map the given address range to the provided file descriptor.
 286 char* os::map_memory_to_file(char* base, size_t size, int fd) {
 287   assert(fd != -1, "File descriptor is not valid");
 288 
 289   // allocate space for the file
 290   int ret = util_posix_fallocate(fd, 0, (off_t)size);
 291   if (ret != 0) {
 292     vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory. error(%d)", ret));
 293     return NULL;
 294   }
 295 
 296   int prot = PROT_READ | PROT_WRITE;
 297   int flags = MAP_SHARED;
 298   if (base != NULL) {
 299     flags |= MAP_FIXED;
 300   }
 301   char* addr = (char*)mmap(base, size, prot, flags, fd, 0);
 302 
 303   if (addr == MAP_FAILED) {
 304     warning("Failed mmap to file. (%s)", os::strerror(errno));
 305     return NULL;
 306   }
 307   if (base != NULL && addr != base) {
 308     if (!os::release_memory(addr, size)) {
 309       warning("Could not release memory on unsuccessful file mapping");
 310     }
 311     return NULL;
 312   }
 313   return addr;
 314 }
 315 
 316 char* os::replace_existing_mapping_with_file_mapping(char* base, size_t size, int fd) {
 317   assert(fd != -1, "File descriptor is not valid");
 318   assert(base != NULL, "Base cannot be NULL");
 319 
 320   return map_memory_to_file(base, size, fd);
 321 }
 322 
 323 static size_t calculate_aligned_extra_size(size_t size, size_t alignment) {
 324   assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
 325       "Alignment must be a multiple of allocation granularity (page size)");
 326   assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
 327 
 328   size_t extra_size = size + alignment;
 329   assert(extra_size >= size, "overflow, size is too large to allow alignment");
 330   return extra_size;
 331 }
 332 
 333 // After a bigger chunk was mapped, unmaps start and end parts to get the requested alignment.
 334 static char* chop_extra_memory(size_t size, size_t alignment, char* extra_base, size_t extra_size) {
 335   // Do manual alignment
 336   char* aligned_base = align_up(extra_base, alignment);
 337 
 338   // [  |                                       |  ]
 339   // ^ extra_base
 340   //    ^ extra_base + begin_offset == aligned_base
 341   //     extra_base + begin_offset + size       ^
 342   //                       extra_base + extra_size ^
 343   // |<>| == begin_offset
 344   //                              end_offset == |<>|
 345   size_t begin_offset = aligned_base - extra_base;
 346   size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
 347 
 348   if (begin_offset > 0) {
 349       os::release_memory(extra_base, begin_offset);
 350   }
 351 
 352   if (end_offset > 0) {
 353       os::release_memory(extra_base + begin_offset + size, end_offset);
 354   }
 355 
 356   return aligned_base;
 357 }
 358 
 359 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
 360 // so on posix, unmap the section at the start and at the end of the chunk that we mapped
 361 // rather than unmapping and remapping the whole chunk to get requested alignment.
 362 char* os::reserve_memory_aligned(size_t size, size_t alignment, bool exec) {
 363   size_t extra_size = calculate_aligned_extra_size(size, alignment);
 364   char* extra_base = os::reserve_memory(extra_size, exec);
 365   if (extra_base == NULL) {
 366     return NULL;
 367   }
 368   return chop_extra_memory(size, alignment, extra_base, extra_size);
 369 }
 370 
 371 char* os::map_memory_to_file_aligned(size_t size, size_t alignment, int file_desc) {
 372   size_t extra_size = calculate_aligned_extra_size(size, alignment);
 373   // For file mapping, we do not call os:map_memory_to_file(size,fd) since:
 374   // - we later chop away parts of the mapping using os::release_memory and that could fail if the
 375   //   original mmap call had been tied to an fd.
 376   // - The memory API os::reserve_memory uses is an implementation detail. It may (and usually is)
 377   //   mmap but it also may System V shared memory which cannot be uncommitted as a whole, so
 378   //   chopping off and unmapping excess bits back and front (see below) would not work.
 379   char* extra_base = reserve_mmapped_memory(extra_size, NULL);
 380   if (extra_base == NULL) {
 381     return NULL;
 382   }
 383   char* aligned_base = chop_extra_memory(size, alignment, extra_base, extra_size);
 384   // After we have an aligned address, we can replace anonymous mapping with file mapping
 385   if (replace_existing_mapping_with_file_mapping(aligned_base, size, file_desc) == NULL) {
 386     vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
 387   }
 388   MemTracker::record_virtual_memory_commit((address)aligned_base, size, CALLER_PC);
 389   return aligned_base;
 390 }
 391 
 392 int os::vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
 393   // All supported POSIX platforms provide C99 semantics.
 394   int result = ::vsnprintf(buf, len, fmt, args);
 395   // If an encoding error occurred (result < 0) then it's not clear
 396   // whether the buffer is NUL terminated, so ensure it is.
 397   if ((result < 0) && (len > 0)) {
 398     buf[len - 1] = '\0';
 399   }
 400   return result;
 401 }
 402 
 403 int os::get_fileno(FILE* fp) {
 404   return NOT_AIX(::)fileno(fp);
 405 }
 406 
 407 struct tm* os::gmtime_pd(const time_t* clock, struct tm*  res) {
 408   return gmtime_r(clock, res);
 409 }
 410 
 411 void os::Posix::print_load_average(outputStream* st) {
 412   st->print("load average: ");
 413   double loadavg[3];
 414   int res = os::loadavg(loadavg, 3);
 415   if (res != -1) {
 416     st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
 417   } else {
 418     st->print(" Unavailable");
 419   }
 420   st->cr();
 421 }
 422 
 423 // boot/uptime information;
 424 // unfortunately it does not work on macOS and Linux because the utx chain has no entry
 425 // for reboot at least on my test machines
 426 void os::Posix::print_uptime_info(outputStream* st) {
 427   int bootsec = -1;
 428   int currsec = time(NULL);
 429   struct utmpx* ent;
 430   setutxent();
 431   while ((ent = getutxent())) {
 432     if (!strcmp("system boot", ent->ut_line)) {
 433       bootsec = ent->ut_tv.tv_sec;
 434       break;
 435     }
 436   }
 437 
 438   if (bootsec != -1) {
 439     os::print_dhm(st, "OS uptime:", (long) (currsec-bootsec));
 440   }
 441 }
 442 
 443 static void print_rlimit(outputStream* st, const char* msg,
 444                          int resource, bool output_k = false) {
 445   struct rlimit rlim;
 446 
 447   st->print(" %s ", msg);
 448   int res = getrlimit(resource, &rlim);
 449   if (res == -1) {
 450     st->print("could not obtain value");
 451   } else {
 452     // soft limit
 453     if (rlim.rlim_cur == RLIM_INFINITY) { st->print("infinity"); }
 454     else {
 455       if (output_k) { st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); }
 456       else { st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur)); }
 457     }
 458     // hard limit
 459     st->print("/");
 460     if (rlim.rlim_max == RLIM_INFINITY) { st->print("infinity"); }
 461     else {
 462       if (output_k) { st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_max) / 1024); }
 463       else { st->print(UINT64_FORMAT, uint64_t(rlim.rlim_max)); }
 464     }
 465   }
 466 }
 467 
 468 void os::Posix::print_rlimit_info(outputStream* st) {
 469   st->print("rlimit (soft/hard):");
 470   print_rlimit(st, "STACK", RLIMIT_STACK, true);
 471   print_rlimit(st, ", CORE", RLIMIT_CORE, true);
 472 
 473 #if defined(AIX)
 474   st->print(", NPROC ");
 475   st->print("%d", sysconf(_SC_CHILD_MAX));
 476 
 477   print_rlimit(st, ", THREADS", RLIMIT_THREADS);
 478 #else
 479   print_rlimit(st, ", NPROC", RLIMIT_NPROC);
 480 #endif
 481 
 482   print_rlimit(st, ", NOFILE", RLIMIT_NOFILE);
 483   print_rlimit(st, ", AS", RLIMIT_AS, true);
 484   print_rlimit(st, ", CPU", RLIMIT_CPU);
 485   print_rlimit(st, ", DATA", RLIMIT_DATA, true);
 486 
 487   // maximum size of files that the process may create
 488   print_rlimit(st, ", FSIZE", RLIMIT_FSIZE, true);
 489 
 490 #if defined(LINUX) || defined(__APPLE__)
 491   // maximum number of bytes of memory that may be locked into RAM
 492   // (rounded down to the nearest  multiple of system pagesize)
 493   print_rlimit(st, ", MEMLOCK", RLIMIT_MEMLOCK, true);
 494 #endif
 495 
 496   // MacOS; The maximum size (in bytes) to which a process's resident set size may grow.
 497 #if defined(__APPLE__)
 498   print_rlimit(st, ", RSS", RLIMIT_RSS, true);
 499 #endif
 500 
 501   st->cr();
 502 }
 503 
 504 void os::Posix::print_uname_info(outputStream* st) {
 505   // kernel
 506   st->print("uname: ");
 507   struct utsname name;
 508   uname(&name);
 509   st->print("%s ", name.sysname);
 510 #ifdef ASSERT
 511   st->print("%s ", name.nodename);
 512 #endif
 513   st->print("%s ", name.release);
 514   st->print("%s ", name.version);
 515   st->print("%s", name.machine);
 516   st->cr();
 517 }
 518 
 519 void os::Posix::print_umask(outputStream* st, mode_t umsk) {
 520   st->print((umsk & S_IRUSR) ? "r" : "-");
 521   st->print((umsk & S_IWUSR) ? "w" : "-");
 522   st->print((umsk & S_IXUSR) ? "x" : "-");
 523   st->print((umsk & S_IRGRP) ? "r" : "-");
 524   st->print((umsk & S_IWGRP) ? "w" : "-");
 525   st->print((umsk & S_IXGRP) ? "x" : "-");
 526   st->print((umsk & S_IROTH) ? "r" : "-");
 527   st->print((umsk & S_IWOTH) ? "w" : "-");
 528   st->print((umsk & S_IXOTH) ? "x" : "-");
 529 }
 530 
 531 void os::Posix::print_user_info(outputStream* st) {
 532   unsigned id = (unsigned) ::getuid();
 533   st->print("uid  : %u ", id);
 534   id = (unsigned) ::geteuid();
 535   st->print("euid : %u ", id);
 536   id = (unsigned) ::getgid();
 537   st->print("gid  : %u ", id);
 538   id = (unsigned) ::getegid();
 539   st->print_cr("egid : %u", id);
 540   st->cr();
 541 
 542   mode_t umsk = ::umask(0);
 543   ::umask(umsk);
 544   st->print("umask: %04o (", (unsigned) umsk);
 545   print_umask(st, umsk);
 546   st->print_cr(")");
 547   st->cr();
 548 }
 549 
 550 
 551 bool os::get_host_name(char* buf, size_t buflen) {
 552   struct utsname name;
 553   uname(&name);
 554   jio_snprintf(buf, buflen, "%s", name.nodename);
 555   return true;
 556 }
 557 
 558 #ifndef _LP64
 559 // Helper, on 32bit, for os::has_allocatable_memory_limit
 560 static bool is_allocatable(size_t s) {
 561   if (s < 2 * G) {
 562     return true;
 563   }
 564   // Use raw anonymous mmap here; no need to go through any
 565   // of our reservation layers. We will unmap right away.
 566   void* p = ::mmap(NULL, s, PROT_NONE,
 567                    MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS, -1, 0);
 568   if (p == MAP_FAILED) {
 569     return false;
 570   } else {
 571     ::munmap(p, s);
 572     return true;
 573   }
 574 }
 575 #endif // !_LP64
 576 
 577 
 578 bool os::has_allocatable_memory_limit(size_t* limit) {
 579   struct rlimit rlim;
 580   int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
 581   // if there was an error when calling getrlimit, assume that there is no limitation
 582   // on virtual memory.
 583   bool result;
 584   if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
 585     result = false;
 586   } else {
 587     *limit = (size_t)rlim.rlim_cur;
 588     result = true;
 589   }
 590 #ifdef _LP64
 591   return result;
 592 #else
 593   // arbitrary virtual space limit for 32 bit Unices found by testing. If
 594   // getrlimit above returned a limit, bound it with this limit. Otherwise
 595   // directly use it.
 596   const size_t max_virtual_limit = 3800*M;
 597   if (result) {
 598     *limit = MIN2(*limit, max_virtual_limit);
 599   } else {
 600     *limit = max_virtual_limit;
 601   }
 602 
 603   // bound by actually allocatable memory. The algorithm uses two bounds, an
 604   // upper and a lower limit. The upper limit is the current highest amount of
 605   // memory that could not be allocated, the lower limit is the current highest
 606   // amount of memory that could be allocated.
 607   // The algorithm iteratively refines the result by halving the difference
 608   // between these limits, updating either the upper limit (if that value could
 609   // not be allocated) or the lower limit (if the that value could be allocated)
 610   // until the difference between these limits is "small".
 611 
 612   // the minimum amount of memory we care about allocating.
 613   const size_t min_allocation_size = M;
 614 
 615   size_t upper_limit = *limit;
 616 
 617   // first check a few trivial cases
 618   if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
 619     *limit = upper_limit;
 620   } else if (!is_allocatable(min_allocation_size)) {
 621     // we found that not even min_allocation_size is allocatable. Return it
 622     // anyway. There is no point to search for a better value any more.
 623     *limit = min_allocation_size;
 624   } else {
 625     // perform the binary search.
 626     size_t lower_limit = min_allocation_size;
 627     while ((upper_limit - lower_limit) > min_allocation_size) {
 628       size_t temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
 629       temp_limit = align_down(temp_limit, min_allocation_size);
 630       if (is_allocatable(temp_limit)) {
 631         lower_limit = temp_limit;
 632       } else {
 633         upper_limit = temp_limit;
 634       }
 635     }
 636     *limit = lower_limit;
 637   }
 638   return true;
 639 #endif
 640 }
 641 
 642 void* os::get_default_process_handle() {
 643 #ifdef __APPLE__
 644   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
 645   // to avoid finding unexpected symbols on second (or later)
 646   // loads of a library.
 647   return (void*)::dlopen(NULL, RTLD_FIRST);
 648 #else
 649   return (void*)::dlopen(NULL, RTLD_LAZY);
 650 #endif
 651 }
 652 
 653 void* os::dll_lookup(void* handle, const char* name) {
 654   return dlsym(handle, name);
 655 }
 656 
 657 void os::dll_unload(void *lib) {
 658   ::dlclose(lib);
 659 }
 660 
 661 jlong os::lseek(int fd, jlong offset, int whence) {
 662   return (jlong) BSD_ONLY(::lseek) NOT_BSD(::lseek64)(fd, offset, whence);
 663 }
 664 
 665 int os::fsync(int fd) {
 666   return ::fsync(fd);
 667 }
 668 
 669 int os::ftruncate(int fd, jlong length) {
 670    return BSD_ONLY(::ftruncate) NOT_BSD(::ftruncate64)(fd, length);
 671 }
 672 
 673 const char* os::get_current_directory(char *buf, size_t buflen) {
 674   return getcwd(buf, buflen);
 675 }
 676 
 677 FILE* os::open(int fd, const char* mode) {
 678   return ::fdopen(fd, mode);
 679 }
 680 
 681 size_t os::write(int fd, const void *buf, unsigned int nBytes) {
 682   size_t res;
 683   RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res);
 684   return res;
 685 }
 686 
 687 ssize_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {
 688   return ::pread(fd, buf, nBytes, offset);
 689 }
 690 
 691 int os::close(int fd) {
 692   return ::close(fd);
 693 }
 694 
 695 void os::flockfile(FILE* fp) {
 696   ::flockfile(fp);
 697 }
 698 
 699 void os::funlockfile(FILE* fp) {
 700   ::funlockfile(fp);
 701 }
 702 
 703 DIR* os::opendir(const char* dirname) {
 704   assert(dirname != NULL, "just checking");
 705   return ::opendir(dirname);
 706 }
 707 
 708 struct dirent* os::readdir(DIR* dirp) {
 709   assert(dirp != NULL, "just checking");
 710   return ::readdir(dirp);
 711 }
 712 
 713 int os::closedir(DIR *dirp) {
 714   assert(dirp != NULL, "just checking");
 715   return ::closedir(dirp);
 716 }
 717 
 718 int os::socket_close(int fd) {
 719   return ::close(fd);
 720 }
 721 
 722 int os::socket(int domain, int type, int protocol) {
 723   return ::socket(domain, type, protocol);
 724 }
 725 
 726 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
 727   RESTARTABLE_RETURN_INT(::recv(fd, buf, nBytes, flags));
 728 }
 729 
 730 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
 731   RESTARTABLE_RETURN_INT(::send(fd, buf, nBytes, flags));
 732 }
 733 
 734 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
 735   return os::send(fd, buf, nBytes, flags);
 736 }
 737 
 738 int os::connect(int fd, struct sockaddr* him, socklen_t len) {
 739   RESTARTABLE_RETURN_INT(::connect(fd, him, len));
 740 }
 741 
 742 struct hostent* os::get_host_by_name(char* name) {
 743   return ::gethostbyname(name);
 744 }
 745 
 746 void os::exit(int num) {
 747   ::exit(num);
 748 }
 749 
 750 void os::_exit(int num) {
 751   ::_exit(num);
 752 }
 753 
 754 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
 755 // which is used to find statically linked in agents.
 756 // Parameters:
 757 //            sym_name: Symbol in library we are looking for
 758 //            lib_name: Name of library to look in, NULL for shared libs.
 759 //            is_absolute_path == true if lib_name is absolute path to agent
 760 //                                     such as "/a/b/libL.so"
 761 //            == false if only the base name of the library is passed in
 762 //               such as "L"
 763 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
 764                                     bool is_absolute_path) {
 765   char *agent_entry_name;
 766   size_t len;
 767   size_t name_len;
 768   size_t prefix_len = strlen(JNI_LIB_PREFIX);
 769   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
 770   const char *start;
 771 
 772   if (lib_name != NULL) {
 773     name_len = strlen(lib_name);
 774     if (is_absolute_path) {
 775       // Need to strip path, prefix and suffix
 776       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
 777         lib_name = ++start;
 778       }
 779       if (strlen(lib_name) <= (prefix_len + suffix_len)) {
 780         return NULL;
 781       }
 782       lib_name += prefix_len;
 783       name_len = strlen(lib_name) - suffix_len;
 784     }
 785   }
 786   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
 787   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
 788   if (agent_entry_name == NULL) {
 789     return NULL;
 790   }
 791   strcpy(agent_entry_name, sym_name);
 792   if (lib_name != NULL) {
 793     strcat(agent_entry_name, "_");
 794     strncat(agent_entry_name, lib_name, name_len);
 795   }
 796   return agent_entry_name;
 797 }
 798 
 799 
 800 void os::naked_short_nanosleep(jlong ns) {
 801   struct timespec req;
 802   assert(ns > -1 && ns < NANOUNITS, "Un-interruptable sleep, short time use only");
 803   req.tv_sec = 0;
 804   req.tv_nsec = ns;
 805   ::nanosleep(&req, NULL);
 806   return;
 807 }
 808 
 809 void os::naked_short_sleep(jlong ms) {
 810   assert(ms < MILLIUNITS, "Un-interruptable sleep, short time use only");
 811   os::naked_short_nanosleep(millis_to_nanos(ms));
 812   return;
 813 }
 814 
 815 char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) {
 816   size_t stack_size = 0;
 817   size_t guard_size = 0;
 818   int detachstate = 0;
 819   pthread_attr_getstacksize(attr, &stack_size);
 820   pthread_attr_getguardsize(attr, &guard_size);
 821   // Work around linux NPTL implementation error, see also os::create_thread() in os_linux.cpp.
 822   LINUX_ONLY(stack_size -= guard_size);
 823   pthread_attr_getdetachstate(attr, &detachstate);
 824   jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s",
 825     stack_size / 1024, guard_size / 1024,
 826     (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable"));
 827   return buf;
 828 }
 829 
 830 char* os::Posix::realpath(const char* filename, char* outbuf, size_t outbuflen) {
 831 
 832   if (filename == NULL || outbuf == NULL || outbuflen < 1) {
 833     assert(false, "os::Posix::realpath: invalid arguments.");
 834     errno = EINVAL;
 835     return NULL;
 836   }
 837 
 838   char* result = NULL;
 839 
 840   // This assumes platform realpath() is implemented according to POSIX.1-2008.
 841   // POSIX.1-2008 allows to specify NULL for the output buffer, in which case
 842   // output buffer is dynamically allocated and must be ::free()'d by the caller.
 843   char* p = ::realpath(filename, NULL);
 844   if (p != NULL) {
 845     if (strlen(p) < outbuflen) {
 846       strcpy(outbuf, p);
 847       result = outbuf;
 848     } else {
 849       errno = ENAMETOOLONG;
 850     }
 851     ::free(p); // *not* os::free
 852   } else {
 853     // Fallback for platforms struggling with modern Posix standards (AIX 5.3, 6.1). If realpath
 854     // returns EINVAL, this may indicate that realpath is not POSIX.1-2008 compatible and
 855     // that it complains about the NULL we handed down as user buffer.
 856     // In this case, use the user provided buffer but at least check whether realpath caused
 857     // a memory overwrite.
 858     if (errno == EINVAL) {
 859       outbuf[outbuflen - 1] = '\0';
 860       p = ::realpath(filename, outbuf);
 861       if (p != NULL) {
 862         guarantee(outbuf[outbuflen - 1] == '\0', "realpath buffer overwrite detected.");
 863         result = p;
 864       }
 865     }
 866   }
 867   return result;
 868 
 869 }
 870 
 871 int os::stat(const char *path, struct stat *sbuf) {
 872   return ::stat(path, sbuf);
 873 }
 874 
 875 char * os::native_path(char *path) {
 876   return path;
 877 }
 878 
 879 bool os::same_files(const char* file1, const char* file2) {
 880   if (file1 == nullptr && file2 == nullptr) {
 881     return true;
 882   }
 883 
 884   if (file1 == nullptr || file2 == nullptr) {
 885     return false;
 886   }
 887 
 888   if (strcmp(file1, file2) == 0) {
 889     return true;
 890   }
 891 
 892   bool is_same = false;
 893   struct stat st1;
 894   struct stat st2;
 895 
 896   if (os::stat(file1, &st1) < 0) {
 897     return false;
 898   }
 899 
 900   if (os::stat(file2, &st2) < 0) {
 901     return false;
 902   }
 903 
 904   if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) {
 905     // same files
 906     is_same = true;
 907   }
 908   return is_same;
 909 }
 910 
 911 // Check minimum allowable stack sizes for thread creation and to initialize
 912 // the java system classes, including StackOverflowError - depends on page
 913 // size.
 914 // The space needed for frames during startup is platform dependent. It
 915 // depends on word size, platform calling conventions, C frame layout and
 916 // interpreter/C1/C2 design decisions. Therefore this is given in a
 917 // platform (os/cpu) dependent constant.
 918 // To this, space for guard mechanisms is added, which depends on the
 919 // page size which again depends on the concrete system the VM is running
 920 // on. Space for libc guard pages is not included in this size.
 921 jint os::Posix::set_minimum_stack_sizes() {
 922   size_t os_min_stack_allowed = PTHREAD_STACK_MIN;
 923 
 924   _java_thread_min_stack_allowed = _java_thread_min_stack_allowed +
 925                                    StackOverflow::stack_guard_zone_size() +
 926                                    StackOverflow::stack_shadow_zone_size();
 927 
 928   _java_thread_min_stack_allowed = align_up(_java_thread_min_stack_allowed, vm_page_size());
 929   _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed, os_min_stack_allowed);
 930 
 931   size_t stack_size_in_bytes = ThreadStackSize * K;
 932   if (stack_size_in_bytes != 0 &&
 933       stack_size_in_bytes < _java_thread_min_stack_allowed) {
 934     // The '-Xss' and '-XX:ThreadStackSize=N' options both set
 935     // ThreadStackSize so we go with "Java thread stack size" instead
 936     // of "ThreadStackSize" to be more friendly.
 937     tty->print_cr("\nThe Java thread stack size specified is too small. "
 938                   "Specify at least " SIZE_FORMAT "k",
 939                   _java_thread_min_stack_allowed / K);
 940     return JNI_ERR;
 941   }
 942 
 943   // Make the stack size a multiple of the page size so that
 944   // the yellow/red zones can be guarded.
 945   JavaThread::set_stack_size_at_create(align_up(stack_size_in_bytes, vm_page_size()));
 946 
 947   // Reminder: a compiler thread is a Java thread.
 948   _compiler_thread_min_stack_allowed = _compiler_thread_min_stack_allowed +
 949                                        StackOverflow::stack_guard_zone_size() +
 950                                        StackOverflow::stack_shadow_zone_size();
 951 
 952   _compiler_thread_min_stack_allowed = align_up(_compiler_thread_min_stack_allowed, vm_page_size());
 953   _compiler_thread_min_stack_allowed = MAX2(_compiler_thread_min_stack_allowed, os_min_stack_allowed);
 954 
 955   stack_size_in_bytes = CompilerThreadStackSize * K;
 956   if (stack_size_in_bytes != 0 &&
 957       stack_size_in_bytes < _compiler_thread_min_stack_allowed) {
 958     tty->print_cr("\nThe CompilerThreadStackSize specified is too small. "
 959                   "Specify at least " SIZE_FORMAT "k",
 960                   _compiler_thread_min_stack_allowed / K);
 961     return JNI_ERR;
 962   }
 963 
 964   _vm_internal_thread_min_stack_allowed = align_up(_vm_internal_thread_min_stack_allowed, vm_page_size());
 965   _vm_internal_thread_min_stack_allowed = MAX2(_vm_internal_thread_min_stack_allowed, os_min_stack_allowed);
 966 
 967   stack_size_in_bytes = VMThreadStackSize * K;
 968   if (stack_size_in_bytes != 0 &&
 969       stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) {
 970     tty->print_cr("\nThe VMThreadStackSize specified is too small. "
 971                   "Specify at least " SIZE_FORMAT "k",
 972                   _vm_internal_thread_min_stack_allowed / K);
 973     return JNI_ERR;
 974   }
 975   return JNI_OK;
 976 }
 977 
 978 // Called when creating the thread.  The minimum stack sizes have already been calculated
 979 size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) {
 980   size_t stack_size;
 981   if (req_stack_size == 0) {
 982     stack_size = default_stack_size(thr_type);
 983   } else {
 984     stack_size = req_stack_size;
 985   }
 986 
 987   switch (thr_type) {
 988   case os::java_thread:
 989     // Java threads use ThreadStackSize which default value can be
 990     // changed with the flag -Xss
 991     if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) {
 992       // no requested size and we have a more specific default value
 993       stack_size = JavaThread::stack_size_at_create();
 994     }
 995     stack_size = MAX2(stack_size,
 996                       _java_thread_min_stack_allowed);
 997     break;
 998   case os::compiler_thread:
 999     if (req_stack_size == 0 && CompilerThreadStackSize > 0) {
1000       // no requested size and we have a more specific default value
1001       stack_size = (size_t)(CompilerThreadStackSize * K);
1002     }
1003     stack_size = MAX2(stack_size,
1004                       _compiler_thread_min_stack_allowed);
1005     break;
1006   case os::vm_thread:
1007   case os::gc_thread:
1008   case os::watcher_thread:
1009   default:  // presume the unknown thr_type is a VM internal
1010     if (req_stack_size == 0 && VMThreadStackSize > 0) {
1011       // no requested size and we have a more specific default value
1012       stack_size = (size_t)(VMThreadStackSize * K);
1013     }
1014 
1015     stack_size = MAX2(stack_size,
1016                       _vm_internal_thread_min_stack_allowed);
1017     break;
1018   }
1019 
1020   // pthread_attr_setstacksize() may require that the size be rounded up to the OS page size.
1021   // Be careful not to round up to 0. Align down in that case.
1022   if (stack_size <= SIZE_MAX - vm_page_size()) {
1023     stack_size = align_up(stack_size, vm_page_size());
1024   } else {
1025     stack_size = align_down(stack_size, vm_page_size());
1026   }
1027 
1028   return stack_size;
1029 }
1030 
1031 #ifndef ZERO
1032 #ifndef ARM
1033 static bool get_frame_at_stack_banging_point(JavaThread* thread, address pc, const void* ucVoid, frame* fr) {
1034   if (Interpreter::contains(pc)) {
1035     // interpreter performs stack banging after the fixed frame header has
1036     // been generated while the compilers perform it before. To maintain
1037     // semantic consistency between interpreted and compiled frames, the
1038     // method returns the Java sender of the current frame.
1039     *fr = os::fetch_frame_from_context(ucVoid);
1040     if (!fr->is_first_java_frame()) {
1041       // get_frame_at_stack_banging_point() is only called when we
1042       // have well defined stacks so java_sender() calls do not need
1043       // to assert safe_for_sender() first.
1044       *fr = fr->java_sender();
1045     }
1046   } else {
1047     // more complex code with compiled code
1048     assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above");
1049     CodeBlob* cb = CodeCache::find_blob(pc);
1050     if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) {
1051       // Not sure where the pc points to, fallback to default
1052       // stack overflow handling
1053       return false;
1054     } else {
1055       // in compiled code, the stack banging is performed just after the return pc
1056       // has been pushed on the stack
1057       *fr = os::fetch_compiled_frame_from_context(ucVoid);
1058       if (!fr->is_java_frame()) {
1059         assert(!fr->is_first_frame(), "Safety check");
1060         // See java_sender() comment above.
1061         *fr = fr->java_sender();
1062       }
1063     }
1064   }
1065   assert(fr->is_java_frame(), "Safety check");
1066   return true;
1067 }
1068 #endif // ARM
1069 
1070 // This return true if the signal handler should just continue, ie. return after calling this
1071 bool os::Posix::handle_stack_overflow(JavaThread* thread, address addr, address pc,
1072                                       const void* ucVoid, address* stub) {
1073   // stack overflow
1074   StackOverflow* overflow_state = thread->stack_overflow_state();
1075   if (overflow_state->in_stack_yellow_reserved_zone(addr)) {
1076     if (thread->thread_state() == _thread_in_Java) {
1077 #ifndef ARM
1078       // arm32 doesn't have this
1079       if (overflow_state->in_stack_reserved_zone(addr)) {
1080         frame fr;
1081         if (get_frame_at_stack_banging_point(thread, pc, ucVoid, &fr)) {
1082           assert(fr.is_java_frame(), "Must be a Java frame");
1083           frame activation =
1084             SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr);
1085           if (activation.sp() != NULL) {
1086             overflow_state->disable_stack_reserved_zone();
1087             if (activation.is_interpreted_frame()) {
1088               overflow_state->set_reserved_stack_activation((address)(activation.fp()
1089                 // Some platforms use frame pointers for interpreter frames, others use initial sp.
1090 #if !defined(PPC64) && !defined(S390)
1091                 + frame::interpreter_frame_initial_sp_offset
1092 #endif
1093                 ));
1094             } else {
1095               overflow_state->set_reserved_stack_activation((address)activation.unextended_sp());
1096             }
1097             return true; // just continue
1098           }
1099         }
1100       }
1101 #endif // ARM
1102       // Throw a stack overflow exception.  Guard pages will be reenabled
1103       // while unwinding the stack.
1104       overflow_state->disable_stack_yellow_reserved_zone();
1105       *stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
1106     } else {
1107       // Thread was in the vm or native code.  Return and try to finish.
1108       overflow_state->disable_stack_yellow_reserved_zone();
1109       return true; // just continue
1110     }
1111   } else if (overflow_state->in_stack_red_zone(addr)) {
1112     // Fatal red zone violation.  Disable the guard pages and fall through
1113     // to handle_unexpected_exception way down below.
1114     overflow_state->disable_stack_red_zone();
1115     tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
1116 
1117     // This is a likely cause, but hard to verify. Let's just print
1118     // it as a hint.
1119     tty->print_raw_cr("Please check if any of your loaded .so files has "
1120                       "enabled executable stack (see man page execstack(8))");
1121 
1122   } else {
1123 #if !defined(AIX) && !defined(__APPLE__)
1124     // bsd and aix don't have this
1125 
1126     // Accessing stack address below sp may cause SEGV if current
1127     // thread has MAP_GROWSDOWN stack. This should only happen when
1128     // current thread was created by user code with MAP_GROWSDOWN flag
1129     // and then attached to VM. See notes in os_linux.cpp.
1130     if (thread->osthread()->expanding_stack() == 0) {
1131        thread->osthread()->set_expanding_stack();
1132        if (os::Linux::manually_expand_stack(thread, addr)) {
1133          thread->osthread()->clear_expanding_stack();
1134          return true; // just continue
1135        }
1136        thread->osthread()->clear_expanding_stack();
1137     } else {
1138        fatal("recursive segv. expanding stack.");
1139     }
1140 #else
1141     tty->print_raw_cr("SIGSEGV happened inside stack but outside yellow and red zone.");
1142 #endif // AIX or BSD
1143   }
1144   return false;
1145 }
1146 #endif // ZERO
1147 
1148 bool os::Posix::is_root(uid_t uid){
1149     return ROOT_UID == uid;
1150 }
1151 
1152 bool os::Posix::matches_effective_uid_or_root(uid_t uid) {
1153     return is_root(uid) || geteuid() == uid;
1154 }
1155 
1156 bool os::Posix::matches_effective_uid_and_gid_or_root(uid_t uid, gid_t gid) {
1157     return is_root(uid) || (geteuid() == uid && getegid() == gid);
1158 }
1159 
1160 Thread* os::ThreadCrashProtection::_protected_thread = NULL;
1161 os::ThreadCrashProtection* os::ThreadCrashProtection::_crash_protection = NULL;
1162 
1163 os::ThreadCrashProtection::ThreadCrashProtection() {
1164   _protected_thread = Thread::current();
1165   assert(_protected_thread->is_JfrSampler_thread(), "should be JFRSampler");
1166 }
1167 
1168 /*
1169  * See the caveats for this class in os_posix.hpp
1170  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
1171  * method and returns false. If none of the signals are raised, returns true.
1172  * The callback is supposed to provide the method that should be protected.
1173  */
1174 bool os::ThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
1175   sigset_t saved_sig_mask;
1176 
1177   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
1178   // since on at least some systems (OS X) siglongjmp will restore the mask
1179   // for the process, not the thread
1180   pthread_sigmask(0, NULL, &saved_sig_mask);
1181   if (sigsetjmp(_jmpbuf, 0) == 0) {
1182     // make sure we can see in the signal handler that we have crash protection
1183     // installed
1184     _crash_protection = this;
1185     cb.call();
1186     // and clear the crash protection
1187     _crash_protection = NULL;
1188     _protected_thread = NULL;
1189     return true;
1190   }
1191   // this happens when we siglongjmp() back
1192   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1193   _crash_protection = NULL;
1194   _protected_thread = NULL;
1195   return false;
1196 }
1197 
1198 void os::ThreadCrashProtection::restore() {
1199   assert(_crash_protection != NULL, "must have crash protection");
1200   siglongjmp(_jmpbuf, 1);
1201 }
1202 
1203 void os::ThreadCrashProtection::check_crash_protection(int sig,
1204     Thread* thread) {
1205 
1206   if (thread != NULL &&
1207       thread == _protected_thread &&
1208       _crash_protection != NULL) {
1209 
1210     if (sig == SIGSEGV || sig == SIGBUS) {
1211       _crash_protection->restore();
1212     }
1213   }
1214 }
1215 
1216 // Shared clock/time and other supporting routines for pthread_mutex/cond
1217 // initialization. This is enabled on Solaris but only some of the clock/time
1218 // functionality is actually used there.
1219 
1220 // Shared condattr object for use with relative timed-waits. Will be associated
1221 // with CLOCK_MONOTONIC if available to avoid issues with time-of-day changes,
1222 // but otherwise whatever default is used by the platform - generally the
1223 // time-of-day clock.
1224 static pthread_condattr_t _condAttr[1];
1225 
1226 // Shared mutexattr to explicitly set the type to PTHREAD_MUTEX_NORMAL as not
1227 // all systems (e.g. FreeBSD) map the default to "normal".
1228 static pthread_mutexattr_t _mutexAttr[1];
1229 
1230 // common basic initialization that is always supported
1231 static void pthread_init_common(void) {
1232   int status;
1233   if ((status = pthread_condattr_init(_condAttr)) != 0) {
1234     fatal("pthread_condattr_init: %s", os::strerror(status));
1235   }
1236   if ((status = pthread_mutexattr_init(_mutexAttr)) != 0) {
1237     fatal("pthread_mutexattr_init: %s", os::strerror(status));
1238   }
1239   if ((status = pthread_mutexattr_settype(_mutexAttr, PTHREAD_MUTEX_NORMAL)) != 0) {
1240     fatal("pthread_mutexattr_settype: %s", os::strerror(status));
1241   }
1242   os::PlatformMutex::init();
1243 }
1244 
1245 static int (*_pthread_condattr_setclock)(pthread_condattr_t *, clockid_t) = NULL;
1246 
1247 static bool _use_clock_monotonic_condattr = false;
1248 
1249 // Determine what POSIX API's are present and do appropriate
1250 // configuration.
1251 void os::Posix::init(void) {
1252 #if defined(_ALLBSD_SOURCE)
1253   clock_tics_per_sec = CLK_TCK;
1254 #else
1255   clock_tics_per_sec = sysconf(_SC_CLK_TCK);
1256 #endif
1257   // NOTE: no logging available when this is called. Put logging
1258   // statements in init_2().
1259 
1260   // Check for pthread_condattr_setclock support.
1261 
1262   // libpthread is already loaded.
1263   int (*condattr_setclock_func)(pthread_condattr_t*, clockid_t) =
1264     (int (*)(pthread_condattr_t*, clockid_t))dlsym(RTLD_DEFAULT,
1265                                                    "pthread_condattr_setclock");
1266   if (condattr_setclock_func != NULL) {
1267     _pthread_condattr_setclock = condattr_setclock_func;
1268   }
1269 
1270   // Now do general initialization.
1271 
1272   pthread_init_common();
1273 
1274   int status;
1275   if (_pthread_condattr_setclock != NULL) {
1276     if ((status = _pthread_condattr_setclock(_condAttr, CLOCK_MONOTONIC)) != 0) {
1277       if (status == EINVAL) {
1278         _use_clock_monotonic_condattr = false;
1279         warning("Unable to use monotonic clock with relative timed-waits" \
1280                 " - changes to the time-of-day clock may have adverse affects");
1281       } else {
1282         fatal("pthread_condattr_setclock: %s", os::strerror(status));
1283       }
1284     } else {
1285       _use_clock_monotonic_condattr = true;
1286     }
1287   }
1288 
1289   initial_time_count = javaTimeNanos();
1290 }
1291 
1292 void os::Posix::init_2(void) {
1293   log_info(os)("Use of CLOCK_MONOTONIC is supported");
1294   log_info(os)("Use of pthread_condattr_setclock is%s supported",
1295                (_pthread_condattr_setclock != NULL ? "" : " not"));
1296   log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with %s",
1297                _use_clock_monotonic_condattr ? "CLOCK_MONOTONIC" : "the default clock");
1298 }
1299 
1300 // Utility to convert the given timeout to an absolute timespec
1301 // (based on the appropriate clock) to use with pthread_cond_timewait,
1302 // and sem_timedwait().
1303 // The clock queried here must be the clock used to manage the
1304 // timeout of the condition variable or semaphore.
1305 //
1306 // The passed in timeout value is either a relative time in nanoseconds
1307 // or an absolute time in milliseconds. A relative timeout will be
1308 // associated with CLOCK_MONOTONIC if available, unless the real-time clock
1309 // is explicitly requested; otherwise, or if absolute,
1310 // the default time-of-day clock will be used.
1311 
1312 // Given time is a 64-bit value and the time_t used in the timespec is
1313 // sometimes a signed-32-bit value we have to watch for overflow if times
1314 // way in the future are given. Further on Solaris versions
1315 // prior to 10 there is a restriction (see cond_timedwait) that the specified
1316 // number of seconds, in abstime, is less than current_time + 100000000.
1317 // As it will be over 20 years before "now + 100000000" will overflow we can
1318 // ignore overflow and just impose a hard-limit on seconds using the value
1319 // of "now + 100000000". This places a limit on the timeout of about 3.17
1320 // years from "now".
1321 //
1322 #define MAX_SECS 100000000
1323 
1324 // Calculate a new absolute time that is "timeout" nanoseconds from "now".
1325 // "unit" indicates the unit of "now_part_sec" (may be nanos or micros depending
1326 // on which clock API is being used).
1327 static void calc_rel_time(timespec* abstime, jlong timeout, jlong now_sec,
1328                           jlong now_part_sec, jlong unit) {
1329   time_t max_secs = now_sec + MAX_SECS;
1330 
1331   jlong seconds = timeout / NANOUNITS;
1332   timeout %= NANOUNITS; // remaining nanos
1333 
1334   if (seconds >= MAX_SECS) {
1335     // More seconds than we can add, so pin to max_secs.
1336     abstime->tv_sec = max_secs;
1337     abstime->tv_nsec = 0;
1338   } else {
1339     abstime->tv_sec = now_sec  + seconds;
1340     long nanos = (now_part_sec * (NANOUNITS / unit)) + timeout;
1341     if (nanos >= NANOUNITS) { // overflow
1342       abstime->tv_sec += 1;
1343       nanos -= NANOUNITS;
1344     }
1345     abstime->tv_nsec = nanos;
1346   }
1347 }
1348 
1349 // Unpack the given deadline in milliseconds since the epoch, into the given timespec.
1350 // The current time in seconds is also passed in to enforce an upper bound as discussed above.
1351 static void unpack_abs_time(timespec* abstime, jlong deadline, jlong now_sec) {
1352   time_t max_secs = now_sec + MAX_SECS;
1353 
1354   jlong seconds = deadline / MILLIUNITS;
1355   jlong millis = deadline % MILLIUNITS;
1356 
1357   if (seconds >= max_secs) {
1358     // Absolute seconds exceeds allowed max, so pin to max_secs.
1359     abstime->tv_sec = max_secs;
1360     abstime->tv_nsec = 0;
1361   } else {
1362     abstime->tv_sec = seconds;
1363     abstime->tv_nsec = millis_to_nanos(millis);
1364   }
1365 }
1366 
1367 static jlong millis_to_nanos_bounded(jlong millis) {
1368   // We have to watch for overflow when converting millis to nanos,
1369   // but if millis is that large then we will end up limiting to
1370   // MAX_SECS anyway, so just do that here.
1371   if (millis / MILLIUNITS > MAX_SECS) {
1372     millis = jlong(MAX_SECS) * MILLIUNITS;
1373   }
1374   return millis_to_nanos(millis);
1375 }
1376 
1377 static void to_abstime(timespec* abstime, jlong timeout,
1378                        bool isAbsolute, bool isRealtime) {
1379   DEBUG_ONLY(int max_secs = MAX_SECS;)
1380 
1381   if (timeout < 0) {
1382     timeout = 0;
1383   }
1384 
1385   clockid_t clock = CLOCK_MONOTONIC;
1386   if (isAbsolute || (!_use_clock_monotonic_condattr || isRealtime)) {
1387     clock = CLOCK_REALTIME;
1388   }
1389 
1390   struct timespec now;
1391   int status = clock_gettime(clock, &now);
1392   assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
1393 
1394   if (!isAbsolute) {
1395     calc_rel_time(abstime, timeout, now.tv_sec, now.tv_nsec, NANOUNITS);
1396   } else {
1397     unpack_abs_time(abstime, timeout, now.tv_sec);
1398   }
1399   DEBUG_ONLY(max_secs += now.tv_sec;)
1400 
1401   assert(abstime->tv_sec >= 0, "tv_sec < 0");
1402   assert(abstime->tv_sec <= max_secs, "tv_sec > max_secs");
1403   assert(abstime->tv_nsec >= 0, "tv_nsec < 0");
1404   assert(abstime->tv_nsec < NANOUNITS, "tv_nsec >= NANOUNITS");
1405 }
1406 
1407 // Create an absolute time 'millis' milliseconds in the future, using the
1408 // real-time (time-of-day) clock. Used by PosixSemaphore.
1409 void os::Posix::to_RTC_abstime(timespec* abstime, int64_t millis) {
1410   to_abstime(abstime, millis_to_nanos_bounded(millis),
1411              false /* not absolute */,
1412              true  /* use real-time clock */);
1413 }
1414 
1415 // Common (partly) shared time functions
1416 
1417 jlong os::javaTimeMillis() {
1418   struct timespec ts;
1419   int status = clock_gettime(CLOCK_REALTIME, &ts);
1420   assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
1421   return jlong(ts.tv_sec) * MILLIUNITS +
1422     jlong(ts.tv_nsec) / NANOUNITS_PER_MILLIUNIT;
1423 }
1424 
1425 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
1426   struct timespec ts;
1427   int status = clock_gettime(CLOCK_REALTIME, &ts);
1428   assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
1429   seconds = jlong(ts.tv_sec);
1430   nanos = jlong(ts.tv_nsec);
1431 }
1432 
1433 // macOS and AIX have platform specific implementations for javaTimeNanos()
1434 // using native clock/timer access APIs. These have historically worked well
1435 // for those platforms, but it may be possible for them to switch to the
1436 // generic clock_gettime mechanism in the future.
1437 #if !defined(__APPLE__) && !defined(AIX)
1438 
1439 jlong os::javaTimeNanos() {
1440   struct timespec tp;
1441   int status = clock_gettime(CLOCK_MONOTONIC, &tp);
1442   assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
1443   jlong result = jlong(tp.tv_sec) * NANOSECS_PER_SEC + jlong(tp.tv_nsec);
1444   return result;
1445 }
1446 
1447 // for timer info max values which include all bits
1448 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
1449 
1450 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1451   // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1452   info_ptr->max_value = ALL_64_BITS;
1453   info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
1454   info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
1455   info_ptr->kind = JVMTI_TIMER_ELAPSED;     // elapsed not CPU time
1456 }
1457 #endif // ! APPLE && !AIX
1458 
1459 // Time since start-up in seconds to a fine granularity.
1460 double os::elapsedTime() {
1461   return ((double)os::elapsed_counter()) / os::elapsed_frequency(); // nanosecond resolution
1462 }
1463 
1464 jlong os::elapsed_counter() {
1465   return os::javaTimeNanos() - initial_time_count;
1466 }
1467 
1468 jlong os::elapsed_frequency() {
1469   return NANOSECS_PER_SEC; // nanosecond resolution
1470 }
1471 
1472 bool os::supports_vtime() { return true; }
1473 
1474 // Return the real, user, and system times in seconds from an
1475 // arbitrary fixed point in the past.
1476 bool os::getTimesSecs(double* process_real_time,
1477                       double* process_user_time,
1478                       double* process_system_time) {
1479   struct tms ticks;
1480   clock_t real_ticks = times(&ticks);
1481 
1482   if (real_ticks == (clock_t) (-1)) {
1483     return false;
1484   } else {
1485     double ticks_per_second = (double) clock_tics_per_sec;
1486     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1487     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1488     *process_real_time = ((double) real_ticks) / ticks_per_second;
1489 
1490     return true;
1491   }
1492 }
1493 
1494 char * os::local_time_string(char *buf, size_t buflen) {
1495   struct tm t;
1496   time_t long_time;
1497   time(&long_time);
1498   localtime_r(&long_time, &t);
1499   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1500                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1501                t.tm_hour, t.tm_min, t.tm_sec);
1502   return buf;
1503 }
1504 
1505 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
1506   return localtime_r(clock, res);
1507 }
1508 
1509 
1510 // Shared pthread_mutex/cond based PlatformEvent implementation.
1511 // Not currently usable by Solaris.
1512 
1513 
1514 // PlatformEvent
1515 //
1516 // Assumption:
1517 //    Only one parker can exist on an event, which is why we allocate
1518 //    them per-thread. Multiple unparkers can coexist.
1519 //
1520 // _event serves as a restricted-range semaphore.
1521 //   -1 : thread is blocked, i.e. there is a waiter
1522 //    0 : neutral: thread is running or ready,
1523 //        could have been signaled after a wait started
1524 //    1 : signaled - thread is running or ready
1525 //
1526 //    Having three states allows for some detection of bad usage - see
1527 //    comments on unpark().
1528 
1529 os::PlatformEvent::PlatformEvent() {
1530   int status = pthread_cond_init(_cond, _condAttr);
1531   assert_status(status == 0, status, "cond_init");
1532   status = pthread_mutex_init(_mutex, _mutexAttr);
1533   assert_status(status == 0, status, "mutex_init");
1534   _event   = 0;
1535   _nParked = 0;
1536 }
1537 
1538 void os::PlatformEvent::park() {       // AKA "down()"
1539   // Transitions for _event:
1540   //   -1 => -1 : illegal
1541   //    1 =>  0 : pass - return immediately
1542   //    0 => -1 : block; then set _event to 0 before returning
1543 
1544   // Invariant: Only the thread associated with the PlatformEvent
1545   // may call park().
1546   assert(_nParked == 0, "invariant");
1547 
1548   int v;
1549 
1550   // atomically decrement _event
1551   for (;;) {
1552     v = _event;
1553     if (Atomic::cmpxchg(&_event, v, v - 1) == v) break;
1554   }
1555   guarantee(v >= 0, "invariant");
1556 
1557   if (v == 0) { // Do this the hard way by blocking ...
1558     int status = pthread_mutex_lock(_mutex);
1559     assert_status(status == 0, status, "mutex_lock");
1560     guarantee(_nParked == 0, "invariant");
1561     ++_nParked;
1562     while (_event < 0) {
1563       // OS-level "spurious wakeups" are ignored
1564       status = pthread_cond_wait(_cond, _mutex);
1565       assert_status(status == 0 MACOS_ONLY(|| status == ETIMEDOUT),
1566                     status, "cond_wait");
1567     }
1568     --_nParked;
1569 
1570     _event = 0;
1571     status = pthread_mutex_unlock(_mutex);
1572     assert_status(status == 0, status, "mutex_unlock");
1573     // Paranoia to ensure our locked and lock-free paths interact
1574     // correctly with each other.
1575     OrderAccess::fence();
1576   }
1577   guarantee(_event >= 0, "invariant");
1578 }
1579 
1580 int os::PlatformEvent::park(jlong millis) {
1581   // Transitions for _event:
1582   //   -1 => -1 : illegal
1583   //    1 =>  0 : pass - return immediately
1584   //    0 => -1 : block; then set _event to 0 before returning
1585 
1586   // Invariant: Only the thread associated with the Event/PlatformEvent
1587   // may call park().
1588   assert(_nParked == 0, "invariant");
1589 
1590   int v;
1591   // atomically decrement _event
1592   for (;;) {
1593     v = _event;
1594     if (Atomic::cmpxchg(&_event, v, v - 1) == v) break;
1595   }
1596   guarantee(v >= 0, "invariant");
1597 
1598   if (v == 0) { // Do this the hard way by blocking ...
1599     struct timespec abst;
1600     to_abstime(&abst, millis_to_nanos_bounded(millis), false, false);
1601 
1602     int ret = OS_TIMEOUT;
1603     int status = pthread_mutex_lock(_mutex);
1604     assert_status(status == 0, status, "mutex_lock");
1605     guarantee(_nParked == 0, "invariant");
1606     ++_nParked;
1607 
1608     while (_event < 0) {
1609       status = pthread_cond_timedwait(_cond, _mutex, &abst);
1610       assert_status(status == 0 || status == ETIMEDOUT,
1611                     status, "cond_timedwait");
1612       // OS-level "spurious wakeups" are ignored unless the archaic
1613       // FilterSpuriousWakeups is set false. That flag should be obsoleted.
1614       if (!FilterSpuriousWakeups) break;
1615       if (status == ETIMEDOUT) break;
1616     }
1617     --_nParked;
1618 
1619     if (_event >= 0) {
1620       ret = OS_OK;
1621     }
1622 
1623     _event = 0;
1624     status = pthread_mutex_unlock(_mutex);
1625     assert_status(status == 0, status, "mutex_unlock");
1626     // Paranoia to ensure our locked and lock-free paths interact
1627     // correctly with each other.
1628     OrderAccess::fence();
1629     return ret;
1630   }
1631   return OS_OK;
1632 }
1633 
1634 void os::PlatformEvent::unpark() {
1635   // Transitions for _event:
1636   //    0 => 1 : just return
1637   //    1 => 1 : just return
1638   //   -1 => either 0 or 1; must signal target thread
1639   //         That is, we can safely transition _event from -1 to either
1640   //         0 or 1.
1641   // See also: "Semaphores in Plan 9" by Mullender & Cox
1642   //
1643   // Note: Forcing a transition from "-1" to "1" on an unpark() means
1644   // that it will take two back-to-back park() calls for the owning
1645   // thread to block. This has the benefit of forcing a spurious return
1646   // from the first park() call after an unpark() call which will help
1647   // shake out uses of park() and unpark() without checking state conditions
1648   // properly. This spurious return doesn't manifest itself in any user code
1649   // but only in the correctly written condition checking loops of ObjectMonitor,
1650   // Mutex/Monitor, and JavaThread::sleep
1651 
1652   if (Atomic::xchg(&_event, 1) >= 0) return;
1653 
1654   int status = pthread_mutex_lock(_mutex);
1655   assert_status(status == 0, status, "mutex_lock");
1656   int anyWaiters = _nParked;
1657   assert(anyWaiters == 0 || anyWaiters == 1, "invariant");
1658   status = pthread_mutex_unlock(_mutex);
1659   assert_status(status == 0, status, "mutex_unlock");
1660 
1661   // Note that we signal() *after* dropping the lock for "immortal" Events.
1662   // This is safe and avoids a common class of futile wakeups.  In rare
1663   // circumstances this can cause a thread to return prematurely from
1664   // cond_{timed}wait() but the spurious wakeup is benign and the victim
1665   // will simply re-test the condition and re-park itself.
1666   // This provides particular benefit if the underlying platform does not
1667   // provide wait morphing.
1668 
1669   if (anyWaiters != 0) {
1670     status = pthread_cond_signal(_cond);
1671     assert_status(status == 0, status, "cond_signal");
1672   }
1673 }
1674 
1675 // JSR166 support
1676 
1677  os::PlatformParker::PlatformParker() : _counter(0), _cur_index(-1) {
1678   int status = pthread_cond_init(&_cond[REL_INDEX], _condAttr);
1679   assert_status(status == 0, status, "cond_init rel");
1680   status = pthread_cond_init(&_cond[ABS_INDEX], NULL);
1681   assert_status(status == 0, status, "cond_init abs");
1682   status = pthread_mutex_init(_mutex, _mutexAttr);
1683   assert_status(status == 0, status, "mutex_init");
1684 }
1685 
1686 os::PlatformParker::~PlatformParker() {
1687   int status = pthread_cond_destroy(&_cond[REL_INDEX]);
1688   assert_status(status == 0, status, "cond_destroy rel");
1689   status = pthread_cond_destroy(&_cond[ABS_INDEX]);
1690   assert_status(status == 0, status, "cond_destroy abs");
1691   status = pthread_mutex_destroy(_mutex);
1692   assert_status(status == 0, status, "mutex_destroy");
1693 }
1694 
1695 // Parker::park decrements count if > 0, else does a condvar wait.  Unpark
1696 // sets count to 1 and signals condvar.  Only one thread ever waits
1697 // on the condvar. Contention seen when trying to park implies that someone
1698 // is unparking you, so don't wait. And spurious returns are fine, so there
1699 // is no need to track notifications.
1700 
1701 void Parker::park(bool isAbsolute, jlong time) {
1702 
1703   // Optional fast-path check:
1704   // Return immediately if a permit is available.
1705   // We depend on Atomic::xchg() having full barrier semantics
1706   // since we are doing a lock-free update to _counter.
1707   if (Atomic::xchg(&_counter, 0) > 0) return;
1708 
1709   JavaThread *jt = JavaThread::current();
1710 
1711   // Optional optimization -- avoid state transitions if there's
1712   // an interrupt pending.
1713   if (jt->is_interrupted(false)) {
1714     return;
1715   }
1716 
1717   // Next, demultiplex/decode time arguments
1718   struct timespec absTime;
1719   if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
1720     return;
1721   }
1722   if (time > 0) {
1723     to_abstime(&absTime, time, isAbsolute, false);
1724   }
1725 
1726   // Enter safepoint region
1727   // Beware of deadlocks such as 6317397.
1728   // The per-thread Parker:: mutex is a classic leaf-lock.
1729   // In particular a thread must never block on the Threads_lock while
1730   // holding the Parker:: mutex.  If safepoints are pending both the
1731   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
1732   ThreadBlockInVM tbivm(jt);
1733 
1734   // Can't access interrupt state now that we are _thread_blocked. If we've
1735   // been interrupted since we checked above then _counter will be > 0.
1736 
1737   // Don't wait if cannot get lock since interference arises from
1738   // unparking.
1739   if (pthread_mutex_trylock(_mutex) != 0) {
1740     return;
1741   }
1742 
1743   int status;
1744   if (_counter > 0)  { // no wait needed
1745     _counter = 0;
1746     status = pthread_mutex_unlock(_mutex);
1747     assert_status(status == 0, status, "invariant");
1748     // Paranoia to ensure our locked and lock-free paths interact
1749     // correctly with each other and Java-level accesses.
1750     OrderAccess::fence();
1751     return;
1752   }
1753 
1754   OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
1755 
1756   assert(_cur_index == -1, "invariant");
1757   if (time == 0) {
1758     _cur_index = REL_INDEX; // arbitrary choice when not timed
1759     status = pthread_cond_wait(&_cond[_cur_index], _mutex);
1760     assert_status(status == 0 MACOS_ONLY(|| status == ETIMEDOUT),
1761                   status, "cond_wait");
1762   }
1763   else {
1764     _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX;
1765     status = pthread_cond_timedwait(&_cond[_cur_index], _mutex, &absTime);
1766     assert_status(status == 0 || status == ETIMEDOUT,
1767                   status, "cond_timedwait");
1768   }
1769   _cur_index = -1;
1770 
1771   _counter = 0;
1772   status = pthread_mutex_unlock(_mutex);
1773   assert_status(status == 0, status, "invariant");
1774   // Paranoia to ensure our locked and lock-free paths interact
1775   // correctly with each other and Java-level accesses.
1776   OrderAccess::fence();
1777 }
1778 
1779 void Parker::unpark() {
1780   int status = pthread_mutex_lock(_mutex);
1781   assert_status(status == 0, status, "invariant");
1782   const int s = _counter;
1783   _counter = 1;
1784   // must capture correct index before unlocking
1785   int index = _cur_index;
1786   status = pthread_mutex_unlock(_mutex);
1787   assert_status(status == 0, status, "invariant");
1788 
1789   // Note that we signal() *after* dropping the lock for "immortal" Events.
1790   // This is safe and avoids a common class of futile wakeups.  In rare
1791   // circumstances this can cause a thread to return prematurely from
1792   // cond_{timed}wait() but the spurious wakeup is benign and the victim
1793   // will simply re-test the condition and re-park itself.
1794   // This provides particular benefit if the underlying platform does not
1795   // provide wait morphing.
1796 
1797   if (s < 1 && index != -1) {
1798     // thread is definitely parked
1799     status = pthread_cond_signal(&_cond[index]);
1800     assert_status(status == 0, status, "invariant");
1801   }
1802 }
1803 
1804 // Platform Mutex/Monitor implementation
1805 
1806 #if PLATFORM_MONITOR_IMPL_INDIRECT
1807 
1808 os::PlatformMutex::Mutex::Mutex() : _next(NULL) {
1809   int status = pthread_mutex_init(&_mutex, _mutexAttr);
1810   assert_status(status == 0, status, "mutex_init");
1811 }
1812 
1813 os::PlatformMutex::Mutex::~Mutex() {
1814   int status = pthread_mutex_destroy(&_mutex);
1815   assert_status(status == 0, status, "mutex_destroy");
1816 }
1817 
1818 pthread_mutex_t os::PlatformMutex::_freelist_lock;
1819 os::PlatformMutex::Mutex* os::PlatformMutex::_mutex_freelist = NULL;
1820 
1821 void os::PlatformMutex::init() {
1822   int status = pthread_mutex_init(&_freelist_lock, _mutexAttr);
1823   assert_status(status == 0, status, "freelist lock init");
1824 }
1825 
1826 struct os::PlatformMutex::WithFreeListLocked : public StackObj {
1827   WithFreeListLocked() {
1828     int status = pthread_mutex_lock(&_freelist_lock);
1829     assert_status(status == 0, status, "freelist lock");
1830   }
1831 
1832   ~WithFreeListLocked() {
1833     int status = pthread_mutex_unlock(&_freelist_lock);
1834     assert_status(status == 0, status, "freelist unlock");
1835   }
1836 };
1837 
1838 os::PlatformMutex::PlatformMutex() {
1839   {
1840     WithFreeListLocked wfl;
1841     _impl = _mutex_freelist;
1842     if (_impl != NULL) {
1843       _mutex_freelist = _impl->_next;
1844       _impl->_next = NULL;
1845       return;
1846     }
1847   }
1848   _impl = new Mutex();
1849 }
1850 
1851 os::PlatformMutex::~PlatformMutex() {
1852   WithFreeListLocked wfl;
1853   assert(_impl->_next == NULL, "invariant");
1854   _impl->_next = _mutex_freelist;
1855   _mutex_freelist = _impl;
1856 }
1857 
1858 os::PlatformMonitor::Cond::Cond() : _next(NULL) {
1859   int status = pthread_cond_init(&_cond, _condAttr);
1860   assert_status(status == 0, status, "cond_init");
1861 }
1862 
1863 os::PlatformMonitor::Cond::~Cond() {
1864   int status = pthread_cond_destroy(&_cond);
1865   assert_status(status == 0, status, "cond_destroy");
1866 }
1867 
1868 os::PlatformMonitor::Cond* os::PlatformMonitor::_cond_freelist = NULL;
1869 
1870 os::PlatformMonitor::PlatformMonitor() {
1871   {
1872     WithFreeListLocked wfl;
1873     _impl = _cond_freelist;
1874     if (_impl != NULL) {
1875       _cond_freelist = _impl->_next;
1876       _impl->_next = NULL;
1877       return;
1878     }
1879   }
1880   _impl = new Cond();
1881 }
1882 
1883 os::PlatformMonitor::~PlatformMonitor() {
1884   WithFreeListLocked wfl;
1885   assert(_impl->_next == NULL, "invariant");
1886   _impl->_next = _cond_freelist;
1887   _cond_freelist = _impl;
1888 }
1889 
1890 #else
1891 
1892 os::PlatformMutex::PlatformMutex() {
1893   int status = pthread_mutex_init(&_mutex, _mutexAttr);
1894   assert_status(status == 0, status, "mutex_init");
1895 }
1896 
1897 os::PlatformMutex::~PlatformMutex() {
1898   int status = pthread_mutex_destroy(&_mutex);
1899   assert_status(status == 0, status, "mutex_destroy");
1900 }
1901 
1902 os::PlatformMonitor::PlatformMonitor() {
1903   int status = pthread_cond_init(&_cond, _condAttr);
1904   assert_status(status == 0, status, "cond_init");
1905 }
1906 
1907 os::PlatformMonitor::~PlatformMonitor() {
1908   int status = pthread_cond_destroy(&_cond);
1909   assert_status(status == 0, status, "cond_destroy");
1910 }
1911 
1912 #endif // PLATFORM_MONITOR_IMPL_INDIRECT
1913 
1914 // Must already be locked
1915 int os::PlatformMonitor::wait(jlong millis) {
1916   assert(millis >= 0, "negative timeout");
1917   if (millis > 0) {
1918     struct timespec abst;
1919     // We have to watch for overflow when converting millis to nanos,
1920     // but if millis is that large then we will end up limiting to
1921     // MAX_SECS anyway, so just do that here.
1922     if (millis / MILLIUNITS > MAX_SECS) {
1923       millis = jlong(MAX_SECS) * MILLIUNITS;
1924     }
1925     to_abstime(&abst, millis_to_nanos(millis), false, false);
1926 
1927     int ret = OS_TIMEOUT;
1928     int status = pthread_cond_timedwait(cond(), mutex(), &abst);
1929     assert_status(status == 0 || status == ETIMEDOUT,
1930                   status, "cond_timedwait");
1931     if (status == 0) {
1932       ret = OS_OK;
1933     }
1934     return ret;
1935   } else {
1936     int status = pthread_cond_wait(cond(), mutex());
1937     assert_status(status == 0 MACOS_ONLY(|| status == ETIMEDOUT),
1938                   status, "cond_wait");
1939     return OS_OK;
1940   }
1941 }
1942 
1943 // Darwin has no "environ" in a dynamic library.
1944 #ifdef __APPLE__
1945   #define environ (*_NSGetEnviron())
1946 #else
1947   extern char** environ;
1948 #endif
1949 
1950 char** os::get_environ() { return environ; }
1951 
1952 // Run the specified command in a separate process. Return its exit value,
1953 // or -1 on failure (e.g. can't fork a new process).
1954 // Notes: -Unlike system(), this function can be called from signal handler. It
1955 //         doesn't block SIGINT et al.
1956 //        -this function is unsafe to use in non-error situations, mainly
1957 //         because the child process will inherit all parent descriptors.
1958 int os::fork_and_exec(const char* cmd, bool prefer_vfork) {
1959   const char * argv[4] = {"sh", "-c", cmd, NULL};
1960 
1961   pid_t pid ;
1962 
1963   char** env = os::get_environ();
1964 
1965   // Use always vfork on AIX, since its safe and helps with analyzing OOM situations.
1966   // Otherwise leave it up to the caller.
1967   AIX_ONLY(prefer_vfork = true;)
1968   #ifdef __APPLE__
1969   pid = ::fork();
1970   #else
1971   pid = prefer_vfork ? ::vfork() : ::fork();
1972   #endif
1973 
1974   if (pid < 0) {
1975     // fork failed
1976     return -1;
1977 
1978   } else if (pid == 0) {
1979     // child process
1980 
1981     ::execve("/bin/sh", (char* const*)argv, env);
1982 
1983     // execve failed
1984     ::_exit(-1);
1985 
1986   } else  {
1987     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
1988     // care about the actual exit code, for now.
1989 
1990     int status;
1991 
1992     // Wait for the child process to exit.  This returns immediately if
1993     // the child has already exited. */
1994     while (::waitpid(pid, &status, 0) < 0) {
1995       switch (errno) {
1996       case ECHILD: return 0;
1997       case EINTR: break;
1998       default: return -1;
1999       }
2000     }
2001 
2002     if (WIFEXITED(status)) {
2003       // The child exited normally; get its exit code.
2004       return WEXITSTATUS(status);
2005     } else if (WIFSIGNALED(status)) {
2006       // The child exited because of a signal
2007       // The best value to return is 0x80 + signal number,
2008       // because that is what all Unix shells do, and because
2009       // it allows callers to distinguish between process exit and
2010       // process death by signal.
2011       return 0x80 + WTERMSIG(status);
2012     } else {
2013       // Unknown exit code; pass it through
2014       return status;
2015     }
2016   }
2017 }
2018 
2019 ////////////////////////////////////////////////////////////////////////////////
2020 // runtime exit support
2021 
2022 // Note: os::shutdown() might be called very early during initialization, or
2023 // called from signal handler. Before adding something to os::shutdown(), make
2024 // sure it is async-safe and can handle partially initialized VM.
2025 void os::shutdown() {
2026 
2027   // allow PerfMemory to attempt cleanup of any persistent resources
2028   perfMemory_exit();
2029 
2030   // needs to remove object in file system
2031   AttachListener::abort();
2032 
2033   // flush buffered output, finish log files
2034   ostream_abort();
2035 
2036   // Check for abort hook
2037   abort_hook_t abort_hook = Arguments::abort_hook();
2038   if (abort_hook != NULL) {
2039     abort_hook();
2040   }
2041 
2042 }
2043 
2044 // Note: os::abort() might be called very early during initialization, or
2045 // called from signal handler. Before adding something to os::abort(), make
2046 // sure it is async-safe and can handle partially initialized VM.
2047 // Also note we can abort while other threads continue to run, so we can
2048 // easily trigger secondary faults in those threads. To reduce the likelihood
2049 // of that we use _exit rather than exit, so that no atexit hooks get run.
2050 // But note that os::shutdown() could also trigger secondary faults.
2051 void os::abort(bool dump_core, void* siginfo, const void* context) {
2052   os::shutdown();
2053   if (dump_core) {
2054     LINUX_ONLY(if (DumpPrivateMappingsInCore) ClassLoader::close_jrt_image();)
2055     ::abort(); // dump core
2056   }
2057   ::_exit(1);
2058 }
2059 
2060 // Die immediately, no exit hook, no abort hook, no cleanup.
2061 // Dump a core file, if possible, for debugging.
2062 void os::die() {
2063   if (TestUnresponsiveErrorHandler && !CreateCoredumpOnCrash) {
2064     // For TimeoutInErrorHandlingTest.java, we just kill the VM
2065     // and don't take the time to generate a core file.
2066     os::signal_raise(SIGKILL);
2067   } else {
2068     ::abort();
2069   }
2070 }