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