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