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