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