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 code blobs if possible")
 950 
 951      if (_verbose) {
 952        const int printed_capacity = max_error_log_print_code;
 953        address printed[printed_capacity];
 954        printed[0] = nullptr;
 955        int printed_len = 0;
 956        // Even though ErrorLogPrintCodeLimit is ranged checked
 957        // during argument parsing, there's no way to prevent it
 958        // subsequently (i.e., after parsing) being set to a
 959        // value outside the range.
 960        int limit = MIN2(ErrorLogPrintCodeLimit, printed_capacity);
 961        if (limit > 0) {
 962          // Check if a pc was found by native stack trace above.
 963          if (lastpc != nullptr) {
 964            if (print_code(st, _thread, lastpc, true, printed, printed_capacity)) {
 965              printed_len++;
 966            }
 967          }
 968 
 969          // Scan the native stack
 970          if (!_print_native_stack_used) {
 971            // Only try to print code of the crashing frame since
 972            // the native stack cannot be walked with next_frame.
 973            if (print_code(st, _thread, _pc, true, printed, printed_capacity)) {
 974              printed_len++;
 975            }
 976          } else {
 977            frame fr = _context ? os::fetch_frame_from_context(_context)
 978                                : os::current_frame();
 979            while (printed_len < limit && fr.pc() != nullptr) {
 980              if (print_code(st, _thread, fr.pc(), fr.pc() == _pc, printed, printed_capacity)) {
 981                printed_len++;
 982              }
 983              fr = next_frame(fr, _thread);
 984            }
 985          }
 986 
 987          // Scan the Java stack
 988          if (_thread != nullptr && _thread->is_Java_thread()) {
 989            JavaThread* jt = _thread->as_Java_thread();
 990            if (jt->has_last_Java_frame()) {
 991              for (StackFrameStream sfs(jt, true /* update */, true /* process_frames */); printed_len < limit && !sfs.is_done(); sfs.next()) {
 992                address pc = sfs.current()->pc();
 993                if (print_code(st, _thread, pc, pc == _pc, printed, printed_capacity)) {
 994                  printed_len++;
 995                }
 996              }
 997            }
 998          }
 999        }
1000      }
1001 
1002   STEP("printing VM operation")
1003 
1004      if (_verbose && _thread && _thread->is_VM_thread()) {
1005         VMThread* t = (VMThread*)_thread;
1006         VM_Operation* op = t->vm_operation();
1007         if (op) {
1008           op->print_on_error(st);
1009           st->cr();
1010           st->cr();
1011         }
1012      }
1013 
1014   STEP("printing process")
1015 
1016      if (_verbose) {
1017        st->cr();
1018        st->print_cr("---------------  P R O C E S S  ---------------");
1019        st->cr();
1020      }
1021 
1022 #ifndef _WIN32
1023   STEP("printing user info")
1024 
1025      if (ExtensiveErrorReports && _verbose) {
1026        os::Posix::print_user_info(st);
1027      }
1028 #endif
1029 
1030   STEP("printing all threads")
1031 
1032      // all threads
1033      if (_verbose && _thread) {
1034        Threads::print_on_error(st, _thread, buf, sizeof(buf));
1035        st->cr();
1036      }
1037 
1038   STEP("printing VM state")
1039 
1040      if (_verbose) {
1041        // Safepoint state
1042        st->print("VM state: ");
1043 
1044        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
1045        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
1046        else st->print("not at safepoint");
1047 
1048        // Also see if error occurred during initialization or shutdown
1049        if (!Universe::is_fully_initialized()) {
1050          st->print(" (not fully initialized)");
1051        } else if (VM_Exit::vm_exited()) {
1052          st->print(" (shutting down)");
1053        } else {
1054          st->print(" (normal execution)");
1055        }
1056        st->cr();
1057        st->cr();
1058      }
1059 
1060   STEP("printing owned locks on error")
1061 
1062      // mutexes/monitors that currently have an owner
1063      if (_verbose) {
1064        print_owned_locks_on_error(st);
1065        st->cr();
1066      }
1067 
1068   STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
1069 
1070      if (_verbose && Exceptions::has_exception_counts()) {
1071        st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1072        Exceptions::print_exception_counts_on_error(st);
1073        st->cr();
1074      }
1075 
1076 #ifdef _LP64
1077   STEP("printing compressed oops mode")
1078 
1079      if (_verbose && UseCompressedOops) {
1080        CompressedOops::print_mode(st);
1081        st->cr();
1082      }
1083 
1084   STEP("printing compressed klass pointers mode")
1085 
1086      if (_verbose && UseCompressedClassPointers) {
1087        CDS_ONLY(MetaspaceShared::print_on(st);)
1088        Metaspace::print_compressed_class_space(st);
1089        CompressedKlassPointers::print_mode(st);
1090        st->cr();
1091      }
1092 #endif
1093 
1094   STEP("printing heap information")
1095 
1096      if (_verbose) {
1097        GCLogPrecious::print_on_error(st);
1098 
1099        if (Universe::heap() != NULL) {
1100          Universe::heap()->print_on_error(st);
1101          st->cr();
1102        }
1103 
1104        if (Universe::is_fully_initialized()) {
1105          st->print_cr("Polling page: " INTPTR_FORMAT, p2i(SafepointMechanism::get_polling_page()));
1106          st->cr();
1107        }
1108      }
1109 
1110   STEP("printing metaspace information")
1111 
1112      if (_verbose && Universe::is_fully_initialized()) {
1113        st->print_cr("Metaspace:");
1114        MetaspaceUtils::print_basic_report(st, 0);
1115      }
1116 
1117   STEP("printing code cache information")
1118 
1119      if (_verbose && Universe::is_fully_initialized()) {
1120        // print code cache information before vm abort
1121        CodeCache::print_summary(st);
1122        st->cr();
1123      }
1124 
1125   STEP("printing ring buffers")
1126 
1127      if (_verbose) {
1128        Events::print_all(st);
1129        st->cr();
1130      }
1131 
1132   STEP("printing dynamic libraries")
1133 
1134      if (_verbose) {
1135        // dynamic libraries, or memory map
1136        os::print_dll_info(st);
1137        st->cr();
1138      }
1139 
1140   STEP("printing native decoder state")
1141 
1142      if (_verbose) {
1143        Decoder::print_state_on(st);
1144        st->cr();
1145      }
1146 
1147   STEP("printing VM options")
1148 
1149      if (_verbose) {
1150        // VM options
1151        Arguments::print_on(st);
1152        st->cr();
1153      }
1154 
1155   STEP("printing flags")
1156 
1157     if (_verbose) {
1158       JVMFlag::printFlags(
1159         st,
1160         true, // with comments
1161         false, // no ranges
1162         true); // skip defaults
1163       st->cr();
1164     }
1165 
1166   STEP("printing warning if internal testing API used")
1167 
1168      if (WhiteBox::used()) {
1169        st->print_cr("Unsupported internal testing APIs have been used.");
1170        st->cr();
1171      }
1172 
1173   STEP("printing log configuration")
1174     if (_verbose){
1175       st->print_cr("Logging:");
1176       LogConfiguration::describe_current_configuration(st);
1177       st->cr();
1178     }
1179 
1180   STEP("printing all environment variables")
1181 
1182      if (_verbose) {
1183        os::print_environment_variables(st, env_list);
1184        st->cr();
1185      }
1186 
1187 #ifndef _WIN32
1188   STEP("printing locale settings")
1189 
1190      if (_verbose) {
1191        os::Posix::print_active_locale(st);
1192        st->cr();
1193      }
1194 #endif
1195 
1196   STEP("printing signal handlers")
1197 
1198      if (_verbose) {
1199        os::print_signal_handlers(st, buf, sizeof(buf));
1200        st->cr();
1201      }
1202 
1203   STEP("Native Memory Tracking")
1204      if (_verbose) {
1205        MemTracker::error_report(st);
1206        st->cr();
1207      }
1208 
1209   STEP("printing periodic trim state")
1210 
1211      if (_verbose) {
1212        NativeHeapTrimmer::print_state(st);
1213        st->cr();
1214      }
1215 
1216   STEP("printing system")
1217 
1218      if (_verbose) {
1219        st->cr();
1220        st->print_cr("---------------  S Y S T E M  ---------------");
1221        st->cr();
1222      }
1223 
1224   STEP("printing OS information")
1225 
1226      if (_verbose) {
1227        os::print_os_info(st);
1228        st->cr();
1229      }
1230 
1231   STEP("printing CPU info")
1232      if (_verbose) {
1233        os::print_cpu_info(st, buf, sizeof(buf));
1234        st->cr();
1235      }
1236 
1237   STEP("printing memory info")
1238 
1239      if (_verbose) {
1240        os::print_memory_info(st);
1241        st->cr();
1242      }
1243 
1244   STEP("printing internal vm info")
1245 
1246      if (_verbose) {
1247        st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
1248        st->cr();
1249      }
1250 
1251   // print a defined marker to show that error handling finished correctly.
1252   STEP("printing end marker")
1253 
1254      if (_verbose) {
1255        st->print_cr("END.");
1256      }
1257 
1258   END
1259 
1260 # undef BEGIN
1261 # undef STEP
1262 # undef END
1263 }
1264 
1265 // Report for the vm_info_cmd. This prints out the information above omitting
1266 // crash and thread specific information.  If output is added above, it should be added
1267 // here also, if it is safe to call during a running process.
1268 void VMError::print_vm_info(outputStream* st) {
1269 
1270   char buf[O_BUFLEN];
1271   report_vm_version(st, buf, sizeof(buf));
1272 
1273   // STEP("printing summary")
1274 
1275   st->cr();
1276   st->print_cr("---------------  S U M M A R Y ------------");
1277   st->cr();
1278 
1279   // STEP("printing VM option summary")
1280 
1281   // VM options
1282   Arguments::print_summary_on(st);
1283   st->cr();
1284 
1285   // STEP("printing summary machine and OS info")
1286 
1287   os::print_summary_info(st, buf, sizeof(buf));
1288 
1289   // STEP("printing date and time")
1290 
1291   os::print_date_and_time(st, buf, sizeof(buf));
1292 
1293   // Skip: STEP("printing thread")
1294 
1295   // STEP("printing process")
1296 
1297   st->cr();
1298   st->print_cr("---------------  P R O C E S S  ---------------");
1299   st->cr();
1300 
1301   // STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
1302 
1303   if (Exceptions::has_exception_counts()) {
1304     st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1305     Exceptions::print_exception_counts_on_error(st);
1306     st->cr();
1307   }
1308 
1309 #ifdef _LP64
1310   // STEP("printing compressed oops mode")
1311   if (UseCompressedOops) {
1312     CompressedOops::print_mode(st);
1313     st->cr();
1314   }
1315 
1316   // STEP("printing compressed class ptrs mode")
1317   if (UseCompressedClassPointers) {
1318     CDS_ONLY(MetaspaceShared::print_on(st);)
1319     Metaspace::print_compressed_class_space(st);
1320     CompressedKlassPointers::print_mode(st);
1321     st->cr();
1322   }
1323 #endif
1324 
1325   // STEP("printing heap information")
1326 
1327   if (Universe::is_fully_initialized()) {
1328     MutexLocker hl(Heap_lock);
1329     GCLogPrecious::print_on_error(st);
1330     Universe::heap()->print_on_error(st);
1331     st->cr();
1332     st->print_cr("Polling page: " INTPTR_FORMAT, p2i(SafepointMechanism::get_polling_page()));
1333     st->cr();
1334   }
1335 
1336   // STEP("printing metaspace information")
1337 
1338   if (Universe::is_fully_initialized()) {
1339     st->print_cr("Metaspace:");
1340     MetaspaceUtils::print_basic_report(st, 0);
1341   }
1342 
1343   // STEP("printing code cache information")
1344 
1345   if (Universe::is_fully_initialized()) {
1346     // print code cache information before vm abort
1347     CodeCache::print_summary(st);
1348     st->cr();
1349   }
1350 
1351   // STEP("printing ring buffers")
1352 
1353   Events::print_all(st);
1354   st->cr();
1355 
1356   // STEP("printing dynamic libraries")
1357 
1358   // dynamic libraries, or memory map
1359   os::print_dll_info(st);
1360   st->cr();
1361 
1362   // STEP("printing VM options")
1363 
1364   // VM options
1365   Arguments::print_on(st);
1366   st->cr();
1367 
1368   // STEP("printing warning if internal testing API used")
1369 
1370   if (WhiteBox::used()) {
1371     st->print_cr("Unsupported internal testing APIs have been used.");
1372     st->cr();
1373   }
1374 
1375   // STEP("printing log configuration")
1376   st->print_cr("Logging:");
1377   LogConfiguration::describe(st);
1378   st->cr();
1379 
1380   // STEP("printing all environment variables")
1381 
1382   os::print_environment_variables(st, env_list);
1383   st->cr();
1384 
1385   // STEP("printing locale settings")
1386 #ifndef _WIN32
1387   os::Posix::print_active_locale(st);
1388   st->cr();
1389 #endif
1390 
1391   // STEP("printing signal handlers")
1392 
1393   os::print_signal_handlers(st, buf, sizeof(buf));
1394   st->cr();
1395 
1396   // STEP("Native Memory Tracking")
1397 
1398   MemTracker::error_report(st);
1399   st->cr();
1400 
1401   // STEP("printing periodic trim state")
1402   NativeHeapTrimmer::print_state(st);
1403   st->cr();
1404 
1405 
1406   // STEP("printing system")
1407   st->print_cr("---------------  S Y S T E M  ---------------");
1408   st->cr();
1409 
1410   // STEP("printing OS information")
1411 
1412   os::print_os_info(st);
1413   st->cr();
1414 
1415   // STEP("printing CPU info")
1416 
1417   os::print_cpu_info(st, buf, sizeof(buf));
1418   st->cr();
1419 
1420   // STEP("printing memory info")
1421 
1422   os::print_memory_info(st);
1423   st->cr();
1424 
1425   // STEP("printing internal vm info")
1426 
1427   st->print_cr("vm_info: %s", VM_Version::internal_vm_info_string());
1428   st->cr();
1429 
1430   // print a defined marker to show that error handling finished correctly.
1431   // STEP("printing end marker")
1432 
1433   st->print_cr("END.");
1434 }
1435 
1436 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
1437 static int expand_and_open(const char* pattern, bool overwrite_existing, char* buf, size_t buflen, size_t pos) {
1438   int fd = -1;
1439   int mode = O_RDWR | O_CREAT;
1440   if (overwrite_existing) {
1441     mode |= O_TRUNC;
1442   } else {
1443     mode |= O_EXCL;
1444   }
1445   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
1446     fd = open(buf, mode, 0666);
1447   }
1448   return fd;
1449 }
1450 
1451 /**
1452  * Construct file name for a log file and return it's file descriptor.
1453  * Name and location depends on pattern, default_pattern params and access
1454  * permissions.
1455  */
1456 static int prepare_log_file(const char* pattern, const char* default_pattern, bool overwrite_existing, char* buf, size_t buflen) {
1457   int fd = -1;
1458 
1459   // If possible, use specified pattern to construct log file name
1460   if (pattern != NULL) {
1461     fd = expand_and_open(pattern, overwrite_existing, buf, buflen, 0);
1462   }
1463 
1464   // Either user didn't specify, or the user's location failed,
1465   // so use the default name in the current directory
1466   if (fd == -1) {
1467     const char* cwd = os::get_current_directory(buf, buflen);
1468     if (cwd != NULL) {
1469       size_t pos = strlen(cwd);
1470       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1471       pos += fsep_len;
1472       if (fsep_len > 0) {
1473         fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
1474       }
1475     }
1476   }
1477 
1478    // try temp directory if it exists.
1479    if (fd == -1) {
1480      const char* tmpdir = os::get_temp_directory();
1481      if (tmpdir != NULL && strlen(tmpdir) > 0) {
1482        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1483        if (pos > 0) {
1484          fd = expand_and_open(default_pattern, overwrite_existing, buf, buflen, pos);
1485        }
1486      }
1487    }
1488 
1489   return fd;
1490 }
1491 
1492 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1493                              void* context, const char* detail_fmt, ...)
1494 {
1495   va_list detail_args;
1496   va_start(detail_args, detail_fmt);
1497   report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1498   va_end(detail_args);
1499 }
1500 
1501 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1502 {
1503   report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1504 }
1505 
1506 void VMError::report_and_die(Thread* thread, void* context, const char* filename, int lineno, const char* message,
1507                              const char* detail_fmt, va_list detail_args)
1508 {
1509   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, context, filename, lineno, 0);
1510 }
1511 
1512 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1513                              VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1514   report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1515 }
1516 
1517 void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1518                              Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1519                              int lineno, size_t size)
1520 {
1521   // A single scratch buffer to be used from here on.
1522   // Do not rely on it being preserved across function calls.
1523   static char buffer[O_BUFLEN];
1524 
1525   // File descriptor to tty to print an error summary to.
1526   // Hard wired to stdout; see JDK-8215004 (compatibility concerns).
1527   static const int fd_out = 1; // stdout
1528 
1529   // File descriptor to the error log file.
1530   static int fd_log = -1;
1531 
1532 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
1533   // Disarm assertion poison page, since from this point on we do not need this mechanism anymore and it may
1534   // cause problems in error handling during native OOM, see JDK-8227275.
1535   disarm_assert_poison();
1536 #endif
1537 
1538   // Use local fdStream objects only. Do not use global instances whose initialization
1539   // relies on dynamic initialization (see JDK-8214975). Do not rely on these instances
1540   // to carry over into recursions or invocations from other threads.
1541   fdStream out(fd_out);
1542   out.set_scratch_buffer(buffer, sizeof(buffer));
1543 
1544   // Depending on the re-entrance depth at this point, fd_log may be -1 or point to an open hs-err file.
1545   fdStream log(fd_log);
1546   log.set_scratch_buffer(buffer, sizeof(buffer));
1547 
1548   // How many errors occurred in error handler when reporting first_error.
1549   static int recursive_error_count;
1550 
1551   // We will first print a brief message to standard out (verbose = false),
1552   // then save detailed information in log file (verbose = true).
1553   static bool out_done = false;         // done printing to standard out
1554   static bool log_done = false;         // done saving error log
1555 
1556   intptr_t mytid = os::current_thread_id();
1557   if (_first_error_tid == -1 &&
1558       Atomic::cmpxchg(&_first_error_tid, (intptr_t)-1, mytid) == -1) {
1559 
1560     if (SuppressFatalErrorMessage) {
1561       os::abort(CreateCoredumpOnCrash);
1562     }
1563 
1564     // Initialize time stamps to use the same base.
1565     out.time_stamp().update_to(1);
1566     log.time_stamp().update_to(1);
1567 
1568     _id = id;
1569     _message = message;
1570     _thread = thread;
1571     _pc = pc;
1572     _siginfo = siginfo;
1573     _context = context;
1574     _filename = filename;
1575     _lineno = lineno;
1576     _size = size;
1577     jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1578 
1579     reporting_started();
1580     if (!TestUnresponsiveErrorHandler) {
1581       // Record reporting_start_time unless we're running the
1582       // TestUnresponsiveErrorHandler test. For that test we record
1583       // reporting_start_time at the beginning of the test.
1584       record_reporting_start_time();
1585     } else {
1586       out.print_raw_cr("Delaying recording reporting_start_time for TestUnresponsiveErrorHandler.");
1587     }
1588 
1589     if (ShowMessageBoxOnError || PauseAtExit) {
1590       show_message_box(buffer, sizeof(buffer));
1591 
1592       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1593       // WatcherThread can kill JVM if the error handler hangs.
1594       ShowMessageBoxOnError = false;
1595     }
1596 
1597     os::check_dump_limit(buffer, sizeof(buffer));
1598 
1599     // reset signal handlers or exception filter; make sure recursive crashes
1600     // are handled properly.
1601     install_secondary_signal_handler();
1602   } else {
1603 #if defined(_WINDOWS)
1604     // If UseOSErrorReporting we call this for each level of the call stack
1605     // while searching for the exception handler.  Only the first level needs
1606     // to be reported.
1607     if (UseOSErrorReporting && log_done) return;
1608 #endif
1609 
1610     // This is not the first error, see if it happened in a different thread
1611     // or in the same thread during error reporting.
1612     if (_first_error_tid != mytid) {
1613       if (!SuppressFatalErrorMessage) {
1614         char msgbuf[64];
1615         jio_snprintf(msgbuf, sizeof(msgbuf),
1616                      "[thread " INTX_FORMAT " also had an error]",
1617                      mytid);
1618         out.print_raw_cr(msgbuf);
1619       }
1620 
1621       // Error reporting is not MT-safe, nor can we let the current thread
1622       // proceed, so we block it.
1623       os::infinite_sleep();
1624 
1625     } else {
1626       if (recursive_error_count++ > 30) {
1627         if (!SuppressFatalErrorMessage) {
1628           out.print_raw_cr("[Too many errors, abort]");
1629         }
1630         os::die();
1631       }
1632 
1633       if (SuppressFatalErrorMessage) {
1634         // If we already hit a secondary error during abort, then calling
1635         // it again is likely to hit another one. But eventually, if we
1636         // don't deadlock somewhere, we will call os::die() above.
1637         os::abort(CreateCoredumpOnCrash);
1638       }
1639 
1640       outputStream* const st = log.is_open() ? &log : &out;
1641       st->cr();
1642 
1643       // Timeout handling.
1644       if (_step_did_timeout) {
1645         // The current step had a timeout. Lets continue reporting with the next step.
1646         st->print_raw("[timeout occurred during error reporting in step \"");
1647         st->print_raw(_current_step_info);
1648         st->print_cr("\"] after " INT64_FORMAT " s.",
1649                      (int64_t)
1650                      ((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1651       } else if (_reporting_did_timeout) {
1652         // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1653         // up, the process is about to be stopped by the WatcherThread.
1654         st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1655                      (int64_t)
1656                      ((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1657         st->flush();
1658         // Watcherthread is about to call os::die. Lets just wait.
1659         os::infinite_sleep();
1660       } else {
1661         // Crash or assert during error reporting. Lets continue reporting with the next step.
1662         stringStream ss(buffer, sizeof(buffer));
1663         // Note: this string does get parsed by a number of jtreg tests,
1664         // see hotspot/jtreg/runtime/ErrorHandling.
1665         ss.print("[error occurred during error reporting (%s), id 0x%x",
1666                    _current_step_info, id);
1667         char signal_name[64];
1668         if (os::exception_name(id, signal_name, sizeof(signal_name))) {
1669           ss.print(", %s (0x%x) at pc=" PTR_FORMAT, signal_name, id, p2i(pc));
1670         } else {
1671           if (should_report_bug(id)) {
1672             ss.print(", Internal Error (%s:%d)",
1673               filename == NULL ? "??" : filename, lineno);
1674           } else {
1675             ss.print(", Out of Memory Error (%s:%d)",
1676               filename == NULL ? "??" : filename, lineno);
1677           }
1678         }
1679         ss.print("]");
1680         st->print_raw_cr(buffer);
1681         st->cr();
1682       }
1683     }
1684   }
1685 
1686   // Part 1: print an abbreviated version (the '#' section) to stdout.
1687   if (!out_done) {
1688     // Suppress this output if we plan to print Part 2 to stdout too.
1689     // No need to have the "#" section twice.
1690     if (!(ErrorFileToStdout && out.fd() == 1)) {
1691       report(&out, false);
1692     }
1693 
1694     out_done = true;
1695 
1696     _current_step = 0;
1697     _current_step_info = "";
1698   }
1699 
1700   // Part 2: print a full error log file (optionally to stdout or stderr).
1701   // print to error log file
1702   if (!log_done) {
1703     // see if log file is already open
1704     if (!log.is_open()) {
1705       // open log file
1706       if (ErrorFileToStdout) {
1707         fd_log = 1;
1708       } else if (ErrorFileToStderr) {
1709         fd_log = 2;
1710       } else {
1711         fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", true,
1712                  buffer, sizeof(buffer));
1713         if (fd_log != -1) {
1714           out.print_raw("# An error report file with more information is saved as:\n# ");
1715           out.print_raw_cr(buffer);
1716         } else {
1717           out.print_raw_cr("# Can not save log file, dump to screen..");
1718           fd_log = 1;
1719         }
1720       }
1721       log.set_fd(fd_log);
1722     }
1723 
1724     report(&log, true);
1725     log_done = true;
1726     _current_step = 0;
1727     _current_step_info = "";
1728 
1729     if (fd_log > 3) {
1730       close(fd_log);
1731       fd_log = -1;
1732     }
1733 
1734     log.set_fd(-1);
1735   }
1736 
1737   JFR_ONLY(Jfr::on_vm_shutdown(true);)
1738 
1739   if (PrintNMTStatistics) {
1740     fdStream fds(fd_out);
1741     MemTracker::final_report(&fds);
1742   }
1743 
1744   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1745   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1746     skip_replay = true;
1747     ciEnv* env = ciEnv::current();
1748     if (env != NULL) {
1749       const bool overwrite = false; // We do not overwrite an existing replay file.
1750       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", overwrite, buffer, sizeof(buffer));
1751       if (fd != -1) {
1752         FILE* replay_data_file = os::open(fd, "w");
1753         if (replay_data_file != NULL) {
1754           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1755           env->dump_replay_data_unsafe(&replay_data_stream);
1756           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1757           out.print_raw_cr(buffer);
1758         } else {
1759           int e = errno;
1760           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1761           out.print_raw_cr(os::strerror(e));
1762           close(fd);
1763         }
1764       }
1765     }
1766   }
1767 
1768   static bool skip_bug_url = !should_submit_bug_report(_id);
1769   if (!skip_bug_url) {
1770     skip_bug_url = true;
1771 
1772     out.print_raw_cr("#");
1773     print_bug_submit_message(&out, _thread);
1774   }
1775 
1776   static bool skip_OnError = false;
1777   if (!skip_OnError && OnError && OnError[0]) {
1778     skip_OnError = true;
1779 
1780     // Flush output and finish logs before running OnError commands.
1781     ostream_abort();
1782 
1783     out.print_raw_cr("#");
1784     out.print_raw   ("# -XX:OnError=\"");
1785     out.print_raw   (OnError);
1786     out.print_raw_cr("\"");
1787 
1788     char* cmd;
1789     const char* ptr = OnError;
1790     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1791       out.print_raw   ("#   Executing ");
1792 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1793       out.print_raw   ("/bin/sh -c ");
1794 #elif defined(_WINDOWS)
1795       out.print_raw   ("cmd /C ");
1796 #endif
1797       out.print_raw   ("\"");
1798       out.print_raw   (cmd);
1799       out.print_raw_cr("\" ...");
1800 
1801       if (os::fork_and_exec(cmd) < 0) {
1802         out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1803                      os::strerror(errno), os::errno_name(errno), errno);
1804       }
1805     }
1806 
1807     // done with OnError
1808     OnError = NULL;
1809   }
1810 
1811   if (WINDOWS_ONLY(!UseOSErrorReporting) NOT_WINDOWS(true)) {
1812     // os::abort() will call abort hooks, try it first.
1813     static bool skip_os_abort = false;
1814     if (!skip_os_abort) {
1815       skip_os_abort = true;
1816       bool dump_core = should_report_bug(_id);
1817       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1818     }
1819 
1820     // if os::abort() doesn't abort, try os::die();
1821     os::die();
1822   }
1823 }
1824 
1825 /*
1826  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1827  * ensures utilities such as jmap can observe the process is a consistent state.
1828  */
1829 class VM_ReportJavaOutOfMemory : public VM_Operation {
1830  private:
1831   const char* _message;
1832  public:
1833   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1834   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1835   void doit();
1836 };
1837 
1838 void VM_ReportJavaOutOfMemory::doit() {
1839   // Don't allocate large buffer on stack
1840   static char buffer[O_BUFLEN];
1841 
1842   tty->print_cr("#");
1843   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1844   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1845 
1846   // make heap parsability
1847   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1848 
1849   char* cmd;
1850   const char* ptr = OnOutOfMemoryError;
1851   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1852     tty->print("#   Executing ");
1853 #if defined(LINUX)
1854     tty->print  ("/bin/sh -c ");
1855 #endif
1856     tty->print_cr("\"%s\"...", cmd);
1857 
1858     if (os::fork_and_exec(cmd, true) < 0) {
1859       tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1860                      os::strerror(errno), os::errno_name(errno), errno);
1861     }
1862   }
1863 }
1864 
1865 void VMError::report_java_out_of_memory(const char* message) {
1866   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1867     MutexLocker ml(Heap_lock);
1868     VM_ReportJavaOutOfMemory op(message);
1869     VMThread::execute(&op);
1870   }
1871 }
1872 
1873 void VMError::show_message_box(char *buf, int buflen) {
1874   bool yes;
1875   do {
1876     error_string(buf, buflen);
1877     yes = os::start_debugging(buf,buflen);
1878   } while (yes);
1879 }
1880 
1881 // Fatal error handling is subject to several timeouts:
1882 // - a global timeout (controlled via ErrorLogTimeout)
1883 // - local error reporting step timeouts.
1884 //
1885 // The latter aims to "give the JVM a kick" if it gets stuck in one particular place during
1886 // error reporting. This prevents one error reporting step from hogging all the time allotted
1887 // to error reporting under ErrorLogTimeout.
1888 //
1889 // VMError::check_timeout() is called from the watcher thread and checks for either global
1890 // or step timeout. If a timeout happened, we interrupt the reporting thread and set either
1891 // _reporting_did_timeout or _step_did_timeout to signal which timeout fired. Function returns
1892 // true if the *global* timeout fired, which will cause WatcherThread to shut down the JVM
1893 // immediately.
1894 bool VMError::check_timeout() {
1895 
1896   // This function is supposed to be called from watcher thread during fatal error handling only.
1897   assert(VMError::is_error_reported(), "Only call during error handling");
1898   assert(Thread::current()->is_Watcher_thread(), "Only call from watcher thread");
1899 
1900   if (ErrorLogTimeout == 0) {
1901     return false;
1902   }
1903 
1904   // There are three situations where we suppress the *global* error timeout:
1905   // - if the JVM is embedded and the launcher has its abort hook installed.
1906   //   That must be allowed to run.
1907   // - if the user specified one or more OnError commands to run, and these
1908   //   did not yet run. These must have finished.
1909   // - if the user (typically developer) specified ShowMessageBoxOnError,
1910   //   and the error box has not yet been shown
1911   const bool ignore_global_timeout =
1912       (ShowMessageBoxOnError
1913             || (OnError != nullptr && OnError[0] != '\0')
1914             || Arguments::abort_hook() != nullptr);
1915 
1916   const jlong now = get_current_timestamp();
1917 
1918   // Global timeout hit?
1919   if (!ignore_global_timeout) {
1920     const jlong reporting_start_time = get_reporting_start_time();
1921     // Timestamp is stored in nanos.
1922     if (reporting_start_time > 0) {
1923       const jlong end = reporting_start_time + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1924       if (end <= now && !_reporting_did_timeout) {
1925         // We hit ErrorLogTimeout and we haven't interrupted the reporting
1926         // thread yet.
1927         _reporting_did_timeout = true;
1928         interrupt_reporting_thread();
1929         return true; // global timeout
1930       }
1931     }
1932   }
1933 
1934   // Reporting step timeout?
1935   const jlong step_start_time = get_step_start_time();
1936   if (step_start_time > 0) {
1937     // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1938     // hang for some reason, so this simple rule allows for three hanging step and still
1939     // hopefully leaves time enough for the rest of the steps to finish.
1940     const int max_step_timeout_secs = 5;
1941     const jlong timeout_duration = MAX2((jlong)max_step_timeout_secs, (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4);
1942     const jlong end = step_start_time + timeout_duration;
1943     if (end <= now && !_step_did_timeout) {
1944       // The step timed out and we haven't interrupted the reporting
1945       // thread yet.
1946       _step_did_timeout = true;
1947       interrupt_reporting_thread();
1948       return false; // (Not a global timeout)
1949     }
1950   }
1951 
1952   return false;
1953 
1954 }
1955 
1956 #ifdef ASSERT
1957 typedef void (*voidfun_t)();
1958 
1959 // Crash with an authentic sigfpe
1960 volatile int sigfpe_int = 0;
1961 static void crash_with_sigfpe() {
1962 
1963   // generate a native synchronous SIGFPE where possible;
1964   sigfpe_int = sigfpe_int/sigfpe_int;
1965 
1966   // if that did not cause a signal (e.g. on ppc), just
1967   // raise the signal.
1968 #ifndef _WIN32
1969   // OSX implements raise(sig) incorrectly so we need to
1970   // explicitly target the current thread
1971   pthread_kill(pthread_self(), SIGFPE);
1972 #endif
1973 
1974 } // end: crash_with_sigfpe
1975 
1976 // crash with sigsegv at non-null address.
1977 static void crash_with_segfault() {
1978 
1979   int* crash_addr = reinterpret_cast<int*>(VMError::segfault_address);
1980   *crash_addr = 1;
1981 
1982 } // end: crash_with_segfault
1983 
1984 // crash in a controlled way:
1985 // 1  - assert
1986 // 2  - guarantee
1987 // 14 - SIGSEGV
1988 // 15 - SIGFPE
1989 void VMError::controlled_crash(int how) {
1990 
1991   // Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java.
1992   // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java.
1993   // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java.
1994   // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
1995 
1996   // We try to grab Threads_lock to keep ThreadsSMRSupport::print_info_on()
1997   // from racing with Threads::add() or Threads::remove() as we
1998   // generate the hs_err_pid file. This makes our ErrorHandling tests
1999   // more stable.
2000   if (!Threads_lock->owned_by_self()) {
2001     Threads_lock->try_lock();
2002     // The VM is going to die so no need to unlock Thread_lock.
2003   }
2004 
2005   switch (how) {
2006     case 1: assert(how == 0, "test assert"); break;
2007     case 2: guarantee(how == 0, "test guarantee"); break;
2008 
2009     // The other cases are unused.
2010     case 14: crash_with_segfault(); break;
2011     case 15: crash_with_sigfpe(); break;
2012     case 16: {
2013       ThreadsListHandle tlh;
2014       fatal("Force crash with an active ThreadsListHandle.");
2015     }
2016     case 17: {
2017       ThreadsListHandle tlh;
2018       {
2019         ThreadsListHandle tlh2;
2020         fatal("Force crash with a nested ThreadsListHandle.");
2021       }
2022     }
2023     default:
2024       // If another number is given, give a generic crash.
2025       fatal("Crashing with number %d", how);
2026   }
2027   tty->print_cr("controlled_crash: survived intentional crash. Did you suppress the assert?");
2028   ShouldNotReachHere();
2029 }
2030 #endif // !ASSERT