1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2017, 2020 SAP SE. All rights reserved.
   4  * Copyright (c) 2023, Red Hat, Inc. and/or its affiliates.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "jvm.h"
  29 #include "cds/metaspaceShared.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "compiler/compileBroker.hpp"
  32 #include "compiler/disassembler.hpp"
  33 #include "gc/shared/gcConfig.hpp"
  34 #include "gc/shared/gcLogPrecious.hpp"
  35 #include "logging/logConfiguration.hpp"
  36 #include "memory/metaspace.hpp"
  37 #include "memory/metaspaceUtils.hpp"
  38 #include "memory/resourceArea.inline.hpp"
  39 #include "memory/universe.hpp"
  40 #include "oops/compressedOops.hpp"
  41 #include "prims/whitebox.hpp"
  42 #include "runtime/arguments.hpp"
  43 #include "runtime/atomic.hpp"
  44 #include "runtime/frame.inline.hpp"
  45 #include "runtime/init.hpp"
  46 #include "runtime/os.hpp"
  47 #include "runtime/osThread.hpp"
  48 #include "runtime/safefetch.hpp"
  49 #include "runtime/safepointMechanism.hpp"
  50 #include "runtime/stackFrameStream.inline.hpp"
  51 #include "runtime/thread.inline.hpp"
  52 #include "runtime/threadSMR.hpp"
  53 #include "runtime/trimNativeHeap.hpp"
  54 #include "runtime/vmThread.hpp"
  55 #include "runtime/vmOperations.hpp"
  56 #include "runtime/vm_version.hpp"
  57 #include "runtime/flags/jvmFlag.hpp"
  58 #include "services/memTracker.hpp"
  59 #include "utilities/debug.hpp"
  60 #include "utilities/decoder.hpp"
  61 #include "utilities/defaultStream.hpp"
  62 #include "utilities/events.hpp"
  63 #include "utilities/vmError.hpp"
  64 #include "utilities/macros.hpp"
  65 #if INCLUDE_JFR
  66 #include "jfr/jfr.hpp"
  67 #endif
  68 
  69 #ifndef PRODUCT
  70 #include <signal.h>
  71 #endif // PRODUCT
  72 
  73 bool              VMError::coredump_status;
  74 char              VMError::coredump_message[O_BUFLEN];
  75 int               VMError::_current_step;
  76 const char*       VMError::_current_step_info;
  77 volatile jlong    VMError::_reporting_start_time = -1;
  78 volatile bool     VMError::_reporting_did_timeout = false;
  79 volatile jlong    VMError::_step_start_time = -1;
  80 volatile bool     VMError::_step_did_timeout = false;
  81 volatile intptr_t VMError::_first_error_tid = -1;
  82 int               VMError::_id;
  83 const char*       VMError::_message;
  84 char              VMError::_detail_msg[1024];
  85 Thread*           VMError::_thread;
  86 address           VMError::_pc;
  87 void*             VMError::_siginfo;
  88 void*             VMError::_context;
  89 bool              VMError::_print_native_stack_used = false;
  90 const char*       VMError::_filename;
  91 int               VMError::_lineno;
  92 size_t            VMError::_size;
  93 
  94 // List of environment variables that should be reported in error log file.
  95 static const char* env_list[] = {
  96   // All platforms
  97   "JAVA_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
  98   "PATH", "USERNAME",
  99 
 100   "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "FC_LANG", "FONTCONFIG_USE_MMAP",
 101 
 102   // Env variables that are defined on Linux/BSD
 103   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
 104   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
 105   "LANG", "LC_ALL", "LC_CTYPE", "LC_NUMERIC", "LC_TIME",
 106   "TERM", "TMPDIR", "TZ",
 107 
 108   // defined on AIX
 109   "LIBPATH", "LDR_PRELOAD", "LDR_PRELOAD64",
 110 
 111   // defined on Linux/AIX/BSD
 112   "_JAVA_SR_SIGNUM",
 113 
 114   // defined on Darwin
 115   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
 116   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
 117   "DYLD_INSERT_LIBRARIES",
 118 
 119   // defined on Windows
 120   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR", "TMP", "TEMP",
 121 
 122   (const char *)0
 123 };
 124 
 125 // A simple parser for -XX:OnError, usage:
 126 //  ptr = OnError;
 127 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
 128 //     ... ...
 129 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
 130   if (ptr == NULL || *ptr == NULL) return NULL;
 131 
 132   const char* cmd = *ptr;
 133 
 134   // skip leading blanks or ';'
 135   while (*cmd == ' ' || *cmd == ';') cmd++;
 136 
 137   if (*cmd == '\0') return NULL;
 138 
 139   const char * cmdend = cmd;
 140   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
 141 
 142   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
 143 
 144   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
 145   return buf;
 146 }
 147 
 148 static void print_bug_submit_message(outputStream *out, Thread *thread) {
 149   if (out == NULL) return;
 150   const char *url = Arguments::java_vendor_url_bug();
 151   if (url == NULL || *url == '\0')
 152     url = JDK_Version::runtime_vendor_vm_bug_url();
 153   if (url != NULL && *url != '\0') {
 154     out->print_raw_cr("# If you would like to submit a bug report, please visit:");
 155     out->print_raw   ("#   ");
 156     out->print_raw_cr(url);
 157   }
 158   // If the crash is in native code, encourage user to submit a bug to the
 159   // provider of that code.
 160   if (thread && thread->is_Java_thread() &&
 161       !thread->is_hidden_from_external_view()) {
 162     if (thread->as_Java_thread()->thread_state() == _thread_in_native) {
 163       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
 164     }
 165   }
 166   out->print_raw_cr("#");
 167 }
 168 
 169 void VMError::record_coredump_status(const char* message, bool status) {
 170   coredump_status = status;
 171   strncpy(coredump_message, message, sizeof(coredump_message));
 172   coredump_message[sizeof(coredump_message)-1] = 0;
 173 }
 174 
 175 // Return a string to describe the error
 176 char* VMError::error_string(char* buf, int buflen) {
 177   char signame_buf[64];
 178   const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
 179 
 180   if (signame) {
 181     jio_snprintf(buf, buflen,
 182                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
 183                  signame, _id, _pc,
 184                  os::current_process_id(), os::current_thread_id());
 185   } else if (_filename != NULL && _lineno > 0) {
 186     // skip directory names
 187     char separator = os::file_separator()[0];
 188     const char *p = strrchr(_filename, separator);
 189     int n = jio_snprintf(buf, buflen,
 190                          "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
 191                          p ? p + 1 : _filename, _lineno,
 192                          os::current_process_id(), os::current_thread_id());
 193     if (n >= 0 && n < buflen && _message) {
 194       if (strlen(_detail_msg) > 0) {
 195         jio_snprintf(buf + n, buflen - n, "%s%s: %s",
 196         os::line_separator(), _message, _detail_msg);
 197       } else {
 198         jio_snprintf(buf + n, buflen - n, "%sError: %s",
 199                      os::line_separator(), _message);
 200       }
 201     }
 202   } else {
 203     jio_snprintf(buf, buflen,
 204                  "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
 205                  _id, os::current_process_id(), os::current_thread_id());
 206   }
 207 
 208   return buf;
 209 }
 210 
 211 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
 212                                 char* buf, int buflen, bool verbose) {
 213 #ifdef ZERO
 214   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
 215     // StackFrameStream uses the frame anchor, which may not have
 216     // been set up.  This can be done at any time in Zero, however,
 217     // so if it hasn't been set up then we just set it up now and
 218     // clear it again when we're done.
 219     bool has_last_Java_frame = jt->has_last_Java_frame();
 220     if (!has_last_Java_frame)
 221       jt->set_last_Java_frame();
 222     st->print("Java frames:");
 223     st->cr();
 224 
 225     // Print the frames
 226     StackFrameStream sfs(jt, true /* update */, true /* process_frames */);
 227     for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
 228       sfs.current()->zero_print_on_error(i, st, buf, buflen);
 229       st->cr();
 230     }
 231 
 232     // Reset the frame anchor if necessary
 233     if (!has_last_Java_frame)
 234       jt->reset_last_Java_frame();
 235   }
 236 #else
 237   if (jt->has_last_Java_frame()) {
 238     st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
 239     for (StackFrameStream sfs(jt, true /* update */, true /* process_frames */); !sfs.is_done(); sfs.next()) {
 240       sfs.current()->print_on_error(st, buf, buflen, verbose);
 241       st->cr();
 242     }
 243   }
 244 #endif // ZERO
 245 }
 246 
 247 /**
 248  * Adds `value` to `list` iff it's not already present and there is sufficient
 249  * capacity (i.e. length(list) < `list_capacity`). The length of the list
 250  * is the index of the first nullptr entry or `list_capacity` if there are
 251  * no nullptr entries.
 252  *
 253  * @ return true if the value was added, false otherwise
 254  */
 255 static bool add_if_absent(address value, address* list, int list_capacity) {
 256   for (int i = 0; i < list_capacity; i++) {
 257     if (list[i] == value) {
 258       return false;
 259     }
 260     if (list[i] == nullptr) {
 261       list[i] = value;
 262       if (i + 1 < list_capacity) {
 263         list[i + 1] = nullptr;
 264       }
 265       return true;
 266     }
 267   }
 268   return false;
 269 }
 270 
 271 /**
 272  * Prints the VM generated code unit, if any, containing `pc` if it has not already
 273  * been printed. If the code unit is an InterpreterCodelet or StubCodeDesc, it is
 274  * only printed if `is_crash_pc` is true.
 275  *
 276  * @param printed array of code units that have already been printed (delimited by NULL entry)
 277  * @param printed_capacity the capacity of `printed`
 278  * @return true if the code unit was printed, false otherwise
 279  */
 280 static bool print_code(outputStream* st, Thread* thread, address pc, bool is_crash_pc,
 281                        address* printed, int printed_capacity) {
 282   if (Interpreter::contains(pc)) {
 283     if (is_crash_pc) {
 284       // The interpreter CodeBlob is very large so try to print the codelet instead.
 285       InterpreterCodelet* codelet = Interpreter::codelet_containing(pc);
 286       if (codelet != nullptr) {
 287         if (add_if_absent((address) codelet, printed, printed_capacity)) {
 288           codelet->print_on(st);
 289           Disassembler::decode(codelet->code_begin(), codelet->code_end(), st);
 290           return true;
 291         }
 292       }
 293     }
 294   } else {
 295     StubCodeDesc* desc = StubCodeDesc::desc_for(pc);
 296     if (desc != nullptr) {
 297       if (is_crash_pc) {
 298         if (add_if_absent((address) desc, printed, printed_capacity)) {
 299           desc->print_on(st);
 300           Disassembler::decode(desc->begin(), desc->end(), st);
 301           return true;
 302         }
 303       }
 304     } else if (thread != nullptr) {
 305       CodeBlob* cb = CodeCache::find_blob(pc);
 306       if (cb != nullptr && add_if_absent((address) cb, printed, printed_capacity)) {
 307         // Disassembling nmethod will incur resource memory allocation,
 308         // only do so when thread is valid.
 309         ResourceMark rm(thread);
 310         Disassembler::decode(cb, st);
 311         st->cr();
 312         return true;
 313       }
 314     }
 315   }
 316   return false;
 317 }
 318 
 319 // Like above, but only try to figure out a short name. Return nullptr if not found.
 320 static const char* find_code_name(address pc) {
 321   if (Interpreter::contains(pc)) {
 322     InterpreterCodelet* codelet = Interpreter::codelet_containing(pc);
 323     if (codelet != nullptr) {
 324       return codelet->description();
 325     }
 326   } else {
 327     StubCodeDesc* desc = StubCodeDesc::desc_for(pc);
 328     if (desc != nullptr) {
 329       return desc->name();
 330     } else {
 331       CodeBlob* cb = CodeCache::find_blob(pc);
 332       if (cb != nullptr) {
 333         return cb->name();
 334       }
 335     }
 336   }
 337   return nullptr;
 338 }
 339 
 340 /**
 341  * Gets the caller frame of `fr`.
 342  *
 343  * @returns an invalid frame (i.e. fr.pc() === 0) if the caller cannot be obtained
 344  */
 345 static frame next_frame(frame fr, Thread* t) {
 346   // Compiled code may use EBP register on x86 so it looks like
 347   // non-walkable C frame. Use frame.sender() for java frames.
 348   frame invalid;
 349   if (t != nullptr && t->is_Java_thread()) {
 350     // Catch very first native frame by using stack address.
 351     // For JavaThread stack_base and stack_size should be set.
 352     if (!t->is_in_full_stack((address)(fr.real_fp() + 1))) {
 353       return invalid;
 354     }
 355     if (fr.is_java_frame() || fr.is_native_frame() || fr.is_runtime_frame()) {
 356       RegisterMap map(t->as_Java_thread(), false); // No update
 357       return fr.sender(&map);
 358     } else {
 359       // is_first_C_frame() does only simple checks for frame pointer,
 360       // it will pass if java compiled code has a pointer in EBP.
 361       if (os::is_first_C_frame(&fr)) return invalid;
 362       return os::get_sender_for_C_frame(&fr);
 363     }
 364   } else {
 365     if (os::is_first_C_frame(&fr)) return invalid;
 366     return os::get_sender_for_C_frame(&fr);
 367   }
 368 }
 369 
 370 void VMError::print_native_stack(outputStream* st, frame fr, Thread* t, char* buf, int buf_size) {
 371 
 372   // see if it's a valid frame
 373   if (fr.pc()) {
 374     st->print_cr("Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)");
 375 
 376     int count = 0;
 377     while (count++ < StackPrintLimit) {
 378       fr.print_on_error(st, buf, buf_size);
 379       if (fr.pc()) { // print source file and line, if available
 380         char buf[128];
 381         int line_no;
 382         if (Decoder::get_source_info(fr.pc(), buf, sizeof(buf), &line_no)) {
 383           st->print("  (%s:%d)", buf, line_no);
 384         }
 385       }
 386       st->cr();
 387       fr = next_frame(fr, t);
 388       if (fr.pc() == nullptr) {
 389         break;
 390       }
 391     }
 392 
 393     if (count > StackPrintLimit) {
 394       st->print_cr("...<more frames>...");
 395     }
 396 
 397     st->cr();
 398   }
 399 }
 400 
 401 static void print_oom_reasons(outputStream* st) {
 402   st->print_cr("# Possible reasons:");
 403   st->print_cr("#   The system is out of physical RAM or swap space");
 404   if (UseCompressedOops) {
 405     st->print_cr("#   This process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
 406   }
 407   if (LogBytesPerWord == 2) {
 408     st->print_cr("#   In 32 bit mode, the process size limit was hit");
 409   }
 410   st->print_cr("# Possible solutions:");
 411   st->print_cr("#   Reduce memory load on the system");
 412   st->print_cr("#   Increase physical memory or swap space");
 413   st->print_cr("#   Check if swap backing store is full");
 414   if (LogBytesPerWord == 2) {
 415     st->print_cr("#   Use 64 bit Java on a 64 bit OS");
 416   }
 417   st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
 418   st->print_cr("#   Decrease number of Java threads");
 419   st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
 420   st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
 421   if (UseCompressedOops) {
 422     switch (CompressedOops::mode()) {
 423       case CompressedOops::UnscaledNarrowOop:
 424         st->print_cr("#   JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
 425         st->print_cr("#     placed in the first 4GB address space. The Java Heap base address is the");
 426         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 427         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
 428         break;
 429       case CompressedOops::ZeroBasedNarrowOop:
 430         st->print_cr("#   JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
 431         st->print_cr("#     placed in the first 32GB address space. The Java Heap base address is the");
 432         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 433         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
 434         break;
 435       default:
 436         break;
 437     }
 438   }
 439   st->print_cr("# This output file may be truncated or incomplete.");
 440 }
 441 
 442 static void report_vm_version(outputStream* st, char* buf, int buflen) {
 443    // VM version
 444    st->print_cr("#");
 445    JDK_Version::current().to_string(buf, buflen);
 446    const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 447                                 JDK_Version::runtime_name() : "";
 448    const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 449                                    JDK_Version::runtime_version() : "";
 450    const char* vendor_version = JDK_Version::runtime_vendor_version() != NULL ?
 451                                   JDK_Version::runtime_vendor_version() : "";
 452    const char* jdk_debug_level = VM_Version::printable_jdk_debug_level() != NULL ?
 453                                    VM_Version::printable_jdk_debug_level() : "";
 454 
 455    st->print_cr("# JRE version: %s%s%s (%s) (%sbuild %s)", runtime_name,
 456                 (*vendor_version != '\0') ? " " : "", vendor_version,
 457                 buf, jdk_debug_level, runtime_version);
 458 
 459    // This is the long version with some default settings added
 460    st->print_cr("# Java VM: %s%s%s (%s%s, %s%s%s%s%s%s, %s, %s)",
 461                  VM_Version::vm_name(),
 462                 (*vendor_version != '\0') ? " " : "", vendor_version,
 463                  jdk_debug_level,
 464                  VM_Version::vm_release(),
 465                  VM_Version::vm_info_string(),
 466                  TieredCompilation ? ", tiered" : "",
 467 #if INCLUDE_JVMCI
 468                  EnableJVMCI ? ", jvmci" : "",
 469                  UseJVMCICompiler ? ", jvmci compiler" : "",
 470 #else
 471                  "", "",
 472 #endif
 473                  UseCompressedOops ? ", compressed oops" : "",
 474                  UseCompressedClassPointers ? ", compressed class ptrs" : "",
 475                  GCConfig::hs_err_name(),
 476                  VM_Version::vm_platform_string()
 477                );
 478 }
 479 
 480 // Returns true if at least one thread reported a fatal error and fatal error handling is in process.
 481 bool VMError::is_error_reported() {
 482   return _first_error_tid != -1;
 483 }
 484 
 485 // Returns true if the current thread reported a fatal error.
 486 bool VMError::is_error_reported_in_current_thread() {
 487   return _first_error_tid == os::current_thread_id();
 488 }
 489 
 490 // Helper, return current timestamp for timeout handling.
 491 jlong VMError::get_current_timestamp() {
 492   return os::javaTimeNanos();
 493 }
 494 // Factor to translate the timestamp to seconds.
 495 #define TIMESTAMP_TO_SECONDS_FACTOR (1000 * 1000 * 1000)
 496 
 497 void VMError::record_reporting_start_time() {
 498   const jlong now = get_current_timestamp();
 499   Atomic::store(&_reporting_start_time, now);
 500 }
 501 
 502 jlong VMError::get_reporting_start_time() {
 503   return Atomic::load(&_reporting_start_time);
 504 }
 505 
 506 void VMError::record_step_start_time() {
 507   const jlong now = get_current_timestamp();
 508   Atomic::store(&_step_start_time, now);
 509 }
 510 
 511 jlong VMError::get_step_start_time() {
 512   return Atomic::load(&_step_start_time);
 513 }
 514 
 515 void VMError::clear_step_start_time() {
 516   return Atomic::store(&_step_start_time, (jlong)0);
 517 }
 518 
 519 // This is the main function to report a fatal error. Only one thread can
 520 // call this function, so we don't need to worry about MT-safety. But it's
 521 // possible that the error handler itself may crash or die on an internal
 522 // error, for example, when the stack/heap is badly damaged. We must be
 523 // able to handle recursive errors that happen inside error handler.
 524 //
 525 // Error reporting is done in several steps. If a crash or internal error
 526 // occurred when reporting an error, the nested signal/exception handler
 527 // can skip steps that are already (or partially) done. Error reporting will
 528 // continue from the next step. This allows us to retrieve and print
 529 // information that may be unsafe to get after a fatal error. If it happens,
 530 // you may find nested report_and_die() frames when you look at the stack
 531 // in a debugger.
 532 //
 533 // In general, a hang in error handler is much worse than a crash or internal
 534 // error, as it's harder to recover from a hang. Deadlock can happen if we
 535 // try to grab a lock that is already owned by current thread, or if the
 536 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 537 // error handler and all the functions it called should avoid grabbing any
 538 // lock. An important thing to notice is that memory allocation needs a lock.
 539 //
 540 // We should avoid using large stack allocated buffers. Many errors happen
 541 // when stack space is already low. Making things even worse is that there
 542 // could be nested report_and_die() calls on stack (see above). Only one
 543 // thread can report error, so large buffers are statically allocated in data
 544 // segment.
 545 void VMError::report(outputStream* st, bool _verbose) {
 546 
 547 # define BEGIN if (_current_step == 0) { _current_step = __LINE__;
 548 # define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; \
 549   record_step_start_time(); _step_did_timeout = false;
 550 # define END clear_step_start_time(); }
 551 
 552   // don't allocate large buffer on stack
 553   static char buf[O_BUFLEN];
 554 
 555   // Native stack trace may get stuck. We try to handle the last pc if it
 556   // belongs to VM generated code.
 557   address lastpc = nullptr;
 558 
 559   BEGIN
 560 
 561   STEP("printing fatal error message")
 562 
 563     st->print_cr("#");
 564     if (should_report_bug(_id)) {
 565       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 566     } else {
 567       st->print_cr("# There is insufficient memory for the Java "
 568                    "Runtime Environment to continue.");
 569     }
 570 
 571 #ifdef ASSERT
 572   // Error handler self tests
 573 
 574   // test secondary error handling. Test it twice, to test that resetting
 575   // error handler after a secondary crash works.
 576   STEP("test secondary crash 1")
 577     if (_verbose && TestCrashInErrorHandler != 0) {
 578       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
 579         TestCrashInErrorHandler);
 580       controlled_crash(TestCrashInErrorHandler);
 581     }
 582 
 583   STEP("test secondary crash 2")
 584     if (_verbose && TestCrashInErrorHandler != 0) {
 585       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
 586         TestCrashInErrorHandler);
 587       controlled_crash(TestCrashInErrorHandler);
 588     }
 589 
 590   // TestUnresponsiveErrorHandler: We want to test both step timeouts and global timeout.
 591   // Step to global timeout ratio is 4:1, so in order to be absolutely sure we hit the
 592   // global timeout, let's execute the timeout step five times.
 593   // See corresponding test in test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java
 594   STEP("setup for test unresponsive error reporting step")
 595     if (_verbose && TestUnresponsiveErrorHandler) {
 596       // We record reporting_start_time for this test here because we
 597       // care about the time spent executing TIMEOUT_TEST_STEP and not
 598       // about the time it took us to get here.
 599       tty->print_cr("Recording reporting_start_time for TestUnresponsiveErrorHandler.");
 600       record_reporting_start_time();
 601     }
 602 
 603   #define TIMEOUT_TEST_STEP STEP("test unresponsive error reporting step") \
 604     if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); }
 605   TIMEOUT_TEST_STEP
 606   TIMEOUT_TEST_STEP
 607   TIMEOUT_TEST_STEP
 608   TIMEOUT_TEST_STEP
 609   TIMEOUT_TEST_STEP
 610 
 611   STEP("test safefetch in error handler")
 612     // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
 613     // to test that resetting the signal handler works correctly.
 614     if (_verbose && TestSafeFetchInErrorHandler) {
 615       st->print_cr("Will test SafeFetch...");
 616       int* const invalid_pointer = (int*)segfault_address;
 617       const int x = 0x76543210;
 618       int i1 = SafeFetch32(invalid_pointer, x);
 619       int i2 = SafeFetch32(invalid_pointer, x);
 620       if (i1 == x && i2 == x) {
 621         st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
 622       } else {
 623         st->print_cr("??");
 624       }
 625     }
 626 #endif // ASSERT
 627 
 628   STEP("printing type of error")
 629 
 630      switch(static_cast<unsigned int>(_id)) {
 631        case OOM_MALLOC_ERROR:
 632        case OOM_MMAP_ERROR:
 633        case OOM_MPROTECT_ERROR:
 634          if (_size) {
 635            st->print("# Native memory allocation ");
 636            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 637                      (_id == (int)OOM_MMAP_ERROR)   ? "(mmap) failed to map " :
 638                                                       "(mprotect) failed to protect ");
 639            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
 640            st->print("%s", buf);
 641            st->print(" bytes.");
 642            if (strlen(_detail_msg) > 0) {
 643              st->print(" Error detail: ");
 644              st->print("%s", _detail_msg);
 645            }
 646            st->cr();
 647          } else {
 648            if (strlen(_detail_msg) > 0) {
 649              st->print("# ");
 650              st->print_cr("%s", _detail_msg);
 651            }
 652          }
 653          // In error file give some solutions
 654          if (_verbose) {
 655            print_oom_reasons(st);
 656          } else {
 657            return;  // that's enough for the screen
 658          }
 659          break;
 660        case INTERNAL_ERROR:
 661        default:
 662          break;
 663      }
 664 
 665   STEP("printing exception/signal name")
 666 
 667      st->print_cr("#");
 668      st->print("#  ");
 669      // Is it an OS exception/signal?
 670      if (os::exception_name(_id, buf, sizeof(buf))) {
 671        st->print("%s", buf);
 672        st->print(" (0x%x)", _id);                // signal number
 673        st->print(" at pc=" PTR_FORMAT, p2i(_pc));
 674        if (_siginfo != NULL && os::signal_sent_by_kill(_siginfo)) {
 675          st->print(" (sent by kill)");
 676        }
 677      } else {
 678        if (should_report_bug(_id)) {
 679          st->print("Internal Error");
 680        } else {
 681          st->print("Out of Memory Error");
 682        }
 683        if (_filename != NULL && _lineno > 0) {
 684 #ifdef PRODUCT
 685          // In product mode chop off pathname?
 686          char separator = os::file_separator()[0];
 687          const char *p = strrchr(_filename, separator);
 688          const char *file = p ? p+1 : _filename;
 689 #else
 690          const char *file = _filename;
 691 #endif
 692          st->print(" (%s:%d)", file, _lineno);
 693        } else {
 694          st->print(" (0x%x)", _id);
 695        }
 696      }
 697 
 698   STEP("printing current thread and pid")
 699 
 700      // process id, thread id
 701      st->print(", pid=%d", os::current_process_id());
 702      st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
 703      st->cr();
 704 
 705   STEP("printing error message")
 706 
 707      if (should_report_bug(_id)) {  // already printed the message.
 708        // error message
 709        if (strlen(_detail_msg) > 0) {
 710          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
 711        } else if (_message) {
 712          st->print_cr("#  Error: %s", _message);
 713        }
 714      }
 715 
 716   STEP("printing Java version string")
 717 
 718      report_vm_version(st, buf, sizeof(buf));
 719 
 720   STEP("printing problematic frame")
 721 
 722      // Print current frame if we have a context (i.e. it's a crash)
 723      if (_context) {
 724        st->print_cr("# Problematic frame:");
 725        st->print("# ");
 726        frame fr = os::fetch_frame_from_context(_context);
 727        fr.print_on_error(st, buf, sizeof(buf));
 728        st->cr();
 729        st->print_cr("#");
 730      }
 731 
 732   STEP("printing core file information")
 733     st->print("# ");
 734     if (CreateCoredumpOnCrash) {
 735       if (coredump_status) {
 736         st->print("Core dump will be written. Default location: %s", coredump_message);
 737       } else {
 738         st->print("No core dump will be written. %s", coredump_message);
 739       }
 740     } else {
 741       st->print("CreateCoredumpOnCrash turned off, no core file dumped");
 742     }
 743     st->cr();
 744     st->print_cr("#");
 745 
 746   JFR_ONLY(STEP("printing jfr information"))
 747   JFR_ONLY(Jfr::on_vm_error_report(st);)
 748 
 749   STEP("printing bug submit message")
 750 
 751      if (should_submit_bug_report(_id) && _verbose) {
 752        print_bug_submit_message(st, _thread);
 753      }
 754 
 755   STEP("printing summary")
 756 
 757      if (_verbose) {
 758        st->cr();
 759        st->print_cr("---------------  S U M M A R Y ------------");
 760        st->cr();
 761      }
 762 
 763   STEP("printing VM option summary")
 764 
 765      if (_verbose) {
 766        // VM options
 767        Arguments::print_summary_on(st);
 768        st->cr();
 769      }
 770 
 771   STEP("printing summary machine and OS info")
 772 
 773      if (_verbose) {
 774        os::print_summary_info(st, buf, sizeof(buf));
 775      }
 776 
 777   STEP("printing date and time")
 778 
 779      if (_verbose) {
 780        os::print_date_and_time(st, buf, sizeof(buf));
 781      }
 782 
 783   STEP("printing thread")
 784 
 785      if (_verbose) {
 786        st->cr();
 787        st->print_cr("---------------  T H R E A D  ---------------");
 788        st->cr();
 789      }
 790 
 791   STEP("printing current thread")
 792 
 793      // current thread
 794      if (_verbose) {
 795        if (_thread) {
 796          st->print("Current thread (" PTR_FORMAT "):  ", p2i(_thread));
 797          _thread->print_on_error(st, buf, sizeof(buf));
 798          st->cr();
 799        } else {
 800          st->print_cr("Current thread is native thread");
 801        }
 802        st->cr();
 803      }
 804 
 805   STEP("printing current compile task")
 806 
 807      if (_verbose && _thread && _thread->is_Compiler_thread()) {
 808         CompilerThread* t = (CompilerThread*)_thread;
 809         if (t->task()) {
 810            st->cr();
 811            st->print_cr("Current CompileTask:");
 812            t->task()->print_line_on_error(st, buf, sizeof(buf));
 813            st->cr();
 814         }
 815      }
 816 
 817   STEP("printing stack bounds")
 818 
 819      if (_verbose) {
 820        st->print("Stack: ");
 821 
 822        address stack_top;
 823        size_t stack_size;
 824 
 825        if (_thread) {
 826           stack_top = _thread->stack_base();
 827           stack_size = _thread->stack_size();
 828        } else {
 829           stack_top = os::current_stack_base();
 830           stack_size = os::current_stack_size();
 831        }
 832 
 833        address stack_bottom = stack_top - stack_size;
 834        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", p2i(stack_bottom), p2i(stack_top));
 835 
 836        frame fr = _context ? os::fetch_frame_from_context(_context)
 837                            : os::current_frame();
 838 
 839        if (fr.sp()) {
 840          st->print(",  sp=" PTR_FORMAT, p2i(fr.sp()));
 841          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 842          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 843        }
 844 
 845        st->cr();
 846      }
 847 
 848   STEP("printing native stack")
 849 
 850    if (_verbose) {
 851      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf), lastpc)) {
 852        // We have printed the native stack in platform-specific code
 853        // Windows/x64 needs special handling.
 854        // Stack walking may get stuck. Try to find the calling code.
 855        if (lastpc != nullptr) {
 856          const char* name = find_code_name(lastpc);
 857          if (name != nullptr) {
 858            st->print_cr("The last pc belongs to %s (printed below).", name);
 859          }
 860        }
 861      } else {
 862        frame fr = _context ? os::fetch_frame_from_context(_context)
 863                            : os::current_frame();
 864 
 865        print_native_stack(st, fr, _thread, buf, sizeof(buf));
 866        _print_native_stack_used = true;
 867      }
 868    }
 869 
 870   STEP("printing Java stack")
 871 
 872      if (_verbose && _thread && _thread->is_Java_thread()) {
 873        print_stack_trace(st, _thread->as_Java_thread(), buf, sizeof(buf));
 874      }
 875 
 876   STEP("printing target Java thread stack")
 877 
 878      // printing Java thread stack trace if it is involved in GC crash
 879      if (_verbose && _thread && (_thread->is_Named_thread())) {
 880        Thread* thread = ((NamedThread *)_thread)->processed_thread();
 881        if (thread != NULL && thread->is_Java_thread()) {
 882          JavaThread* jt = thread->as_Java_thread();
 883          st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
 884          print_stack_trace(st, jt, buf, sizeof(buf), true);
 885        }
 886      }
 887 
 888   STEP("printing siginfo")
 889 
 890      // signal no, signal code, address that caused the fault
 891      if (_verbose && _siginfo) {
 892        st->cr();
 893        os::print_siginfo(st, _siginfo);
 894        st->cr();
 895      }
 896 
 897   STEP("CDS archive access warning")
 898 
 899      // Print an explicit hint if we crashed on access to the CDS archive.
 900      if (_verbose && _siginfo) {
 901        check_failing_cds_access(st, _siginfo);
 902        st->cr();
 903      }
 904 
 905   STEP("printing registers")
 906 
 907      // printing registers
 908      if (_verbose && _context) {
 909        os::print_context(st, _context);
 910        st->cr();
 911      }
 912 
 913   STEP("printing register info")
 914 
 915      // decode register contents if possible
 916      if (_verbose && _context && _thread && Universe::is_fully_initialized()) {
 917        ResourceMark rm(_thread);
 918        os::print_register_info(st, _context);
 919        st->cr();
 920      }
 921 
 922   STEP("printing top of stack, instructions near pc")
 923 
 924      // printing top of stack, instructions near pc
 925      if (_verbose && _context) {
 926        os::print_tos_pc(st, _context);
 927        st->cr();
 928      }
 929 
 930   STEP("inspecting top of stack")
 931 
 932      // decode stack contents if possible
 933      if (_verbose && _context && _thread && Universe::is_fully_initialized()) {
 934        frame fr = os::fetch_frame_from_context(_context);
 935        const int slots = 8;
 936        const intptr_t *start = fr.sp();
 937        const intptr_t *end = start + slots;
 938        if (is_aligned(start, sizeof(intptr_t)) && os::is_readable_range(start, end)) {
 939          st->print_cr("Stack slot to memory mapping:");
 940          for (int i = 0; i < slots; ++i) {
 941            st->print("stack at sp + %d slots: ", i);
 942            ResourceMark rm(_thread);
 943            os::print_location(st, *(start + i));
 944          }
 945        }
 946        st->cr();
 947      }
 948 
 949   STEP("printing lock stack")
 950 
 951     if (_verbose && _thread != nullptr && _thread->is_Java_thread() && LockingMode == LM_LIGHTWEIGHT) {
 952       st->print_cr("Lock stack of current Java thread (top to bottom):");
 953       _thread->as_Java_thread()->lock_stack().print_on(st);
 954       st->cr();
 955     }
 956 
 957   STEP("printing code blobs if possible")
 958 
 959      if (_verbose) {
 960        const int printed_capacity = max_error_log_print_code;
 961        address printed[printed_capacity];
 962        printed[0] = nullptr;
 963        int printed_len = 0;
 964        // Even though ErrorLogPrintCodeLimit is ranged checked
 965        // during argument parsing, there's no way to prevent it
 966        // subsequently (i.e., after parsing) being set to a
 967        // value outside the range.
 968        int limit = MIN2(ErrorLogPrintCodeLimit, printed_capacity);
 969        if (limit > 0) {
 970          // Check if a pc was found by native stack trace above.
 971          if (lastpc != nullptr) {
 972            if (print_code(st, _thread, lastpc, true, printed, printed_capacity)) {
 973              printed_len++;
 974            }
 975          }
 976 
 977          // Scan the native stack
 978          if (!_print_native_stack_used) {
 979            // Only try to print code of the crashing frame since
 980            // the native stack cannot be walked with next_frame.
 981            if (print_code(st, _thread, _pc, true, printed, printed_capacity)) {
 982              printed_len++;
 983            }
 984          } else {
 985            frame fr = _context ? os::fetch_frame_from_context(_context)
 986                                : os::current_frame();
 987            while (printed_len < limit && fr.pc() != nullptr) {
 988              if (print_code(st, _thread, fr.pc(), fr.pc() == _pc, printed, printed_capacity)) {
 989                printed_len++;
 990              }
 991              fr = next_frame(fr, _thread);
 992            }
 993          }
 994 
 995          // Scan the Java stack
 996          if (_thread != nullptr && _thread->is_Java_thread()) {
 997            JavaThread* jt = _thread->as_Java_thread();
 998            if (jt->has_last_Java_frame()) {
 999              for (StackFrameStream sfs(jt, true /* update */, true /* process_frames */); printed_len < limit && !sfs.is_done(); sfs.next()) {
1000                address pc = sfs.current()->pc();
1001                if (print_code(st, _thread, pc, pc == _pc, printed, printed_capacity)) {
1002                  printed_len++;
1003                }
1004              }
1005            }
1006          }
1007        }
1008      }
1009 
1010   STEP("printing VM operation")
1011 
1012      if (_verbose && _thread && _thread->is_VM_thread()) {
1013         VMThread* t = (VMThread*)_thread;
1014         VM_Operation* op = t->vm_operation();
1015         if (op) {
1016           op->print_on_error(st);
1017           st->cr();
1018           st->cr();
1019         }
1020      }
1021 
1022   STEP("printing process")
1023 
1024      if (_verbose) {
1025        st->cr();
1026        st->print_cr("---------------  P R O C E S S  ---------------");
1027        st->cr();
1028      }
1029 
1030 #ifndef _WIN32
1031   STEP("printing user info")
1032 
1033      if (ExtensiveErrorReports && _verbose) {
1034        os::Posix::print_user_info(st);
1035      }
1036 #endif
1037 
1038   STEP("printing all threads")
1039 
1040      // all threads
1041      if (_verbose && _thread) {
1042        Threads::print_on_error(st, _thread, buf, sizeof(buf));
1043        st->cr();
1044      }
1045 
1046   STEP("printing VM state")
1047 
1048      if (_verbose) {
1049        // Safepoint state
1050        st->print("VM state: ");
1051 
1052        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
1053        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
1054        else st->print("not at safepoint");
1055 
1056        // Also see if error occurred during initialization or shutdown
1057        if (!Universe::is_fully_initialized()) {
1058          st->print(" (not fully initialized)");
1059        } else if (VM_Exit::vm_exited()) {
1060          st->print(" (shutting down)");
1061        } else {
1062          st->print(" (normal execution)");
1063        }
1064        st->cr();
1065        st->cr();
1066      }
1067 
1068   STEP("printing owned locks on error")
1069 
1070      // mutexes/monitors that currently have an owner
1071      if (_verbose) {
1072        print_owned_locks_on_error(st);
1073        st->cr();
1074      }
1075 
1076   STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
1077 
1078      if (_verbose && Exceptions::has_exception_counts()) {
1079        st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1080        Exceptions::print_exception_counts_on_error(st);
1081        st->cr();
1082      }
1083 
1084 #ifdef _LP64
1085   STEP("printing compressed oops mode")
1086 
1087      if (_verbose && UseCompressedOops) {
1088        CompressedOops::print_mode(st);
1089        st->cr();
1090      }
1091 
1092   STEP("printing compressed klass pointers mode")
1093 
1094      if (_verbose && UseCompressedClassPointers) {
1095        CDS_ONLY(MetaspaceShared::print_on(st);)
1096        Metaspace::print_compressed_class_space(st);
1097        CompressedKlassPointers::print_mode(st);
1098        st->cr();
1099      }
1100 #endif
1101 
1102   STEP("printing heap information")
1103 
1104      if (_verbose) {
1105        GCLogPrecious::print_on_error(st);
1106 
1107        if (Universe::heap() != NULL) {
1108          Universe::heap()->print_on_error(st);
1109          st->cr();
1110        }
1111 
1112        if (Universe::is_fully_initialized()) {
1113          st->print_cr("Polling page: " INTPTR_FORMAT, p2i(SafepointMechanism::get_polling_page()));
1114          st->cr();
1115        }
1116      }
1117 
1118   STEP("printing metaspace information")
1119 
1120      if (_verbose && Universe::is_fully_initialized()) {
1121        st->print_cr("Metaspace:");
1122        MetaspaceUtils::print_basic_report(st, 0);
1123      }
1124 
1125   STEP("printing code cache information")
1126 
1127      if (_verbose && Universe::is_fully_initialized()) {
1128        // print code cache information before vm abort
1129        CodeCache::print_summary(st);
1130        st->cr();
1131      }
1132 
1133   STEP("printing ring buffers")
1134 
1135      if (_verbose) {
1136        Events::print_all(st);
1137        st->cr();
1138      }
1139 
1140   STEP("printing dynamic libraries")
1141 
1142      if (_verbose) {
1143        // dynamic libraries, or memory map
1144        os::print_dll_info(st);
1145        st->cr();
1146      }
1147 
1148   STEP("printing native decoder state")
1149 
1150      if (_verbose) {
1151        Decoder::print_state_on(st);
1152        st->cr();
1153      }
1154 
1155   STEP("printing VM options")
1156 
1157      if (_verbose) {
1158        // VM options
1159        Arguments::print_on(st);
1160        st->cr();
1161      }
1162 
1163   STEP("printing flags")
1164 
1165     if (_verbose) {
1166       JVMFlag::printFlags(
1167         st,
1168         true, // with comments
1169         false, // no ranges
1170         true); // skip defaults
1171       st->cr();
1172     }
1173 
1174   STEP("printing warning if internal testing API used")
1175 
1176      if (WhiteBox::used()) {
1177        st->print_cr("Unsupported internal testing APIs have been used.");
1178        st->cr();
1179      }
1180 
1181   STEP("printing log configuration")
1182     if (_verbose){
1183       st->print_cr("Logging:");
1184       LogConfiguration::describe_current_configuration(st);
1185       st->cr();
1186     }
1187 
1188   STEP("printing all environment variables")
1189 
1190      if (_verbose) {
1191        os::print_environment_variables(st, env_list);
1192        st->cr();
1193      }
1194 
1195 #ifndef _WIN32
1196   STEP("printing locale settings")
1197 
1198      if (_verbose) {
1199        os::Posix::print_active_locale(st);
1200        st->cr();
1201      }
1202 #endif
1203 
1204   STEP("printing signal handlers")
1205 
1206      if (_verbose) {
1207        os::print_signal_handlers(st, buf, sizeof(buf));
1208        st->cr();
1209      }
1210 
1211   STEP("Native Memory Tracking")
1212      if (_verbose) {
1213        MemTracker::error_report(st);
1214        st->cr();
1215      }
1216 
1217   STEP("printing periodic trim state")
1218 
1219      if (_verbose) {
1220        NativeHeapTrimmer::print_state(st);
1221        st->cr();
1222      }
1223 
1224   STEP("printing system")
1225 
1226      if (_verbose) {
1227        st->cr();
1228        st->print_cr("---------------  S Y S T E M  ---------------");
1229        st->cr();
1230      }
1231 
1232   STEP("printing OS information")
1233 
1234      if (_verbose) {
1235        os::print_os_info(st);
1236        st->cr();
1237      }
1238 
1239   STEP("printing CPU info")
1240      if (_verbose) {
1241        os::print_cpu_info(st, buf, sizeof(buf));
1242        st->cr();
1243      }
1244 
1245   STEP("printing memory info")
1246 
1247      if (_verbose) {
1248        os::print_memory_info(st);
1249        st->cr();
1250      }
1251 
1252   STEP("printing internal vm info")
1253 
1254      if (_verbose) {
1255        st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
1256        st->cr();
1257      }
1258 
1259   // print a defined marker to show that error handling finished correctly.
1260   STEP("printing end marker")
1261 
1262      if (_verbose) {
1263        st->print_cr("END.");
1264      }
1265 
1266   END
1267 
1268 # undef BEGIN
1269 # undef STEP
1270 # undef END
1271 }
1272 
1273 // Report for the vm_info_cmd. This prints out the information above omitting
1274 // crash and thread specific information.  If output is added above, it should be added
1275 // here also, if it is safe to call during a running process.
1276 void VMError::print_vm_info(outputStream* st) {
1277 
1278   char buf[O_BUFLEN];
1279   report_vm_version(st, buf, sizeof(buf));
1280 
1281   // STEP("printing summary")
1282 
1283   st->cr();
1284   st->print_cr("---------------  S U M M A R Y ------------");
1285   st->cr();
1286 
1287   // STEP("printing VM option summary")
1288 
1289   // VM options
1290   Arguments::print_summary_on(st);
1291   st->cr();
1292 
1293   // STEP("printing summary machine and OS info")
1294 
1295   os::print_summary_info(st, buf, sizeof(buf));
1296 
1297   // STEP("printing date and time")
1298 
1299   os::print_date_and_time(st, buf, sizeof(buf));
1300 
1301   // Skip: STEP("printing thread")
1302 
1303   // STEP("printing process")
1304 
1305   st->cr();
1306   st->print_cr("---------------  P R O C E S S  ---------------");
1307   st->cr();
1308 
1309   // STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
1310 
1311   if (Exceptions::has_exception_counts()) {
1312     st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1313     Exceptions::print_exception_counts_on_error(st);
1314     st->cr();
1315   }
1316 
1317 #ifdef _LP64
1318   // STEP("printing compressed oops mode")
1319   if (UseCompressedOops) {
1320     CompressedOops::print_mode(st);
1321     st->cr();
1322   }
1323 
1324   // STEP("printing compressed class ptrs mode")
1325   if (UseCompressedClassPointers) {
1326     CDS_ONLY(MetaspaceShared::print_on(st);)
1327     Metaspace::print_compressed_class_space(st);
1328     CompressedKlassPointers::print_mode(st);
1329     st->cr();
1330   }
1331 #endif
1332 
1333   // STEP("printing heap information")
1334 
1335   if (Universe::is_fully_initialized()) {
1336     MutexLocker hl(Heap_lock);
1337     GCLogPrecious::print_on_error(st);
1338     Universe::heap()->print_on_error(st);
1339     st->cr();
1340     st->print_cr("Polling page: " INTPTR_FORMAT, p2i(SafepointMechanism::get_polling_page()));
1341     st->cr();
1342   }
1343 
1344   // STEP("printing metaspace information")
1345 
1346   if (Universe::is_fully_initialized()) {
1347     st->print_cr("Metaspace:");
1348     MetaspaceUtils::print_basic_report(st, 0);
1349   }
1350 
1351   // STEP("printing code cache information")
1352 
1353   if (Universe::is_fully_initialized()) {
1354     // print code cache information before vm abort
1355     CodeCache::print_summary(st);
1356     st->cr();
1357   }
1358 
1359   // STEP("printing ring buffers")
1360 
1361   Events::print_all(st);
1362   st->cr();
1363 
1364   // STEP("printing dynamic libraries")
1365 
1366   // dynamic libraries, or memory map
1367   os::print_dll_info(st);
1368   st->cr();
1369 
1370   // STEP("printing VM options")
1371 
1372   // VM options
1373   Arguments::print_on(st);
1374   st->cr();
1375 
1376   // STEP("printing warning if internal testing API used")
1377 
1378   if (WhiteBox::used()) {
1379     st->print_cr("Unsupported internal testing APIs have been used.");
1380     st->cr();
1381   }
1382 
1383   // STEP("printing log configuration")
1384   st->print_cr("Logging:");
1385   LogConfiguration::describe(st);
1386   st->cr();
1387 
1388   // STEP("printing all environment variables")
1389 
1390   os::print_environment_variables(st, env_list);
1391   st->cr();
1392 
1393   // STEP("printing locale settings")
1394 #ifndef _WIN32
1395   os::Posix::print_active_locale(st);
1396   st->cr();
1397 #endif
1398 
1399   // STEP("printing signal handlers")
1400 
1401   os::print_signal_handlers(st, buf, sizeof(buf));
1402   st->cr();
1403 
1404   // STEP("Native Memory Tracking")
1405 
1406   MemTracker::error_report(st);
1407   st->cr();
1408 
1409   // STEP("printing periodic trim state")
1410   NativeHeapTrimmer::print_state(st);
1411   st->cr();
1412 
1413 
1414   // STEP("printing system")
1415   st->print_cr("---------------  S Y S T E M  ---------------");
1416   st->cr();
1417 
1418   // STEP("printing OS information")
1419 
1420   os::print_os_info(st);
1421   st->cr();
1422 
1423   // STEP("printing CPU info")
1424 
1425   os::print_cpu_info(st, buf, sizeof(buf));
1426   st->cr();
1427 
1428   // STEP("printing memory info")
1429 
1430   os::print_memory_info(st);
1431   st->cr();
1432 
1433   // STEP("printing internal vm info")
1434 
1435   st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
1436   st->cr();
1437 
1438   // print a defined marker to show that error handling finished correctly.
1439   // STEP("printing end marker")
1440 
1441   st->print_cr("END.");
1442 }
1443 
1444 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
1445 static int expand_and_open(const char* pattern, bool overwrite_existing, char* buf, size_t buflen, size_t pos) {
1446   int fd = -1;
1447   int mode = O_RDWR | O_CREAT;
1448   if (overwrite_existing) {
1449     mode |= O_TRUNC;
1450   } else {
1451     mode |= O_EXCL;
1452   }
1453   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
1454     fd = open(buf, mode, 0666);
1455   }
1456   return fd;
1457 }
1458 
1459 /**
1460  * Construct file name for a log file and return it's file descriptor.
1461  * Name and location depends on pattern, default_pattern params and access
1462  * permissions.
1463  */
1464 static int prepare_log_file(const char* pattern, const char* default_pattern, bool overwrite_existing, char* buf, size_t buflen) {
1465   int fd = -1;
1466 
1467   // If possible, use specified pattern to construct log file name
1468   if (pattern != NULL) {
1469     fd = expand_and_open(pattern, overwrite_existing, buf, buflen, 0);
1470   }
1471 
1472   // Either user didn't specify, or the user's location failed,
1473   // so use the default name in the current directory
1474   if (fd == -1) {
1475     const char* cwd = os::get_current_directory(buf, buflen);
1476     if (cwd != NULL) {
1477       size_t pos = strlen(cwd);
1478       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1479       pos += fsep_len;
1480       if (fsep_len > 0) {
1481         fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
1482       }
1483     }
1484   }
1485 
1486    // try temp directory if it exists.
1487    if (fd == -1) {
1488      const char* tmpdir = os::get_temp_directory();
1489      if (tmpdir != NULL && strlen(tmpdir) > 0) {
1490        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1491        if (pos > 0) {
1492          fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
1493        }
1494      }
1495    }
1496 
1497   return fd;
1498 }
1499 
1500 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1501                              void* context, const char* detail_fmt, ...)
1502 {
1503   va_list detail_args;
1504   va_start(detail_args, detail_fmt);
1505   report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1506   va_end(detail_args);
1507 }
1508 
1509 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1510 {
1511   report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1512 }
1513 
1514 void VMError::report_and_die(Thread* thread, void* context, const char* filename, int lineno, const char* message,
1515                              const char* detail_fmt, va_list detail_args)
1516 {
1517   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, context, filename, lineno, 0);
1518 }
1519 
1520 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1521                              VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1522   report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1523 }
1524 
1525 void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1526                              Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1527                              int lineno, size_t size)
1528 {
1529   // A single scratch buffer to be used from here on.
1530   // Do not rely on it being preserved across function calls.
1531   static char buffer[O_BUFLEN];
1532 
1533   // File descriptor to tty to print an error summary to.
1534   // Hard wired to stdout; see JDK-8215004 (compatibility concerns).
1535   static const int fd_out = 1; // stdout
1536 
1537   // File descriptor to the error log file.
1538   static int fd_log = -1;
1539 
1540 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
1541   // Disarm assertion poison page, since from this point on we do not need this mechanism anymore and it may
1542   // cause problems in error handling during native OOM, see JDK-8227275.
1543   disarm_assert_poison();
1544 #endif
1545 
1546   // Use local fdStream objects only. Do not use global instances whose initialization
1547   // relies on dynamic initialization (see JDK-8214975). Do not rely on these instances
1548   // to carry over into recursions or invocations from other threads.
1549   fdStream out(fd_out);
1550   out.set_scratch_buffer(buffer, sizeof(buffer));
1551 
1552   // Depending on the re-entrance depth at this point, fd_log may be -1 or point to an open hs-err file.
1553   fdStream log(fd_log);
1554   log.set_scratch_buffer(buffer, sizeof(buffer));
1555 
1556   // How many errors occurred in error handler when reporting first_error.
1557   static int recursive_error_count;
1558 
1559   // We will first print a brief message to standard out (verbose = false),
1560   // then save detailed information in log file (verbose = true).
1561   static bool out_done = false;         // done printing to standard out
1562   static bool log_done = false;         // done saving error log
1563 
1564   intptr_t mytid = os::current_thread_id();
1565   if (_first_error_tid == -1 &&
1566       Atomic::cmpxchg(&_first_error_tid, (intptr_t)-1, mytid) == -1) {
1567 
1568     if (SuppressFatalErrorMessage) {
1569       os::abort(CreateCoredumpOnCrash);
1570     }
1571 
1572     // Initialize time stamps to use the same base.
1573     out.time_stamp().update_to(1);
1574     log.time_stamp().update_to(1);
1575 
1576     _id = id;
1577     _message = message;
1578     _thread = thread;
1579     _pc = pc;
1580     _siginfo = siginfo;
1581     _context = context;
1582     _filename = filename;
1583     _lineno = lineno;
1584     _size = size;
1585     jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1586 
1587     reporting_started();
1588     if (!TestUnresponsiveErrorHandler) {
1589       // Record reporting_start_time unless we're running the
1590       // TestUnresponsiveErrorHandler test. For that test we record
1591       // reporting_start_time at the beginning of the test.
1592       record_reporting_start_time();
1593     } else {
1594       out.print_raw_cr("Delaying recording reporting_start_time for TestUnresponsiveErrorHandler.");
1595     }
1596 
1597     if (ShowMessageBoxOnError || PauseAtExit) {
1598       show_message_box(buffer, sizeof(buffer));
1599 
1600       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1601       // WatcherThread can kill JVM if the error handler hangs.
1602       ShowMessageBoxOnError = false;
1603     }
1604 
1605     os::check_dump_limit(buffer, sizeof(buffer));
1606 
1607     // reset signal handlers or exception filter; make sure recursive crashes
1608     // are handled properly.
1609     install_secondary_signal_handler();
1610   } else {
1611 #if defined(_WINDOWS)
1612     // If UseOSErrorReporting we call this for each level of the call stack
1613     // while searching for the exception handler.  Only the first level needs
1614     // to be reported.
1615     if (UseOSErrorReporting && log_done) return;
1616 #endif
1617 
1618     // This is not the first error, see if it happened in a different thread
1619     // or in the same thread during error reporting.
1620     if (_first_error_tid != mytid) {
1621       if (!SuppressFatalErrorMessage) {
1622         char msgbuf[64];
1623         jio_snprintf(msgbuf, sizeof(msgbuf),
1624                      "[thread " INTX_FORMAT " also had an error]",
1625                      mytid);
1626         out.print_raw_cr(msgbuf);
1627       }
1628 
1629       // Error reporting is not MT-safe, nor can we let the current thread
1630       // proceed, so we block it.
1631       os::infinite_sleep();
1632 
1633     } else {
1634       if (recursive_error_count++ > 30) {
1635         if (!SuppressFatalErrorMessage) {
1636           out.print_raw_cr("[Too many errors, abort]");
1637         }
1638         os::die();
1639       }
1640 
1641       if (SuppressFatalErrorMessage) {
1642         // If we already hit a secondary error during abort, then calling
1643         // it again is likely to hit another one. But eventually, if we
1644         // don't deadlock somewhere, we will call os::die() above.
1645         os::abort(CreateCoredumpOnCrash);
1646       }
1647 
1648       outputStream* const st = log.is_open() ? &log : &out;
1649       st->cr();
1650 
1651       // Timeout handling.
1652       if (_step_did_timeout) {
1653         // The current step had a timeout. Lets continue reporting with the next step.
1654         st->print_raw("[timeout occurred during error reporting in step \"");
1655         st->print_raw(_current_step_info);
1656         st->print_cr("\"] after " INT64_FORMAT " s.",
1657                      (int64_t)
1658                      ((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1659       } else if (_reporting_did_timeout) {
1660         // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1661         // up, the process is about to be stopped by the WatcherThread.
1662         st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1663                      (int64_t)
1664                      ((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1665         st->flush();
1666         // Watcherthread is about to call os::die. Lets just wait.
1667         os::infinite_sleep();
1668       } else {
1669         // Crash or assert during error reporting. Lets continue reporting with the next step.
1670         stringStream ss(buffer, sizeof(buffer));
1671         // Note: this string does get parsed by a number of jtreg tests,
1672         // see hotspot/jtreg/runtime/ErrorHandling.
1673         ss.print("[error occurred during error reporting (%s), id 0x%x",
1674                    _current_step_info, id);
1675         char signal_name[64];
1676         if (os::exception_name(id, signal_name, sizeof(signal_name))) {
1677           ss.print(", %s (0x%x) at pc=" PTR_FORMAT, signal_name, id, p2i(pc));
1678         } else {
1679           if (should_report_bug(id)) {
1680             ss.print(", Internal Error (%s:%d)",
1681               filename == NULL ? "??" : filename, lineno);
1682           } else {
1683             ss.print(", Out of Memory Error (%s:%d)",
1684               filename == NULL ? "??" : filename, lineno);
1685           }
1686         }
1687         ss.print("]");
1688         st->print_raw_cr(buffer);
1689         st->cr();
1690       }
1691     }
1692   }
1693 
1694   // Part 1: print an abbreviated version (the '#' section) to stdout.
1695   if (!out_done) {
1696     // Suppress this output if we plan to print Part 2 to stdout too.
1697     // No need to have the "#" section twice.
1698     if (!(ErrorFileToStdout && out.fd() == 1)) {
1699       report(&out, false);
1700     }
1701 
1702     out_done = true;
1703 
1704     _current_step = 0;
1705     _current_step_info = "";
1706   }
1707 
1708   // Part 2: print a full error log file (optionally to stdout or stderr).
1709   // print to error log file
1710   if (!log_done) {
1711     // see if log file is already open
1712     if (!log.is_open()) {
1713       // open log file
1714       if (ErrorFileToStdout) {
1715         fd_log = 1;
1716       } else if (ErrorFileToStderr) {
1717         fd_log = 2;
1718       } else {
1719         fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", true,
1720                  buffer, sizeof(buffer));
1721         if (fd_log != -1) {
1722           out.print_raw("# An error report file with more information is saved as:\n# ");
1723           out.print_raw_cr(buffer);
1724         } else {
1725           out.print_raw_cr("# Can not save log file, dump to screen..");
1726           fd_log = 1;
1727         }
1728       }
1729       log.set_fd(fd_log);
1730     }
1731 
1732     report(&log, true);
1733     log_done = true;
1734     _current_step = 0;
1735     _current_step_info = "";
1736 
1737     if (fd_log > 3) {
1738       close(fd_log);
1739       fd_log = -1;
1740     }
1741 
1742     log.set_fd(-1);
1743   }
1744 
1745   JFR_ONLY(Jfr::on_vm_shutdown(true);)
1746 
1747   if (PrintNMTStatistics) {
1748     fdStream fds(fd_out);
1749     MemTracker::final_report(&fds);
1750   }
1751 
1752   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1753   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1754     skip_replay = true;
1755     ciEnv* env = ciEnv::current();
1756     if (env != NULL) {
1757       const bool overwrite = false; // We do not overwrite an existing replay file.
1758       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", overwrite, buffer, sizeof(buffer));
1759       if (fd != -1) {
1760         FILE* replay_data_file = os::open(fd, "w");
1761         if (replay_data_file != NULL) {
1762           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1763           env->dump_replay_data_unsafe(&replay_data_stream);
1764           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1765           out.print_raw_cr(buffer);
1766         } else {
1767           int e = errno;
1768           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1769           out.print_raw_cr(os::strerror(e));
1770           close(fd);
1771         }
1772       }
1773     }
1774   }
1775 
1776   static bool skip_bug_url = !should_submit_bug_report(_id);
1777   if (!skip_bug_url) {
1778     skip_bug_url = true;
1779 
1780     out.print_raw_cr("#");
1781     print_bug_submit_message(&out, _thread);
1782   }
1783 
1784   static bool skip_OnError = false;
1785   if (!skip_OnError && OnError && OnError[0]) {
1786     skip_OnError = true;
1787 
1788     // Flush output and finish logs before running OnError commands.
1789     ostream_abort();
1790 
1791     out.print_raw_cr("#");
1792     out.print_raw   ("# -XX:OnError=\"");
1793     out.print_raw   (OnError);
1794     out.print_raw_cr("\"");
1795 
1796     char* cmd;
1797     const char* ptr = OnError;
1798     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1799       out.print_raw   ("#   Executing ");
1800 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1801       out.print_raw   ("/bin/sh -c ");
1802 #elif defined(_WINDOWS)
1803       out.print_raw   ("cmd /C ");
1804 #endif
1805       out.print_raw   ("\"");
1806       out.print_raw   (cmd);
1807       out.print_raw_cr("\" ...");
1808 
1809       if (os::fork_and_exec(cmd) < 0) {
1810         out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1811                      os::strerror(errno), os::errno_name(errno), errno);
1812       }
1813     }
1814 
1815     // done with OnError
1816     OnError = NULL;
1817   }
1818 
1819   if (WINDOWS_ONLY(!UseOSErrorReporting) NOT_WINDOWS(true)) {
1820     // os::abort() will call abort hooks, try it first.
1821     static bool skip_os_abort = false;
1822     if (!skip_os_abort) {
1823       skip_os_abort = true;
1824       bool dump_core = should_report_bug(_id);
1825       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1826     }
1827 
1828     // if os::abort() doesn't abort, try os::die();
1829     os::die();
1830   }
1831 }
1832 
1833 /*
1834  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1835  * ensures utilities such as jmap can observe the process is a consistent state.
1836  */
1837 class VM_ReportJavaOutOfMemory : public VM_Operation {
1838  private:
1839   const char* _message;
1840  public:
1841   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1842   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1843   void doit();
1844 };
1845 
1846 void VM_ReportJavaOutOfMemory::doit() {
1847   // Don't allocate large buffer on stack
1848   static char buffer[O_BUFLEN];
1849 
1850   tty->print_cr("#");
1851   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1852   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1853 
1854   // make heap parsability
1855   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1856 
1857   char* cmd;
1858   const char* ptr = OnOutOfMemoryError;
1859   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1860     tty->print("#   Executing ");
1861 #if defined(LINUX)
1862     tty->print  ("/bin/sh -c ");
1863 #endif
1864     tty->print_cr("\"%s\"...", cmd);
1865 
1866     if (os::fork_and_exec(cmd, true) < 0) {
1867       tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1868                      os::strerror(errno), os::errno_name(errno), errno);
1869     }
1870   }
1871 }
1872 
1873 void VMError::report_java_out_of_memory(const char* message) {
1874   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1875     MutexLocker ml(Heap_lock);
1876     VM_ReportJavaOutOfMemory op(message);
1877     VMThread::execute(&op);
1878   }
1879 }
1880 
1881 void VMError::show_message_box(char *buf, int buflen) {
1882   bool yes;
1883   do {
1884     error_string(buf, buflen);
1885     yes = os::start_debugging(buf,buflen);
1886   } while (yes);
1887 }
1888 
1889 // Fatal error handling is subject to several timeouts:
1890 // - a global timeout (controlled via ErrorLogTimeout)
1891 // - local error reporting step timeouts.
1892 //
1893 // The latter aims to "give the JVM a kick" if it gets stuck in one particular place during
1894 // error reporting. This prevents one error reporting step from hogging all the time allotted
1895 // to error reporting under ErrorLogTimeout.
1896 //
1897 // VMError::check_timeout() is called from the watcher thread and checks for either global
1898 // or step timeout. If a timeout happened, we interrupt the reporting thread and set either
1899 // _reporting_did_timeout or _step_did_timeout to signal which timeout fired. Function returns
1900 // true if the *global* timeout fired, which will cause WatcherThread to shut down the JVM
1901 // immediately.
1902 bool VMError::check_timeout() {
1903 
1904   // This function is supposed to be called from watcher thread during fatal error handling only.
1905   assert(VMError::is_error_reported(), "Only call during error handling");
1906   assert(Thread::current()->is_Watcher_thread(), "Only call from watcher thread");
1907 
1908   if (ErrorLogTimeout == 0) {
1909     return false;
1910   }
1911 
1912   // There are three situations where we suppress the *global* error timeout:
1913   // - if the JVM is embedded and the launcher has its abort hook installed.
1914   //   That must be allowed to run.
1915   // - if the user specified one or more OnError commands to run, and these
1916   //   did not yet run. These must have finished.
1917   // - if the user (typically developer) specified ShowMessageBoxOnError,
1918   //   and the error box has not yet been shown
1919   const bool ignore_global_timeout =
1920       (ShowMessageBoxOnError
1921             || (OnError != nullptr && OnError[0] != '\0')
1922             || Arguments::abort_hook() != nullptr);
1923 
1924   const jlong now = get_current_timestamp();
1925 
1926   // Global timeout hit?
1927   if (!ignore_global_timeout) {
1928     const jlong reporting_start_time = get_reporting_start_time();
1929     // Timestamp is stored in nanos.
1930     if (reporting_start_time > 0) {
1931       const jlong end = reporting_start_time + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1932       if (end <= now && !_reporting_did_timeout) {
1933         // We hit ErrorLogTimeout and we haven't interrupted the reporting
1934         // thread yet.
1935         _reporting_did_timeout = true;
1936         interrupt_reporting_thread();
1937         return true; // global timeout
1938       }
1939     }
1940   }
1941 
1942   // Reporting step timeout?
1943   const jlong step_start_time = get_step_start_time();
1944   if (step_start_time > 0) {
1945     // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1946     // hang for some reason, so this simple rule allows for three hanging step and still
1947     // hopefully leaves time enough for the rest of the steps to finish.
1948     const int max_step_timeout_secs = 5;
1949     const jlong timeout_duration = MAX2((jlong)max_step_timeout_secs, (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4);
1950     const jlong end = step_start_time + timeout_duration;
1951     if (end <= now && !_step_did_timeout) {
1952       // The step timed out and we haven't interrupted the reporting
1953       // thread yet.
1954       _step_did_timeout = true;
1955       interrupt_reporting_thread();
1956       return false; // (Not a global timeout)
1957     }
1958   }
1959 
1960   return false;
1961 
1962 }
1963 
1964 #ifdef ASSERT
1965 typedef void (*voidfun_t)();
1966 
1967 // Crash with an authentic sigfpe
1968 volatile int sigfpe_int = 0;
1969 static void crash_with_sigfpe() {
1970 
1971   // generate a native synchronous SIGFPE where possible;
1972   sigfpe_int = sigfpe_int/sigfpe_int;
1973 
1974   // if that did not cause a signal (e.g. on ppc), just
1975   // raise the signal.
1976 #ifndef _WIN32
1977   // OSX implements raise(sig) incorrectly so we need to
1978   // explicitly target the current thread
1979   pthread_kill(pthread_self(), SIGFPE);
1980 #endif
1981 
1982 } // end: crash_with_sigfpe
1983 
1984 // crash with sigsegv at non-null address.
1985 static void crash_with_segfault() {
1986 
1987   int* crash_addr = reinterpret_cast<int*>(VMError::segfault_address);
1988   *crash_addr = 1;
1989 
1990 } // end: crash_with_segfault
1991 
1992 // crash in a controlled way:
1993 // 1  - assert
1994 // 2  - guarantee
1995 // 14 - SIGSEGV
1996 // 15 - SIGFPE
1997 void VMError::controlled_crash(int how) {
1998 
1999   // Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java.
2000   // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java.
2001   // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java.
2002   // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
2003 
2004   // We try to grab Threads_lock to keep ThreadsSMRSupport::print_info_on()
2005   // from racing with Threads::add() or Threads::remove() as we
2006   // generate the hs_err_pid file. This makes our ErrorHandling tests
2007   // more stable.
2008   if (!Threads_lock->owned_by_self()) {
2009     Threads_lock->try_lock();
2010     // The VM is going to die so no need to unlock Thread_lock.
2011   }
2012 
2013   switch (how) {
2014     case 1: assert(how == 0, "test assert"); break;
2015     case 2: guarantee(how == 0, "test guarantee"); break;
2016 
2017     // The other cases are unused.
2018     case 14: crash_with_segfault(); break;
2019     case 15: crash_with_sigfpe(); break;
2020     case 16: {
2021       ThreadsListHandle tlh;
2022       fatal("Force crash with an active ThreadsListHandle.");
2023     }
2024     case 17: {
2025       ThreadsListHandle tlh;
2026       {
2027         ThreadsListHandle tlh2;
2028         fatal("Force crash with a nested ThreadsListHandle.");
2029       }
2030     }
2031     default:
2032       // If another number is given, give a generic crash.
2033       fatal("Crashing with number %d", how);
2034   }
2035   tty->print_cr("controlled_crash: survived intentional crash. Did you suppress the assert?");
2036   ShouldNotReachHere();
2037 }
2038 #endif // !ASSERT