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     // NB: i is an unsigned int here because SA_RESETHAND is on some
 623     // systems 0x80000000, which is implicitly unsigned.  Assignining
 624     // it to an int field would be an overflow in unsigned-to-signed
 625     // conversion.
 626     unsigned int i;
 627     const char* s;
 628   } flaginfo [] = {
 629     { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
 630     { SA_ONSTACK,   "SA_ONSTACK"   },
 631     { SA_RESETHAND, "SA_RESETHAND" },
 632     { SA_RESTART,   "SA_RESTART"   },
 633     { SA_SIGINFO,   "SA_SIGINFO"   },
 634     { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
 635     { SA_NODEFER,   "SA_NODEFER"   },
 636 #ifdef AIX
 637     { SA_ONSTACK,   "SA_ONSTACK"   },
 638     { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
 639 #endif
 640     { 0, NULL }
 641   };
 642 
 643   for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
 644     if (flags & flaginfo[idx].i) {
 645       if (first) {
 646         jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
 647         first = false;
 648       } else {
 649         jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
 650       }
 651       const size_t len = strlen(p);
 652       p += len;
 653       remaining -= len;
 654     }
 655   }
 656 
 657   buffer[size - 1] = '\0';
 658 
 659   return buffer;
 660 }
 661 
 662 // Prints one-line description of a combination of sigaction.sa_flags.
 663 void os::Posix::print_sa_flags(outputStream* st, int flags) {
 664   char buffer[0x100];
 665   os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
 666   st->print("%s", buffer);
 667 }
 668 
 669 // Helper function for os::Posix::print_siginfo_...():
 670 // return a textual description for signal code.
 671 struct enum_sigcode_desc_t {
 672   const char* s_name;
 673   const char* s_desc;
 674 };
 675 
 676 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
 677 
 678   const struct {
 679     int sig; int code; const char* s_code; const char* s_desc;
 680   } t1 [] = {
 681     { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
 682     { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
 683     { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
 684     { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
 685     { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
 686     { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
 687     { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
 688     { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
 689 #if defined(IA64) && defined(LINUX)
 690     { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
 691     { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
 692 #endif
 693     { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
 694     { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
 695     { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
 696     { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
 697     { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
 698     { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
 699     { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
 700     { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
 701     { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
 702     { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
 703 #ifdef AIX
 704     // no explanation found what keyerr would be
 705     { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
 706 #endif
 707 #if defined(IA64) && !defined(AIX)
 708     { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
 709 #endif
 710 #if defined(__sparc) && defined(SOLARIS)
 711 // define Solaris Sparc M7 ADI SEGV signals
 712 #if !defined(SEGV_ACCADI)
 713 #define SEGV_ACCADI 3
 714 #endif
 715     { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
 716 #if !defined(SEGV_ACCDERR)
 717 #define SEGV_ACCDERR 4
 718 #endif
 719     { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
 720 #if !defined(SEGV_ACCPERR)
 721 #define SEGV_ACCPERR 5
 722 #endif
 723     { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
 724 #endif // defined(__sparc) && defined(SOLARIS)
 725     { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
 726     { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
 727     { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
 728     { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
 729     { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
 730     { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
 731     { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
 732     { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
 733     { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
 734     { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
 735     { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
 736 #ifdef SIGPOLL
 737     { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
 738     { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
 739     { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
 740     { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
 741     { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
 742 #endif
 743     { -1, -1, NULL, NULL }
 744   };
 745 
 746   // Codes valid in any signal context.
 747   const struct {
 748     int code; const char* s_code; const char* s_desc;
 749   } t2 [] = {
 750     { SI_USER,      "SI_USER",     "Signal sent by kill()." },
 751     { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
 752     { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
 753     { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
 754     { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
 755     // Linux specific
 756 #ifdef SI_TKILL
 757     { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
 758 #endif
 759 #ifdef SI_DETHREAD
 760     { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
 761 #endif
 762 #ifdef SI_KERNEL
 763     { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
 764 #endif
 765 #ifdef SI_SIGIO
 766     { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
 767 #endif
 768 
 769 #ifdef AIX
 770     { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
 771     { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
 772 #endif
 773 
 774 #ifdef __sun
 775     { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
 776     { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
 777     { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
 778 #endif
 779 
 780     { -1, NULL, NULL }
 781   };
 782 
 783   const char* s_code = NULL;
 784   const char* s_desc = NULL;
 785 
 786   for (int i = 0; t1[i].sig != -1; i ++) {
 787     if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
 788       s_code = t1[i].s_code;
 789       s_desc = t1[i].s_desc;
 790       break;
 791     }
 792   }
 793 
 794   if (s_code == NULL) {
 795     for (int i = 0; t2[i].s_code != NULL; i ++) {
 796       if (t2[i].code == si->si_code) {
 797         s_code = t2[i].s_code;
 798         s_desc = t2[i].s_desc;
 799       }
 800     }
 801   }
 802 
 803   if (s_code == NULL) {
 804     out->s_name = "unknown";
 805     out->s_desc = "unknown";
 806     return false;
 807   }
 808 
 809   out->s_name = s_code;
 810   out->s_desc = s_desc;
 811 
 812   return true;
 813 }
 814 
 815 // A POSIX conform, platform-independend siginfo print routine.
 816 // Short print out on one line.
 817 void os::Posix::print_siginfo_brief(outputStream* os, const siginfo_t* si) {
 818   char buf[20];
 819   os->print("siginfo: ");
 820 
 821   if (!si) {
 822     os->print("<null>");
 823     return;
 824   }
 825 
 826   // See print_siginfo_full() for details.
 827   const int sig = si->si_signo;
 828 
 829   os->print("si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
 830 
 831   enum_sigcode_desc_t ed;
 832   if (get_signal_code_description(si, &ed)) {
 833     os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
 834   } else {
 835     os->print(", si_code: %d (unknown)", si->si_code);
 836   }
 837 
 838   if (si->si_errno) {
 839     os->print(", si_errno: %d", si->si_errno);
 840   }
 841 
 842   const int me = (int) ::getpid();
 843   const int pid = (int) si->si_pid;
 844 
 845   if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
 846     if (IS_VALID_PID(pid) && pid != me) {
 847       os->print(", sent from pid: %d (uid: %d)", pid, (int) si->si_uid);
 848     }
 849   } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
 850              sig == SIGTRAP || sig == SIGFPE) {
 851     os->print(", si_addr: " PTR_FORMAT, si->si_addr);
 852 #ifdef SIGPOLL
 853   } else if (sig == SIGPOLL) {
 854     os->print(", si_band: " PTR64_FORMAT, (uint64_t)si->si_band);
 855 #endif
 856   } else if (sig == SIGCHLD) {
 857     os->print_cr(", si_pid: %d, si_uid: %d, si_status: %d", (int) si->si_pid, si->si_uid, si->si_status);
 858   }
 859 }
 860 
 861 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
 862   assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
 863 }
 864 
 865 /*
 866  * See the caveats for this class in os_posix.hpp
 867  * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
 868  * method and returns false. If none of the signals are raised, returns true.
 869  * The callback is supposed to provide the method that should be protected.
 870  */
 871 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
 872   sigset_t saved_sig_mask;
 873 
 874   assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
 875   assert(!WatcherThread::watcher_thread()->has_crash_protection(),
 876       "crash_protection already set?");
 877 
 878   // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
 879   // since on at least some systems (OS X) siglongjmp will restore the mask
 880   // for the process, not the thread
 881   pthread_sigmask(0, NULL, &saved_sig_mask);
 882   if (sigsetjmp(_jmpbuf, 0) == 0) {
 883     // make sure we can see in the signal handler that we have crash protection
 884     // installed
 885     WatcherThread::watcher_thread()->set_crash_protection(this);
 886     cb.call();
 887     // and clear the crash protection
 888     WatcherThread::watcher_thread()->set_crash_protection(NULL);
 889     return true;
 890   }
 891   // this happens when we siglongjmp() back
 892   pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
 893   WatcherThread::watcher_thread()->set_crash_protection(NULL);
 894   return false;
 895 }
 896 
 897 void os::WatcherThreadCrashProtection::restore() {
 898   assert(WatcherThread::watcher_thread()->has_crash_protection(),
 899       "must have crash protection");
 900 
 901   siglongjmp(_jmpbuf, 1);
 902 }
 903 
 904 void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
 905     Thread* thread) {
 906 
 907   if (thread != NULL &&
 908       thread->is_Watcher_thread() &&
 909       WatcherThread::watcher_thread()->has_crash_protection()) {
 910 
 911     if (sig == SIGSEGV || sig == SIGBUS) {
 912       WatcherThread::watcher_thread()->crash_protection()->restore();
 913     }
 914   }
 915 }