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