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