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