1 /*
   2  * Copyright (c) 1999, 2016, 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 "utilities/globalDefinitions.hpp"
  26 #include "prims/jvm.h"
  27 #include "semaphore_posix.hpp"
  28 #include "runtime/frame.inline.hpp"
  29 #include "runtime/interfaceSupport.hpp"
  30 #include "runtime/os.hpp"
  31 #include "utilities/macros.hpp"
  32 #include "utilities/vmError.hpp"
  33 
  34 #include <signal.h>
  35 #include <unistd.h>
  36 #include <sys/resource.h>
  37 #include <sys/utsname.h>
  38 #include <pthread.h>
  39 #include <semaphore.h>
  40 #include <signal.h>
  41 #include <sys/mman.h>
  42 
  43 // Todo: provide a os::get_max_process_id() or similar. Number of processes
  44 // may have been configured, can be read more accurately from proc fs etc.
  45 #ifndef MAX_PID
  46 #define MAX_PID INT_MAX
  47 #endif
  48 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
  49 
  50 // Check core dump limit and report possible place where core can be found
  51 void os::check_dump_limit(char* buffer, size_t bufferSize) {
  52   if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) {
  53     jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line");
  54     VMError::record_coredump_status(buffer, false);
  55     return;
  56   }
  57 
  58   int n;
  59   struct rlimit rlim;
  60   bool success;
  61 
  62   char core_path[PATH_MAX];
  63   n = get_core_path(core_path, PATH_MAX);
  64 
  65   if (n <= 0) {
  66     jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
  67     success = true;
  68 #ifdef LINUX
  69   } else if (core_path[0] == '"') { // redirect to user process
  70     jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
  71     success = true;
  72 #endif
  73   } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
  74     jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
  75     success = true;
  76   } else {
  77     switch(rlim.rlim_cur) {
  78       case RLIM_INFINITY:
  79         jio_snprintf(buffer, bufferSize, "%s", core_path);
  80         success = true;
  81         break;
  82       case 0:
  83         jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
  84         success = false;
  85         break;
  86       default:
  87         jio_snprintf(buffer, bufferSize, "%s (max size %lu kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, (unsigned long)(rlim.rlim_cur >> 10));
  88         success = true;
  89         break;
  90     }
  91   }
  92 
  93   VMError::record_coredump_status(buffer, success);
  94 }
  95 
  96 int os::get_native_stack(address* stack, int frames, int toSkip) {
  97   int frame_idx = 0;
  98   int num_of_frames;  // number of frames captured
  99   frame fr = os::current_frame();
 100   while (fr.pc() && frame_idx < frames) {
 101     if (toSkip > 0) {
 102       toSkip --;
 103     } else {
 104       stack[frame_idx ++] = fr.pc();
 105     }
 106     if (fr.fp() == NULL || fr.cb() != NULL ||
 107         fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
 108 
 109     if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
 110       fr = os::get_sender_for_C_frame(&fr);
 111     } else {
 112       break;
 113     }
 114   }
 115   num_of_frames = frame_idx;
 116   for (; frame_idx < frames; frame_idx ++) {
 117     stack[frame_idx] = NULL;
 118   }
 119 
 120   return num_of_frames;
 121 }
 122 
 123 
 124 bool os::unsetenv(const char* name) {
 125   assert(name != NULL, "Null pointer");
 126   return (::unsetenv(name) == 0);
 127 }
 128 
 129 int os::get_last_error() {
 130   return errno;
 131 }
 132 
 133 bool os::is_debugger_attached() {
 134   // not implemented
 135   return false;
 136 }
 137 
 138 void os::wait_for_keypress_at_exit(void) {
 139   // don't do anything on posix platforms
 140   return;
 141 }
 142 
 143 // Helper function to create a temp file in the given directory.
 144 int os::create_file_for_heap(const char* dir, size_t size) {
 145 
 146   const char name_template[] = "/jvmheap.XXXXXX";
 147 
 148   char *fullname = (char*)::malloc(strlen(dir) + sizeof(name_template));
 149   if (fullname == NULL) {
 150     vm_exit_during_initialization(err_msg("malloc failed"));
 151     return -1;
 152   }
 153   (void)strcpy(fullname, dir);
 154   (void)strcat(fullname, name_template);
 155 
 156   sigset_t set, oldset;
 157   int ret = sigfillset(&set);
 158   assert(ret == 0, "sigfillset error");
 159 
 160   // block all signals while we do the file operation.
 161   ret = pthread_sigmask(SIG_BLOCK, &set, &oldset);
 162   assert(ret == 0, "pthread_sigmask error");
 163 
 164   // set the file creation mask.
 165   mode_t file_mode = S_IRUSR | S_IWUSR;
 166 
 167   // create a new file.
 168   int fd = mkstemp(fullname);
 169 
 170   if (fd < 0) {
 171     // reset the signal mask.
 172     ret = pthread_sigmask(SIG_SETMASK, &oldset, NULL);
 173     assert(ret == 0, "pthread_sigmask error");
 174     ::free(fullname);
 175     return -1;
 176   }
 177 
 178   // change file permissions; mkstemp creates file with permissions 0600 (glibc versions after 2.06) or 0666 (2.06 and earlier versions)
 179   ret = fchmod(fd, file_mode);
 180   assert(ret == 0, "fchmod error");
 181 
 182   // delete the name from the filesystem. When 'fd' is closed, the file (and space) will be deleted.
 183   ret = unlink(fullname);
 184   assert(ret == 0, "unlink error");
 185 
 186   // reset the signal mask.
 187   ret = pthread_sigmask(SIG_SETMASK, &oldset, NULL);
 188   assert(ret == 0, "pthread_sigmask error");
 189 
 190   ::free(fullname);
 191   return fd;
 192 }
 193 
 194 static char* reserve_mmaped_memory(size_t bytes, char* requested_addr) {
 195   char * addr;
 196   int flags;
 197 
 198   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
 199   if (requested_addr != NULL) {
 200     assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
 201     flags |= MAP_FIXED;
 202   }
 203 
 204   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
 205   // touch an uncommitted page. Otherwise, the read/write might
 206   // succeed if we have enough swap space to back the physical page.
 207   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
 208     flags, -1, 0);
 209 
 210   if (addr != MAP_FAILED) {
 211     MemTracker::record_virtual_memory_reserve((address)addr, bytes, CALLER_PC);
 212     return addr;
 213   }
 214   return NULL;
 215 }
 216 
 217 static int util_posix_fallocate(int fd, off_t offset, off_t len) {
 218 #ifdef __APPLE__
 219   fstore_t store = { F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, len };
 220   // First we try to get a continous chunk of disk space
 221   int ret = fcntl(fd, F_PREALLOCATE, &store);
 222   if (ret == -1) {
 223     // Maybe we are too fragmented, try to allocate non-continuous range
 224     store.fst_flags = F_ALLOCATEALL;
 225     ret = fcntl(fd, F_PREALLOCATE, &store);
 226     if (ret == -1)
 227       return -1;
 228   }
 229   return ftruncate(fd, len);
 230 #else
 231   return posix_fallocate(fd, offset, len);
 232 #endif
 233 }
 234 
 235 // Map the given address range to the provided file descriptor.
 236 char* os::map_memory_to_dax_file(char* base, size_t size, int fd) {
 237   assert(fd != -1, "File descriptor is not valid");
 238 
 239   // allocate space for the file
 240   if (util_posix_fallocate(fd, 0, (off_t)size) != 0) {
 241     vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory (%s)", os::strerror(errno)));
 242     return NULL;
 243   }
 244 
 245   int prot = PROT_READ | PROT_WRITE;
 246   int flags = MAP_SHARED;
 247   if (base != NULL) {
 248     flags |= MAP_FIXED;
 249   }
 250   char* addr = (char*)mmap(base, size, prot, flags, fd, 0);
 251 
 252   if (addr == MAP_FAILED || (base != NULL && addr != base)) {
 253     if (addr != MAP_FAILED) {
 254       if (!os::release_memory(addr, size)) {
 255         warning("Could not release memory on unsuccessful file mapping");
 256       }
 257     }
 258     return NULL;
 259   }
 260 
 261   return addr;
 262 }
 263 
 264 char* os::replace_existing_mapping_with_dax_file_mapping(char* base, size_t size, int fd) {
 265   assert(fd != -1, "File descriptor is not valid");
 266   assert(base != NULL, "base cannot be NULL");
 267 
 268   return map_memory_to_dax_file(base, size, fd);
 269 
 270 }
 271 
 272 char* os::attempt_reserve_memory_at(size_t bytes, char* addr, int file_desc) {
 273 
 274   // We would want to use the complex logic in pd_attempt_reserve_memory_at(), especially in Linux.
 275   // So we call pd_attempt_reserve_memory_at() to purely reserve mmemory
 276   // and then replace the anonymous mapping with file mapping.
 277   // Unfortunately for AIX, we need to pass new bool parameter to pd_attempt_reserve_memory_at()
 278   // to indicate not to use SHM
 279   #if defined(AIX)
 280     char* result = pd_attempt_reserve_memory_at(bytes, addr, file_desc == -1 /*can use SHM*/);
 281   #else
 282     char* result = pd_attempt_reserve_memory_at(bytes, addr);
 283   #endif
 284   if (result != NULL && file_desc != -1) {
 285     if (replace_existing_mapping_with_dax_file_mapping(result, bytes, file_desc) == NULL) {
 286       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
 287     }
 288     MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
 289     return result;
 290   }
 291   if (result != NULL) {
 292     MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
 293   }
 294   return result;
 295 }
 296 
 297 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
 298 // so on posix, unmap the section at the start and at the end of the chunk that we mapped
 299 // rather than unmapping and remapping the whole chunk to get requested alignment.
 300 char* os::reserve_memory_aligned(size_t size, size_t alignment, int file_desc) {
 301   assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
 302       "Alignment must be a multiple of allocation granularity (page size)");
 303   assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
 304 
 305   size_t extra_size = size + alignment;
 306   assert(extra_size >= size, "overflow, size is too large to allow alignment");
 307 
 308   char* extra_base;
 309   if (file_desc != -1) {
 310     // For file mapping, we do not call os:reserve_memory(extra_size, NULL, alignment, file_desc) because
 311     // we need to deal with shrinking of the file space later when we release extra memory after alignment.
 312     // We also cannot called os:reserve_memory() with file_desc set to -1 because on aix we might get SHM memory.
 313     // So here to call a helper function while reserve memory for us. After we have a aligned base,
 314     // we will replace anonymous mapping with file mapping.
 315     extra_base = reserve_mmaped_memory(extra_size, NULL);
 316     if (extra_base != NULL) {
 317       MemTracker::record_virtual_memory_reserve((address)extra_base, extra_size, CALLER_PC);
 318     }
 319   }
 320   else {
 321     extra_base = os::reserve_memory(extra_size, NULL, alignment);
 322   }
 323 
 324   if (extra_base == NULL) {
 325     return NULL;
 326   }
 327 
 328   // Do manual alignment
 329   char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
 330 
 331   // [  |                                       |  ]
 332   // ^ extra_base
 333   //    ^ extra_base + begin_offset == aligned_base
 334   //     extra_base + begin_offset + size       ^
 335   //                       extra_base + extra_size ^
 336   // |<>| == begin_offset
 337   //                              end_offset == |<>|
 338   size_t begin_offset = aligned_base - extra_base;
 339   size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
 340 
 341   if (begin_offset > 0) {
 342       os::release_memory(extra_base, begin_offset);
 343   }
 344 
 345   if (end_offset > 0) {
 346       os::release_memory(extra_base + begin_offset + size, end_offset);
 347   }
 348 
 349   if (file_desc != -1) {
 350     // After we have an aligned address, we can replace anonymopus mapping with file mapping
 351     if (replace_existing_mapping_with_dax_file_mapping(aligned_base, size, file_desc) == NULL) {
 352       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
 353     }
 354     MemTracker::record_virtual_memory_commit((address)aligned_base, size, CALLER_PC);
 355   }
 356   return aligned_base;
 357 }
 358 
 359 int os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
 360     return vsnprintf(buf, len, fmt, args);
 361 }
 362 
 363 int os::get_fileno(FILE* fp) {
 364   return NOT_AIX(::)fileno(fp);
 365 }
 366 
 367 struct tm* os::gmtime_pd(const time_t* clock, struct tm*  res) {
 368   return gmtime_r(clock, res);
 369 }
 370 
 371 void os::Posix::print_load_average(outputStream* st) {
 372   st->print("load average:");
 373   double loadavg[3];
 374   os::loadavg(loadavg, 3);
 375   st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
 376   st->cr();
 377 }
 378 
 379 void os::Posix::print_rlimit_info(outputStream* st) {
 380   st->print("rlimit:");
 381   struct rlimit rlim;
 382 
 383   st->print(" STACK ");
 384   getrlimit(RLIMIT_STACK, &rlim);
 385   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 386   else st->print("%luk", rlim.rlim_cur >> 10);
 387 
 388   st->print(", CORE ");
 389   getrlimit(RLIMIT_CORE, &rlim);
 390   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 391   else st->print("%luk", rlim.rlim_cur >> 10);
 392 
 393   // Isn't there on solaris
 394 #if !defined(SOLARIS) && !defined(AIX)
 395   st->print(", NPROC ");
 396   getrlimit(RLIMIT_NPROC, &rlim);
 397   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 398   else st->print("%lu", rlim.rlim_cur);
 399 #endif
 400 
 401   st->print(", NOFILE ");
 402   getrlimit(RLIMIT_NOFILE, &rlim);
 403   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 404   else st->print("%lu", rlim.rlim_cur);
 405 
 406   st->print(", AS ");
 407   getrlimit(RLIMIT_AS, &rlim);
 408   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 409   else st->print("%luk", rlim.rlim_cur >> 10);
 410   st->cr();
 411 }
 412 
 413 void os::Posix::print_uname_info(outputStream* st) {
 414   // kernel
 415   st->print("uname:");
 416   struct utsname name;
 417   uname(&name);
 418   st->print("%s ", name.sysname);
 419 #ifdef ASSERT
 420   st->print("%s ", name.nodename);
 421 #endif
 422   st->print("%s ", name.release);
 423   st->print("%s ", name.version);
 424   st->print("%s", name.machine);
 425   st->cr();
 426 }
 427 
 428 bool os::get_host_name(char* buf, size_t buflen) {
 429   struct utsname name;
 430   uname(&name);
 431   jio_snprintf(buf, buflen, "%s", name.nodename);
 432   return true;
 433 }
 434 
 435 bool os::has_allocatable_memory_limit(julong* limit) {
 436   struct rlimit rlim;
 437   int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
 438   // if there was an error when calling getrlimit, assume that there is no limitation
 439   // on virtual memory.
 440   bool result;
 441   if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
 442     result = false;
 443   } else {
 444     *limit = (julong)rlim.rlim_cur;
 445     result = true;
 446   }
 447 #ifdef _LP64
 448   return result;
 449 #else
 450   // arbitrary virtual space limit for 32 bit Unices found by testing. If
 451   // getrlimit above returned a limit, bound it with this limit. Otherwise
 452   // directly use it.
 453   const julong max_virtual_limit = (julong)3800*M;
 454   if (result) {
 455     *limit = MIN2(*limit, max_virtual_limit);
 456   } else {
 457     *limit = max_virtual_limit;
 458   }
 459 
 460   // bound by actually allocatable memory. The algorithm uses two bounds, an
 461   // upper and a lower limit. The upper limit is the current highest amount of
 462   // memory that could not be allocated, the lower limit is the current highest
 463   // amount of memory that could be allocated.
 464   // The algorithm iteratively refines the result by halving the difference
 465   // between these limits, updating either the upper limit (if that value could
 466   // not be allocated) or the lower limit (if the that value could be allocated)
 467   // until the difference between these limits is "small".
 468 
 469   // the minimum amount of memory we care about allocating.
 470   const julong min_allocation_size = M;
 471 
 472   julong upper_limit = *limit;
 473 
 474   // first check a few trivial cases
 475   if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
 476     *limit = upper_limit;
 477   } else if (!is_allocatable(min_allocation_size)) {
 478     // we found that not even min_allocation_size is allocatable. Return it
 479     // anyway. There is no point to search for a better value any more.
 480     *limit = min_allocation_size;
 481   } else {
 482     // perform the binary search.
 483     julong lower_limit = min_allocation_size;
 484     while ((upper_limit - lower_limit) > min_allocation_size) {
 485       julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
 486       temp_limit = align_size_down_(temp_limit, min_allocation_size);
 487       if (is_allocatable(temp_limit)) {
 488         lower_limit = temp_limit;
 489       } else {
 490         upper_limit = temp_limit;
 491       }
 492     }
 493     *limit = lower_limit;
 494   }
 495   return true;
 496 #endif
 497 }
 498 
 499 const char* os::get_current_directory(char *buf, size_t buflen) {
 500   return getcwd(buf, buflen);
 501 }
 502 
 503 FILE* os::open(int fd, const char* mode) {
 504   return ::fdopen(fd, mode);
 505 }
 506 
 507 void os::flockfile(FILE* fp) {
 508   ::flockfile(fp);
 509 }
 510 
 511 void os::funlockfile(FILE* fp) {
 512   ::funlockfile(fp);
 513 }
 514 
 515 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
 516 // which is used to find statically linked in agents.
 517 // Parameters:
 518 //            sym_name: Symbol in library we are looking for
 519 //            lib_name: Name of library to look in, NULL for shared libs.
 520 //            is_absolute_path == true if lib_name is absolute path to agent
 521 //                                     such as "/a/b/libL.so"
 522 //            == false if only the base name of the library is passed in
 523 //               such as "L"
 524 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
 525                                     bool is_absolute_path) {
 526   char *agent_entry_name;
 527   size_t len;
 528   size_t name_len;
 529   size_t prefix_len = strlen(JNI_LIB_PREFIX);
 530   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
 531   const char *start;
 532 
 533   if (lib_name != NULL) {
 534     name_len = strlen(lib_name);
 535     if (is_absolute_path) {
 536       // Need to strip path, prefix and suffix
 537       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
 538         lib_name = ++start;
 539       }
 540       if (strlen(lib_name) <= (prefix_len + suffix_len)) {
 541         return NULL;
 542       }
 543       lib_name += prefix_len;
 544       name_len = strlen(lib_name) - suffix_len;
 545     }
 546   }
 547   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
 548   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
 549   if (agent_entry_name == NULL) {
 550     return NULL;
 551   }
 552   strcpy(agent_entry_name, sym_name);
 553   if (lib_name != NULL) {
 554     strcat(agent_entry_name, "_");
 555     strncat(agent_entry_name, lib_name, name_len);
 556   }
 557   return agent_entry_name;
 558 }
 559 
 560 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
 561   assert(thread == Thread::current(),  "thread consistency check");
 562 
 563   ParkEvent * const slp = thread->_SleepEvent ;
 564   slp->reset() ;
 565   OrderAccess::fence() ;
 566 
 567   if (interruptible) {
 568     jlong prevtime = javaTimeNanos();
 569 
 570     for (;;) {
 571       if (os::is_interrupted(thread, true)) {
 572         return OS_INTRPT;
 573       }
 574 
 575       jlong newtime = javaTimeNanos();
 576 
 577       if (newtime - prevtime < 0) {
 578         // time moving backwards, should only happen if no monotonic clock
 579         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 580         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
 581       } else {
 582         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 583       }
 584 
 585       if (millis <= 0) {
 586         return OS_OK;
 587       }
 588 
 589       prevtime = newtime;
 590 
 591       {
 592         assert(thread->is_Java_thread(), "sanity check");
 593         JavaThread *jt = (JavaThread *) thread;
 594         ThreadBlockInVM tbivm(jt);
 595         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
 596 
 597         jt->set_suspend_equivalent();
 598         // cleared by handle_special_suspend_equivalent_condition() or
 599         // java_suspend_self() via check_and_wait_while_suspended()
 600 
 601         slp->park(millis);
 602 
 603         // were we externally suspended while we were waiting?
 604         jt->check_and_wait_while_suspended();
 605       }
 606     }
 607   } else {
 608     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
 609     jlong prevtime = javaTimeNanos();
 610 
 611     for (;;) {
 612       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
 613       // the 1st iteration ...
 614       jlong newtime = javaTimeNanos();
 615 
 616       if (newtime - prevtime < 0) {
 617         // time moving backwards, should only happen if no monotonic clock
 618         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 619         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
 620       } else {
 621         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 622       }
 623 
 624       if (millis <= 0) break ;
 625 
 626       prevtime = newtime;
 627       slp->park(millis);
 628     }
 629     return OS_OK ;
 630   }
 631 }
 632 
 633 ////////////////////////////////////////////////////////////////////////////////
 634 // interrupt support
 635 
 636 void os::interrupt(Thread* thread) {
 637   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 638     "possibility of dangling Thread pointer");
 639 
 640   OSThread* osthread = thread->osthread();
 641 
 642   if (!osthread->interrupted()) {
 643     osthread->set_interrupted(true);
 644     // More than one thread can get here with the same value of osthread,
 645     // resulting in multiple notifications.  We do, however, want the store
 646     // to interrupted() to be visible to other threads before we execute unpark().
 647     OrderAccess::fence();
 648     ParkEvent * const slp = thread->_SleepEvent ;
 649     if (slp != NULL) slp->unpark() ;
 650   }
 651 
 652   // For JSR166. Unpark even if interrupt status already was set
 653   if (thread->is_Java_thread())
 654     ((JavaThread*)thread)->parker()->unpark();
 655 
 656   ParkEvent * ev = thread->_ParkEvent ;
 657   if (ev != NULL) ev->unpark() ;
 658 
 659 }
 660 
 661 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
 662   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 663     "possibility of dangling Thread pointer");
 664 
 665   OSThread* osthread = thread->osthread();
 666 
 667   bool interrupted = osthread->interrupted();
 668 
 669   // NOTE that since there is no "lock" around the interrupt and
 670   // is_interrupted operations, there is the possibility that the
 671   // interrupted flag (in osThread) will be "false" but that the
 672   // low-level events will be in the signaled state. This is
 673   // intentional. The effect of this is that Object.wait() and
 674   // LockSupport.park() will appear to have a spurious wakeup, which
 675   // is allowed and not harmful, and the possibility is so rare that
 676   // it is not worth the added complexity to add yet another lock.
 677   // For the sleep event an explicit reset is performed on entry
 678   // to os::sleep, so there is no early return. It has also been
 679   // recommended not to put the interrupted flag into the "event"
 680   // structure because it hides the issue.
 681   if (interrupted && clear_interrupted) {
 682     osthread->set_interrupted(false);
 683     // consider thread->_SleepEvent->reset() ... optional optimization
 684   }
 685 
 686   return interrupted;
 687 }
 688 
 689 
 690 
 691 static const struct {
 692   int sig; const char* name;
 693 }
 694  g_signal_info[] =
 695   {
 696   {  SIGABRT,     "SIGABRT" },
 697 #ifdef SIGAIO
 698   {  SIGAIO,      "SIGAIO" },
 699 #endif
 700   {  SIGALRM,     "SIGALRM" },
 701 #ifdef SIGALRM1
 702   {  SIGALRM1,    "SIGALRM1" },
 703 #endif
 704   {  SIGBUS,      "SIGBUS" },
 705 #ifdef SIGCANCEL
 706   {  SIGCANCEL,   "SIGCANCEL" },
 707 #endif
 708   {  SIGCHLD,     "SIGCHLD" },
 709 #ifdef SIGCLD
 710   {  SIGCLD,      "SIGCLD" },
 711 #endif
 712   {  SIGCONT,     "SIGCONT" },
 713 #ifdef SIGCPUFAIL
 714   {  SIGCPUFAIL,  "SIGCPUFAIL" },
 715 #endif
 716 #ifdef SIGDANGER
 717   {  SIGDANGER,   "SIGDANGER" },
 718 #endif
 719 #ifdef SIGDIL
 720   {  SIGDIL,      "SIGDIL" },
 721 #endif
 722 #ifdef SIGEMT
 723   {  SIGEMT,      "SIGEMT" },
 724 #endif
 725   {  SIGFPE,      "SIGFPE" },
 726 #ifdef SIGFREEZE
 727   {  SIGFREEZE,   "SIGFREEZE" },
 728 #endif
 729 #ifdef SIGGFAULT
 730   {  SIGGFAULT,   "SIGGFAULT" },
 731 #endif
 732 #ifdef SIGGRANT
 733   {  SIGGRANT,    "SIGGRANT" },
 734 #endif
 735   {  SIGHUP,      "SIGHUP" },
 736   {  SIGILL,      "SIGILL" },
 737   {  SIGINT,      "SIGINT" },
 738 #ifdef SIGIO
 739   {  SIGIO,       "SIGIO" },
 740 #endif
 741 #ifdef SIGIOINT
 742   {  SIGIOINT,    "SIGIOINT" },
 743 #endif
 744 #ifdef SIGIOT
 745 // SIGIOT is there for BSD compatibility, but on most Unices just a
 746 // synonym for SIGABRT. The result should be "SIGABRT", not
 747 // "SIGIOT".
 748 #if (SIGIOT != SIGABRT )
 749   {  SIGIOT,      "SIGIOT" },
 750 #endif
 751 #endif
 752 #ifdef SIGKAP
 753   {  SIGKAP,      "SIGKAP" },
 754 #endif
 755   {  SIGKILL,     "SIGKILL" },
 756 #ifdef SIGLOST
 757   {  SIGLOST,     "SIGLOST" },
 758 #endif
 759 #ifdef SIGLWP
 760   {  SIGLWP,      "SIGLWP" },
 761 #endif
 762 #ifdef SIGLWPTIMER
 763   {  SIGLWPTIMER, "SIGLWPTIMER" },
 764 #endif
 765 #ifdef SIGMIGRATE
 766   {  SIGMIGRATE,  "SIGMIGRATE" },
 767 #endif
 768 #ifdef SIGMSG
 769   {  SIGMSG,      "SIGMSG" },
 770 #endif
 771   {  SIGPIPE,     "SIGPIPE" },
 772 #ifdef SIGPOLL
 773   {  SIGPOLL,     "SIGPOLL" },
 774 #endif
 775 #ifdef SIGPRE
 776   {  SIGPRE,      "SIGPRE" },
 777 #endif
 778   {  SIGPROF,     "SIGPROF" },
 779 #ifdef SIGPTY
 780   {  SIGPTY,      "SIGPTY" },
 781 #endif
 782 #ifdef SIGPWR
 783   {  SIGPWR,      "SIGPWR" },
 784 #endif
 785   {  SIGQUIT,     "SIGQUIT" },
 786 #ifdef SIGRECONFIG
 787   {  SIGRECONFIG, "SIGRECONFIG" },
 788 #endif
 789 #ifdef SIGRECOVERY
 790   {  SIGRECOVERY, "SIGRECOVERY" },
 791 #endif
 792 #ifdef SIGRESERVE
 793   {  SIGRESERVE,  "SIGRESERVE" },
 794 #endif
 795 #ifdef SIGRETRACT
 796   {  SIGRETRACT,  "SIGRETRACT" },
 797 #endif
 798 #ifdef SIGSAK
 799   {  SIGSAK,      "SIGSAK" },
 800 #endif
 801   {  SIGSEGV,     "SIGSEGV" },
 802 #ifdef SIGSOUND
 803   {  SIGSOUND,    "SIGSOUND" },
 804 #endif
 805 #ifdef SIGSTKFLT
 806   {  SIGSTKFLT,    "SIGSTKFLT" },
 807 #endif
 808   {  SIGSTOP,     "SIGSTOP" },
 809   {  SIGSYS,      "SIGSYS" },
 810 #ifdef SIGSYSERROR
 811   {  SIGSYSERROR, "SIGSYSERROR" },
 812 #endif
 813 #ifdef SIGTALRM
 814   {  SIGTALRM,    "SIGTALRM" },
 815 #endif
 816   {  SIGTERM,     "SIGTERM" },
 817 #ifdef SIGTHAW
 818   {  SIGTHAW,     "SIGTHAW" },
 819 #endif
 820   {  SIGTRAP,     "SIGTRAP" },
 821 #ifdef SIGTSTP
 822   {  SIGTSTP,     "SIGTSTP" },
 823 #endif
 824   {  SIGTTIN,     "SIGTTIN" },
 825   {  SIGTTOU,     "SIGTTOU" },
 826 #ifdef SIGURG
 827   {  SIGURG,      "SIGURG" },
 828 #endif
 829   {  SIGUSR1,     "SIGUSR1" },
 830   {  SIGUSR2,     "SIGUSR2" },
 831 #ifdef SIGVIRT
 832   {  SIGVIRT,     "SIGVIRT" },
 833 #endif
 834   {  SIGVTALRM,   "SIGVTALRM" },
 835 #ifdef SIGWAITING
 836   {  SIGWAITING,  "SIGWAITING" },
 837 #endif
 838 #ifdef SIGWINCH
 839   {  SIGWINCH,    "SIGWINCH" },
 840 #endif
 841 #ifdef SIGWINDOW
 842   {  SIGWINDOW,   "SIGWINDOW" },
 843 #endif
 844   {  SIGXCPU,     "SIGXCPU" },
 845   {  SIGXFSZ,     "SIGXFSZ" },
 846 #ifdef SIGXRES
 847   {  SIGXRES,     "SIGXRES" },
 848 #endif
 849   { -1, NULL }
 850 };
 851 
 852 // Returned string is a constant. For unknown signals "UNKNOWN" is returned.
 853 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
 854 
 855   const char* ret = NULL;
 856 
 857 #ifdef SIGRTMIN
 858   if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
 859     if (sig == SIGRTMIN) {
 860       ret = "SIGRTMIN";
 861     } else if (sig == SIGRTMAX) {
 862       ret = "SIGRTMAX";
 863     } else {
 864       jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
 865       return out;
 866     }
 867   }
 868 #endif
 869 
 870   if (sig > 0) {
 871     for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
 872       if (g_signal_info[idx].sig == sig) {
 873         ret = g_signal_info[idx].name;
 874         break;
 875       }
 876     }
 877   }
 878 
 879   if (!ret) {
 880     if (!is_valid_signal(sig)) {
 881       ret = "INVALID";
 882     } else {
 883       ret = "UNKNOWN";
 884     }
 885   }
 886 
 887   if (out && outlen > 0) {
 888     strncpy(out, ret, outlen);
 889     out[outlen - 1] = '\0';
 890   }
 891   return out;
 892 }
 893 
 894 int os::Posix::get_signal_number(const char* signal_name) {
 895   char tmp[30];
 896   const char* s = signal_name;
 897   if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
 898     jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
 899     s = tmp;
 900   }
 901   for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
 902     if (strcmp(g_signal_info[idx].name, s) == 0) {
 903       return g_signal_info[idx].sig;
 904     }
 905   }
 906   return -1;
 907 }
 908 
 909 int os::get_signal_number(const char* signal_name) {
 910   return os::Posix::get_signal_number(signal_name);
 911 }
 912 
 913 // Returns true if signal number is valid.
 914 bool os::Posix::is_valid_signal(int sig) {
 915   // MacOS not really POSIX compliant: sigaddset does not return
 916   // an error for invalid signal numbers. However, MacOS does not
 917   // support real time signals and simply seems to have just 33
 918   // signals with no holes in the signal range.
 919 #ifdef __APPLE__
 920   return sig >= 1 && sig < NSIG;
 921 #else
 922   // Use sigaddset to check for signal validity.
 923   sigset_t set;
 924   if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
 925     return false;
 926   }
 927   return true;
 928 #endif
 929 }
 930 
 931 // Returns:
 932 // NULL for an invalid signal number
 933 // "SIG<num>" for a valid but unknown signal number
 934 // signal name otherwise.
 935 const char* os::exception_name(int sig, char* buf, size_t size) {
 936   if (!os::Posix::is_valid_signal(sig)) {
 937     return NULL;
 938   }
 939   const char* const name = os::Posix::get_signal_name(sig, buf, size);
 940   if (strcmp(name, "UNKNOWN") == 0) {
 941     jio_snprintf(buf, size, "SIG%d", sig);
 942   }
 943   return buf;
 944 }
 945 
 946 #define NUM_IMPORTANT_SIGS 32
 947 // Returns one-line short description of a signal set in a user provided buffer.
 948 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
 949   assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
 950   // Note: for shortness, just print out the first 32. That should
 951   // cover most of the useful ones, apart from realtime signals.
 952   for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
 953     const int rc = sigismember(set, sig);
 954     if (rc == -1 && errno == EINVAL) {
 955       buffer[sig-1] = '?';
 956     } else {
 957       buffer[sig-1] = rc == 0 ? '0' : '1';
 958     }
 959   }
 960   buffer[NUM_IMPORTANT_SIGS] = 0;
 961   return buffer;
 962 }
 963 
 964 // Prints one-line description of a signal set.
 965 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
 966   char buf[NUM_IMPORTANT_SIGS + 1];
 967   os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
 968   st->print("%s", buf);
 969 }
 970 
 971 // Writes one-line description of a combination of sigaction.sa_flags into a user
 972 // provided buffer. Returns that buffer.
 973 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
 974   char* p = buffer;
 975   size_t remaining = size;
 976   bool first = true;
 977   int idx = 0;
 978 
 979   assert(buffer, "invalid argument");
 980 
 981   if (size == 0) {
 982     return buffer;
 983   }
 984 
 985   strncpy(buffer, "none", size);
 986 
 987   const struct {
 988     // NB: i is an unsigned int here because SA_RESETHAND is on some
 989     // systems 0x80000000, which is implicitly unsigned.  Assignining
 990     // it to an int field would be an overflow in unsigned-to-signed
 991     // conversion.
 992     unsigned int i;
 993     const char* s;
 994   } flaginfo [] = {
 995     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
 996     { SA_ONSTACK,   "SA_ONSTACK"   },
 997     { SA_RESETHAND, "SA_RESETHAND" },
 998     { SA_RESTART,   "SA_RESTART"   },
 999     { SA_SIGINFO,   "SA_SIGINFO"   },
1000     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
1001     { SA_NODEFER,   "SA_NODEFER"   },
1002 #ifdef AIX
1003     { SA_ONSTACK,   "SA_ONSTACK"   },
1004     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
1005 #endif
1006     { 0, NULL }
1007   };
1008 
1009   for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
1010     if (flags & flaginfo[idx].i) {
1011       if (first) {
1012         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
1013         first = false;
1014       } else {
1015         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
1016       }
1017       const size_t len = strlen(p);
1018       p += len;
1019       remaining -= len;
1020     }
1021   }
1022 
1023   buffer[size - 1] = '\0';
1024 
1025   return buffer;
1026 }
1027 
1028 // Prints one-line description of a combination of sigaction.sa_flags.
1029 void os::Posix::print_sa_flags(outputStream* st, int flags) {
1030   char buffer[0x100];
1031   os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
1032   st->print("%s", buffer);
1033 }
1034 
1035 // Helper function for os::Posix::print_siginfo_...():
1036 // return a textual description for signal code.
1037 struct enum_sigcode_desc_t {
1038   const char* s_name;
1039   const char* s_desc;
1040 };
1041 
1042 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
1043 
1044   const struct {
1045     int sig; int code; const char* s_code; const char* s_desc;
1046   } t1 [] = {
1047     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
1048     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
1049     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
1050     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
1051     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
1052     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
1053     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
1054     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
1055 #if defined(IA64) && defined(LINUX)
1056     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
1057     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
1058 #endif
1059     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
1060     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
1061     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
1062     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
1063     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
1064     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
1065     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
1066     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
1067     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
1068     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
1069 #ifdef AIX
1070     // no explanation found what keyerr would be
1071     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
1072 #endif
1073 #if defined(IA64) && !defined(AIX)
1074     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
1075 #endif
1076 #if defined(__sparc) && defined(SOLARIS)
1077 // define Solaris Sparc M7 ADI SEGV signals
1078 #if !defined(SEGV_ACCADI)
1079 #define SEGV_ACCADI 3
1080 #endif
1081     { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
1082 #if !defined(SEGV_ACCDERR)
1083 #define SEGV_ACCDERR 4
1084 #endif
1085     { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
1086 #if !defined(SEGV_ACCPERR)
1087 #define SEGV_ACCPERR 5
1088 #endif
1089     { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
1090 #endif // defined(__sparc) && defined(SOLARIS)
1091     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
1092     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
1093     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
1094     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
1095     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
1096     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
1097     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
1098     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
1099     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
1100     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
1101     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
1102 #ifdef SIGPOLL
1103     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
1104     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
1105     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
1106     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
1107     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
1108 #endif
1109     { -1, -1, NULL, NULL }
1110   };
1111 
1112   // Codes valid in any signal context.
1113   const struct {
1114     int code; const char* s_code; const char* s_desc;
1115   } t2 [] = {
1116     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
1117     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
1118     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
1119     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
1120     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
1121     // Linux specific
1122 #ifdef SI_TKILL
1123     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
1124 #endif
1125 #ifdef SI_DETHREAD
1126     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
1127 #endif
1128 #ifdef SI_KERNEL
1129     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
1130 #endif
1131 #ifdef SI_SIGIO
1132     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
1133 #endif
1134 
1135 #ifdef AIX
1136     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
1137     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
1138 #endif
1139 
1140 #ifdef __sun
1141     { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
1142     { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
1143     { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
1144 #endif
1145 
1146     { -1, NULL, NULL }
1147   };
1148 
1149   const char* s_code = NULL;
1150   const char* s_desc = NULL;
1151 
1152   for (int i = 0; t1[i].sig != -1; i ++) {
1153     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
1154       s_code = t1[i].s_code;
1155       s_desc = t1[i].s_desc;
1156       break;
1157     }
1158   }
1159 
1160   if (s_code == NULL) {
1161     for (int i = 0; t2[i].s_code != NULL; i ++) {
1162       if (t2[i].code == si->si_code) {
1163         s_code = t2[i].s_code;
1164         s_desc = t2[i].s_desc;
1165       }
1166     }
1167   }
1168 
1169   if (s_code == NULL) {
1170     out->s_name = "unknown";
1171     out->s_desc = "unknown";
1172     return false;
1173   }
1174 
1175   out->s_name = s_code;
1176   out->s_desc = s_desc;
1177 
1178   return true;
1179 }
1180 
1181 void os::print_siginfo(outputStream* os, const void* si0) {
1182 
1183   const siginfo_t* const si = (const siginfo_t*) si0;
1184 
1185   char buf[20];
1186   os->print("siginfo:");
1187 
1188   if (!si) {
1189     os->print(" <null>");
1190     return;
1191   }
1192 
1193   const int sig = si->si_signo;
1194 
1195   os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
1196 
1197   enum_sigcode_desc_t ed;
1198   get_signal_code_description(si, &ed);
1199   os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1200 
1201   if (si->si_errno) {
1202     os->print(", si_errno: %d", si->si_errno);
1203   }
1204 
1205   // Output additional information depending on the signal code.
1206 
1207   // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1208   // so it depends on the context which member to use. For synchronous error signals,
1209   // we print si_addr, unless the signal was sent by another process or thread, in
1210   // which case we print out pid or tid of the sender.
1211   if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
1212     const pid_t pid = si->si_pid;
1213     os->print(", si_pid: %ld", (long) pid);
1214     if (IS_VALID_PID(pid)) {
1215       const pid_t me = getpid();
1216       if (me == pid) {
1217         os->print(" (current process)");
1218       }
1219     } else {
1220       os->print(" (invalid)");
1221     }
1222     os->print(", si_uid: %ld", (long) si->si_uid);
1223     if (sig == SIGCHLD) {
1224       os->print(", si_status: %d", si->si_status);
1225     }
1226   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1227              sig == SIGTRAP || sig == SIGFPE) {
1228     os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1229 #ifdef SIGPOLL
1230   } else if (sig == SIGPOLL) {
1231     os->print(", si_band: %ld", si->si_band);
1232 #endif
1233   }
1234 
1235 }
1236 
1237 int os::Posix::unblock_thread_signal_mask(const sigset_t *set) {
1238   return pthread_sigmask(SIG_UNBLOCK, set, NULL);
1239 }
1240 
1241 address os::Posix::ucontext_get_pc(const ucontext_t* ctx) {
1242 #if defined(AIX)
1243    return Aix::ucontext_get_pc(ctx);
1244 #elif defined(BSD)
1245    return Bsd::ucontext_get_pc(ctx);
1246 #elif defined(LINUX)
1247    return Linux::ucontext_get_pc(ctx);
1248 #elif defined(SOLARIS)
1249    return Solaris::ucontext_get_pc(ctx);
1250 #else
1251    VMError::report_and_die("unimplemented ucontext_get_pc");
1252 #endif
1253 }
1254 
1255 void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) {
1256 #if defined(AIX)
1257    Aix::ucontext_set_pc(ctx, pc);
1258 #elif defined(BSD)
1259    Bsd::ucontext_set_pc(ctx, pc);
1260 #elif defined(LINUX)
1261    Linux::ucontext_set_pc(ctx, pc);
1262 #elif defined(SOLARIS)
1263    Solaris::ucontext_set_pc(ctx, pc);
1264 #else
1265    VMError::report_and_die("unimplemented ucontext_get_pc");
1266 #endif
1267 }
1268 
1269 char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) {
1270   size_t stack_size = 0;
1271   size_t guard_size = 0;
1272   int detachstate = 0;
1273   pthread_attr_getstacksize(attr, &stack_size);
1274   pthread_attr_getguardsize(attr, &guard_size);
1275   pthread_attr_getdetachstate(attr, &detachstate);
1276   jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s",
1277     stack_size / 1024, guard_size / 1024,
1278     (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable"));
1279   return buf;
1280 }
1281 
1282 // Check minimum allowable stack sizes for thread creation and to initialize
1283 // the java system classes, including StackOverflowError - depends on page
1284 // size.  Add two 4K pages for compiler2 recursion in main thread.
1285 // Add in 4*BytesPerWord 4K pages to account for VM stack during
1286 // class initialization depending on 32 or 64 bit VM.
1287 jint os::Posix::set_minimum_stack_sizes() {
1288   _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed,
1289                                         JavaThread::stack_guard_zone_size() +
1290                                         JavaThread::stack_shadow_zone_size() +
1291                                         (4 * BytesPerWord COMPILER2_PRESENT(+ 2)) * 4 * K);
1292 
1293   _java_thread_min_stack_allowed = align_size_up(_java_thread_min_stack_allowed, vm_page_size());
1294 
1295   size_t stack_size_in_bytes = ThreadStackSize * K;
1296   if (stack_size_in_bytes != 0 &&
1297       stack_size_in_bytes < _java_thread_min_stack_allowed) {
1298     // The '-Xss' and '-XX:ThreadStackSize=N' options both set
1299     // ThreadStackSize so we go with "Java thread stack size" instead
1300     // of "ThreadStackSize" to be more friendly.
1301     tty->print_cr("\nThe Java thread stack size specified is too small. "
1302                   "Specify at least " SIZE_FORMAT "k",
1303                   _java_thread_min_stack_allowed / K);
1304     return JNI_ERR;
1305   }
1306 
1307 #ifdef SOLARIS
1308   // For 64kbps there will be a 64kb page size, which makes
1309   // the usable default stack size quite a bit less.  Increase the
1310   // stack for 64kb (or any > than 8kb) pages, this increases
1311   // virtual memory fragmentation (since we're not creating the
1312   // stack on a power of 2 boundary.  The real fix for this
1313   // should be to fix the guard page mechanism.
1314 
1315   if (vm_page_size() > 8*K) {
1316     stack_size_in_bytes = (stack_size_in_bytes != 0)
1317        ? stack_size_in_bytes +
1318          JavaThread::stack_red_zone_size() +
1319          JavaThread::stack_yellow_zone_size()
1320        : 0;
1321     ThreadStackSize = stack_size_in_bytes/K;
1322   }
1323 #endif // SOLARIS
1324 
1325   // Make the stack size a multiple of the page size so that
1326   // the yellow/red zones can be guarded.
1327   JavaThread::set_stack_size_at_create(round_to(stack_size_in_bytes,
1328                                                 vm_page_size()));
1329 
1330   _compiler_thread_min_stack_allowed = align_size_up(_compiler_thread_min_stack_allowed, vm_page_size());
1331 
1332   stack_size_in_bytes = CompilerThreadStackSize * K;
1333   if (stack_size_in_bytes != 0 &&
1334       stack_size_in_bytes < _compiler_thread_min_stack_allowed) {
1335     tty->print_cr("\nThe CompilerThreadStackSize specified is too small. "
1336                   "Specify at least " SIZE_FORMAT "k",
1337                   _compiler_thread_min_stack_allowed / K);
1338     return JNI_ERR;
1339   }
1340 
1341   _vm_internal_thread_min_stack_allowed = align_size_up(_vm_internal_thread_min_stack_allowed, vm_page_size());
1342 
1343   stack_size_in_bytes = VMThreadStackSize * K;
1344   if (stack_size_in_bytes != 0 &&
1345       stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) {
1346     tty->print_cr("\nThe VMThreadStackSize specified is too small. "
1347                   "Specify at least " SIZE_FORMAT "k",
1348                   _vm_internal_thread_min_stack_allowed / K);
1349     return JNI_ERR;
1350   }
1351   return JNI_OK;
1352 }
1353 
1354 // Called when creating the thread.  The minimum stack sizes have already been calculated
1355 size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) {
1356   size_t stack_size;
1357   if (req_stack_size == 0) {
1358     stack_size = default_stack_size(thr_type);
1359   } else {
1360     stack_size = req_stack_size;
1361   }
1362 
1363   switch (thr_type) {
1364   case os::java_thread:
1365     // Java threads use ThreadStackSize which default value can be
1366     // changed with the flag -Xss
1367     if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) {
1368       // no requested size and we have a more specific default value
1369       stack_size = JavaThread::stack_size_at_create();
1370     }
1371     stack_size = MAX2(stack_size,
1372                       _java_thread_min_stack_allowed);
1373     break;
1374   case os::compiler_thread:
1375     if (req_stack_size == 0 && CompilerThreadStackSize > 0) {
1376       // no requested size and we have a more specific default value
1377       stack_size = (size_t)(CompilerThreadStackSize * K);
1378     }
1379     stack_size = MAX2(stack_size,
1380                       _compiler_thread_min_stack_allowed);
1381     break;
1382   case os::vm_thread:
1383   case os::pgc_thread:
1384   case os::cgc_thread:
1385   case os::watcher_thread:
1386   default:  // presume the unknown thr_type is a VM internal
1387     if (req_stack_size == 0 && VMThreadStackSize > 0) {
1388       // no requested size and we have a more specific default value
1389       stack_size = (size_t)(VMThreadStackSize * K);
1390     }
1391 
1392     stack_size = MAX2(stack_size,
1393                       _vm_internal_thread_min_stack_allowed);
1394     break;
1395   }
1396 
1397   return stack_size;
1398 }
1399 
1400 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
1401   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
1402 }
1403 
1404 /*
1405  * See the caveats for this class in os_posix.hpp
1406  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
1407  * method and returns false. If none of the signals are raised, returns true.
1408  * The callback is supposed to provide the method that should be protected.
1409  */
1410 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
1411   sigset_t saved_sig_mask;
1412 
1413   assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
1414   assert(!WatcherThread::watcher_thread()->has_crash_protection(),
1415       "crash_protection already set?");
1416 
1417   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
1418   // since on at least some systems (OS X) siglongjmp will restore the mask
1419   // for the process, not the thread
1420   pthread_sigmask(0, NULL, &saved_sig_mask);
1421   if (sigsetjmp(_jmpbuf, 0) == 0) {
1422     // make sure we can see in the signal handler that we have crash protection
1423     // installed
1424     WatcherThread::watcher_thread()->set_crash_protection(this);
1425     cb.call();
1426     // and clear the crash protection
1427     WatcherThread::watcher_thread()->set_crash_protection(NULL);
1428     return true;
1429   }
1430   // this happens when we siglongjmp() back
1431   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1432   WatcherThread::watcher_thread()->set_crash_protection(NULL);
1433   return false;
1434 }
1435 
1436 void os::WatcherThreadCrashProtection::restore() {
1437   assert(WatcherThread::watcher_thread()->has_crash_protection(),
1438       "must have crash protection");
1439 
1440   siglongjmp(_jmpbuf, 1);
1441 }
1442 
1443 void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
1444     Thread* thread) {
1445 
1446   if (thread != NULL &&
1447       thread->is_Watcher_thread() &&
1448       WatcherThread::watcher_thread()->has_crash_protection()) {
1449 
1450     if (sig == SIGSEGV || sig == SIGBUS) {
1451       WatcherThread::watcher_thread()->crash_protection()->restore();
1452     }
1453   }
1454 }
1455 
1456 #define check_with_errno(check_type, cond, msg)                             \
1457   do {                                                                      \
1458     int err = errno;                                                        \
1459     check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
1460                os::errno_name(err));                                        \
1461 } while (false)
1462 
1463 #define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
1464 #define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
1465 
1466 // POSIX unamed semaphores are not supported on OS X.
1467 #ifndef __APPLE__
1468 
1469 PosixSemaphore::PosixSemaphore(uint value) {
1470   int ret = sem_init(&_semaphore, 0, value);
1471 
1472   guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
1473 }
1474 
1475 PosixSemaphore::~PosixSemaphore() {
1476   sem_destroy(&_semaphore);
1477 }
1478 
1479 void PosixSemaphore::signal(uint count) {
1480   for (uint i = 0; i < count; i++) {
1481     int ret = sem_post(&_semaphore);
1482 
1483     assert_with_errno(ret == 0, "sem_post failed");
1484   }
1485 }
1486 
1487 void PosixSemaphore::wait() {
1488   int ret;
1489 
1490   do {
1491     ret = sem_wait(&_semaphore);
1492   } while (ret != 0 && errno == EINTR);
1493 
1494   assert_with_errno(ret == 0, "sem_wait failed");
1495 }
1496 
1497 bool PosixSemaphore::trywait() {
1498   int ret;
1499 
1500   do {
1501     ret = sem_trywait(&_semaphore);
1502   } while (ret != 0 && errno == EINTR);
1503 
1504   assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
1505 
1506   return ret == 0;
1507 }
1508 
1509 bool PosixSemaphore::timedwait(struct timespec ts) {
1510   while (true) {
1511     int result = sem_timedwait(&_semaphore, &ts);
1512     if (result == 0) {
1513       return true;
1514     } else if (errno == EINTR) {
1515       continue;
1516     } else if (errno == ETIMEDOUT) {
1517       return false;
1518     } else {
1519       assert_with_errno(false, "timedwait failed");
1520       return false;
1521     }
1522   }
1523 }
1524 
1525 #endif // __APPLE__