src/share/vm/utilities/vmError.cpp

Wed, 03 Jul 2019 20:42:37 +0800

author
aoqi
date
Wed, 03 Jul 2019 20:42:37 +0800
changeset 9637
eef07cd490d4
parent 9448
73d689add964
parent 9620
97d605522fcb
child 9852
70aa912cebe5
permissions
-rw-r--r--

Merge

     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  */
    25 /*
    26  * This file has been modified by Loongson Technology in 2018. These
    27  * modifications are Copyright (c) 2018 Loongson Technology, and are made
    28  * available on the same license terms set forth above.
    29  *
    30 */
    32 #include <fcntl.h>
    33 #include "precompiled.hpp"
    34 #include "compiler/compileBroker.hpp"
    35 #include "gc_interface/collectedHeap.hpp"
    36 #include "prims/whitebox.hpp"
    37 #include "runtime/arguments.hpp"
    38 #include "runtime/frame.inline.hpp"
    39 #include "runtime/init.hpp"
    40 #include "runtime/os.hpp"
    41 #include "runtime/thread.inline.hpp"
    42 #include "runtime/vmThread.hpp"
    43 #include "runtime/vm_operations.hpp"
    44 #include "services/memTracker.hpp"
    45 #include "utilities/debug.hpp"
    46 #include "utilities/decoder.hpp"
    47 #include "utilities/defaultStream.hpp"
    48 #include "utilities/errorReporter.hpp"
    49 #include "utilities/events.hpp"
    50 #include "utilities/top.hpp"
    51 #include "utilities/vmError.hpp"
    53 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    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",
    61   // Env variables that are defined on Solaris/Linux/BSD
    62   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
    63   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
    65   // defined on Linux
    66   "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
    68   // defined on Darwin
    69   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
    70   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
    71   "DYLD_INSERT_LIBRARIES",
    73   // defined on Windows
    74   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
    76   (const char *)0
    77 };
    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().
    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;
    96     _verbose = false;
    97     _current_step = 0;
    98     _current_step_info = NULL;
   100     _message = NULL;
   101     _detail_msg = NULL;
   102     _filename = NULL;
   103     _lineno = 0;
   105     _size = 0;
   106 }
   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;
   119   _verbose = false;
   120   _current_step = 0;
   121   _current_step_info = NULL;
   123   _pc = NULL;
   124   _siginfo = NULL;
   125   _context = NULL;
   127   _size = 0;
   128 }
   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;
   140     _verbose = false;
   141     _current_step = 0;
   142     _current_step_info = NULL;
   144     _pc = NULL;
   145     _siginfo = NULL;
   146     _context = NULL;
   148     _size = size;
   149 }
   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;
   161     _verbose = false;
   162     _current_step = 0;
   163     _current_step_info = NULL;
   165     _pc = NULL;
   166     _siginfo = NULL;
   167     _context = NULL;
   169     _size = 0;
   170 }
   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"             // ?#!@#
   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;
   188   const char* cmd = *ptr;
   190   // skip leading blanks or ';'
   191   while (*cmd == ' ' || *cmd == ';') cmd++;
   193   if (*cmd == '\0') return NULL;
   195   const char * cmdend = cmd;
   196   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
   198   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
   200   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
   201   return buf;
   202 }
   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 }
   222 bool VMError::coredump_status;
   223 char VMError::coredump_message[O_BUFLEN];
   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 }
   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));
   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   }
   265   return buf;
   266 }
   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:");
   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();
   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     }
   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 }
   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 }
   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.
   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 }
   387   // don't allocate large buffer on stack
   388   static char buf[O_BUFLEN];
   390   BEGIN
   392   STEP(10, "(printing fatal error message)")
   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     }
   402   STEP(15, "(printing type of error)")
   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      }
   436   STEP(20, "(printing exception/signal name)")
   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);
   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      }
   473   STEP(30, "(printing current thread and pid)")
   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();
   480   STEP(40, "(printing error message)")
   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     }
   491   STEP(50, "(printing Java version string)")
   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 #ifdef LOONGSON_RUNTIME_NAME
   501      const char* loongson_runtime_name_and_version = LOONGSON_RUNTIME_NAME;
   502 #else
   503      const char* loongson_runtime_name_and_version = "";
   504 #endif
   505      st->print_cr("# JRE version: %s (%s) (build %s) (%s)", runtime_name, buf, runtime_version, loongson_runtime_name_and_version);
   506      st->print_cr("# Java VM: %s (%s %s %s %s)",
   507                    Abstract_VM_Version::vm_name(),
   508                    Abstract_VM_Version::vm_release(),
   509                    Abstract_VM_Version::vm_info_string(),
   510                    Abstract_VM_Version::vm_platform_string(),
   511                    UseCompressedOops ? "compressed oops" : ""
   512                  );
   514   STEP(60, "(printing problematic frame)")
   516      // Print current frame if we have a context (i.e. it's a crash)
   517      if (_context) {
   518        st->print_cr("# Problematic frame:");
   519        st->print("# ");
   520        frame fr = os::fetch_frame_from_context(_context);
   521        fr.print_on_error(st, buf, sizeof(buf));
   522        st->cr();
   523        st->print_cr("#");
   524      }
   525   STEP(63, "(printing core file information)")
   526     st->print("# ");
   527     if (coredump_status) {
   528       st->print("Core dump written. Default location: %s", coredump_message);
   529     } else {
   530       st->print("Failed to write core dump. %s", coredump_message);
   531     }
   532     st->cr();
   533     st->print_cr("#");
   535   STEP(65, "(printing bug submit message)")
   537      if (should_report_bug(_id) && _verbose) {
   538        print_bug_submit_message(st, _thread);
   539      }
   541   STEP(70, "(printing thread)" )
   543      if (_verbose) {
   544        st->cr();
   545        st->print_cr("---------------  T H R E A D  ---------------");
   546        st->cr();
   547      }
   549   STEP(80, "(printing current thread)" )
   551      // current thread
   552      if (_verbose) {
   553        if (_thread) {
   554          st->print("Current thread (" PTR_FORMAT "):  ", _thread);
   555          _thread->print_on_error(st, buf, sizeof(buf));
   556          st->cr();
   557        } else {
   558          st->print_cr("Current thread is native thread");
   559        }
   560        st->cr();
   561      }
   563   STEP(90, "(printing siginfo)" )
   565      // signal no, signal code, address that caused the fault
   566      if (_verbose && _siginfo) {
   567        os::print_siginfo(st, _siginfo);
   568        st->cr();
   569      }
   571   STEP(100, "(printing registers, top of stack, instructions near pc)")
   573      // registers, top of stack, instructions near pc
   574      if (_verbose && _context) {
   575        os::print_context(st, _context);
   576        st->cr();
   577      }
   579   STEP(105, "(printing register info)")
   581      // decode register contents if possible
   582      if (_verbose && _context && Universe::is_fully_initialized()) {
   583        os::print_register_info(st, _context);
   584        st->cr();
   585      }
   587   STEP(110, "(printing stack bounds)" )
   589      if (_verbose) {
   590        st->print("Stack: ");
   592        address stack_top;
   593        size_t stack_size;
   595        if (_thread) {
   596           stack_top = _thread->stack_base();
   597           stack_size = _thread->stack_size();
   598        } else {
   599           stack_top = os::current_stack_base();
   600           stack_size = os::current_stack_size();
   601        }
   603        address stack_bottom = stack_top - stack_size;
   604        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", stack_bottom, stack_top);
   606        frame fr = _context ? os::fetch_frame_from_context(_context)
   607                            : os::current_frame();
   609        if (fr.sp()) {
   610          st->print(",  sp=" PTR_FORMAT, fr.sp());
   611          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
   612          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
   613        }
   615        st->cr();
   616      }
   618   STEP(120, "(printing native stack)" )
   620    if (_verbose) {
   621      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
   622        // We have printed the native stack in platform-specific code
   623        // Windows/x64 needs special handling.
   624      } else {
   625        frame fr = _context ? os::fetch_frame_from_context(_context)
   626                            : os::current_frame();
   628        print_native_stack(st, fr, _thread, buf, sizeof(buf));
   629      }
   630    }
   632   STEP(130, "(printing Java stack)" )
   634      if (_verbose && _thread && _thread->is_Java_thread()) {
   635        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
   636      }
   638   STEP(135, "(printing target Java thread stack)" )
   640      // printing Java thread stack trace if it is involved in GC crash
   641      if (_verbose && _thread && (_thread->is_Named_thread())) {
   642        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
   643        if (jt != NULL) {
   644          st->print_cr("JavaThread " PTR_FORMAT " (nid = " UINTX_FORMAT ") was being processed", jt, jt->osthread()->thread_id());
   645          print_stack_trace(st, jt, buf, sizeof(buf), true);
   646        }
   647      }
   649   STEP(140, "(printing VM operation)" )
   651      if (_verbose && _thread && _thread->is_VM_thread()) {
   652         VMThread* t = (VMThread*)_thread;
   653         VM_Operation* op = t->vm_operation();
   654         if (op) {
   655           op->print_on_error(st);
   656           st->cr();
   657           st->cr();
   658         }
   659      }
   661   STEP(150, "(printing current compile task)" )
   663      if (_verbose && _thread && _thread->is_Compiler_thread()) {
   664         CompilerThread* t = (CompilerThread*)_thread;
   665         if (t->task()) {
   666            st->cr();
   667            st->print_cr("Current CompileTask:");
   668            t->task()->print_line_on_error(st, buf, sizeof(buf));
   669            st->cr();
   670         }
   671      }
   673   STEP(160, "(printing process)" )
   675      if (_verbose) {
   676        st->cr();
   677        st->print_cr("---------------  P R O C E S S  ---------------");
   678        st->cr();
   679      }
   681   STEP(170, "(printing all threads)" )
   683      // all threads
   684      if (_verbose && _thread) {
   685        Threads::print_on_error(st, _thread, buf, sizeof(buf));
   686        st->cr();
   687      }
   689   STEP(175, "(printing VM state)" )
   691      if (_verbose) {
   692        // Safepoint state
   693        st->print("VM state:");
   695        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
   696        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
   697        else st->print("not at safepoint");
   699        // Also see if error occurred during initialization or shutdown
   700        if (!Universe::is_fully_initialized()) {
   701          st->print(" (not fully initialized)");
   702        } else if (VM_Exit::vm_exited()) {
   703          st->print(" (shutting down)");
   704        } else {
   705          st->print(" (normal execution)");
   706        }
   707        st->cr();
   708        st->cr();
   709      }
   711   STEP(180, "(printing owned locks on error)" )
   713      // mutexes/monitors that currently have an owner
   714      if (_verbose) {
   715        print_owned_locks_on_error(st);
   716        st->cr();
   717      }
   719   STEP(182, "(printing number of OutOfMemoryError and StackOverflow exceptions)")
   721      if (_verbose && Exceptions::has_exception_counts()) {
   722        st->print_cr("OutOfMemory and StackOverflow Exception counts:");
   723        Exceptions::print_exception_counts_on_error(st);
   724        st->cr();
   725      }
   727   STEP(185, "(printing compressed oops mode")
   729      if (_verbose && UseCompressedOops) {
   730        Universe::print_compressed_oops_mode(st);
   731        if (UseCompressedClassPointers) {
   732          Metaspace::print_compressed_class_space(st);
   733        }
   734        st->cr();
   735      }
   737   STEP(190, "(printing heap information)" )
   739      if (_verbose && Universe::is_fully_initialized()) {
   740        Universe::heap()->print_on_error(st);
   741        st->cr();
   743        st->print_cr("Polling page: " INTPTR_FORMAT, os::get_polling_page());
   744        st->cr();
   745      }
   747   STEP(195, "(printing code cache information)" )
   749      if (_verbose && Universe::is_fully_initialized()) {
   750        // print code cache information before vm abort
   751        CodeCache::print_summary(st);
   752        st->cr();
   753      }
   755   STEP(200, "(printing ring buffers)" )
   757      if (_verbose) {
   758        Events::print_all(st);
   759        st->cr();
   760      }
   762   STEP(205, "(printing dynamic libraries)" )
   764      if (_verbose) {
   765        // dynamic libraries, or memory map
   766        os::print_dll_info(st);
   767        st->cr();
   768      }
   770   STEP(210, "(printing VM options)" )
   772      if (_verbose) {
   773        // VM options
   774        Arguments::print_on(st);
   775        st->cr();
   776      }
   778   STEP(215, "(printing warning if internal testing API used)" )
   780      if (WhiteBox::used()) {
   781        st->print_cr("Unsupported internal testing APIs have been used.");
   782        st->cr();
   783      }
   785   STEP(220, "(printing environment variables)" )
   787      if (_verbose) {
   788        os::print_environment_variables(st, env_list, buf, sizeof(buf));
   789        st->cr();
   790      }
   792   STEP(225, "(printing signal handlers)" )
   794      if (_verbose) {
   795        os::print_signal_handlers(st, buf, sizeof(buf));
   796        st->cr();
   797      }
   799   STEP(228, "(Native Memory Tracking)" )
   800      if (_verbose) {
   801        MemTracker::error_report(st);
   802      }
   804   STEP(230, "" )
   806      if (_verbose) {
   807        st->cr();
   808        st->print_cr("---------------  S Y S T E M  ---------------");
   809        st->cr();
   810      }
   812   STEP(240, "(printing OS information)" )
   814      if (_verbose) {
   815        os::print_os_info(st);
   816        st->cr();
   817      }
   819   STEP(250, "(printing CPU info)" )
   820      if (_verbose) {
   821        os::print_cpu_info(st);
   822        st->cr();
   823      }
   825   STEP(260, "(printing memory info)" )
   827      if (_verbose) {
   828        os::print_memory_info(st);
   829        st->cr();
   830      }
   832   STEP(270, "(printing internal vm info)" )
   834      if (_verbose) {
   835        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
   836        st->cr();
   837      }
   839   STEP(280, "(printing date and time)" )
   841      if (_verbose) {
   842        os::print_date_and_time(st, buf, sizeof(buf));
   843        st->cr();
   844      }
   846   END
   848 # undef BEGIN
   849 # undef STEP
   850 # undef END
   851 }
   853 VMError* volatile VMError::first_error = NULL;
   854 volatile jlong VMError::first_error_tid = -1;
   856 // An error could happen before tty is initialized or after it has been
   857 // destroyed. Here we use a very simple unbuffered fdStream for printing.
   858 // Only out.print_raw() and out.print_raw_cr() should be used, as other
   859 // printing methods need to allocate large buffer on stack. To format a
   860 // string, use jio_snprintf() with a static buffer or use staticBufferStream.
   861 fdStream VMError::out(defaultStream::output_fd());
   862 fdStream VMError::log; // error log used by VMError::report_and_die()
   864 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
   865 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
   866   int fd = -1;
   867   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
   868     // the O_EXCL flag will cause the open to fail if the file exists
   869     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
   870   }
   871   return fd;
   872 }
   874 /**
   875  * Construct file name for a log file and return it's file descriptor.
   876  * Name and location depends on pattern, default_pattern params and access
   877  * permissions.
   878  */
   879 static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
   880   int fd = -1;
   882   // If possible, use specified pattern to construct log file name
   883   if (pattern != NULL) {
   884     fd = expand_and_open(pattern, buf, buflen, 0);
   885   }
   887   // Either user didn't specify, or the user's location failed,
   888   // so use the default name in the current directory
   889   if (fd == -1) {
   890     const char* cwd = os::get_current_directory(buf, buflen);
   891     if (cwd != NULL) {
   892       size_t pos = strlen(cwd);
   893       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
   894       pos += fsep_len;
   895       if (fsep_len > 0) {
   896         fd = expand_and_open(default_pattern, buf, buflen, pos);
   897       }
   898     }
   899   }
   901    // try temp directory if it exists.
   902    if (fd == -1) {
   903      const char* tmpdir = os::get_temp_directory();
   904      if (tmpdir != NULL && strlen(tmpdir) > 0) {
   905        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
   906        if (pos > 0) {
   907          fd = expand_and_open(default_pattern, buf, buflen, pos);
   908        }
   909      }
   910    }
   912   return fd;
   913 }
   915 void VMError::report_and_die() {
   916   // Don't allocate large buffer on stack
   917   static char buffer[O_BUFLEN];
   919   // How many errors occurred in error handler when reporting first_error.
   920   static int recursive_error_count;
   922   // We will first print a brief message to standard out (verbose = false),
   923   // then save detailed information in log file (verbose = true).
   924   static bool out_done = false;         // done printing to standard out
   925   static bool log_done = false;         // done saving error log
   926   static bool transmit_report_done = false; // done error reporting
   928   if (SuppressFatalErrorMessage) {
   929       os::abort();
   930   }
   931   jlong mytid = os::current_thread_id();
   932   if (first_error == NULL &&
   933       Atomic::cmpxchg_ptr(this, &first_error, NULL) == NULL) {
   935     // first time
   936     first_error_tid = mytid;
   937     set_error_reported();
   939     if (ShowMessageBoxOnError || PauseAtExit) {
   940       show_message_box(buffer, sizeof(buffer));
   942       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
   943       // WatcherThread can kill JVM if the error handler hangs.
   944       ShowMessageBoxOnError = false;
   945     }
   947     // Write a minidump on Windows, check core dump limits on Linux/Solaris
   948     os::check_or_create_dump(_siginfo, _context, buffer, sizeof(buffer));
   950     // reset signal handlers or exception filter; make sure recursive crashes
   951     // are handled properly.
   952     reset_signal_handlers();
   954   } else {
   955     // If UseOsErrorReporting we call this for each level of the call stack
   956     // while searching for the exception handler.  Only the first level needs
   957     // to be reported.
   958     if (UseOSErrorReporting && log_done) return;
   960     // This is not the first error, see if it happened in a different thread
   961     // or in the same thread during error reporting.
   962     if (first_error_tid != mytid) {
   963       char msgbuf[64];
   964       jio_snprintf(msgbuf, sizeof(msgbuf),
   965                    "[thread " INT64_FORMAT " also had an error]",
   966                    mytid);
   967       out.print_raw_cr(msgbuf);
   969       // error reporting is not MT-safe, block current thread
   970       os::infinite_sleep();
   972     } else {
   973       if (recursive_error_count++ > 30) {
   974         out.print_raw_cr("[Too many errors, abort]");
   975         os::die();
   976       }
   978       jio_snprintf(buffer, sizeof(buffer),
   979                    "[error occurred during error reporting %s, id 0x%x]",
   980                    first_error ? first_error->_current_step_info : "",
   981                    _id);
   982       if (log.is_open()) {
   983         log.cr();
   984         log.print_raw_cr(buffer);
   985         log.cr();
   986       } else {
   987         out.cr();
   988         out.print_raw_cr(buffer);
   989         out.cr();
   990       }
   991     }
   992   }
   994   // print to screen
   995   if (!out_done) {
   996     first_error->_verbose = false;
   998     staticBufferStream sbs(buffer, sizeof(buffer), &out);
   999     first_error->report(&sbs);
  1001     out_done = true;
  1003     first_error->_current_step = 0;         // reset current_step
  1004     first_error->_current_step_info = "";   // reset current_step string
  1007   // print to error log file
  1008   if (!log_done) {
  1009     first_error->_verbose = true;
  1011     // see if log file is already open
  1012     if (!log.is_open()) {
  1013       // open log file
  1014       int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
  1015       if (fd != -1) {
  1016         out.print_raw("# An error report file with more information is saved as:\n# ");
  1017         out.print_raw_cr(buffer);
  1019         log.set_fd(fd);
  1020       } else {
  1021         out.print_raw_cr("# Can not save log file, dump to screen..");
  1022         log.set_fd(defaultStream::output_fd());
  1023         /* Error reporting currently needs dumpfile.
  1024          * Maybe implement direct streaming in the future.*/
  1025         transmit_report_done = true;
  1029     staticBufferStream sbs(buffer, O_BUFLEN, &log);
  1030     first_error->report(&sbs);
  1031     first_error->_current_step = 0;         // reset current_step
  1032     first_error->_current_step_info = "";   // reset current_step string
  1034     // Run error reporting to determine whether or not to report the crash.
  1035     if (!transmit_report_done && should_report_bug(first_error->_id)) {
  1036       transmit_report_done = true;
  1037       FILE* hs_err = os::open(log.fd(), "r");
  1038       if (NULL != hs_err) {
  1039         ErrorReporter er;
  1040         er.call(hs_err, buffer, O_BUFLEN);
  1044     if (log.fd() != defaultStream::output_fd()) {
  1045       close(log.fd());
  1048     log.set_fd(-1);
  1049     log_done = true;
  1053   static bool skip_OnError = false;
  1054   if (!skip_OnError && OnError && OnError[0]) {
  1055     skip_OnError = true;
  1057     out.print_raw_cr("#");
  1058     out.print_raw   ("# -XX:OnError=\"");
  1059     out.print_raw   (OnError);
  1060     out.print_raw_cr("\"");
  1062     char* cmd;
  1063     const char* ptr = OnError;
  1064     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
  1065       out.print_raw   ("#   Executing ");
  1066 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
  1067       out.print_raw   ("/bin/sh -c ");
  1068 #elif defined(SOLARIS)
  1069       out.print_raw   ("/usr/bin/sh -c ");
  1070 #endif
  1071       out.print_raw   ("\"");
  1072       out.print_raw   (cmd);
  1073       out.print_raw_cr("\" ...");
  1075       if (os::fork_and_exec(cmd, true) < 0) {
  1076         out.print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
  1080     // done with OnError
  1081     OnError = NULL;
  1084   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
  1085   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
  1086     skip_replay = true;
  1087     ciEnv* env = ciEnv::current();
  1088     if (env != NULL) {
  1089       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
  1090       if (fd != -1) {
  1091         FILE* replay_data_file = os::open(fd, "w");
  1092         if (replay_data_file != NULL) {
  1093           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
  1094           env->dump_replay_data_unsafe(&replay_data_stream);
  1095           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
  1096           out.print_raw_cr(buffer);
  1097         } else {
  1098           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
  1099           out.print_raw_cr(strerror(os::get_last_error()));
  1105   static bool skip_bug_url = !should_report_bug(first_error->_id);
  1106   if (!skip_bug_url) {
  1107     skip_bug_url = true;
  1109     out.print_raw_cr("#");
  1110     print_bug_submit_message(&out, _thread);
  1113   if (!UseOSErrorReporting) {
  1114     // os::abort() will call abort hooks, try it first.
  1115     static bool skip_os_abort = false;
  1116     if (!skip_os_abort) {
  1117       skip_os_abort = true;
  1118       bool dump_core = should_report_bug(first_error->_id);
  1119       os::abort(dump_core);
  1122     // if os::abort() doesn't abort, try os::die();
  1123     os::die();
  1127 /*
  1128  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
  1129  * ensures utilities such as jmap can observe the process is a consistent state.
  1130  */
  1131 class VM_ReportJavaOutOfMemory : public VM_Operation {
  1132  private:
  1133   VMError *_err;
  1134  public:
  1135   VM_ReportJavaOutOfMemory(VMError *err) { _err = err; }
  1136   VMOp_Type type() const                 { return VMOp_ReportJavaOutOfMemory; }
  1137   void doit();
  1138 };
  1140 void VM_ReportJavaOutOfMemory::doit() {
  1141   // Don't allocate large buffer on stack
  1142   static char buffer[O_BUFLEN];
  1144   tty->print_cr("#");
  1145   tty->print_cr("# java.lang.OutOfMemoryError: %s", _err->message());
  1146   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
  1148   // make heap parsability
  1149   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
  1151   char* cmd;
  1152   const char* ptr = OnOutOfMemoryError;
  1153   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
  1154     tty->print("#   Executing ");
  1155 #if defined(LINUX)
  1156     tty->print  ("/bin/sh -c ");
  1157 #elif defined(SOLARIS)
  1158     tty->print  ("/usr/bin/sh -c ");
  1159 #endif
  1160     tty->print_cr("\"%s\"...", cmd);
  1162     if (os::fork_and_exec(cmd) < 0) {
  1163       tty->print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
  1168 void VMError::report_java_out_of_memory() {
  1169   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
  1170     MutexLocker ml(Heap_lock);
  1171     VM_ReportJavaOutOfMemory op(this);
  1172     VMThread::execute(&op);

mercurial