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