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