1 /*
   2  * Copyright (c) 2003, 2017, 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 "code/codeCache.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/collectedHeap.hpp"
  31 #include "logging/logConfiguration.hpp"
  32 #include "prims/jvm.h"
  33 #include "prims/whitebox.hpp"
  34 #include "runtime/arguments.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "runtime/frame.inline.hpp"
  37 #include "runtime/init.hpp"
  38 #include "runtime/os.hpp"
  39 #include "runtime/thread.inline.hpp"
  40 #include "runtime/vmThread.hpp"
  41 #include "runtime/vm_operations.hpp"
  42 #include "runtime/vm_version.hpp"
  43 #include "services/memTracker.hpp"
  44 #include "trace/traceMacros.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/vmError.hpp"
  51 
  52 // List of environment variables that should be reported in error log file.
  53 const char *env_list[] = {
  54   // All platforms
  55   "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
  56   "JAVA_COMPILER", "PATH", "USERNAME",
  57 
  58   // Env variables that are defined on Solaris/Linux/BSD
  59   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
  60   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
  61 
  62   // defined on Linux
  63   "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
  64 
  65   // defined on Darwin
  66   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
  67   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
  68   "DYLD_INSERT_LIBRARIES",
  69 
  70   // defined on Windows
  71   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
  72 
  73   (const char *)0
  74 };
  75 
  76 // A simple parser for -XX:OnError, usage:
  77 //  ptr = OnError;
  78 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
  79 //     ... ...
  80 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
  81   if (ptr == NULL || *ptr == NULL) return NULL;
  82 
  83   const char* cmd = *ptr;
  84 
  85   // skip leading blanks or ';'
  86   while (*cmd == ' ' || *cmd == ';') cmd++;
  87 
  88   if (*cmd == '\0') return NULL;
  89 
  90   const char * cmdend = cmd;
  91   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
  92 
  93   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
  94 
  95   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
  96   return buf;
  97 }
  98 
  99 static void print_bug_submit_message(outputStream *out, Thread *thread) {
 100   if (out == NULL) return;
 101   out->print_raw_cr("# If you would like to submit a bug report, please visit:");
 102   out->print_raw   ("#   ");
 103   out->print_raw_cr(Arguments::java_vendor_url_bug());
 104   // If the crash is in native code, encourage user to submit a bug to the
 105   // provider of that code.
 106   if (thread && thread->is_Java_thread() &&
 107       !thread->is_hidden_from_external_view()) {
 108     JavaThread* jt = (JavaThread*)thread;
 109     if (jt->thread_state() == _thread_in_native) {
 110       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
 111     }
 112   }
 113   out->print_raw_cr("#");
 114 }
 115 
 116 bool VMError::coredump_status;
 117 char VMError::coredump_message[O_BUFLEN];
 118 
 119 void VMError::record_coredump_status(const char* message, bool status) {
 120   coredump_status = status;
 121   strncpy(coredump_message, message, sizeof(coredump_message));
 122   coredump_message[sizeof(coredump_message)-1] = 0;
 123 }
 124 
 125 // Return a string to describe the error
 126 char* VMError::error_string(char* buf, int buflen) {
 127   char signame_buf[64];
 128   const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
 129 
 130   if (signame) {
 131     jio_snprintf(buf, buflen,
 132                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
 133                  signame, _id, _pc,
 134                  os::current_process_id(), os::current_thread_id());
 135   } else if (_filename != NULL && _lineno > 0) {
 136     // skip directory names
 137     char separator = os::file_separator()[0];
 138     const char *p = strrchr(_filename, separator);
 139     int n = jio_snprintf(buf, buflen,
 140                          "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
 141                          p ? p + 1 : _filename, _lineno,
 142                          os::current_process_id(), os::current_thread_id());
 143     if (n >= 0 && n < buflen && _message) {
 144       if (strlen(_detail_msg) > 0) {
 145         jio_snprintf(buf + n, buflen - n, "%s%s: %s",
 146         os::line_separator(), _message, _detail_msg);
 147       } else {
 148         jio_snprintf(buf + n, buflen - n, "%sError: %s",
 149                      os::line_separator(), _message);
 150       }
 151     }
 152   } else {
 153     jio_snprintf(buf, buflen,
 154                  "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
 155                  _id, os::current_process_id(), os::current_thread_id());
 156   }
 157 
 158   return buf;
 159 }
 160 
 161 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
 162                                 char* buf, int buflen, bool verbose) {
 163 #ifdef ZERO
 164   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
 165     // StackFrameStream uses the frame anchor, which may not have
 166     // been set up.  This can be done at any time in Zero, however,
 167     // so if it hasn't been set up then we just set it up now and
 168     // clear it again when we're done.
 169     bool has_last_Java_frame = jt->has_last_Java_frame();
 170     if (!has_last_Java_frame)
 171       jt->set_last_Java_frame();
 172     st->print("Java frames:");
 173 
 174     // If the top frame is a Shark frame and the frame anchor isn't
 175     // set up then it's possible that the information in the frame
 176     // is garbage: it could be from a previous decache, or it could
 177     // simply have never been written.  So we print a warning...
 178     StackFrameStream sfs(jt);
 179     if (!has_last_Java_frame && !sfs.is_done()) {
 180       if (sfs.current()->zeroframe()->is_shark_frame()) {
 181         st->print(" (TOP FRAME MAY BE JUNK)");
 182       }
 183     }
 184     st->cr();
 185 
 186     // Print the frames
 187     for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
 188       sfs.current()->zero_print_on_error(i, st, buf, buflen);
 189       st->cr();
 190     }
 191 
 192     // Reset the frame anchor if necessary
 193     if (!has_last_Java_frame)
 194       jt->reset_last_Java_frame();
 195   }
 196 #else
 197   if (jt->has_last_Java_frame()) {
 198     st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
 199     for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
 200       sfs.current()->print_on_error(st, buf, buflen, verbose);
 201       st->cr();
 202     }
 203   }
 204 #endif // ZERO
 205 }
 206 
 207 void VMError::print_native_stack(outputStream* st, frame fr, Thread* t, char* buf, int buf_size) {
 208 
 209   // see if it's a valid frame
 210   if (fr.pc()) {
 211     st->print_cr("Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)");
 212 
 213     int count = 0;
 214     while (count++ < StackPrintLimit) {
 215       fr.print_on_error(st, buf, buf_size);
 216       st->cr();
 217       // Compiled code may use EBP register on x86 so it looks like
 218       // non-walkable C frame. Use frame.sender() for java frames.
 219       if (t && t->is_Java_thread()) {
 220         // Catch very first native frame by using stack address.
 221         // For JavaThread stack_base and stack_size should be set.
 222         if (!t->on_local_stack((address)(fr.real_fp() + 1))) {
 223           break;
 224         }
 225         if (fr.is_java_frame() || fr.is_native_frame() || fr.is_runtime_frame()) {
 226           RegisterMap map((JavaThread*)t, false); // No update
 227           fr = fr.sender(&map);
 228         } else {
 229           fr = os::get_sender_for_C_frame(&fr);
 230         }
 231       } else {
 232         // is_first_C_frame() does only simple checks for frame pointer,
 233         // it will pass if java compiled code has a pointer in EBP.
 234         if (os::is_first_C_frame(&fr)) break;
 235         fr = os::get_sender_for_C_frame(&fr);
 236       }
 237     }
 238 
 239     if (count > StackPrintLimit) {
 240       st->print_cr("...<more frames>...");
 241     }
 242 
 243     st->cr();
 244   }
 245 }
 246 
 247 static void print_oom_reasons(outputStream* st) {
 248   st->print_cr("# Possible reasons:");
 249   st->print_cr("#   The system is out of physical RAM or swap space");
 250   if (UseCompressedOops) {
 251     st->print_cr("#   The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
 252   }
 253   if (LogBytesPerWord == 2) {
 254     st->print_cr("#   In 32 bit mode, the process size limit was hit");
 255   }
 256   st->print_cr("# Possible solutions:");
 257   st->print_cr("#   Reduce memory load on the system");
 258   st->print_cr("#   Increase physical memory or swap space");
 259   st->print_cr("#   Check if swap backing store is full");
 260   if (LogBytesPerWord == 2) {
 261     st->print_cr("#   Use 64 bit Java on a 64 bit OS");
 262   }
 263   st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
 264   st->print_cr("#   Decrease number of Java threads");
 265   st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
 266   st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
 267   if (UseCompressedOops) {
 268     switch (Universe::narrow_oop_mode()) {
 269       case Universe::UnscaledNarrowOop:
 270         st->print_cr("#   JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
 271         st->print_cr("#     placed in the first 4GB address space. The Java Heap base address is the");
 272         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 273         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
 274         break;
 275       case Universe::ZeroBasedNarrowOop:
 276         st->print_cr("#   JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
 277         st->print_cr("#     placed in the first 32GB address space. The Java Heap base address is the");
 278         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 279         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
 280         break;
 281     }
 282   }
 283   st->print_cr("# This output file may be truncated or incomplete.");
 284 }
 285 
 286 static const char* gc_mode() {
 287   if (UseG1GC)            return "g1 gc";
 288   if (UseParallelGC)      return "parallel gc";
 289   if (UseConcMarkSweepGC) return "concurrent mark sweep gc";
 290   if (UseSerialGC)        return "serial gc";
 291   return "ERROR in GC mode";
 292 }
 293 
 294 static void report_vm_version(outputStream* st, char* buf, int buflen) {
 295    // VM version
 296    st->print_cr("#");
 297    JDK_Version::current().to_string(buf, buflen);
 298    const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 299                                 JDK_Version::runtime_name() : "";
 300    const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 301                                    JDK_Version::runtime_version() : "";
 302    const char* jdk_debug_level = Abstract_VM_Version::printable_jdk_debug_level() != NULL ?
 303                                    Abstract_VM_Version::printable_jdk_debug_level() : "";
 304 
 305    st->print_cr("# JRE version: %s (%s) (%sbuild %s)", runtime_name, buf,
 306                  jdk_debug_level, runtime_version);
 307 
 308    // This is the long version with some default settings added
 309    st->print_cr("# Java VM: %s (%s%s, %s%s%s%s%s, %s, %s)",
 310                  Abstract_VM_Version::vm_name(),
 311                  jdk_debug_level,
 312                  Abstract_VM_Version::vm_release(),
 313                  Abstract_VM_Version::vm_info_string(),
 314                  TieredCompilation ? ", tiered" : "",
 315 #if INCLUDE_JVMCI
 316                  EnableJVMCI ? ", jvmci" : "",
 317                  UseJVMCICompiler ? ", jvmci compiler" : "",
 318 #else
 319                  "", "",
 320 #endif
 321                  UseCompressedOops ? ", compressed oops" : "",
 322                  gc_mode(),
 323                  Abstract_VM_Version::vm_platform_string()
 324                );
 325 }
 326 
 327 // This is the main function to report a fatal error. Only one thread can
 328 // call this function, so we don't need to worry about MT-safety. But it's
 329 // possible that the error handler itself may crash or die on an internal
 330 // error, for example, when the stack/heap is badly damaged. We must be
 331 // able to handle recursive errors that happen inside error handler.
 332 //
 333 // Error reporting is done in several steps. If a crash or internal error
 334 // occurred when reporting an error, the nested signal/exception handler
 335 // can skip steps that are already (or partially) done. Error reporting will
 336 // continue from the next step. This allows us to retrieve and print
 337 // information that may be unsafe to get after a fatal error. If it happens,
 338 // you may find nested report_and_die() frames when you look at the stack
 339 // in a debugger.
 340 //
 341 // In general, a hang in error handler is much worse than a crash or internal
 342 // error, as it's harder to recover from a hang. Deadlock can happen if we
 343 // try to grab a lock that is already owned by current thread, or if the
 344 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 345 // error handler and all the functions it called should avoid grabbing any
 346 // lock. An important thing to notice is that memory allocation needs a lock.
 347 //
 348 // We should avoid using large stack allocated buffers. Many errors happen
 349 // when stack space is already low. Making things even worse is that there
 350 // could be nested report_and_die() calls on stack (see above). Only one
 351 // thread can report error, so large buffers are statically allocated in data
 352 // segment.
 353 
 354 int          VMError::_current_step;
 355 const char*  VMError::_current_step_info;
 356 
 357 volatile jlong VMError::_reporting_start_time = -1;
 358 volatile bool VMError::_reporting_did_timeout = false;
 359 volatile jlong VMError::_step_start_time = -1;
 360 volatile bool VMError::_step_did_timeout = false;
 361 
 362 // Helper, return current timestamp for timeout handling.
 363 jlong VMError::get_current_timestamp() {
 364   return os::javaTimeNanos();
 365 }
 366 // Factor to translate the timestamp to seconds.
 367 #define TIMESTAMP_TO_SECONDS_FACTOR (1000 * 1000 * 1000)
 368 
 369 void VMError::record_reporting_start_time() {
 370   const jlong now = get_current_timestamp();
 371   Atomic::store(now, &_reporting_start_time);
 372 }
 373 
 374 jlong VMError::get_reporting_start_time() {
 375   return Atomic::load(&_reporting_start_time);
 376 }
 377 
 378 void VMError::record_step_start_time() {
 379   const jlong now = get_current_timestamp();
 380   Atomic::store(now, &_step_start_time);
 381 }
 382 
 383 jlong VMError::get_step_start_time() {
 384   return Atomic::load(&_step_start_time);
 385 }
 386 
 387 void VMError::report(outputStream* st, bool _verbose) {
 388 
 389 # define BEGIN if (_current_step == 0) { _current_step = __LINE__;
 390 # define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; \
 391   record_step_start_time(); _step_did_timeout = false;
 392 # define END }
 393 
 394   // don't allocate large buffer on stack
 395   static char buf[O_BUFLEN];
 396 
 397   BEGIN
 398 
 399   STEP("printing fatal error message")
 400 
 401     st->print_cr("#");
 402     if (should_report_bug(_id)) {
 403       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 404     } else {
 405       st->print_cr("# There is insufficient memory for the Java "
 406                    "Runtime Environment to continue.");
 407     }
 408 
 409 #ifndef PRODUCT
 410   // Error handler self tests
 411 
 412   // test secondary error handling. Test it twice, to test that resetting
 413   // error handler after a secondary crash works.
 414   STEP("test secondary crash 1")
 415     if (_verbose && TestCrashInErrorHandler != 0) {
 416       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
 417         TestCrashInErrorHandler);
 418       controlled_crash(TestCrashInErrorHandler);
 419     }
 420 
 421   STEP("test secondary crash 2")
 422     if (_verbose && TestCrashInErrorHandler != 0) {
 423       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
 424         TestCrashInErrorHandler);
 425       controlled_crash(TestCrashInErrorHandler);
 426     }
 427 
 428   // TestUnresponsiveErrorHandler: We want to test both step timeouts and global timeout.
 429   // Step to global timeout ratio is 4:1, so in order to be absolutely sure we hit the
 430   // global timeout, let's execute the timeout step five times.
 431   // See corresponding test in test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java
 432   #define TIMEOUT_TEST_STEP STEP("test unresponsive error reporting step") \
 433     if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); }
 434   TIMEOUT_TEST_STEP
 435   TIMEOUT_TEST_STEP
 436   TIMEOUT_TEST_STEP
 437   TIMEOUT_TEST_STEP
 438   TIMEOUT_TEST_STEP
 439 
 440   STEP("test safefetch in error handler")
 441     // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
 442     // to test that resetting the signal handler works correctly.
 443     if (_verbose && TestSafeFetchInErrorHandler) {
 444       st->print_cr("Will test SafeFetch...");
 445       if (CanUseSafeFetch32()) {
 446         int* const invalid_pointer = (int*) get_segfault_address();
 447         const int x = 0x76543210;
 448         int i1 = SafeFetch32(invalid_pointer, x);
 449         int i2 = SafeFetch32(invalid_pointer, x);
 450         if (i1 == x && i2 == x) {
 451           st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
 452         } else {
 453           st->print_cr("??");
 454         }
 455       } else {
 456         st->print_cr("not possible; skipped.");
 457       }
 458     }
 459 #endif // PRODUCT
 460 
 461   STEP("printing type of error")
 462 
 463      switch(_id) {
 464        case OOM_MALLOC_ERROR:
 465        case OOM_MMAP_ERROR:
 466          if (_size) {
 467            st->print("# Native memory allocation ");
 468            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 469                                                  "(mmap) failed to map ");
 470            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
 471            st->print("%s", buf);
 472            st->print(" bytes");
 473            if (strlen(_detail_msg) > 0) {
 474              st->print(" for ");
 475              st->print("%s", _detail_msg);
 476            }
 477            st->cr();
 478          } else {
 479            if (strlen(_detail_msg) > 0) {
 480              st->print("# ");
 481              st->print_cr("%s", _detail_msg);
 482            }
 483          }
 484          // In error file give some solutions
 485          if (_verbose) {
 486            print_oom_reasons(st);
 487          } else {
 488            return;  // that's enough for the screen
 489          }
 490          break;
 491        case INTERNAL_ERROR:
 492        default:
 493          break;
 494      }
 495 
 496   STEP("printing exception/signal name")
 497 
 498      st->print_cr("#");
 499      st->print("#  ");
 500      // Is it an OS exception/signal?
 501      if (os::exception_name(_id, buf, sizeof(buf))) {
 502        st->print("%s", buf);
 503        st->print(" (0x%x)", _id);                // signal number
 504        st->print(" at pc=" PTR_FORMAT, p2i(_pc));
 505      } else {
 506        if (should_report_bug(_id)) {
 507          st->print("Internal Error");
 508        } else {
 509          st->print("Out of Memory Error");
 510        }
 511        if (_filename != NULL && _lineno > 0) {
 512 #ifdef PRODUCT
 513          // In product mode chop off pathname?
 514          char separator = os::file_separator()[0];
 515          const char *p = strrchr(_filename, separator);
 516          const char *file = p ? p+1 : _filename;
 517 #else
 518          const char *file = _filename;
 519 #endif
 520          st->print(" (%s:%d)", file, _lineno);
 521        } else {
 522          st->print(" (0x%x)", _id);
 523        }
 524      }
 525 
 526   STEP("printing current thread and pid")
 527 
 528      // process id, thread id
 529      st->print(", pid=%d", os::current_process_id());
 530      st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
 531      st->cr();
 532 
 533   STEP("printing error message")
 534 
 535      if (should_report_bug(_id)) {  // already printed the message.
 536        // error message
 537        if (strlen(_detail_msg) > 0) {
 538          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
 539        } else if (_message) {
 540          st->print_cr("#  Error: %s", _message);
 541        }
 542      }
 543 
 544   STEP("printing Java version string")
 545 
 546      report_vm_version(st, buf, sizeof(buf));
 547 
 548   STEP("printing problematic frame")
 549 
 550      // Print current frame if we have a context (i.e. it's a crash)
 551      if (_context) {
 552        st->print_cr("# Problematic frame:");
 553        st->print("# ");
 554        frame fr = os::fetch_frame_from_context(_context);
 555        fr.print_on_error(st, buf, sizeof(buf));
 556        st->cr();
 557        st->print_cr("#");
 558      }
 559 
 560   STEP("printing core file information")
 561     st->print("# ");
 562     if (CreateCoredumpOnCrash) {
 563       if (coredump_status) {
 564         st->print("Core dump will be written. Default location: %s", coredump_message);
 565       } else {
 566         st->print("No core dump will be written. %s", coredump_message);
 567       }
 568     } else {
 569       st->print("CreateCoredumpOnCrash turned off, no core file dumped");
 570     }
 571     st->cr();
 572     st->print_cr("#");
 573 
 574   STEP("printing bug submit message")
 575 
 576      if (should_report_bug(_id) && _verbose) {
 577        print_bug_submit_message(st, _thread);
 578      }
 579 
 580   STEP("printing summary")
 581 
 582      if (_verbose) {
 583        st->cr();
 584        st->print_cr("---------------  S U M M A R Y ------------");
 585        st->cr();
 586      }
 587 
 588   STEP("printing VM option summary")
 589 
 590      if (_verbose) {
 591        // VM options
 592        Arguments::print_summary_on(st);
 593        st->cr();
 594      }
 595 
 596   STEP("printing summary machine and OS info")
 597 
 598      if (_verbose) {
 599        os::print_summary_info(st, buf, sizeof(buf));
 600      }
 601 
 602 
 603   STEP("printing date and time")
 604 
 605      if (_verbose) {
 606        os::print_date_and_time(st, buf, sizeof(buf));
 607      }
 608 
 609   STEP("printing thread")
 610 
 611      if (_verbose) {
 612        st->cr();
 613        st->print_cr("---------------  T H R E A D  ---------------");
 614        st->cr();
 615      }
 616 
 617   STEP("printing current thread")
 618 
 619      // current thread
 620      if (_verbose) {
 621        if (_thread) {
 622          st->print("Current thread (" PTR_FORMAT "):  ", p2i(_thread));
 623          _thread->print_on_error(st, buf, sizeof(buf));
 624          st->cr();
 625        } else {
 626          st->print_cr("Current thread is native thread");
 627        }
 628        st->cr();
 629      }
 630 
 631   STEP("printing current compile task")
 632 
 633      if (_verbose && _thread && _thread->is_Compiler_thread()) {
 634         CompilerThread* t = (CompilerThread*)_thread;
 635         if (t->task()) {
 636            st->cr();
 637            st->print_cr("Current CompileTask:");
 638            t->task()->print_line_on_error(st, buf, sizeof(buf));
 639            st->cr();
 640         }
 641      }
 642 
 643 
 644   STEP("printing stack bounds")
 645 
 646      if (_verbose) {
 647        st->print("Stack: ");
 648 
 649        address stack_top;
 650        size_t stack_size;
 651 
 652        if (_thread) {
 653           stack_top = _thread->stack_base();
 654           stack_size = _thread->stack_size();
 655        } else {
 656           stack_top = os::current_stack_base();
 657           stack_size = os::current_stack_size();
 658        }
 659 
 660        address stack_bottom = stack_top - stack_size;
 661        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", p2i(stack_bottom), p2i(stack_top));
 662 
 663        frame fr = _context ? os::fetch_frame_from_context(_context)
 664                            : os::current_frame();
 665 
 666        if (fr.sp()) {
 667          st->print(",  sp=" PTR_FORMAT, p2i(fr.sp()));
 668          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 669          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 670        }
 671 
 672        st->cr();
 673      }
 674 
 675   STEP("printing native stack")
 676 
 677    if (_verbose) {
 678      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
 679        // We have printed the native stack in platform-specific code
 680        // Windows/x64 needs special handling.
 681      } else {
 682        frame fr = _context ? os::fetch_frame_from_context(_context)
 683                            : os::current_frame();
 684 
 685        print_native_stack(st, fr, _thread, buf, sizeof(buf));
 686      }
 687    }
 688 
 689   STEP("printing Java stack")
 690 
 691      if (_verbose && _thread && _thread->is_Java_thread()) {
 692        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
 693      }
 694 
 695   STEP("printing target Java thread stack")
 696 
 697      // printing Java thread stack trace if it is involved in GC crash
 698      if (_verbose && _thread && (_thread->is_Named_thread())) {
 699        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
 700        if (jt != NULL) {
 701          st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
 702          print_stack_trace(st, jt, buf, sizeof(buf), true);
 703        }
 704      }
 705 
 706   STEP("printing siginfo")
 707 
 708      // signal no, signal code, address that caused the fault
 709      if (_verbose && _siginfo) {
 710        st->cr();
 711        os::print_siginfo(st, _siginfo);
 712        st->cr();
 713      }
 714 
 715   STEP("CDS archive access warning")
 716 
 717      // Print an explicit hint if we crashed on access to the CDS archive.
 718      if (_verbose && _siginfo) {
 719        check_failing_cds_access(st, _siginfo);
 720        st->cr();
 721      }
 722 
 723   STEP("printing register info")
 724 
 725      // decode register contents if possible
 726      if (_verbose && _context && Universe::is_fully_initialized()) {
 727        os::print_register_info(st, _context);
 728        st->cr();
 729      }
 730 
 731   STEP("printing registers, top of stack, instructions near pc")
 732 
 733      // registers, top of stack, instructions near pc
 734      if (_verbose && _context) {
 735        os::print_context(st, _context);
 736        st->cr();
 737      }
 738 
 739   STEP("printing code blob if possible")
 740 
 741      if (_verbose && _context) {
 742        CodeBlob* cb = CodeCache::find_blob(_pc);
 743        if (cb != NULL) {
 744          if (Interpreter::contains(_pc)) {
 745            // The interpreter CodeBlob is very large so try to print the codelet instead.
 746            InterpreterCodelet* codelet = Interpreter::codelet_containing(_pc);
 747            if (codelet != NULL) {
 748              codelet->print_on(st);
 749              Disassembler::decode(codelet->code_begin(), codelet->code_end(), st);
 750            }
 751          } else {
 752            StubCodeDesc* desc = StubCodeDesc::desc_for(_pc);
 753            if (desc != NULL) {
 754              desc->print_on(st);
 755              Disassembler::decode(desc->begin(), desc->end(), st);
 756            } else {
 757              Disassembler::decode(cb, st);
 758              st->cr();
 759            }
 760          }
 761        }
 762      }
 763 
 764   STEP("printing VM operation")
 765 
 766      if (_verbose && _thread && _thread->is_VM_thread()) {
 767         VMThread* t = (VMThread*)_thread;
 768         VM_Operation* op = t->vm_operation();
 769         if (op) {
 770           op->print_on_error(st);
 771           st->cr();
 772           st->cr();
 773         }
 774      }
 775 
 776   STEP("printing process")
 777 
 778      if (_verbose) {
 779        st->cr();
 780        st->print_cr("---------------  P R O C E S S  ---------------");
 781        st->cr();
 782      }
 783 
 784   STEP("printing all threads")
 785 
 786      // all threads
 787      if (_verbose && _thread) {
 788        Threads::print_on_error(st, _thread, buf, sizeof(buf));
 789        st->cr();
 790      }
 791 
 792   STEP("printing VM state")
 793 
 794      if (_verbose) {
 795        // Safepoint state
 796        st->print("VM state:");
 797 
 798        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
 799        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
 800        else st->print("not at safepoint");
 801 
 802        // Also see if error occurred during initialization or shutdown
 803        if (!Universe::is_fully_initialized()) {
 804          st->print(" (not fully initialized)");
 805        } else if (VM_Exit::vm_exited()) {
 806          st->print(" (shutting down)");
 807        } else {
 808          st->print(" (normal execution)");
 809        }
 810        st->cr();
 811        st->cr();
 812      }
 813 
 814   STEP("printing owned locks on error")
 815 
 816      // mutexes/monitors that currently have an owner
 817      if (_verbose) {
 818        print_owned_locks_on_error(st);
 819        st->cr();
 820      }
 821 
 822   STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
 823 
 824      if (_verbose && Exceptions::has_exception_counts()) {
 825        st->print_cr("OutOfMemory and StackOverflow Exception counts:");
 826        Exceptions::print_exception_counts_on_error(st);
 827        st->cr();
 828      }
 829 
 830   STEP("printing compressed oops mode")
 831 
 832      if (_verbose && UseCompressedOops) {
 833        Universe::print_compressed_oops_mode(st);
 834        if (UseCompressedClassPointers) {
 835          Metaspace::print_compressed_class_space(st);
 836        }
 837        st->cr();
 838      }
 839 
 840   STEP("printing heap information")
 841 
 842      if (_verbose && Universe::is_fully_initialized()) {
 843        Universe::heap()->print_on_error(st);
 844        st->cr();
 845        st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
 846        st->cr();
 847      }
 848 
 849   STEP("printing code cache information")
 850 
 851      if (_verbose && Universe::is_fully_initialized()) {
 852        // print code cache information before vm abort
 853        CodeCache::print_summary(st);
 854        st->cr();
 855      }
 856 
 857   STEP("printing ring buffers")
 858 
 859      if (_verbose) {
 860        Events::print_all(st);
 861        st->cr();
 862      }
 863 
 864   STEP("printing dynamic libraries")
 865 
 866      if (_verbose) {
 867        // dynamic libraries, or memory map
 868        os::print_dll_info(st);
 869        st->cr();
 870      }
 871 
 872   STEP("printing VM options")
 873 
 874      if (_verbose) {
 875        // VM options
 876        Arguments::print_on(st);
 877        st->cr();
 878      }
 879 
 880   STEP("printing warning if internal testing API used")
 881 
 882      if (WhiteBox::used()) {
 883        st->print_cr("Unsupported internal testing APIs have been used.");
 884        st->cr();
 885      }
 886 
 887   STEP("printing log configuration")
 888     if (_verbose){
 889       st->print_cr("Logging:");
 890       LogConfiguration::describe_current_configuration(st);
 891       st->cr();
 892     }
 893 
 894   STEP("printing all environment variables")
 895 
 896      if (_verbose) {
 897        os::print_environment_variables(st, env_list);
 898        st->cr();
 899      }
 900 
 901   STEP("printing signal handlers")
 902 
 903      if (_verbose) {
 904        os::print_signal_handlers(st, buf, sizeof(buf));
 905        st->cr();
 906      }
 907 
 908   STEP("Native Memory Tracking")
 909      if (_verbose) {
 910        MemTracker::error_report(st);
 911      }
 912 
 913   STEP("printing system")
 914 
 915      if (_verbose) {
 916        st->cr();
 917        st->print_cr("---------------  S Y S T E M  ---------------");
 918        st->cr();
 919      }
 920 
 921   STEP("printing OS information")
 922 
 923      if (_verbose) {
 924        os::print_os_info(st);
 925        st->cr();
 926      }
 927 
 928   STEP("printing CPU info")
 929      if (_verbose) {
 930        os::print_cpu_info(st, buf, sizeof(buf));
 931        st->cr();
 932      }
 933 
 934   STEP("printing memory info")
 935 
 936      if (_verbose) {
 937        os::print_memory_info(st);
 938        st->cr();
 939      }
 940 
 941   STEP("printing internal vm info")
 942 
 943      if (_verbose) {
 944        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
 945        st->cr();
 946      }
 947 
 948   // print a defined marker to show that error handling finished correctly.
 949   STEP("printing end marker")
 950 
 951      if (_verbose) {
 952        st->print_cr("END.");
 953      }
 954 
 955   END
 956 
 957 # undef BEGIN
 958 # undef STEP
 959 # undef END
 960 }
 961 
 962 // Report for the vm_info_cmd. This prints out the information above omitting
 963 // crash and thread specific information.  If output is added above, it should be added
 964 // here also, if it is safe to call during a running process.
 965 void VMError::print_vm_info(outputStream* st) {
 966 
 967   char buf[O_BUFLEN];
 968   report_vm_version(st, buf, sizeof(buf));
 969 
 970   // STEP("printing summary")
 971 
 972   st->cr();
 973   st->print_cr("---------------  S U M M A R Y ------------");
 974   st->cr();
 975 
 976   // STEP("printing VM option summary")
 977 
 978   // VM options
 979   Arguments::print_summary_on(st);
 980   st->cr();
 981 
 982   // STEP("printing summary machine and OS info")
 983 
 984   os::print_summary_info(st, buf, sizeof(buf));
 985 
 986   // STEP("printing date and time")
 987 
 988   os::print_date_and_time(st, buf, sizeof(buf));
 989 
 990   // Skip: STEP("printing thread")
 991 
 992   // STEP("printing process")
 993 
 994   st->cr();
 995   st->print_cr("---------------  P R O C E S S  ---------------");
 996   st->cr();
 997 
 998   // STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
 999 
1000   if (Exceptions::has_exception_counts()) {
1001     st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1002     Exceptions::print_exception_counts_on_error(st);
1003     st->cr();
1004   }
1005 
1006   // STEP("printing compressed oops mode")
1007 
1008   if (UseCompressedOops) {
1009     Universe::print_compressed_oops_mode(st);
1010     if (UseCompressedClassPointers) {
1011       Metaspace::print_compressed_class_space(st);
1012     }
1013     st->cr();
1014   }
1015 
1016   // STEP("printing heap information")
1017 
1018   if (Universe::is_fully_initialized()) {
1019     MutexLocker hl(Heap_lock);
1020     Universe::heap()->print_on_error(st);
1021     st->cr();
1022     st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
1023     st->cr();
1024   }
1025 
1026   // STEP("printing code cache information")
1027 
1028   if (Universe::is_fully_initialized()) {
1029     // print code cache information before vm abort
1030     CodeCache::print_summary(st);
1031     st->cr();
1032   }
1033 
1034   // STEP("printing ring buffers")
1035 
1036   Events::print_all(st);
1037   st->cr();
1038 
1039   // STEP("printing dynamic libraries")
1040 
1041   // dynamic libraries, or memory map
1042   os::print_dll_info(st);
1043   st->cr();
1044 
1045   // STEP("printing VM options")
1046 
1047   // VM options
1048   Arguments::print_on(st);
1049   st->cr();
1050 
1051   // STEP("printing warning if internal testing API used")
1052 
1053   if (WhiteBox::used()) {
1054     st->print_cr("Unsupported internal testing APIs have been used.");
1055     st->cr();
1056   }
1057 
1058   // STEP("printing log configuration")
1059   st->print_cr("Logging:");
1060   LogConfiguration::describe(st);
1061   st->cr();
1062 
1063   // STEP("printing all environment variables")
1064 
1065   os::print_environment_variables(st, env_list);
1066   st->cr();
1067 
1068   // STEP("printing signal handlers")
1069 
1070   os::print_signal_handlers(st, buf, sizeof(buf));
1071   st->cr();
1072 
1073   // STEP("Native Memory Tracking")
1074 
1075   MemTracker::error_report(st);
1076 
1077   // STEP("printing system")
1078 
1079   st->cr();
1080   st->print_cr("---------------  S Y S T E M  ---------------");
1081   st->cr();
1082 
1083   // STEP("printing OS information")
1084 
1085   os::print_os_info(st);
1086   st->cr();
1087 
1088   // STEP("printing CPU info")
1089 
1090   os::print_cpu_info(st, buf, sizeof(buf));
1091   st->cr();
1092 
1093   // STEP("printing memory info")
1094 
1095   os::print_memory_info(st);
1096   st->cr();
1097 
1098   // STEP("printing internal vm info")
1099 
1100   st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
1101   st->cr();
1102 
1103   // print a defined marker to show that error handling finished correctly.
1104   // STEP("printing end marker")
1105 
1106   st->print_cr("END.");
1107 }
1108 
1109 volatile intptr_t VMError::first_error_tid = -1;
1110 
1111 // An error could happen before tty is initialized or after it has been
1112 // destroyed.
1113 // Please note: to prevent large stack allocations, the log- and
1114 // output-stream use a global scratch buffer for format printing.
1115 // (see VmError::report_and_die(). Access to those streams is synchronized
1116 // in  VmError::report_and_die() - there is only one reporting thread at
1117 // any given time.
1118 fdStream VMError::out(defaultStream::output_fd());
1119 fdStream VMError::log; // error log used by VMError::report_and_die()
1120 
1121 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
1122 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
1123   int fd = -1;
1124   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
1125     // the O_EXCL flag will cause the open to fail if the file exists
1126     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
1127   }
1128   return fd;
1129 }
1130 
1131 /**
1132  * Construct file name for a log file and return it's file descriptor.
1133  * Name and location depends on pattern, default_pattern params and access
1134  * permissions.
1135  */
1136 static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
1137   int fd = -1;
1138 
1139   // If possible, use specified pattern to construct log file name
1140   if (pattern != NULL) {
1141     fd = expand_and_open(pattern, buf, buflen, 0);
1142   }
1143 
1144   // Either user didn't specify, or the user's location failed,
1145   // so use the default name in the current directory
1146   if (fd == -1) {
1147     const char* cwd = os::get_current_directory(buf, buflen);
1148     if (cwd != NULL) {
1149       size_t pos = strlen(cwd);
1150       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1151       pos += fsep_len;
1152       if (fsep_len > 0) {
1153         fd = expand_and_open(default_pattern, buf, buflen, pos);
1154       }
1155     }
1156   }
1157 
1158    // try temp directory if it exists.
1159    if (fd == -1) {
1160      const char* tmpdir = os::get_temp_directory();
1161      if (tmpdir != NULL && strlen(tmpdir) > 0) {
1162        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1163        if (pos > 0) {
1164          fd = expand_and_open(default_pattern, buf, buflen, pos);
1165        }
1166      }
1167    }
1168 
1169   return fd;
1170 }
1171 
1172 int         VMError::_id;
1173 const char* VMError::_message;
1174 char        VMError::_detail_msg[1024];
1175 Thread*     VMError::_thread;
1176 address     VMError::_pc;
1177 void*       VMError::_siginfo;
1178 void*       VMError::_context;
1179 const char* VMError::_filename;
1180 int         VMError::_lineno;
1181 size_t      VMError::_size;
1182 
1183 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1184                              void* context, const char* detail_fmt, ...)
1185 {
1186   va_list detail_args;
1187   va_start(detail_args, detail_fmt);
1188   report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1189   va_end(detail_args);
1190 }
1191 
1192 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1193 {
1194   report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1195 }
1196 
1197 void VMError::report_and_die(const char* message, const char* detail_fmt, ...)
1198 {
1199   va_list detail_args;
1200   va_start(detail_args, detail_fmt);
1201   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, NULL, NULL, NULL, NULL, NULL, 0, 0);
1202   va_end(detail_args);
1203 }
1204 
1205 void VMError::report_and_die(const char* message)
1206 {
1207   report_and_die(message, "%s", "");
1208 }
1209 
1210 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, const char* message,
1211                              const char* detail_fmt, va_list detail_args)
1212 {
1213   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, 0);
1214 }
1215 
1216 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1217                              VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1218   report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1219 }
1220 
1221 void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1222                              Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1223                              int lineno, size_t size)
1224 {
1225   // Don't allocate large buffer on stack
1226   static char buffer[O_BUFLEN];
1227   out.set_scratch_buffer(buffer, sizeof(buffer));
1228   log.set_scratch_buffer(buffer, sizeof(buffer));
1229 
1230   // How many errors occurred in error handler when reporting first_error.
1231   static int recursive_error_count;
1232 
1233   // We will first print a brief message to standard out (verbose = false),
1234   // then save detailed information in log file (verbose = true).
1235   static bool out_done = false;         // done printing to standard out
1236   static bool log_done = false;         // done saving error log
1237   static bool transmit_report_done = false; // done error reporting
1238 
1239   if (SuppressFatalErrorMessage) {
1240       os::abort(CreateCoredumpOnCrash);
1241   }
1242   intptr_t mytid = os::current_thread_id();
1243   if (first_error_tid == -1 &&
1244       Atomic::cmpxchg_ptr(mytid, &first_error_tid, -1) == -1) {
1245 
1246     // Initialize time stamps to use the same base.
1247     out.time_stamp().update_to(1);
1248     log.time_stamp().update_to(1);
1249 
1250     _id = id;
1251     _message = message;
1252     _thread = thread;
1253     _pc = pc;
1254     _siginfo = siginfo;
1255     _context = context;
1256     _filename = filename;
1257     _lineno = lineno;
1258     _size = size;
1259     jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1260 
1261     // first time
1262     set_error_reported();
1263 
1264     reporting_started();
1265     record_reporting_start_time();
1266 
1267     if (ShowMessageBoxOnError || PauseAtExit) {
1268       show_message_box(buffer, sizeof(buffer));
1269 
1270       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1271       // WatcherThread can kill JVM if the error handler hangs.
1272       ShowMessageBoxOnError = false;
1273     }
1274 
1275     os::check_dump_limit(buffer, sizeof(buffer));
1276 
1277     // reset signal handlers or exception filter; make sure recursive crashes
1278     // are handled properly.
1279     reset_signal_handlers();
1280 
1281     TRACE_VM_ERROR();
1282 
1283   } else {
1284     // If UseOsErrorReporting we call this for each level of the call stack
1285     // while searching for the exception handler.  Only the first level needs
1286     // to be reported.
1287     if (UseOSErrorReporting && log_done) return;
1288 
1289     // This is not the first error, see if it happened in a different thread
1290     // or in the same thread during error reporting.
1291     if (first_error_tid != mytid) {
1292       char msgbuf[64];
1293       jio_snprintf(msgbuf, sizeof(msgbuf),
1294                    "[thread " INTX_FORMAT " also had an error]",
1295                    mytid);
1296       out.print_raw_cr(msgbuf);
1297 
1298       // error reporting is not MT-safe, block current thread
1299       os::infinite_sleep();
1300 
1301     } else {
1302       if (recursive_error_count++ > 30) {
1303         out.print_raw_cr("[Too many errors, abort]");
1304         os::die();
1305       }
1306 
1307       outputStream* const st = log.is_open() ? &log : &out;
1308       st->cr();
1309 
1310       // Timeout handling.
1311       if (_step_did_timeout) {
1312         // The current step had a timeout. Lets continue reporting with the next step.
1313         st->print_raw("[timeout occurred during error reporting in step \"");
1314         st->print_raw(_current_step_info);
1315         st->print_cr("\"] after " INT64_FORMAT " s.",
1316           (get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR);
1317       } else if (_reporting_did_timeout) {
1318         // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1319         // up, the process is about to be stopped by the WatcherThread.
1320         st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1321           (get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR);
1322         st->flush();
1323         // Watcherthread is about to call os::die. Lets just wait.
1324         os::infinite_sleep();
1325       } else {
1326         // Crash or assert during error reporting. Lets continue reporting with the next step.
1327         jio_snprintf(buffer, sizeof(buffer),
1328            "[error occurred during error reporting (%s), id 0x%x]",
1329                    _current_step_info, _id);
1330         st->print_raw_cr(buffer);
1331         st->cr();
1332       }
1333     }
1334   }
1335 
1336   // print to screen
1337   if (!out_done) {
1338     report(&out, false);
1339 
1340     out_done = true;
1341 
1342     _current_step = 0;
1343     _current_step_info = "";
1344   }
1345 
1346   // print to error log file
1347   if (!log_done) {
1348     // see if log file is already open
1349     if (!log.is_open()) {
1350       // open log file
1351       int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1352       if (fd != -1) {
1353         out.print_raw("# An error report file with more information is saved as:\n# ");
1354         out.print_raw_cr(buffer);
1355 
1356         log.set_fd(fd);
1357       } else {
1358         out.print_raw_cr("# Can not save log file, dump to screen..");
1359         log.set_fd(defaultStream::output_fd());
1360         /* Error reporting currently needs dumpfile.
1361          * Maybe implement direct streaming in the future.*/
1362         transmit_report_done = true;
1363       }
1364     }
1365 
1366     report(&log, true);
1367     log_done = true;
1368     _current_step = 0;
1369     _current_step_info = "";
1370 
1371     // Run error reporting to determine whether or not to report the crash.
1372     if (!transmit_report_done && should_report_bug(_id)) {
1373       transmit_report_done = true;
1374       const int fd2 = ::dup(log.fd());
1375       if (fd2 != -1) {
1376         FILE* const hs_err = ::fdopen(fd2, "r");
1377         if (NULL != hs_err) {
1378           ErrorReporter er;
1379           er.call(hs_err, buffer, O_BUFLEN);
1380           ::fclose(hs_err);
1381         }
1382       }
1383     }
1384 
1385     if (log.fd() != defaultStream::output_fd()) {
1386       close(log.fd());
1387     }
1388 
1389     log.set_fd(-1);
1390   }
1391 
1392   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1393   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1394     skip_replay = true;
1395     ciEnv* env = ciEnv::current();
1396     if (env != NULL) {
1397       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1398       if (fd != -1) {
1399         FILE* replay_data_file = os::open(fd, "w");
1400         if (replay_data_file != NULL) {
1401           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1402           env->dump_replay_data_unsafe(&replay_data_stream);
1403           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1404           out.print_raw_cr(buffer);
1405         } else {
1406           int e = errno;
1407           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1408           out.print_raw_cr(os::strerror(e));
1409         }
1410       }
1411     }
1412   }
1413 
1414   static bool skip_bug_url = !should_report_bug(_id);
1415   if (!skip_bug_url) {
1416     skip_bug_url = true;
1417 
1418     out.print_raw_cr("#");
1419     print_bug_submit_message(&out, _thread);
1420   }
1421 
1422   static bool skip_OnError = false;
1423   if (!skip_OnError && OnError && OnError[0]) {
1424     skip_OnError = true;
1425 
1426     // Flush output and finish logs before running OnError commands.
1427     ostream_abort();
1428 
1429     out.print_raw_cr("#");
1430     out.print_raw   ("# -XX:OnError=\"");
1431     out.print_raw   (OnError);
1432     out.print_raw_cr("\"");
1433 
1434     char* cmd;
1435     const char* ptr = OnError;
1436     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1437       out.print_raw   ("#   Executing ");
1438 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1439       out.print_raw   ("/bin/sh -c ");
1440 #elif defined(SOLARIS)
1441       out.print_raw   ("/usr/bin/sh -c ");
1442 #elif defined(WINDOWS)
1443       out.print_raw   ("cmd /C ");
1444 #endif
1445       out.print_raw   ("\"");
1446       out.print_raw   (cmd);
1447       out.print_raw_cr("\" ...");
1448 
1449       if (os::fork_and_exec(cmd) < 0) {
1450         out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1451                      os::strerror(errno), os::errno_name(errno), errno);
1452       }
1453     }
1454 
1455     // done with OnError
1456     OnError = NULL;
1457   }
1458 
1459   if (!UseOSErrorReporting) {
1460     // os::abort() will call abort hooks, try it first.
1461     static bool skip_os_abort = false;
1462     if (!skip_os_abort) {
1463       skip_os_abort = true;
1464       bool dump_core = should_report_bug(_id);
1465       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1466     }
1467 
1468     // if os::abort() doesn't abort, try os::die();
1469     os::die();
1470   }
1471 }
1472 
1473 /*
1474  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1475  * ensures utilities such as jmap can observe the process is a consistent state.
1476  */
1477 class VM_ReportJavaOutOfMemory : public VM_Operation {
1478  private:
1479   const char* _message;
1480  public:
1481   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1482   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1483   void doit();
1484 };
1485 
1486 void VM_ReportJavaOutOfMemory::doit() {
1487   // Don't allocate large buffer on stack
1488   static char buffer[O_BUFLEN];
1489 
1490   tty->print_cr("#");
1491   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1492   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1493 
1494   // make heap parsability
1495   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1496 
1497   char* cmd;
1498   const char* ptr = OnOutOfMemoryError;
1499   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1500     tty->print("#   Executing ");
1501 #if defined(LINUX)
1502     tty->print  ("/bin/sh -c ");
1503 #elif defined(SOLARIS)
1504     tty->print  ("/usr/bin/sh -c ");
1505 #endif
1506     tty->print_cr("\"%s\"...", cmd);
1507 
1508     if (os::fork_and_exec(cmd) < 0) {
1509       tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1510                      os::strerror(errno), os::errno_name(errno), errno);
1511     }
1512   }
1513 }
1514 
1515 void VMError::report_java_out_of_memory(const char* message) {
1516   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1517     MutexLocker ml(Heap_lock);
1518     VM_ReportJavaOutOfMemory op(message);
1519     VMThread::execute(&op);
1520   }
1521 }
1522 
1523 void VMError::show_message_box(char *buf, int buflen) {
1524   bool yes;
1525   do {
1526     error_string(buf, buflen);
1527     yes = os::start_debugging(buf,buflen);
1528   } while (yes);
1529 }
1530 
1531 // Timeout handling: check if a timeout happened (either a single step did
1532 // timeout or the whole of error reporting hit ErrorLogTimeout). Interrupt
1533 // the reporting thread if that is the case.
1534 bool VMError::check_timeout() {
1535 
1536   if (ErrorLogTimeout == 0) {
1537     return false;
1538   }
1539 
1540   // Do not check for timeouts if we still have a message box to show to the
1541   // user or if there are OnError handlers to be run.
1542   if (ShowMessageBoxOnError
1543       || (OnError != NULL && OnError[0] != '\0')
1544       || Arguments::abort_hook() != NULL) {
1545     return false;
1546   }
1547 
1548   const jlong reporting_start_time_l = get_reporting_start_time();
1549   const jlong now = get_current_timestamp();
1550   // Timestamp is stored in nanos.
1551   if (reporting_start_time_l > 0) {
1552     const jlong end = reporting_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1553     if (end <= now) {
1554       _reporting_did_timeout = true;
1555       interrupt_reporting_thread();
1556       return true; // global timeout
1557     }
1558   }
1559 
1560   const jlong step_start_time_l = get_step_start_time();
1561   if (step_start_time_l > 0) {
1562     // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1563     // hang for some reason, so this simple rule allows for three hanging step and still
1564     // hopefully leaves time enough for the rest of the steps to finish.
1565     const jlong end = step_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4;
1566     if (end <= now) {
1567       _step_did_timeout = true;
1568       interrupt_reporting_thread();
1569       return false; // (Not a global timeout)
1570     }
1571   }
1572 
1573   return false;
1574 
1575 }
1576