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