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