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