1 /*
   2  * Copyright (c) 1999, 2014, 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 "runtime/frame.inline.hpp"
  28 #include "runtime/interfaceSupport.hpp"
  29 #include "runtime/os.hpp"
  30 #include "utilities/vmError.hpp"
  31 
  32 #include <signal.h>
  33 #include <unistd.h>
  34 #include <sys/resource.h>
  35 #include <sys/utsname.h>
  36 #include <pthread.h>
  37 #include <signal.h>
  38 
  39 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  40 
  41 // Todo: provide a os::get_max_process_id() or similar. Number of processes
  42 // may have been configured, can be read more accurately from proc fs etc.
  43 #ifndef MAX_PID
  44 #define MAX_PID INT_MAX
  45 #endif
  46 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
  47 
  48 // Check core dump limit and report possible place where core can be found
  49 void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize) {
  50   int n;
  51   struct rlimit rlim;
  52   bool success;
  53 
  54   char *core_path = (char *)os::malloc(PATH_MAX, mtInternal);
  55   if (core_path == NULL) {
  56     VMError::report_coredump_status("", false);
  57     return;
  58   }
  59 
  60   n = get_core_path(core_path, PATH_MAX);
  61 
  62   if (n <= 0) {
  63     jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
  64     success = true;
  65 #ifdef LINUX
  66   } else if (core_path[0] == '"') { // redirect to user process
  67     jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
  68     success = true;
  69 #endif
  70   } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
  71     jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
  72     success = true;
  73   } else {
  74     switch(rlim.rlim_cur) {
  75       case RLIM_INFINITY:
  76         jio_snprintf(buffer, bufferSize, "%s", core_path);
  77         success = true;
  78         break;
  79       case 0:
  80         jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
  81         success = false;
  82         break;
  83       default:
  84         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));
  85         success = true;
  86         break;
  87     }
  88   }
  89 
  90   os::free(core_path);
  91   VMError::report_coredump_status(buffer, success);
  92 }
  93 
  94 int os::get_native_stack(address* stack, int frames, int toSkip) {
  95 #ifdef _NMT_NOINLINE_
  96   toSkip++;
  97 #endif
  98 
  99   int frame_idx = 0;
 100   int num_of_frames;  // number of frames captured
 101   frame fr = os::current_frame();
 102   while (fr.pc() && frame_idx < frames) {
 103     if (toSkip > 0) {
 104       toSkip --;
 105     } else {
 106       stack[frame_idx ++] = fr.pc();
 107     }
 108     if (fr.fp() == NULL || os::is_first_C_frame(&fr)
 109         ||fr.sender_pc() == NULL || fr.cb() != NULL) break;
 110 
 111     if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
 112       fr = os::get_sender_for_C_frame(&fr);
 113     } else {
 114       break;
 115     }
 116   }
 117   num_of_frames = frame_idx;
 118   for (; frame_idx < frames; frame_idx ++) {
 119     stack[frame_idx] = NULL;
 120   }
 121 
 122   return num_of_frames;
 123 }
 124 
 125 
 126 bool os::unsetenv(const char* name) {
 127   assert(name != NULL, "Null pointer");
 128   return (::unsetenv(name) == 0);
 129 }
 130 
 131 int os::get_last_error() {
 132   return errno;
 133 }
 134 
 135 bool os::is_debugger_attached() {
 136   // not implemented
 137   return false;
 138 }
 139 
 140 void os::wait_for_keypress_at_exit(void) {
 141   // don't do anything on posix platforms
 142   return;
 143 }
 144 
 145 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
 146 // so on posix, unmap the section at the start and at the end of the chunk that we mapped
 147 // rather than unmapping and remapping the whole chunk to get requested alignment.
 148 char* os::reserve_memory_aligned(size_t size, size_t alignment) {
 149   assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
 150       "Alignment must be a multiple of allocation granularity (page size)");
 151   assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
 152 
 153   size_t extra_size = size + alignment;
 154   assert(extra_size >= size, "overflow, size is too large to allow alignment");
 155 
 156   char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
 157 
 158   if (extra_base == NULL) {
 159     return NULL;
 160   }
 161 
 162   // Do manual alignment
 163   char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
 164 
 165   // [  |                                       |  ]
 166   // ^ extra_base
 167   //    ^ extra_base + begin_offset == aligned_base
 168   //     extra_base + begin_offset + size       ^
 169   //                       extra_base + extra_size ^
 170   // |<>| == begin_offset
 171   //                              end_offset == |<>|
 172   size_t begin_offset = aligned_base - extra_base;
 173   size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
 174 
 175   if (begin_offset > 0) {
 176       os::release_memory(extra_base, begin_offset);
 177   }
 178 
 179   if (end_offset > 0) {
 180       os::release_memory(extra_base + begin_offset + size, end_offset);
 181   }
 182 
 183   return aligned_base;
 184 }
 185 
 186 void os::Posix::print_load_average(outputStream* st) {
 187   st->print("load average:");
 188   double loadavg[3];
 189   os::loadavg(loadavg, 3);
 190   st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
 191   st->cr();
 192 }
 193 
 194 void os::Posix::print_rlimit_info(outputStream* st) {
 195   st->print("rlimit:");
 196   struct rlimit rlim;
 197 
 198   st->print(" STACK ");
 199   getrlimit(RLIMIT_STACK, &rlim);
 200   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 201   else st->print("%uk", rlim.rlim_cur >> 10);
 202 
 203   st->print(", CORE ");
 204   getrlimit(RLIMIT_CORE, &rlim);
 205   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 206   else st->print("%uk", rlim.rlim_cur >> 10);
 207 
 208   // Isn't there on solaris
 209 #if !defined(TARGET_OS_FAMILY_solaris) && !defined(TARGET_OS_FAMILY_aix)
 210   st->print(", NPROC ");
 211   getrlimit(RLIMIT_NPROC, &rlim);
 212   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 213   else st->print("%d", rlim.rlim_cur);
 214 #endif
 215 
 216   st->print(", NOFILE ");
 217   getrlimit(RLIMIT_NOFILE, &rlim);
 218   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 219   else st->print("%d", rlim.rlim_cur);
 220 
 221   st->print(", AS ");
 222   getrlimit(RLIMIT_AS, &rlim);
 223   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
 224   else st->print("%uk", rlim.rlim_cur >> 10);
 225   st->cr();
 226 }
 227 
 228 void os::Posix::print_uname_info(outputStream* st) {
 229   // kernel
 230   st->print("uname:");
 231   struct utsname name;
 232   uname(&name);
 233   st->print("%s ", name.sysname);
 234 #ifdef ASSERT
 235   st->print("%s ", name.nodename);
 236 #endif
 237   st->print("%s ", name.release);
 238   st->print("%s ", name.version);
 239   st->print("%s", name.machine);
 240   st->cr();
 241 }
 242 
 243 bool os::has_allocatable_memory_limit(julong* limit) {
 244   struct rlimit rlim;
 245   int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
 246   // if there was an error when calling getrlimit, assume that there is no limitation
 247   // on virtual memory.
 248   bool result;
 249   if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
 250     result = false;
 251   } else {
 252     *limit = (julong)rlim.rlim_cur;
 253     result = true;
 254   }
 255 #ifdef _LP64
 256   return result;
 257 #else
 258   // arbitrary virtual space limit for 32 bit Unices found by testing. If
 259   // getrlimit above returned a limit, bound it with this limit. Otherwise
 260   // directly use it.
 261   const julong max_virtual_limit = (julong)3800*M;
 262   if (result) {
 263     *limit = MIN2(*limit, max_virtual_limit);
 264   } else {
 265     *limit = max_virtual_limit;
 266   }
 267 
 268   // bound by actually allocatable memory. The algorithm uses two bounds, an
 269   // upper and a lower limit. The upper limit is the current highest amount of
 270   // memory that could not be allocated, the lower limit is the current highest
 271   // amount of memory that could be allocated.
 272   // The algorithm iteratively refines the result by halving the difference
 273   // between these limits, updating either the upper limit (if that value could
 274   // not be allocated) or the lower limit (if the that value could be allocated)
 275   // until the difference between these limits is "small".
 276 
 277   // the minimum amount of memory we care about allocating.
 278   const julong min_allocation_size = M;
 279 
 280   julong upper_limit = *limit;
 281 
 282   // first check a few trivial cases
 283   if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
 284     *limit = upper_limit;
 285   } else if (!is_allocatable(min_allocation_size)) {
 286     // we found that not even min_allocation_size is allocatable. Return it
 287     // anyway. There is no point to search for a better value any more.
 288     *limit = min_allocation_size;
 289   } else {
 290     // perform the binary search.
 291     julong lower_limit = min_allocation_size;
 292     while ((upper_limit - lower_limit) > min_allocation_size) {
 293       julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
 294       temp_limit = align_size_down_(temp_limit, min_allocation_size);
 295       if (is_allocatable(temp_limit)) {
 296         lower_limit = temp_limit;
 297       } else {
 298         upper_limit = temp_limit;
 299       }
 300     }
 301     *limit = lower_limit;
 302   }
 303   return true;
 304 #endif
 305 }
 306 
 307 const char* os::get_current_directory(char *buf, size_t buflen) {
 308   return getcwd(buf, buflen);
 309 }
 310 
 311 FILE* os::open(int fd, const char* mode) {
 312   return ::fdopen(fd, mode);
 313 }
 314 
 315 // Builds a platform dependent Agent_OnLoad_<lib_name> function name
 316 // which is used to find statically linked in agents.
 317 // Parameters:
 318 //            sym_name: Symbol in library we are looking for
 319 //            lib_name: Name of library to look in, NULL for shared libs.
 320 //            is_absolute_path == true if lib_name is absolute path to agent
 321 //                                     such as "/a/b/libL.so"
 322 //            == false if only the base name of the library is passed in
 323 //               such as "L"
 324 char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
 325                                     bool is_absolute_path) {
 326   char *agent_entry_name;
 327   size_t len;
 328   size_t name_len;
 329   size_t prefix_len = strlen(JNI_LIB_PREFIX);
 330   size_t suffix_len = strlen(JNI_LIB_SUFFIX);
 331   const char *start;
 332 
 333   if (lib_name != NULL) {
 334     len = name_len = strlen(lib_name);
 335     if (is_absolute_path) {
 336       // Need to strip path, prefix and suffix
 337       if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
 338         lib_name = ++start;
 339       }
 340       if (len <= (prefix_len + suffix_len)) {
 341         return NULL;
 342       }
 343       lib_name += prefix_len;
 344       name_len = strlen(lib_name) - suffix_len;
 345     }
 346   }
 347   len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
 348   agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
 349   if (agent_entry_name == NULL) {
 350     return NULL;
 351   }
 352   strcpy(agent_entry_name, sym_name);
 353   if (lib_name != NULL) {
 354     strcat(agent_entry_name, "_");
 355     strncat(agent_entry_name, lib_name, name_len);
 356   }
 357   return agent_entry_name;
 358 }
 359 
 360 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
 361   assert(thread == Thread::current(),  "thread consistency check");
 362 
 363   ParkEvent * const slp = thread->_SleepEvent ;
 364   slp->reset() ;
 365   OrderAccess::fence() ;
 366 
 367   if (interruptible) {
 368     jlong prevtime = javaTimeNanos();
 369 
 370     for (;;) {
 371       if (os::is_interrupted(thread, true)) {
 372         return OS_INTRPT;
 373       }
 374 
 375       jlong newtime = javaTimeNanos();
 376 
 377       if (newtime - prevtime < 0) {
 378         // time moving backwards, should only happen if no monotonic clock
 379         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 380         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
 381       } else {
 382         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 383       }
 384 
 385       if (millis <= 0) {
 386         return OS_OK;
 387       }
 388 
 389       prevtime = newtime;
 390 
 391       {
 392         assert(thread->is_Java_thread(), "sanity check");
 393         JavaThread *jt = (JavaThread *) thread;
 394         ThreadBlockInVM tbivm(jt);
 395         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
 396 
 397         jt->set_suspend_equivalent();
 398         // cleared by handle_special_suspend_equivalent_condition() or
 399         // java_suspend_self() via check_and_wait_while_suspended()
 400 
 401         slp->park(millis);
 402 
 403         // were we externally suspended while we were waiting?
 404         jt->check_and_wait_while_suspended();
 405       }
 406     }
 407   } else {
 408     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
 409     jlong prevtime = javaTimeNanos();
 410 
 411     for (;;) {
 412       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
 413       // the 1st iteration ...
 414       jlong newtime = javaTimeNanos();
 415 
 416       if (newtime - prevtime < 0) {
 417         // time moving backwards, should only happen if no monotonic clock
 418         // not a guarantee() because JVM should not abort on kernel/glibc bugs
 419         assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
 420       } else {
 421         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
 422       }
 423 
 424       if (millis <= 0) break ;
 425 
 426       prevtime = newtime;
 427       slp->park(millis);
 428     }
 429     return OS_OK ;
 430   }
 431 }
 432 
 433 ////////////////////////////////////////////////////////////////////////////////
 434 // interrupt support
 435 
 436 void os::interrupt(Thread* thread) {
 437   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 438     "possibility of dangling Thread pointer");
 439 
 440   OSThread* osthread = thread->osthread();
 441 
 442   if (!osthread->interrupted()) {
 443     osthread->set_interrupted(true);
 444     // More than one thread can get here with the same value of osthread,
 445     // resulting in multiple notifications.  We do, however, want the store
 446     // to interrupted() to be visible to other threads before we execute unpark().
 447     OrderAccess::fence();
 448     ParkEvent * const slp = thread->_SleepEvent ;
 449     if (slp != NULL) slp->unpark() ;
 450   }
 451 
 452   // For JSR166. Unpark even if interrupt status already was set
 453   if (thread->is_Java_thread())
 454     ((JavaThread*)thread)->parker()->unpark();
 455 
 456   ParkEvent * ev = thread->_ParkEvent ;
 457   if (ev != NULL) ev->unpark() ;
 458 
 459 }
 460 
 461 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
 462   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
 463     "possibility of dangling Thread pointer");
 464 
 465   OSThread* osthread = thread->osthread();
 466 
 467   bool interrupted = osthread->interrupted();
 468 
 469   // NOTE that since there is no "lock" around the interrupt and
 470   // is_interrupted operations, there is the possibility that the
 471   // interrupted flag (in osThread) will be "false" but that the
 472   // low-level events will be in the signaled state. This is
 473   // intentional. The effect of this is that Object.wait() and
 474   // LockSupport.park() will appear to have a spurious wakeup, which
 475   // is allowed and not harmful, and the possibility is so rare that
 476   // it is not worth the added complexity to add yet another lock.
 477   // For the sleep event an explicit reset is performed on entry
 478   // to os::sleep, so there is no early return. It has also been
 479   // recommended not to put the interrupted flag into the "event"
 480   // structure because it hides the issue.
 481   if (interrupted && clear_interrupted) {
 482     osthread->set_interrupted(false);
 483     // consider thread->_SleepEvent->reset() ... optional optimization
 484   }
 485 
 486   return interrupted;
 487 }
 488 
 489 // Returned string is a constant. For unknown signals "UNKNOWN" is returned.
 490 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
 491 
 492   static const struct {
 493     int sig; const char* name;
 494   }
 495   info[] =
 496   {
 497     {  SIGABRT,     "SIGABRT" },
 498 #ifdef SIGAIO
 499     {  SIGAIO,      "SIGAIO" },
 500 #endif
 501     {  SIGALRM,     "SIGALRM" },
 502 #ifdef SIGALRM1
 503     {  SIGALRM1,    "SIGALRM1" },
 504 #endif
 505     {  SIGBUS,      "SIGBUS" },
 506 #ifdef SIGCANCEL
 507     {  SIGCANCEL,   "SIGCANCEL" },
 508 #endif
 509     {  SIGCHLD,     "SIGCHLD" },
 510 #ifdef SIGCLD
 511     {  SIGCLD,      "SIGCLD" },
 512 #endif
 513     {  SIGCONT,     "SIGCONT" },
 514 #ifdef SIGCPUFAIL
 515     {  SIGCPUFAIL,  "SIGCPUFAIL" },
 516 #endif
 517 #ifdef SIGDANGER
 518     {  SIGDANGER,   "SIGDANGER" },
 519 #endif
 520 #ifdef SIGDIL
 521     {  SIGDIL,      "SIGDIL" },
 522 #endif
 523 #ifdef SIGEMT
 524     {  SIGEMT,      "SIGEMT" },
 525 #endif
 526     {  SIGFPE,      "SIGFPE" },
 527 #ifdef SIGFREEZE
 528     {  SIGFREEZE,   "SIGFREEZE" },
 529 #endif
 530 #ifdef SIGGFAULT
 531     {  SIGGFAULT,   "SIGGFAULT" },
 532 #endif
 533 #ifdef SIGGRANT
 534     {  SIGGRANT,    "SIGGRANT" },
 535 #endif
 536     {  SIGHUP,      "SIGHUP" },
 537     {  SIGILL,      "SIGILL" },
 538     {  SIGINT,      "SIGINT" },
 539 #ifdef SIGIO
 540     {  SIGIO,       "SIGIO" },
 541 #endif
 542 #ifdef SIGIOINT
 543     {  SIGIOINT,    "SIGIOINT" },
 544 #endif
 545 #ifdef SIGIOT
 546   // SIGIOT is there for BSD compatibility, but on most Unices just a
 547   // synonym for SIGABRT. The result should be "SIGABRT", not
 548   // "SIGIOT".
 549   #if (SIGIOT != SIGABRT )
 550     {  SIGIOT,      "SIGIOT" },
 551   #endif
 552 #endif
 553 #ifdef SIGKAP
 554     {  SIGKAP,      "SIGKAP" },
 555 #endif
 556     {  SIGKILL,     "SIGKILL" },
 557 #ifdef SIGLOST
 558     {  SIGLOST,     "SIGLOST" },
 559 #endif
 560 #ifdef SIGLWP
 561     {  SIGLWP,      "SIGLWP" },
 562 #endif
 563 #ifdef SIGLWPTIMER
 564     {  SIGLWPTIMER, "SIGLWPTIMER" },
 565 #endif
 566 #ifdef SIGMIGRATE
 567     {  SIGMIGRATE,  "SIGMIGRATE" },
 568 #endif
 569 #ifdef SIGMSG
 570     {  SIGMSG,      "SIGMSG" },
 571 #endif
 572     {  SIGPIPE,     "SIGPIPE" },
 573 #ifdef SIGPOLL
 574     {  SIGPOLL,     "SIGPOLL" },
 575 #endif
 576 #ifdef SIGPRE
 577     {  SIGPRE,      "SIGPRE" },
 578 #endif
 579     {  SIGPROF,     "SIGPROF" },
 580 #ifdef SIGPTY
 581     {  SIGPTY,      "SIGPTY" },
 582 #endif
 583 #ifdef SIGPWR
 584     {  SIGPWR,      "SIGPWR" },
 585 #endif
 586     {  SIGQUIT,     "SIGQUIT" },
 587 #ifdef SIGRECONFIG
 588     {  SIGRECONFIG, "SIGRECONFIG" },
 589 #endif
 590 #ifdef SIGRECOVERY
 591     {  SIGRECOVERY, "SIGRECOVERY" },
 592 #endif
 593 #ifdef SIGRESERVE
 594     {  SIGRESERVE,  "SIGRESERVE" },
 595 #endif
 596 #ifdef SIGRETRACT
 597     {  SIGRETRACT,  "SIGRETRACT" },
 598 #endif
 599 #ifdef SIGSAK
 600     {  SIGSAK,      "SIGSAK" },
 601 #endif
 602     {  SIGSEGV,     "SIGSEGV" },
 603 #ifdef SIGSOUND
 604     {  SIGSOUND,    "SIGSOUND" },
 605 #endif
 606     {  SIGSTOP,     "SIGSTOP" },
 607     {  SIGSYS,      "SIGSYS" },
 608 #ifdef SIGSYSERROR
 609     {  SIGSYSERROR, "SIGSYSERROR" },
 610 #endif
 611 #ifdef SIGTALRM
 612     {  SIGTALRM,    "SIGTALRM" },
 613 #endif
 614     {  SIGTERM,     "SIGTERM" },
 615 #ifdef SIGTHAW
 616     {  SIGTHAW,     "SIGTHAW" },
 617 #endif
 618     {  SIGTRAP,     "SIGTRAP" },
 619 #ifdef SIGTSTP
 620     {  SIGTSTP,     "SIGTSTP" },
 621 #endif
 622     {  SIGTTIN,     "SIGTTIN" },
 623     {  SIGTTOU,     "SIGTTOU" },
 624 #ifdef SIGURG
 625     {  SIGURG,      "SIGURG" },
 626 #endif
 627     {  SIGUSR1,     "SIGUSR1" },
 628     {  SIGUSR2,     "SIGUSR2" },
 629 #ifdef SIGVIRT
 630     {  SIGVIRT,     "SIGVIRT" },
 631 #endif
 632     {  SIGVTALRM,   "SIGVTALRM" },
 633 #ifdef SIGWAITING
 634     {  SIGWAITING,  "SIGWAITING" },
 635 #endif
 636 #ifdef SIGWINCH
 637     {  SIGWINCH,    "SIGWINCH" },
 638 #endif
 639 #ifdef SIGWINDOW
 640     {  SIGWINDOW,   "SIGWINDOW" },
 641 #endif
 642     {  SIGXCPU,     "SIGXCPU" },
 643     {  SIGXFSZ,     "SIGXFSZ" },
 644 #ifdef SIGXRES
 645     {  SIGXRES,     "SIGXRES" },
 646 #endif
 647     { -1, NULL }
 648   };
 649 
 650   const char* ret = NULL;
 651 
 652 #ifdef SIGRTMIN
 653   if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
 654     if (sig == SIGRTMIN) {
 655       ret = "SIGRTMIN";
 656     } else if (sig == SIGRTMAX) {
 657       ret = "SIGRTMAX";
 658     } else {
 659       jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
 660       return out;
 661     }
 662   }
 663 #endif
 664 
 665   if (sig > 0) {
 666     for (int idx = 0; info[idx].sig != -1; idx ++) {
 667       if (info[idx].sig == sig) {
 668         ret = info[idx].name;
 669         break;
 670       }
 671     }
 672   }
 673 
 674   if (!ret) {
 675     if (!is_valid_signal(sig)) {
 676       ret = "INVALID";
 677     } else {
 678       ret = "UNKNOWN";
 679     }
 680   }
 681 
 682   if (out && outlen > 0) {
 683     strncpy(out, ret, outlen);
 684     out[outlen - 1] = '\0';
 685   }
 686   return out;
 687 }
 688 
 689 // Returns true if signal number is valid.
 690 bool os::Posix::is_valid_signal(int sig) {
 691   // MacOS not really POSIX compliant: sigaddset does not return
 692   // an error for invalid signal numbers. However, MacOS does not
 693   // support real time signals and simply seems to have just 33
 694   // signals with no holes in the signal range.
 695 #ifdef __APPLE__
 696   return sig >= 1 && sig < NSIG;
 697 #else
 698   // Use sigaddset to check for signal validity.
 699   sigset_t set;
 700   if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
 701     return false;
 702   }
 703   return true;
 704 #endif
 705 }
 706 
 707 #define NUM_IMPORTANT_SIGS 32
 708 // Returns one-line short description of a signal set in a user provided buffer.
 709 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
 710   assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
 711   // Note: for shortness, just print out the first 32. That should
 712   // cover most of the useful ones, apart from realtime signals.
 713   for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
 714     const int rc = sigismember(set, sig);
 715     if (rc == -1 && errno == EINVAL) {
 716       buffer[sig-1] = '?';
 717     } else {
 718       buffer[sig-1] = rc == 0 ? '0' : '1';
 719     }
 720   }
 721   buffer[NUM_IMPORTANT_SIGS] = 0;
 722   return buffer;
 723 }
 724 
 725 // Prints one-line description of a signal set.
 726 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
 727   char buf[NUM_IMPORTANT_SIGS + 1];
 728   os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
 729   st->print("%s", buf);
 730 }
 731 
 732 // Writes one-line description of a combination of sigaction.sa_flags into a user
 733 // provided buffer. Returns that buffer.
 734 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
 735   char* p = buffer;
 736   size_t remaining = size;
 737   bool first = true;
 738   int idx = 0;
 739 
 740   assert(buffer, "invalid argument");
 741 
 742   if (size == 0) {
 743     return buffer;
 744   }
 745 
 746   strncpy(buffer, "none", size);
 747 
 748   const struct {
 749     int i;
 750     const char* s;
 751   } flaginfo [] = {
 752     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
 753     { SA_ONSTACK,   "SA_ONSTACK"   },
 754     { SA_RESETHAND, "SA_RESETHAND" },
 755     { SA_RESTART,   "SA_RESTART"   },
 756     { SA_SIGINFO,   "SA_SIGINFO"   },
 757     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
 758     { SA_NODEFER,   "SA_NODEFER"   },
 759 #ifdef AIX
 760     { SA_ONSTACK,   "SA_ONSTACK"   },
 761     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
 762 #endif
 763     { 0, NULL }
 764   };
 765 
 766   for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
 767     if (flags & flaginfo[idx].i) {
 768       if (first) {
 769         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
 770         first = false;
 771       } else {
 772         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
 773       }
 774       const size_t len = strlen(p);
 775       p += len;
 776       remaining -= len;
 777     }
 778   }
 779 
 780   buffer[size - 1] = '\0';
 781 
 782   return buffer;
 783 }
 784 
 785 // Prints one-line description of a combination of sigaction.sa_flags.
 786 void os::Posix::print_sa_flags(outputStream* st, int flags) {
 787   char buffer[0x100];
 788   os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
 789   st->print("%s", buffer);
 790 }
 791 
 792 // Helper function for os::Posix::print_siginfo_...():
 793 // return a textual description for signal code.
 794 struct enum_sigcode_desc_t {
 795   const char* s_name;
 796   const char* s_desc;
 797 };
 798 
 799 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
 800 
 801   const struct {
 802     int sig; int code; const char* s_code; const char* s_desc;
 803   } t1 [] = {
 804     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
 805     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
 806     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
 807     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
 808     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
 809     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
 810     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
 811     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
 812 #if defined(IA64) && defined(LINUX)
 813     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
 814     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
 815 #endif
 816     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
 817     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
 818     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
 819     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
 820     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
 821     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
 822     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
 823     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
 824     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
 825     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
 826 #ifdef AIX
 827     // no explanation found what keyerr would be
 828     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
 829 #endif
 830 #if defined(IA64) && !defined(AIX)
 831     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
 832 #endif
 833     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
 834     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
 835     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
 836     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
 837     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
 838     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
 839     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
 840     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
 841     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
 842     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
 843     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
 844 #ifdef SIGPOLL
 845     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
 846     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
 847     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
 848     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
 849     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
 850 #endif
 851     { -1, -1, NULL, NULL }
 852   };
 853 
 854   // Codes valid in any signal context.
 855   const struct {
 856     int code; const char* s_code; const char* s_desc;
 857   } t2 [] = {
 858     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
 859     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
 860     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
 861     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
 862     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
 863     // Linux specific
 864 #ifdef SI_TKILL
 865     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
 866 #endif
 867 #ifdef SI_DETHREAD
 868     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
 869 #endif
 870 #ifdef SI_KERNEL
 871     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
 872 #endif
 873 #ifdef SI_SIGIO
 874     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
 875 #endif
 876 
 877 #ifdef AIX
 878     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
 879     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
 880 #endif
 881 
 882 #ifdef __sun
 883     { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
 884     { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
 885     { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
 886 #endif
 887 
 888     { -1, NULL, NULL }
 889   };
 890 
 891   const char* s_code = NULL;
 892   const char* s_desc = NULL;
 893 
 894   for (int i = 0; t1[i].sig != -1; i ++) {
 895     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
 896       s_code = t1[i].s_code;
 897       s_desc = t1[i].s_desc;
 898       break;
 899     }
 900   }
 901 
 902   if (s_code == NULL) {
 903     for (int i = 0; t2[i].s_code != NULL; i ++) {
 904       if (t2[i].code == si->si_code) {
 905         s_code = t2[i].s_code;
 906         s_desc = t2[i].s_desc;
 907       }
 908     }
 909   }
 910 
 911   if (s_code == NULL) {
 912     out->s_name = "unknown";
 913     out->s_desc = "unknown";
 914     return false;
 915   }
 916 
 917   out->s_name = s_code;
 918   out->s_desc = s_desc;
 919 
 920   return true;
 921 }
 922 
 923 // A POSIX conform, platform-independend siginfo print routine.
 924 // Short print out on one line.
 925 void os::Posix::print_siginfo_brief(outputStream* os, const siginfo_t* si) {
 926   char buf[20];
 927   os->print("siginfo: ");
 928 
 929   if (!si) {
 930     os->print("<null>");
 931     return;
 932   }
 933 
 934   // See print_siginfo_full() for details.
 935   const int sig = si->si_signo;
 936 
 937   os->print("si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
 938 
 939   enum_sigcode_desc_t ed;
 940   if (get_signal_code_description(si, &ed)) {
 941     os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
 942   } else {
 943     os->print(", si_code: %d (unknown)", si->si_code);
 944   }
 945 
 946   if (si->si_errno) {
 947     os->print(", si_errno: %d", si->si_errno);
 948   }
 949 
 950   const int me = (int) ::getpid();
 951   const int pid = (int) si->si_pid;
 952 
 953   if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
 954     if (IS_VALID_PID(pid) && pid != me) {
 955       os->print(", sent from pid: %d (uid: %d)", pid, (int) si->si_uid);
 956     }
 957   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
 958              sig == SIGTRAP || sig == SIGFPE) {
 959     os->print(", si_addr: " PTR_FORMAT, si->si_addr);
 960 #ifdef SIGPOLL
 961   } else if (sig == SIGPOLL) {
 962     os->print(", si_band: " PTR64_FORMAT, (uint64_t)si->si_band);
 963 #endif
 964   } else if (sig == SIGCHLD) {
 965     os->print_cr(", si_pid: %d, si_uid: %d, si_status: %d", (int) si->si_pid, si->si_uid, si->si_status);
 966   }
 967 }
 968 
 969 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
 970   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
 971 }
 972 
 973 /*
 974  * See the caveats for this class in os_posix.hpp
 975  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
 976  * method and returns false. If none of the signals are raised, returns true.
 977  * The callback is supposed to provide the method that should be protected.
 978  */
 979 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
 980   sigset_t saved_sig_mask;
 981 
 982   assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
 983   assert(!WatcherThread::watcher_thread()->has_crash_protection(),
 984       "crash_protection already set?");
 985 
 986   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
 987   // since on at least some systems (OS X) siglongjmp will restore the mask
 988   // for the process, not the thread
 989   pthread_sigmask(0, NULL, &saved_sig_mask);
 990   if (sigsetjmp(_jmpbuf, 0) == 0) {
 991     // make sure we can see in the signal handler that we have crash protection
 992     // installed
 993     WatcherThread::watcher_thread()->set_crash_protection(this);
 994     cb.call();
 995     // and clear the crash protection
 996     WatcherThread::watcher_thread()->set_crash_protection(NULL);
 997     return true;
 998   }
 999   // this happens when we siglongjmp() back
1000   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1001   WatcherThread::watcher_thread()->set_crash_protection(NULL);
1002   return false;
1003 }
1004 
1005 void os::WatcherThreadCrashProtection::restore() {
1006   assert(WatcherThread::watcher_thread()->has_crash_protection(),
1007       "must have crash protection");
1008 
1009   siglongjmp(_jmpbuf, 1);
1010 }
1011 
1012 void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
1013     Thread* thread) {
1014 
1015   if (thread != NULL &&
1016       thread->is_Watcher_thread() &&
1017       WatcherThread::watcher_thread()->has_crash_protection()) {
1018 
1019     if (sig == SIGSEGV || sig == SIGBUS) {
1020       WatcherThread::watcher_thread()->crash_protection()->restore();
1021     }
1022   }
1023 }