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