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