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