1 /*
   2  * Copyright (c) 2003, 2019, 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 <fcntl.h>
  26 #include "precompiled.hpp"
  27 #include "compiler/compileBroker.hpp"
  28 #include "gc_interface/collectedHeap.hpp"
  29 #if INCLUDE_JFR
  30 #include "jfr/jfrEvents.hpp"
  31 #endif
  32 #include "prims/whitebox.hpp"
  33 #include "runtime/arguments.hpp"
  34 #include "runtime/frame.inline.hpp"
  35 #include "runtime/init.hpp"
  36 #include "runtime/os.hpp"
  37 #include "runtime/thread.inline.hpp"
  38 #include "runtime/vmThread.hpp"
  39 #include "runtime/vm_operations.hpp"
  40 #include "services/memTracker.hpp"
  41 #include "utilities/debug.hpp"
  42 #include "utilities/decoder.hpp"
  43 #include "utilities/defaultStream.hpp"
  44 #include "utilities/errorReporter.hpp"
  45 #include "utilities/events.hpp"
  46 #include "utilities/top.hpp"
  47 #include "utilities/vmError.hpp"
  48 #include "utilities/macros.hpp"
  49 #if INCLUDE_JFR
  50 #include "jfr/jfr.hpp"
  51 #endif
  52 
  53 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  54 
  55 // List of environment variables that should be reported in error log file.
  56 const char *env_list[] = {
  57   // All platforms
  58   "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
  59   "JAVA_COMPILER", "PATH", "USERNAME",
  60 
  61   // Env variables that are defined on Solaris/Linux/BSD
  62   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
  63   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
  64 
  65   // defined on Linux
  66   "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
  67 
  68   // defined on Darwin
  69   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
  70   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
  71   "DYLD_INSERT_LIBRARIES",
  72 
  73   // defined on Windows
  74   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
  75 
  76   (const char *)0
  77 };
  78 
  79 // Fatal error handler for internal errors and crashes.
  80 //
  81 // The default behavior of fatal error handler is to print a brief message
  82 // to standard out (defaultStream::output_fd()), then save detailed information
  83 // into an error report file (hs_err_pid<pid>.log) and abort VM. If multiple
  84 // threads are having troubles at the same time, only one error is reported.
  85 // The thread that is reporting error will abort VM when it is done, all other
  86 // threads are blocked forever inside report_and_die().
  87 
  88 // Constructor for crashes
  89 VMError::VMError(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context) {
  90     _thread = thread;
  91     _id = sig;
  92     _pc   = pc;
  93     _siginfo = siginfo;
  94     _context = context;
  95 
  96     _verbose = false;
  97     _current_step = 0;
  98     _current_step_info = NULL;
  99 
 100     _message = NULL;
 101     _detail_msg = NULL;
 102     _filename = NULL;
 103     _lineno = 0;
 104 
 105     _size = 0;
 106 }
 107 
 108 // Constructor for internal errors
 109 VMError::VMError(Thread* thread, const char* filename, int lineno,
 110                  const char* message, const char * detail_msg)
 111 {
 112   _thread = thread;
 113   _id = INTERNAL_ERROR;     // Value that's not an OS exception/signal
 114   _filename = filename;
 115   _lineno = lineno;
 116   _message = message;
 117   _detail_msg = detail_msg;
 118 
 119   _verbose = false;
 120   _current_step = 0;
 121   _current_step_info = NULL;
 122 
 123   _pc = NULL;
 124   _siginfo = NULL;
 125   _context = NULL;
 126 
 127   _size = 0;
 128 }
 129 
 130 // Constructor for OOM errors
 131 VMError::VMError(Thread* thread, const char* filename, int lineno, size_t size,
 132                  VMErrorType vm_err_type, const char* message) {
 133     _thread = thread;
 134     _id = vm_err_type; // Value that's not an OS exception/signal
 135     _filename = filename;
 136     _lineno = lineno;
 137     _message = message;
 138     _detail_msg = NULL;
 139 
 140     _verbose = false;
 141     _current_step = 0;
 142     _current_step_info = NULL;
 143 
 144     _pc = NULL;
 145     _siginfo = NULL;
 146     _context = NULL;
 147 
 148     _size = size;
 149 }
 150 
 151 
 152 // Constructor for non-fatal errors
 153 VMError::VMError(const char* message) {
 154     _thread = NULL;
 155     _id = INTERNAL_ERROR;     // Value that's not an OS exception/signal
 156     _filename = NULL;
 157     _lineno = 0;
 158     _message = message;
 159     _detail_msg = NULL;
 160 
 161     _verbose = false;
 162     _current_step = 0;
 163     _current_step_info = NULL;
 164 
 165     _pc = NULL;
 166     _siginfo = NULL;
 167     _context = NULL;
 168 
 169     _size = 0;
 170 }
 171 
 172 // -XX:OnError=<string>, where <string> can be a list of commands, separated
 173 // by ';'. "%p" is replaced by current process id (pid); "%%" is replaced by
 174 // a single "%". Some examples:
 175 //
 176 // -XX:OnError="pmap %p"                // show memory map
 177 // -XX:OnError="gcore %p; dbx - %p"     // dump core and launch debugger
 178 // -XX:OnError="cat hs_err_pid%p.log | mail my_email@sun.com"
 179 // -XX:OnError="kill -9 %p"             // ?#!@#
 180 
 181 // A simple parser for -XX:OnError, usage:
 182 //  ptr = OnError;
 183 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
 184 //     ... ...
 185 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
 186   if (ptr == NULL || *ptr == NULL) return NULL;
 187 
 188   const char* cmd = *ptr;
 189 
 190   // skip leading blanks or ';'
 191   while (*cmd == ' ' || *cmd == ';') cmd++;
 192 
 193   if (*cmd == '\0') return NULL;
 194 
 195   const char * cmdend = cmd;
 196   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
 197 
 198   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
 199 
 200   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
 201   return buf;
 202 }
 203 
 204 
 205 static void print_bug_submit_message(outputStream *out, Thread *thread) {
 206   if (out == NULL) return;
 207   out->print_raw_cr("# If you would like to submit a bug report, please visit:");
 208   out->print_raw   ("#   ");
 209   out->print_raw_cr(Arguments::java_vendor_url_bug());
 210   // If the crash is in native code, encourage user to submit a bug to the
 211   // provider of that code.
 212   if (thread && thread->is_Java_thread() &&
 213       !thread->is_hidden_from_external_view()) {
 214     JavaThread* jt = (JavaThread*)thread;
 215     if (jt->thread_state() == _thread_in_native) {
 216       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
 217     }
 218   }
 219   out->print_raw_cr("#");
 220 }
 221 
 222 bool VMError::coredump_status;
 223 char VMError::coredump_message[O_BUFLEN];
 224 
 225 void VMError::report_coredump_status(const char* message, bool status) {
 226   coredump_status = status;
 227   strncpy(coredump_message, message, sizeof(coredump_message));
 228   coredump_message[sizeof(coredump_message)-1] = 0;
 229 }
 230 
 231 
 232 // Return a string to describe the error
 233 char* VMError::error_string(char* buf, int buflen) {
 234   char signame_buf[64];
 235   const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
 236 
 237   if (signame) {
 238     jio_snprintf(buf, buflen,
 239                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" INTPTR_FORMAT,
 240                  signame, _id, _pc,
 241                  os::current_process_id(), os::current_thread_id());
 242   } else if (_filename != NULL && _lineno > 0) {
 243     // skip directory names
 244     char separator = os::file_separator()[0];
 245     const char *p = strrchr(_filename, separator);
 246     int n = jio_snprintf(buf, buflen,
 247                          "Internal Error at %s:%d, pid=%d, tid=" INTPTR_FORMAT,
 248                          p ? p + 1 : _filename, _lineno,
 249                          os::current_process_id(), os::current_thread_id());
 250     if (n >= 0 && n < buflen && _message) {
 251       if (_detail_msg) {
 252         jio_snprintf(buf + n, buflen - n, "%s%s: %s",
 253                      os::line_separator(), _message, _detail_msg);
 254       } else {
 255         jio_snprintf(buf + n, buflen - n, "%sError: %s",
 256                      os::line_separator(), _message);
 257       }
 258     }
 259   } else {
 260     jio_snprintf(buf, buflen,
 261                  "Internal Error (0x%x), pid=%d, tid=" INTPTR_FORMAT,
 262                  _id, os::current_process_id(), os::current_thread_id());
 263   }
 264 
 265   return buf;
 266 }
 267 
 268 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
 269                                 char* buf, int buflen, bool verbose) {
 270 #ifdef ZERO
 271   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
 272     // StackFrameStream uses the frame anchor, which may not have
 273     // been set up.  This can be done at any time in Zero, however,
 274     // so if it hasn't been set up then we just set it up now and
 275     // clear it again when we're done.
 276     bool has_last_Java_frame = jt->has_last_Java_frame();
 277     if (!has_last_Java_frame)
 278       jt->set_last_Java_frame();
 279     st->print("Java frames:");
 280 
 281     // If the top frame is a Shark frame and the frame anchor isn't
 282     // set up then it's possible that the information in the frame
 283     // is garbage: it could be from a previous decache, or it could
 284     // simply have never been written.  So we print a warning...
 285     StackFrameStream sfs(jt);
 286     if (!has_last_Java_frame && !sfs.is_done()) {
 287       if (sfs.current()->zeroframe()->is_shark_frame()) {
 288         st->print(" (TOP FRAME MAY BE JUNK)");
 289       }
 290     }
 291     st->cr();
 292 
 293     // Print the frames
 294     for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
 295       sfs.current()->zero_print_on_error(i, st, buf, buflen);
 296       st->cr();
 297     }
 298 
 299     // Reset the frame anchor if necessary
 300     if (!has_last_Java_frame)
 301       jt->reset_last_Java_frame();
 302   }
 303 #else
 304   if (jt->has_last_Java_frame()) {
 305     st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
 306     for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
 307       sfs.current()->print_on_error(st, buf, buflen, verbose);
 308       st->cr();
 309     }
 310   }
 311 #endif // ZERO
 312 }
 313 
 314 static void print_oom_reasons(outputStream* st) {
 315   st->print_cr("# Possible reasons:");
 316   st->print_cr("#   The system is out of physical RAM or swap space");
 317   if (UseCompressedOops) {
 318     st->print_cr("#   The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
 319   }
 320   if (LogBytesPerWord == 2) {
 321     st->print_cr("#   In 32 bit mode, the process size limit was hit");
 322   }
 323   st->print_cr("# Possible solutions:");
 324   st->print_cr("#   Reduce memory load on the system");
 325   st->print_cr("#   Increase physical memory or swap space");
 326   st->print_cr("#   Check if swap backing store is full");
 327   if (LogBytesPerWord == 2) {
 328     st->print_cr("#   Use 64 bit Java on a 64 bit OS");
 329   }
 330   st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
 331   st->print_cr("#   Decrease number of Java threads");
 332   st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
 333   st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
 334   if (UseCompressedOops) {
 335     switch (Universe::narrow_oop_mode()) {
 336       case Universe::UnscaledNarrowOop:
 337         st->print_cr("#   JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
 338         st->print_cr("#     placed in the first 4GB address space. The Java Heap base address is the");
 339         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 340         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
 341         break;
 342       case Universe::ZeroBasedNarrowOop:
 343         st->print_cr("#   JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
 344         st->print_cr("#     placed in the first 32GB address space. The Java Heap base address is the");
 345         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 346         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
 347         break;
 348       default:
 349         break;
 350     }
 351   }
 352   st->print_cr("# This output file may be truncated or incomplete.");
 353 }
 354 
 355 // This is the main function to report a fatal error. Only one thread can
 356 // call this function, so we don't need to worry about MT-safety. But it's
 357 // possible that the error handler itself may crash or die on an internal
 358 // error, for example, when the stack/heap is badly damaged. We must be
 359 // able to handle recursive errors that happen inside error handler.
 360 //
 361 // Error reporting is done in several steps. If a crash or internal error
 362 // occurred when reporting an error, the nested signal/exception handler
 363 // can skip steps that are already (or partially) done. Error reporting will
 364 // continue from the next step. This allows us to retrieve and print
 365 // information that may be unsafe to get after a fatal error. If it happens,
 366 // you may find nested report_and_die() frames when you look at the stack
 367 // in a debugger.
 368 //
 369 // In general, a hang in error handler is much worse than a crash or internal
 370 // error, as it's harder to recover from a hang. Deadlock can happen if we
 371 // try to grab a lock that is already owned by current thread, or if the
 372 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 373 // error handler and all the functions it called should avoid grabbing any
 374 // lock. An important thing to notice is that memory allocation needs a lock.
 375 //
 376 // We should avoid using large stack allocated buffers. Many errors happen
 377 // when stack space is already low. Making things even worse is that there
 378 // could be nested report_and_die() calls on stack (see above). Only one
 379 // thread can report error, so large buffers are statically allocated in data
 380 // segment.
 381 
 382 void VMError::report(outputStream* st) {
 383 # define BEGIN if (_current_step == 0) { _current_step = 1;
 384 # define STEP(n, s) } if (_current_step < n) { _current_step = n; _current_step_info = s;
 385 # define END }
 386 
 387   // don't allocate large buffer on stack
 388   static char buf[O_BUFLEN];
 389 
 390   BEGIN
 391 
 392   STEP(10, "(printing fatal error message)")
 393 
 394     st->print_cr("#");
 395     if (should_report_bug(_id)) {
 396       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 397     } else {
 398       st->print_cr("# There is insufficient memory for the Java "
 399                    "Runtime Environment to continue.");
 400     }
 401 
 402   STEP(15, "(printing type of error)")
 403 
 404      switch(_id) {
 405        case OOM_MALLOC_ERROR:
 406        case OOM_MMAP_ERROR:
 407          if (_size) {
 408            st->print("# Native memory allocation ");
 409            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 410                                                  "(mmap) failed to map ");
 411            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
 412            st->print("%s", buf);
 413            st->print(" bytes");
 414            if (_message != NULL) {
 415              st->print(" for ");
 416              st->print("%s", _message);
 417            }
 418            st->cr();
 419          } else {
 420            if (_message != NULL)
 421              st->print("# ");
 422              st->print_cr("%s", _message);
 423          }
 424          // In error file give some solutions
 425          if (_verbose) {
 426            print_oom_reasons(st);
 427          } else {
 428            return;  // that's enough for the screen
 429          }
 430          break;
 431        case INTERNAL_ERROR:
 432        default:
 433          break;
 434      }
 435 
 436   STEP(20, "(printing exception/signal name)")
 437 
 438      st->print_cr("#");
 439      st->print("#  ");
 440      // Is it an OS exception/signal?
 441      if (os::exception_name(_id, buf, sizeof(buf))) {
 442        st->print("%s", buf);
 443        st->print(" (0x%x)", _id);                // signal number
 444        st->print(" at pc=" PTR_FORMAT, _pc);
 445      } else {
 446        if (should_report_bug(_id)) {
 447          st->print("Internal Error");
 448        } else {
 449          st->print("Out of Memory Error");
 450        }
 451        if (_filename != NULL && _lineno > 0) {
 452 #ifdef PRODUCT
 453          // In product mode chop off pathname?
 454          char separator = os::file_separator()[0];
 455          const char *p = strrchr(_filename, separator);
 456          const char *file = p ? p+1 : _filename;
 457 #else
 458          const char *file = _filename;
 459 #endif
 460          size_t len = strlen(file);
 461          size_t buflen = sizeof(buf);
 462 
 463          strncpy(buf, file, buflen);
 464          if (len + 10 < buflen) {
 465            sprintf(buf + len, ":%d", _lineno);
 466          }
 467          st->print(" (%s)", buf);
 468        } else {
 469          st->print(" (0x%x)", _id);
 470        }
 471      }
 472 
 473   STEP(30, "(printing current thread and pid)")
 474 
 475      // process id, thread id
 476      st->print(", pid=%d", os::current_process_id());
 477      st->print(", tid=" INTPTR_FORMAT, os::current_thread_id());
 478      st->cr();
 479 
 480   STEP(40, "(printing error message)")
 481 
 482      if (should_report_bug(_id)) {  // already printed the message.
 483        // error message
 484        if (_detail_msg) {
 485          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
 486        } else if (_message) {
 487          st->print_cr("#  Error: %s", _message);
 488        }
 489     }
 490 
 491   STEP(50, "(printing Java version string)")
 492 
 493      // VM version
 494      st->print_cr("#");
 495      JDK_Version::current().to_string(buf, sizeof(buf));
 496      const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 497                                   JDK_Version::runtime_name() : "";
 498      const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 499                                   JDK_Version::runtime_version() : "";
 500      st->print_cr("# JRE version: %s (%s) (build %s)", runtime_name, buf, runtime_version);
 501      st->print_cr("# Java VM: %s (%s %s %s %s)",
 502                    Abstract_VM_Version::vm_name(),
 503                    Abstract_VM_Version::vm_release(),
 504                    Abstract_VM_Version::vm_info_string(),
 505                    Abstract_VM_Version::vm_platform_string(),
 506                    UseCompressedOops ? "compressed oops" : ""
 507                  );
 508 
 509   STEP(60, "(printing problematic frame)")
 510 
 511      // Print current frame if we have a context (i.e. it's a crash)
 512      if (_context) {
 513        st->print_cr("# Problematic frame:");
 514        st->print("# ");
 515        frame fr = os::fetch_frame_from_context(_context);
 516        fr.print_on_error(st, buf, sizeof(buf));
 517        st->cr();
 518        st->print_cr("#");
 519      }
 520   STEP(63, "(printing core file information)")
 521     st->print("# ");
 522     if (coredump_status) {
 523       st->print("Core dump written. Default location: %s", coredump_message);
 524     } else {
 525       st->print("Failed to write core dump. %s", coredump_message);
 526     }
 527     st->cr();
 528     st->print_cr("#");
 529 
 530   STEP(65, "(printing bug submit message)")
 531 
 532      if (should_report_bug(_id) && _verbose) {
 533        print_bug_submit_message(st, _thread);
 534      }
 535 
 536   STEP(70, "(printing thread)" )
 537 
 538      if (_verbose) {
 539        st->cr();
 540        st->print_cr("---------------  T H R E A D  ---------------");
 541        st->cr();
 542      }
 543 
 544   STEP(80, "(printing current thread)" )
 545 
 546      // current thread
 547      if (_verbose) {
 548        if (_thread) {
 549          st->print("Current thread (" PTR_FORMAT "):  ", _thread);
 550          _thread->print_on_error(st, buf, sizeof(buf));
 551          st->cr();
 552        } else {
 553          st->print_cr("Current thread is native thread");
 554        }
 555        st->cr();
 556      }
 557 
 558   STEP(90, "(printing siginfo)" )
 559 
 560      // signal no, signal code, address that caused the fault
 561      if (_verbose && _siginfo) {
 562        os::print_siginfo(st, _siginfo);
 563        st->cr();
 564      }
 565 
 566   STEP(100, "(printing registers, top of stack, instructions near pc)")
 567 
 568      // registers, top of stack, instructions near pc
 569      if (_verbose && _context) {
 570        os::print_context(st, _context);
 571        st->cr();
 572      }
 573 
 574   STEP(105, "(printing register info)")
 575 
 576      // decode register contents if possible
 577      if (_verbose && _context && Universe::is_fully_initialized()) {
 578        os::print_register_info(st, _context);
 579        st->cr();
 580      }
 581 
 582   STEP(110, "(printing stack bounds)" )
 583 
 584      if (_verbose) {
 585        st->print("Stack: ");
 586 
 587        address stack_top;
 588        size_t stack_size;
 589 
 590        if (_thread) {
 591           stack_top = _thread->stack_base();
 592           stack_size = _thread->stack_size();
 593        } else {
 594           stack_top = os::current_stack_base();
 595           stack_size = os::current_stack_size();
 596        }
 597 
 598        address stack_bottom = stack_top - stack_size;
 599        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", stack_bottom, stack_top);
 600 
 601        frame fr = _context ? os::fetch_frame_from_context(_context)
 602                            : os::current_frame();
 603 
 604        if (fr.sp()) {
 605          st->print(",  sp=" PTR_FORMAT, fr.sp());
 606          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 607          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 608        }
 609 
 610        st->cr();
 611      }
 612 
 613   STEP(120, "(printing native stack)" )
 614 
 615    if (_verbose) {
 616      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
 617        // We have printed the native stack in platform-specific code
 618        // Windows/x64 needs special handling.
 619      } else {
 620        frame fr = _context ? os::fetch_frame_from_context(_context)
 621                            : os::current_frame();
 622 
 623        print_native_stack(st, fr, _thread, buf, sizeof(buf));
 624      }
 625    }
 626 
 627   STEP(130, "(printing Java stack)" )
 628 
 629      if (_verbose && _thread && _thread->is_Java_thread()) {
 630        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
 631      }
 632 
 633   STEP(135, "(printing target Java thread stack)" )
 634 
 635      // printing Java thread stack trace if it is involved in GC crash
 636      if (_verbose && _thread && (_thread->is_Named_thread())) {
 637        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
 638        if (jt != NULL) {
 639          st->print_cr("JavaThread " PTR_FORMAT " (nid = " UINTX_FORMAT ") was being processed", jt, jt->osthread()->thread_id());
 640          print_stack_trace(st, jt, buf, sizeof(buf), true);
 641        }
 642      }
 643 
 644   STEP(140, "(printing VM operation)" )
 645 
 646      if (_verbose && _thread && _thread->is_VM_thread()) {
 647         VMThread* t = (VMThread*)_thread;
 648         VM_Operation* op = t->vm_operation();
 649         if (op) {
 650           op->print_on_error(st);
 651           st->cr();
 652           st->cr();
 653         }
 654      }
 655 
 656   STEP(150, "(printing current compile task)" )
 657 
 658      if (_verbose && _thread && _thread->is_Compiler_thread()) {
 659         CompilerThread* t = (CompilerThread*)_thread;
 660         if (t->task()) {
 661            st->cr();
 662            st->print_cr("Current CompileTask:");
 663            t->task()->print_line_on_error(st, buf, sizeof(buf));
 664            st->cr();
 665         }
 666      }
 667 
 668   STEP(160, "(printing process)" )
 669 
 670      if (_verbose) {
 671        st->cr();
 672        st->print_cr("---------------  P R O C E S S  ---------------");
 673        st->cr();
 674      }
 675 
 676   STEP(170, "(printing all threads)" )
 677 
 678      // all threads
 679      if (_verbose && _thread) {
 680        Threads::print_on_error(st, _thread, buf, sizeof(buf));
 681        st->cr();
 682      }
 683 
 684   STEP(175, "(printing VM state)" )
 685 
 686      if (_verbose) {
 687        // Safepoint state
 688        st->print("VM state:");
 689 
 690        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
 691        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
 692        else st->print("not at safepoint");
 693 
 694        // Also see if error occurred during initialization or shutdown
 695        if (!Universe::is_fully_initialized()) {
 696          st->print(" (not fully initialized)");
 697        } else if (VM_Exit::vm_exited()) {
 698          st->print(" (shutting down)");
 699        } else {
 700          st->print(" (normal execution)");
 701        }
 702        st->cr();
 703        st->cr();
 704      }
 705 
 706   STEP(180, "(printing owned locks on error)" )
 707 
 708      // mutexes/monitors that currently have an owner
 709      if (_verbose) {
 710        print_owned_locks_on_error(st);
 711        st->cr();
 712      }
 713 
 714   STEP(182, "(printing number of OutOfMemoryError and StackOverflow exceptions)")
 715 
 716      if (_verbose && Exceptions::has_exception_counts()) {
 717        st->print_cr("OutOfMemory and StackOverflow Exception counts:");
 718        Exceptions::print_exception_counts_on_error(st);
 719        st->cr();
 720      }
 721 
 722   STEP(185, "(printing compressed oops mode")
 723 
 724      if (_verbose && UseCompressedOops) {
 725        Universe::print_compressed_oops_mode(st);
 726        if (UseCompressedClassPointers) {
 727          Metaspace::print_compressed_class_space(st);
 728        }
 729        st->cr();
 730      }
 731 
 732   STEP(190, "(printing heap information)" )
 733 
 734      if (_verbose && Universe::is_fully_initialized()) {
 735        Universe::heap()->print_on_error(st);
 736        st->cr();
 737 
 738        st->print_cr("Polling page: " INTPTR_FORMAT, os::get_polling_page());
 739        st->cr();
 740      }
 741 
 742   STEP(195, "(printing code cache information)" )
 743 
 744      if (_verbose && Universe::is_fully_initialized()) {
 745        // print code cache information before vm abort
 746        CodeCache::print_summary(st);
 747        st->cr();
 748      }
 749 
 750   STEP(200, "(printing ring buffers)" )
 751 
 752      if (_verbose) {
 753        Events::print_all(st);
 754        st->cr();
 755      }
 756 
 757   STEP(205, "(printing dynamic libraries)" )
 758 
 759      if (_verbose) {
 760        // dynamic libraries, or memory map
 761        os::print_dll_info(st);
 762        st->cr();
 763      }
 764 
 765   STEP(210, "(printing VM options)" )
 766 
 767      if (_verbose) {
 768        // VM options
 769        Arguments::print_on(st);
 770        st->cr();
 771      }
 772 
 773   STEP(215, "(printing warning if internal testing API used)" )
 774 
 775      if (WhiteBox::used()) {
 776        st->print_cr("Unsupported internal testing APIs have been used.");
 777        st->cr();
 778      }
 779 
 780   STEP(220, "(printing environment variables)" )
 781 
 782      if (_verbose) {
 783        os::print_environment_variables(st, env_list, buf, sizeof(buf));
 784        st->cr();
 785      }
 786 
 787   STEP(225, "(printing signal handlers)" )
 788 
 789      if (_verbose) {
 790        os::print_signal_handlers(st, buf, sizeof(buf));
 791        st->cr();
 792      }
 793 
 794   STEP(228, "(Native Memory Tracking)" )
 795      if (_verbose) {
 796        MemTracker::error_report(st);
 797      }
 798 
 799   STEP(230, "" )
 800 
 801      if (_verbose) {
 802        st->cr();
 803        st->print_cr("---------------  S Y S T E M  ---------------");
 804        st->cr();
 805      }
 806 
 807   STEP(240, "(printing OS information)" )
 808 
 809      if (_verbose) {
 810        os::print_os_info(st);
 811        st->cr();
 812      }
 813 
 814   STEP(250, "(printing CPU info)" )
 815      if (_verbose) {
 816        os::print_cpu_info(st);
 817        st->cr();
 818      }
 819 
 820   STEP(260, "(printing memory info)" )
 821 
 822      if (_verbose) {
 823        os::print_memory_info(st);
 824        st->cr();
 825      }
 826 
 827   STEP(270, "(printing internal vm info)" )
 828 
 829      if (_verbose) {
 830        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
 831        st->cr();
 832      }
 833 
 834   STEP(280, "(printing date and time)" )
 835 
 836      if (_verbose) {
 837        os::print_date_and_time(st, buf, sizeof(buf));
 838        st->cr();
 839      }
 840 
 841   END
 842 
 843 # undef BEGIN
 844 # undef STEP
 845 # undef END
 846 }
 847 
 848 VMError* volatile VMError::first_error = NULL;
 849 volatile jlong VMError::first_error_tid = -1;
 850 
 851 // An error could happen before tty is initialized or after it has been
 852 // destroyed. Here we use a very simple unbuffered fdStream for printing.
 853 // Only out.print_raw() and out.print_raw_cr() should be used, as other
 854 // printing methods need to allocate large buffer on stack. To format a
 855 // string, use jio_snprintf() with a static buffer or use staticBufferStream.
 856 fdStream VMError::out(defaultStream::output_fd());
 857 fdStream VMError::log; // error log used by VMError::report_and_die()
 858 
 859 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
 860 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
 861   int fd = -1;
 862   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
 863     // the O_EXCL flag will cause the open to fail if the file exists
 864     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
 865   }
 866   return fd;
 867 }
 868 
 869 /**
 870  * Construct file name for a log file and return it's file descriptor.
 871  * Name and location depends on pattern, default_pattern params and access
 872  * permissions.
 873  */
 874 static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
 875   int fd = -1;
 876 
 877   // If possible, use specified pattern to construct log file name
 878   if (pattern != NULL) {
 879     fd = expand_and_open(pattern, buf, buflen, 0);
 880   }
 881 
 882   // Either user didn't specify, or the user's location failed,
 883   // so use the default name in the current directory
 884   if (fd == -1) {
 885     const char* cwd = os::get_current_directory(buf, buflen);
 886     if (cwd != NULL) {
 887       size_t pos = strlen(cwd);
 888       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
 889       pos += fsep_len;
 890       if (fsep_len > 0) {
 891         fd = expand_and_open(default_pattern, buf, buflen, pos);
 892       }
 893     }
 894   }
 895 
 896    // try temp directory if it exists.
 897    if (fd == -1) {
 898      const char* tmpdir = os::get_temp_directory();
 899      if (tmpdir != NULL && strlen(tmpdir) > 0) {
 900        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
 901        if (pos > 0) {
 902          fd = expand_and_open(default_pattern, buf, buflen, pos);
 903        }
 904      }
 905    }
 906 
 907   return fd;
 908 }
 909 
 910 void VMError::report_and_die() {
 911   // Don't allocate large buffer on stack
 912   static char buffer[O_BUFLEN];
 913 
 914   // How many errors occurred in error handler when reporting first_error.
 915   static int recursive_error_count;
 916 
 917   // We will first print a brief message to standard out (verbose = false),
 918   // then save detailed information in log file (verbose = true).
 919   static bool out_done = false;         // done printing to standard out
 920   static bool log_done = false;         // done saving error log
 921   static bool transmit_report_done = false; // done error reporting
 922 
 923   if (SuppressFatalErrorMessage) {
 924       os::abort();
 925   }
 926   jlong mytid = os::current_thread_id();
 927   if (first_error == NULL &&
 928       Atomic::cmpxchg_ptr(this, &first_error, NULL) == NULL) {
 929 
 930     // first time
 931     first_error_tid = mytid;
 932     set_error_reported();
 933 
 934     if (ShowMessageBoxOnError || PauseAtExit) {
 935       show_message_box(buffer, sizeof(buffer));
 936 
 937       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
 938       // WatcherThread can kill JVM if the error handler hangs.
 939       ShowMessageBoxOnError = false;
 940     }
 941 
 942     // Write a minidump on Windows, check core dump limits on Linux/Solaris
 943     os::check_or_create_dump(_siginfo, _context, buffer, sizeof(buffer));
 944 
 945     // reset signal handlers or exception filter; make sure recursive crashes
 946     // are handled properly.
 947     reset_signal_handlers();
 948 
 949 #if INCLUDE_JFR
 950     EventShutdown e;
 951     if (e.should_commit()) {
 952       e.set_reason("VM Error");
 953       e.commit();
 954     }
 955 #endif
 956     JFR_ONLY(Jfr::on_vm_shutdown(true);)
 957   } else {
 958     // If UseOsErrorReporting we call this for each level of the call stack
 959     // while searching for the exception handler.  Only the first level needs
 960     // to be reported.
 961     if (UseOSErrorReporting && log_done) return;
 962 
 963     // This is not the first error, see if it happened in a different thread
 964     // or in the same thread during error reporting.
 965     if (first_error_tid != mytid) {
 966       char msgbuf[64];
 967       jio_snprintf(msgbuf, sizeof(msgbuf),
 968                    "[thread " INT64_FORMAT " also had an error]",
 969                    mytid);
 970       out.print_raw_cr(msgbuf);
 971 
 972       // error reporting is not MT-safe, block current thread
 973       os::infinite_sleep();
 974 
 975     } else {
 976       if (recursive_error_count++ > 30) {
 977         out.print_raw_cr("[Too many errors, abort]");
 978         os::die();
 979       }
 980 
 981       jio_snprintf(buffer, sizeof(buffer),
 982                    "[error occurred during error reporting %s, id 0x%x]",
 983                    first_error ? first_error->_current_step_info : "",
 984                    _id);
 985       if (log.is_open()) {
 986         log.cr();
 987         log.print_raw_cr(buffer);
 988         log.cr();
 989       } else {
 990         out.cr();
 991         out.print_raw_cr(buffer);
 992         out.cr();
 993       }
 994     }
 995   }
 996 
 997   // print to screen
 998   if (!out_done) {
 999     first_error->_verbose = false;
1000 
1001     staticBufferStream sbs(buffer, sizeof(buffer), &out);
1002     first_error->report(&sbs);
1003 
1004     out_done = true;
1005 
1006     first_error->_current_step = 0;         // reset current_step
1007     first_error->_current_step_info = "";   // reset current_step string
1008   }
1009 
1010   // print to error log file
1011   if (!log_done) {
1012     first_error->_verbose = true;
1013 
1014     // see if log file is already open
1015     if (!log.is_open()) {
1016       // open log file
1017       int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1018       if (fd != -1) {
1019         out.print_raw("# An error report file with more information is saved as:\n# ");
1020         out.print_raw_cr(buffer);
1021 
1022         log.set_fd(fd);
1023       } else {
1024         out.print_raw_cr("# Can not save log file, dump to screen..");
1025         log.set_fd(defaultStream::output_fd());
1026         /* Error reporting currently needs dumpfile.
1027          * Maybe implement direct streaming in the future.*/
1028         transmit_report_done = true;
1029       }
1030     }
1031 
1032     staticBufferStream sbs(buffer, O_BUFLEN, &log);
1033     first_error->report(&sbs);
1034     first_error->_current_step = 0;         // reset current_step
1035     first_error->_current_step_info = "";   // reset current_step string
1036 
1037     // Run error reporting to determine whether or not to report the crash.
1038     if (!transmit_report_done && should_report_bug(first_error->_id)) {
1039       transmit_report_done = true;
1040       FILE* hs_err = os::open(log.fd(), "r");
1041       if (NULL != hs_err) {
1042         ErrorReporter er;
1043         er.call(hs_err, buffer, O_BUFLEN);
1044       }
1045     }
1046 
1047     if (log.fd() != defaultStream::output_fd()) {
1048       close(log.fd());
1049     }
1050 
1051     log.set_fd(-1);
1052     log_done = true;
1053   }
1054 
1055 
1056   static bool skip_OnError = false;
1057   if (!skip_OnError && OnError && OnError[0]) {
1058     skip_OnError = true;
1059 
1060     out.print_raw_cr("#");
1061     out.print_raw   ("# -XX:OnError=\"");
1062     out.print_raw   (OnError);
1063     out.print_raw_cr("\"");
1064 
1065     char* cmd;
1066     const char* ptr = OnError;
1067     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1068       out.print_raw   ("#   Executing ");
1069 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1070       out.print_raw   ("/bin/sh -c ");
1071 #elif defined(SOLARIS)
1072       out.print_raw   ("/usr/bin/sh -c ");
1073 #endif
1074       out.print_raw   ("\"");
1075       out.print_raw   (cmd);
1076       out.print_raw_cr("\" ...");
1077 
1078       if (os::fork_and_exec(cmd, true) < 0) {
1079         out.print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1080       }
1081     }
1082 
1083     // done with OnError
1084     OnError = NULL;
1085   }
1086 
1087   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1088   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1089     skip_replay = true;
1090     ciEnv* env = ciEnv::current();
1091     if (env != NULL) {
1092       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1093       if (fd != -1) {
1094         FILE* replay_data_file = os::open(fd, "w");
1095         if (replay_data_file != NULL) {
1096           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1097           env->dump_replay_data_unsafe(&replay_data_stream);
1098           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1099           out.print_raw_cr(buffer);
1100         } else {
1101           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1102           out.print_raw_cr(strerror(os::get_last_error()));
1103         }
1104       }
1105     }
1106   }
1107 
1108   static bool skip_bug_url = !should_report_bug(first_error->_id);
1109   if (!skip_bug_url) {
1110     skip_bug_url = true;
1111 
1112     out.print_raw_cr("#");
1113     print_bug_submit_message(&out, _thread);
1114   }
1115 
1116   if (!UseOSErrorReporting) {
1117     // os::abort() will call abort hooks, try it first.
1118     static bool skip_os_abort = false;
1119     if (!skip_os_abort) {
1120       skip_os_abort = true;
1121       bool dump_core = should_report_bug(first_error->_id);
1122       os::abort(dump_core);
1123     }
1124 
1125     // if os::abort() doesn't abort, try os::die();
1126     os::die();
1127   }
1128 }
1129 
1130 /*
1131  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1132  * ensures utilities such as jmap can observe the process is a consistent state.
1133  */
1134 class VM_ReportJavaOutOfMemory : public VM_Operation {
1135  private:
1136   VMError *_err;
1137  public:
1138   VM_ReportJavaOutOfMemory(VMError *err) { _err = err; }
1139   VMOp_Type type() const                 { return VMOp_ReportJavaOutOfMemory; }
1140   void doit();
1141 };
1142 
1143 void VM_ReportJavaOutOfMemory::doit() {
1144   // Don't allocate large buffer on stack
1145   static char buffer[O_BUFLEN];
1146 
1147   tty->print_cr("#");
1148   tty->print_cr("# java.lang.OutOfMemoryError: %s", _err->message());
1149   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1150 
1151   // make heap parsability
1152   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1153 
1154   char* cmd;
1155   const char* ptr = OnOutOfMemoryError;
1156   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1157     tty->print("#   Executing ");
1158 #if defined(LINUX)
1159     tty->print  ("/bin/sh -c ");
1160 #elif defined(SOLARIS)
1161     tty->print  ("/usr/bin/sh -c ");
1162 #endif
1163     tty->print_cr("\"%s\"...", cmd);
1164 
1165     if (os::fork_and_exec(cmd) < 0) {
1166       tty->print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1167     }
1168   }
1169 }
1170 
1171 void VMError::report_java_out_of_memory() {
1172   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1173     MutexLocker ml(Heap_lock);
1174     VM_ReportJavaOutOfMemory op(this);
1175     VMThread::execute(&op);
1176   }
1177 }