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