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