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