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