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