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/thread.inline.hpp"
  42 #include "runtime/threadSMR.hpp"
  43 #include "runtime/vmThread.hpp"
  44 #include "runtime/vmOperations.hpp"
  45 #include "runtime/vm_version.hpp"
  46 #include "runtime/flags/jvmFlag.hpp"
  47 #include "services/memTracker.hpp"
  48 #include "utilities/debug.hpp"
  49 #include "utilities/decoder.hpp"
  50 #include "utilities/defaultStream.hpp"
  51 #include "utilities/events.hpp"
  52 #include "utilities/vmError.hpp"
  53 #include "utilities/macros.hpp"
  54 #if INCLUDE_JFR
  55 #include "jfr/jfr.hpp"
  56 #endif
  57 
  58 #ifndef PRODUCT
  59 #include <signal.h>
  60 #endif // PRODUCT
  61 
  62 bool VMError::_error_reported = false;
  63 
  64 // call this when the VM is dying--it might loosen some asserts
  65 bool VMError::is_error_reported() { return _error_reported; }
  66 
  67 // returns an address which is guaranteed to generate a SIGSEGV on read,
  68 // for test purposes, which is not NULL and contains bits in every word
  69 void* VMError::get_segfault_address() {
  70   return (void*)
  71 #ifdef _LP64
  72     0xABC0000000000ABCULL;
  73 #else
  74     0x00000ABC;
  75 #endif
  76 }
  77 
  78 // List of environment variables that should be reported in error log file.
  79 const char *env_list[] = {
  80   // All platforms
  81   "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
  82   "JAVA_COMPILER", "PATH", "USERNAME",
  83 
  84   // Env variables that are defined on Solaris/Linux/BSD
  85   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
  86   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
  87 
  88   // defined on AIX
  89   "LIBPATH", "LDR_PRELOAD", "LDR_PRELOAD64",
  90 
  91   // defined on Linux
  92   "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
  93 
  94   // defined on Darwin
  95   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
  96   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
  97   "DYLD_INSERT_LIBRARIES",
  98 
  99   // defined on Windows
 100   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
 101 
 102   (const char *)0
 103 };
 104 
 105 // A simple parser for -XX:OnError, usage:
 106 //  ptr = OnError;
 107 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
 108 //     ... ...
 109 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
 110   if (ptr == NULL || *ptr == NULL) return NULL;
 111 
 112   const char* cmd = *ptr;
 113 
 114   // skip leading blanks or ';'
 115   while (*cmd == ' ' || *cmd == ';') cmd++;
 116 
 117   if (*cmd == '\0') return NULL;
 118 
 119   const char * cmdend = cmd;
 120   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
 121 
 122   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
 123 
 124   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
 125   return buf;
 126 }
 127 
 128 static void print_bug_submit_message(outputStream *out, Thread *thread) {
 129   if (out == NULL) return;
 130   const char *url = Arguments::java_vendor_url_bug();
 131   if (url == NULL || *url == '\0')
 132     url = JDK_Version::runtime_vendor_vm_bug_url();
 133   if (url != NULL && *url != '\0') {
 134     out->print_raw_cr("# If you would like to submit a bug report, please visit:");
 135     out->print_raw   ("#   ");
 136     out->print_raw_cr(url);
 137   }
 138   // If the crash is in native code, encourage user to submit a bug to the
 139   // provider of that code.
 140   if (thread && thread->is_Java_thread() &&
 141       !thread->is_hidden_from_external_view()) {
 142     JavaThread* jt = (JavaThread*)thread;
 143     if (jt->thread_state() == _thread_in_native) {
 144       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
 145     }
 146   }
 147   out->print_raw_cr("#");
 148 }
 149 
 150 bool VMError::coredump_status;
 151 char VMError::coredump_message[O_BUFLEN];
 152 
 153 void VMError::record_coredump_status(const char* message, bool status) {
 154   coredump_status = status;
 155   strncpy(coredump_message, message, sizeof(coredump_message));
 156   coredump_message[sizeof(coredump_message)-1] = 0;
 157 }
 158 
 159 // Return a string to describe the error
 160 char* VMError::error_string(char* buf, int buflen) {
 161   char signame_buf[64];
 162   const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
 163 
 164   if (signame) {
 165     jio_snprintf(buf, buflen,
 166                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
 167                  signame, _id, _pc,
 168                  os::current_process_id(), os::current_thread_id());
 169   } else if (_filename != NULL && _lineno > 0) {
 170     // skip directory names
 171     char separator = os::file_separator()[0];
 172     const char *p = strrchr(_filename, separator);
 173     int n = jio_snprintf(buf, buflen,
 174                          "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
 175                          p ? p + 1 : _filename, _lineno,
 176                          os::current_process_id(), os::current_thread_id());
 177     if (n >= 0 && n < buflen && _message) {
 178       if (strlen(_detail_msg) > 0) {
 179         jio_snprintf(buf + n, buflen - n, "%s%s: %s",
 180         os::line_separator(), _message, _detail_msg);
 181       } else {
 182         jio_snprintf(buf + n, buflen - n, "%sError: %s",
 183                      os::line_separator(), _message);
 184       }
 185     }
 186   } else {
 187     jio_snprintf(buf, buflen,
 188                  "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
 189                  _id, os::current_process_id(), os::current_thread_id());
 190   }
 191 
 192   return buf;
 193 }
 194 
 195 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
 196                                 char* buf, int buflen, bool verbose) {
 197 #ifdef ZERO
 198   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
 199     // StackFrameStream uses the frame anchor, which may not have
 200     // been set up.  This can be done at any time in Zero, however,
 201     // so if it hasn't been set up then we just set it up now and
 202     // clear it again when we're done.
 203     bool has_last_Java_frame = jt->has_last_Java_frame();
 204     if (!has_last_Java_frame)
 205       jt->set_last_Java_frame();
 206     st->print("Java frames:");
 207     st->cr();
 208 
 209     // Print the frames
 210     StackFrameStream sfs(jt);
 211     for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
 212       sfs.current()->zero_print_on_error(i, st, buf, buflen);
 213       st->cr();
 214     }
 215 
 216     // Reset the frame anchor if necessary
 217     if (!has_last_Java_frame)
 218       jt->reset_last_Java_frame();
 219   }
 220 #else
 221   if (jt->has_last_Java_frame()) {
 222     st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
 223     for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
 224       sfs.current()->print_on_error(st, buf, buflen, verbose);
 225       st->cr();
 226     }
 227   }
 228 #endif // ZERO
 229 }
 230 
 231 void VMError::print_native_stack(outputStream* st, frame fr, Thread* t, char* buf, int buf_size) {
 232 
 233   // see if it's a valid frame
 234   if (fr.pc()) {
 235     st->print_cr("Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)");
 236 
 237     int count = 0;
 238     while (count++ < StackPrintLimit) {
 239       fr.print_on_error(st, buf, buf_size);
 240       if (fr.pc()) { // print source file and line, if available
 241         char buf[128];
 242         int line_no;
 243         if (Decoder::get_source_info(fr.pc(), buf, sizeof(buf), &line_no)) {
 244           st->print("  (%s:%d)", buf, line_no);
 245         }
 246       }
 247       st->cr();
 248       // Compiled code may use EBP register on x86 so it looks like
 249       // non-walkable C frame. Use frame.sender() for java frames.
 250       if (t && t->is_Java_thread()) {
 251         // Catch very first native frame by using stack address.
 252         // For JavaThread stack_base and stack_size should be set.
 253         if (!t->is_in_full_stack((address)(fr.real_fp() + 1))) {
 254           break;
 255         }
 256         if (fr.is_java_frame() || fr.is_native_frame() || fr.is_runtime_frame()) {
 257           RegisterMap map((JavaThread*)t, false); // No update
 258           fr = fr.sender(&map);
 259         } else {
 260           // is_first_C_frame() does only simple checks for frame pointer,
 261           // it will pass if java compiled code has a pointer in EBP.
 262           if (os::is_first_C_frame(&fr)) break;
 263           fr = os::get_sender_for_C_frame(&fr);
 264         }
 265       } else {
 266         if (os::is_first_C_frame(&fr)) break;
 267         fr = os::get_sender_for_C_frame(&fr);
 268       }
 269     }
 270 
 271     if (count > StackPrintLimit) {
 272       st->print_cr("...<more frames>...");
 273     }
 274 
 275     st->cr();
 276   }
 277 }
 278 
 279 static void print_oom_reasons(outputStream* st) {
 280   st->print_cr("# Possible reasons:");
 281   st->print_cr("#   The system is out of physical RAM or swap space");
 282   if (UseCompressedOops) {
 283     st->print_cr("#   The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
 284   }
 285   if (LogBytesPerWord == 2) {
 286     st->print_cr("#   In 32 bit mode, the process size limit was hit");
 287   }
 288   st->print_cr("# Possible solutions:");
 289   st->print_cr("#   Reduce memory load on the system");
 290   st->print_cr("#   Increase physical memory or swap space");
 291   st->print_cr("#   Check if swap backing store is full");
 292   if (LogBytesPerWord == 2) {
 293     st->print_cr("#   Use 64 bit Java on a 64 bit OS");
 294   }
 295   st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
 296   st->print_cr("#   Decrease number of Java threads");
 297   st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
 298   st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
 299   if (UseCompressedOops) {
 300     switch (CompressedOops::mode()) {
 301       case CompressedOops::UnscaledNarrowOop:
 302         st->print_cr("#   JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
 303         st->print_cr("#     placed in the first 4GB address space. The Java Heap base address is the");
 304         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 305         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
 306         break;
 307       case CompressedOops::ZeroBasedNarrowOop:
 308         st->print_cr("#   JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
 309         st->print_cr("#     placed in the first 32GB address space. The Java Heap base address is the");
 310         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
 311         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
 312         break;
 313       default:
 314         break;
 315     }
 316   }
 317   st->print_cr("# This output file may be truncated or incomplete.");
 318 }
 319 
 320 static void report_vm_version(outputStream* st, char* buf, int buflen) {
 321    // VM version
 322    st->print_cr("#");
 323    JDK_Version::current().to_string(buf, buflen);
 324    const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 325                                 JDK_Version::runtime_name() : "";
 326    const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 327                                    JDK_Version::runtime_version() : "";
 328    const char* vendor_version = JDK_Version::runtime_vendor_version() != NULL ?
 329                                   JDK_Version::runtime_vendor_version() : "";
 330    const char* jdk_debug_level = VM_Version::printable_jdk_debug_level() != NULL ?
 331                                    VM_Version::printable_jdk_debug_level() : "";
 332 
 333    st->print_cr("# JRE version: %s%s%s (%s) (%sbuild %s)", runtime_name,
 334                 (*vendor_version != '\0') ? " " : "", vendor_version,
 335                 buf, jdk_debug_level, runtime_version);
 336 
 337    // This is the long version with some default settings added
 338    st->print_cr("# Java VM: %s%s%s (%s%s, %s%s%s%s%s, %s, %s)",
 339                  VM_Version::vm_name(),
 340                 (*vendor_version != '\0') ? " " : "", vendor_version,
 341                  jdk_debug_level,
 342                  VM_Version::vm_release(),
 343                  VM_Version::vm_info_string(),
 344                  TieredCompilation ? ", tiered" : "",
 345 #if INCLUDE_JVMCI
 346                  EnableJVMCI ? ", jvmci" : "",
 347                  UseJVMCICompiler ? ", jvmci compiler" : "",
 348 #else
 349                  "", "",
 350 #endif
 351                  UseCompressedOops ? ", compressed oops" : "",
 352                  GCConfig::hs_err_name(),
 353                  VM_Version::vm_platform_string()
 354                );
 355 }
 356 
 357 // This is the main function to report a fatal error. Only one thread can
 358 // call this function, so we don't need to worry about MT-safety. But it's
 359 // possible that the error handler itself may crash or die on an internal
 360 // error, for example, when the stack/heap is badly damaged. We must be
 361 // able to handle recursive errors that happen inside error handler.
 362 //
 363 // Error reporting is done in several steps. If a crash or internal error
 364 // occurred when reporting an error, the nested signal/exception handler
 365 // can skip steps that are already (or partially) done. Error reporting will
 366 // continue from the next step. This allows us to retrieve and print
 367 // information that may be unsafe to get after a fatal error. If it happens,
 368 // you may find nested report_and_die() frames when you look at the stack
 369 // in a debugger.
 370 //
 371 // In general, a hang in error handler is much worse than a crash or internal
 372 // error, as it's harder to recover from a hang. Deadlock can happen if we
 373 // try to grab a lock that is already owned by current thread, or if the
 374 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 375 // error handler and all the functions it called should avoid grabbing any
 376 // lock. An important thing to notice is that memory allocation needs a lock.
 377 //
 378 // We should avoid using large stack allocated buffers. Many errors happen
 379 // when stack space is already low. Making things even worse is that there
 380 // could be nested report_and_die() calls on stack (see above). Only one
 381 // thread can report error, so large buffers are statically allocated in data
 382 // segment.
 383 
 384 int          VMError::_current_step;
 385 const char*  VMError::_current_step_info;
 386 
 387 volatile jlong VMError::_reporting_start_time = -1;
 388 volatile bool VMError::_reporting_did_timeout = false;
 389 volatile jlong VMError::_step_start_time = -1;
 390 volatile bool VMError::_step_did_timeout = false;
 391 
 392 // Helper, return current timestamp for timeout handling.
 393 jlong VMError::get_current_timestamp() {
 394   return os::javaTimeNanos();
 395 }
 396 // Factor to translate the timestamp to seconds.
 397 #define TIMESTAMP_TO_SECONDS_FACTOR (1000 * 1000 * 1000)
 398 
 399 void VMError::record_reporting_start_time() {
 400   const jlong now = get_current_timestamp();
 401   Atomic::store(&_reporting_start_time, now);
 402 }
 403 
 404 jlong VMError::get_reporting_start_time() {
 405   return Atomic::load(&_reporting_start_time);
 406 }
 407 
 408 void VMError::record_step_start_time() {
 409   const jlong now = get_current_timestamp();
 410   Atomic::store(&_step_start_time, now);
 411 }
 412 
 413 jlong VMError::get_step_start_time() {
 414   return Atomic::load(&_step_start_time);
 415 }
 416 
 417 void VMError::clear_step_start_time() {
 418   return Atomic::store(&_step_start_time, (jlong)0);
 419 }
 420 
 421 void VMError::report(outputStream* st, bool _verbose) {
 422 
 423 # define BEGIN if (_current_step == 0) { _current_step = __LINE__;
 424 # define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; \
 425   record_step_start_time(); _step_did_timeout = false;
 426 # define END clear_step_start_time(); }
 427 
 428   // don't allocate large buffer on stack
 429   static char buf[O_BUFLEN];
 430 
 431   BEGIN
 432 
 433   STEP("printing fatal error message")
 434 
 435     st->print_cr("#");
 436     if (should_report_bug(_id)) {
 437       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 438     } else {
 439       st->print_cr("# There is insufficient memory for the Java "
 440                    "Runtime Environment to continue.");
 441     }
 442 
 443 #ifndef PRODUCT
 444   // Error handler self tests
 445 
 446   // test secondary error handling. Test it twice, to test that resetting
 447   // error handler after a secondary crash works.
 448   STEP("test secondary crash 1")
 449     if (_verbose && TestCrashInErrorHandler != 0) {
 450       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
 451         TestCrashInErrorHandler);
 452       controlled_crash(TestCrashInErrorHandler);
 453     }
 454 
 455   STEP("test secondary crash 2")
 456     if (_verbose && TestCrashInErrorHandler != 0) {
 457       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
 458         TestCrashInErrorHandler);
 459       controlled_crash(TestCrashInErrorHandler);
 460     }
 461 
 462   // TestUnresponsiveErrorHandler: We want to test both step timeouts and global timeout.
 463   // Step to global timeout ratio is 4:1, so in order to be absolutely sure we hit the
 464   // global timeout, let's execute the timeout step five times.
 465   // See corresponding test in test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java
 466   STEP("setup for test unresponsive error reporting step")
 467     if (_verbose && TestUnresponsiveErrorHandler) {
 468       // We record reporting_start_time for this test here because we
 469       // care about the time spent executing TIMEOUT_TEST_STEP and not
 470       // about the time it took us to get here.
 471       tty->print_cr("Recording reporting_start_time for TestUnresponsiveErrorHandler.");
 472       record_reporting_start_time();
 473     }
 474 
 475   #define TIMEOUT_TEST_STEP STEP("test unresponsive error reporting step") \
 476     if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); }
 477   TIMEOUT_TEST_STEP
 478   TIMEOUT_TEST_STEP
 479   TIMEOUT_TEST_STEP
 480   TIMEOUT_TEST_STEP
 481   TIMEOUT_TEST_STEP
 482 
 483   STEP("test safefetch in error handler")
 484     // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
 485     // to test that resetting the signal handler works correctly.
 486     if (_verbose && TestSafeFetchInErrorHandler) {
 487       st->print_cr("Will test SafeFetch...");
 488       if (CanUseSafeFetch32()) {
 489         int* const invalid_pointer = (int*) get_segfault_address();
 490         const int x = 0x76543210;
 491         int i1 = SafeFetch32(invalid_pointer, x);
 492         int i2 = SafeFetch32(invalid_pointer, x);
 493         if (i1 == x && i2 == x) {
 494           st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
 495         } else {
 496           st->print_cr("??");
 497         }
 498       } else {
 499         st->print_cr("not possible; skipped.");
 500       }
 501     }
 502 #endif // PRODUCT
 503 
 504   STEP("printing type of error")
 505 
 506      switch(static_cast<unsigned int>(_id)) {
 507        case OOM_MALLOC_ERROR:
 508        case OOM_MMAP_ERROR:
 509          if (_size) {
 510            st->print("# Native memory allocation ");
 511            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 512                                                  "(mmap) failed to map ");
 513            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
 514            st->print("%s", buf);
 515            st->print(" bytes");
 516            if (strlen(_detail_msg) > 0) {
 517              st->print(" for ");
 518              st->print("%s", _detail_msg);
 519            }
 520            st->cr();
 521          } else {
 522            if (strlen(_detail_msg) > 0) {
 523              st->print("# ");
 524              st->print_cr("%s", _detail_msg);
 525            }
 526          }
 527          // In error file give some solutions
 528          if (_verbose) {
 529            print_oom_reasons(st);
 530          } else {
 531            return;  // that's enough for the screen
 532          }
 533          break;
 534        case INTERNAL_ERROR:
 535        default:
 536          break;
 537      }
 538 
 539   STEP("printing exception/signal name")
 540 
 541      st->print_cr("#");
 542      st->print("#  ");
 543      // Is it an OS exception/signal?
 544      if (os::exception_name(_id, buf, sizeof(buf))) {
 545        st->print("%s", buf);
 546        st->print(" (0x%x)", _id);                // signal number
 547        st->print(" at pc=" PTR_FORMAT, p2i(_pc));
 548        if (_siginfo != NULL && os::signal_sent_by_kill(_siginfo)) {
 549          st->print(" (sent by kill)");
 550        }
 551      } else {
 552        if (should_report_bug(_id)) {
 553          st->print("Internal Error");
 554        } else {
 555          st->print("Out of Memory Error");
 556        }
 557        if (_filename != NULL && _lineno > 0) {
 558 #ifdef PRODUCT
 559          // In product mode chop off pathname?
 560          char separator = os::file_separator()[0];
 561          const char *p = strrchr(_filename, separator);
 562          const char *file = p ? p+1 : _filename;
 563 #else
 564          const char *file = _filename;
 565 #endif
 566          st->print(" (%s:%d)", file, _lineno);
 567        } else {
 568          st->print(" (0x%x)", _id);
 569        }
 570      }
 571 
 572   STEP("printing current thread and pid")
 573 
 574      // process id, thread id
 575      st->print(", pid=%d", os::current_process_id());
 576      st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
 577      st->cr();
 578 
 579   STEP("printing error message")
 580 
 581      if (should_report_bug(_id)) {  // already printed the message.
 582        // error message
 583        if (strlen(_detail_msg) > 0) {
 584          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
 585        } else if (_message) {
 586          st->print_cr("#  Error: %s", _message);
 587        }
 588      }
 589 
 590   STEP("printing Java version string")
 591 
 592      report_vm_version(st, buf, sizeof(buf));
 593 
 594   STEP("printing problematic frame")
 595 
 596      // Print current frame if we have a context (i.e. it's a crash)
 597      if (_context) {
 598        st->print_cr("# Problematic frame:");
 599        st->print("# ");
 600        frame fr = os::fetch_frame_from_context(_context);
 601        fr.print_on_error(st, buf, sizeof(buf));
 602        st->cr();
 603        st->print_cr("#");
 604      }
 605 
 606   STEP("printing core file information")
 607     st->print("# ");
 608     if (CreateCoredumpOnCrash) {
 609       if (coredump_status) {
 610         st->print("Core dump will be written. Default location: %s", coredump_message);
 611       } else {
 612         st->print("No core dump will be written. %s", coredump_message);
 613       }
 614     } else {
 615       st->print("CreateCoredumpOnCrash turned off, no core file dumped");
 616     }
 617     st->cr();
 618     st->print_cr("#");
 619 
 620   JFR_ONLY(STEP("printing jfr information"))
 621   JFR_ONLY(Jfr::on_vm_error_report(st);)
 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(os::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(os::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   } else {
1414     // If UseOsErrorReporting we call this for each level of the call stack
1415     // while searching for the exception handler.  Only the first level needs
1416     // to be reported.
1417     if (UseOSErrorReporting && log_done) return;
1418 
1419     // This is not the first error, see if it happened in a different thread
1420     // or in the same thread during error reporting.
1421     if (_first_error_tid != mytid) {
1422       char msgbuf[64];
1423       jio_snprintf(msgbuf, sizeof(msgbuf),
1424                    "[thread " INTX_FORMAT " also had an error]",
1425                    mytid);
1426       out.print_raw_cr(msgbuf);
1427 
1428       // error reporting is not MT-safe, block current thread
1429       os::infinite_sleep();
1430 
1431     } else {
1432       if (recursive_error_count++ > 30) {
1433         out.print_raw_cr("[Too many errors, abort]");
1434         os::die();
1435       }
1436 
1437       outputStream* const st = log.is_open() ? &log : &out;
1438       st->cr();
1439 
1440       // Timeout handling.
1441       if (_step_did_timeout) {
1442         // The current step had a timeout. Lets continue reporting with the next step.
1443         st->print_raw("[timeout occurred during error reporting in step \"");
1444         st->print_raw(_current_step_info);
1445         st->print_cr("\"] after " INT64_FORMAT " s.",
1446                      (int64_t)
1447                      ((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1448       } else if (_reporting_did_timeout) {
1449         // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1450         // up, the process is about to be stopped by the WatcherThread.
1451         st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1452                      (int64_t)
1453                      ((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1454         st->flush();
1455         // Watcherthread is about to call os::die. Lets just wait.
1456         os::infinite_sleep();
1457       } else {
1458         // Crash or assert during error reporting. Lets continue reporting with the next step.
1459         stringStream ss(buffer, sizeof(buffer));
1460         // Note: this string does get parsed by a number of jtreg tests,
1461         // see hotspot/jtreg/runtime/ErrorHandling.
1462         ss.print("[error occurred during error reporting (%s), id 0x%x",
1463                    _current_step_info, id);
1464         char signal_name[64];
1465         if (os::exception_name(id, signal_name, sizeof(signal_name))) {
1466           ss.print(", %s (0x%x) at pc=" PTR_FORMAT, signal_name, id, p2i(pc));
1467         } else {
1468           if (should_report_bug(id)) {
1469             ss.print(", Internal Error (%s:%d)",
1470               filename == NULL ? "??" : filename, lineno);
1471           } else {
1472             ss.print(", Out of Memory Error (%s:%d)",
1473               filename == NULL ? "??" : filename, lineno);
1474           }
1475         }
1476         ss.print("]");
1477         st->print_raw_cr(buffer);
1478         st->cr();
1479       }
1480     }
1481   }
1482 
1483   // Part 1: print an abbreviated version (the '#' section) to stdout.
1484   if (!out_done) {
1485     // Suppress this output if we plan to print Part 2 to stdout too.
1486     // No need to have the "#" section twice.
1487     if (!(ErrorFileToStdout && out.fd() == 1)) {
1488       report(&out, false);
1489     }
1490 
1491     out_done = true;
1492 
1493     _current_step = 0;
1494     _current_step_info = "";
1495   }
1496 
1497   // Part 2: print a full error log file (optionally to stdout or stderr).
1498   // print to error log file
1499   if (!log_done) {
1500     // see if log file is already open
1501     if (!log.is_open()) {
1502       // open log file
1503       if (ErrorFileToStdout) {
1504         fd_log = 1;
1505       } else if (ErrorFileToStderr) {
1506         fd_log = 2;
1507       } else {
1508         fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", true,
1509                  buffer, sizeof(buffer));
1510         if (fd_log != -1) {
1511           out.print_raw("# An error report file with more information is saved as:\n# ");
1512           out.print_raw_cr(buffer);
1513         } else {
1514           out.print_raw_cr("# Can not save log file, dump to screen..");
1515           fd_log = 1;
1516         }
1517       }
1518       log.set_fd(fd_log);
1519     }
1520 
1521     report(&log, true);
1522     log_done = true;
1523     _current_step = 0;
1524     _current_step_info = "";
1525 
1526     if (fd_log > 3) {
1527       close(fd_log);
1528       fd_log = -1;
1529     }
1530 
1531     log.set_fd(-1);
1532   }
1533 
1534   JFR_ONLY(Jfr::on_vm_shutdown(true);)
1535 
1536   if (PrintNMTStatistics) {
1537     fdStream fds(fd_out);
1538     MemTracker::final_report(&fds);
1539   }
1540 
1541   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1542   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1543     skip_replay = true;
1544     ciEnv* env = ciEnv::current();
1545     if (env != NULL) {
1546       const bool overwrite = false; // We do not overwrite an existing replay file.
1547       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", overwrite, buffer, sizeof(buffer));
1548       if (fd != -1) {
1549         FILE* replay_data_file = os::open(fd, "w");
1550         if (replay_data_file != NULL) {
1551           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1552           env->dump_replay_data_unsafe(&replay_data_stream);
1553           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1554           out.print_raw_cr(buffer);
1555         } else {
1556           int e = errno;
1557           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1558           out.print_raw_cr(os::strerror(e));
1559         }
1560       }
1561     }
1562   }
1563 
1564   static bool skip_bug_url = !should_report_bug(_id);
1565   if (!skip_bug_url) {
1566     skip_bug_url = true;
1567 
1568     out.print_raw_cr("#");
1569     print_bug_submit_message(&out, _thread);
1570   }
1571 
1572   static bool skip_OnError = false;
1573   if (!skip_OnError && OnError && OnError[0]) {
1574     skip_OnError = true;
1575 
1576     // Flush output and finish logs before running OnError commands.
1577     ostream_abort();
1578 
1579     out.print_raw_cr("#");
1580     out.print_raw   ("# -XX:OnError=\"");
1581     out.print_raw   (OnError);
1582     out.print_raw_cr("\"");
1583 
1584     char* cmd;
1585     const char* ptr = OnError;
1586     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1587       out.print_raw   ("#   Executing ");
1588 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1589       out.print_raw   ("/bin/sh -c ");
1590 #elif defined(SOLARIS)
1591       out.print_raw   ("/usr/bin/sh -c ");
1592 #elif defined(_WINDOWS)
1593       out.print_raw   ("cmd /C ");
1594 #endif
1595       out.print_raw   ("\"");
1596       out.print_raw   (cmd);
1597       out.print_raw_cr("\" ...");
1598 
1599       if (os::fork_and_exec(cmd) < 0) {
1600         out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1601                      os::strerror(errno), os::errno_name(errno), errno);
1602       }
1603     }
1604 
1605     // done with OnError
1606     OnError = NULL;
1607   }
1608 
1609   if (!UseOSErrorReporting) {
1610     // os::abort() will call abort hooks, try it first.
1611     static bool skip_os_abort = false;
1612     if (!skip_os_abort) {
1613       skip_os_abort = true;
1614       bool dump_core = should_report_bug(_id);
1615       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1616     }
1617 
1618     // if os::abort() doesn't abort, try os::die();
1619     os::die();
1620   }
1621 }
1622 
1623 /*
1624  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1625  * ensures utilities such as jmap can observe the process is a consistent state.
1626  */
1627 class VM_ReportJavaOutOfMemory : public VM_Operation {
1628  private:
1629   const char* _message;
1630  public:
1631   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1632   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1633   void doit();
1634 };
1635 
1636 void VM_ReportJavaOutOfMemory::doit() {
1637   // Don't allocate large buffer on stack
1638   static char buffer[O_BUFLEN];
1639 
1640   tty->print_cr("#");
1641   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1642   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1643 
1644   // make heap parsability
1645   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1646 
1647   char* cmd;
1648   const char* ptr = OnOutOfMemoryError;
1649   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1650     tty->print("#   Executing ");
1651 #if defined(LINUX)
1652     tty->print  ("/bin/sh -c ");
1653 #elif defined(SOLARIS)
1654     tty->print  ("/usr/bin/sh -c ");
1655 #endif
1656     tty->print_cr("\"%s\"...", cmd);
1657 
1658     if (os::fork_and_exec(cmd, true) < 0) {
1659       tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1660                      os::strerror(errno), os::errno_name(errno), errno);
1661     }
1662   }
1663 }
1664 
1665 void VMError::report_java_out_of_memory(const char* message) {
1666   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1667     MutexLocker ml(Heap_lock);
1668     VM_ReportJavaOutOfMemory op(message);
1669     VMThread::execute(&op);
1670   }
1671 }
1672 
1673 void VMError::show_message_box(char *buf, int buflen) {
1674   bool yes;
1675   do {
1676     error_string(buf, buflen);
1677     yes = os::start_debugging(buf,buflen);
1678   } while (yes);
1679 }
1680 
1681 // Timeout handling: check if a timeout happened (either a single step did
1682 // timeout or the whole of error reporting hit ErrorLogTimeout). Interrupt
1683 // the reporting thread if that is the case.
1684 bool VMError::check_timeout() {
1685 
1686   if (ErrorLogTimeout == 0) {
1687     return false;
1688   }
1689 
1690   // Do not check for timeouts if we still have a message box to show to the
1691   // user or if there are OnError handlers to be run.
1692   if (ShowMessageBoxOnError
1693       || (OnError != NULL && OnError[0] != '\0')
1694       || Arguments::abort_hook() != NULL) {
1695     return false;
1696   }
1697 
1698   const jlong reporting_start_time_l = get_reporting_start_time();
1699   const jlong now = get_current_timestamp();
1700   // Timestamp is stored in nanos.
1701   if (reporting_start_time_l > 0) {
1702     const jlong end = reporting_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1703     if (end <= now && !_reporting_did_timeout) {
1704       // We hit ErrorLogTimeout and we haven't interrupted the reporting
1705       // thread yet.
1706       _reporting_did_timeout = true;
1707       interrupt_reporting_thread();
1708       return true; // global timeout
1709     }
1710   }
1711 
1712   const jlong step_start_time_l = get_step_start_time();
1713   if (step_start_time_l > 0) {
1714     // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1715     // hang for some reason, so this simple rule allows for three hanging step and still
1716     // hopefully leaves time enough for the rest of the steps to finish.
1717     const jlong end = step_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4;
1718     if (end <= now && !_step_did_timeout) {
1719       // The step timed out and we haven't interrupted the reporting
1720       // thread yet.
1721       _step_did_timeout = true;
1722       interrupt_reporting_thread();
1723       return false; // (Not a global timeout)
1724     }
1725   }
1726 
1727   return false;
1728 
1729 }
1730 
1731 #ifndef PRODUCT
1732 #if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140
1733 #pragma error_messages(off, SEC_NULL_PTR_DEREF)
1734 #endif
1735 typedef void (*voidfun_t)();
1736 // Crash with an authentic sigfpe
1737 static void crash_with_sigfpe() {
1738   // generate a native synchronous SIGFPE where possible;
1739   // if that did not cause a signal (e.g. on ppc), just
1740   // raise the signal.
1741   volatile int x = 0;
1742   volatile int y = 1/x;
1743 #ifndef _WIN32
1744   // OSX implements raise(sig) incorrectly so we need to
1745   // explicitly target the current thread
1746   pthread_kill(pthread_self(), SIGFPE);
1747 #endif
1748 } // end: crash_with_sigfpe
1749 
1750 // crash with sigsegv at non-null address.
1751 static void crash_with_segfault() {
1752 
1753   char* const crash_addr = (char*) VMError::get_segfault_address();
1754   *crash_addr = 'X';
1755 
1756 } // end: crash_with_segfault
1757 
1758 void VMError::test_error_handler() {
1759   controlled_crash(ErrorHandlerTest);
1760 }
1761 
1762 // crash in a controlled way:
1763 // how can be one of:
1764 // 1,2 - asserts
1765 // 3,4 - guarantee
1766 // 5-7 - fatal
1767 // 8 - vm_exit_out_of_memory
1768 // 9 - ShouldNotCallThis
1769 // 10 - ShouldNotReachHere
1770 // 11 - Unimplemented
1771 // 12,13 - (not guaranteed) crashes
1772 // 14 - SIGSEGV
1773 // 15 - SIGFPE
1774 void VMError::controlled_crash(int how) {
1775   if (how == 0) return;
1776 
1777   // If asserts are disabled, use the corresponding guarantee instead.
1778   NOT_DEBUG(if (how <= 2) how += 2);
1779 
1780   const char* const str = "hello";
1781   const size_t      num = (size_t)os::vm_page_size();
1782 
1783   const char* const eol = os::line_separator();
1784   const char* const msg = "this message should be truncated during formatting";
1785   char * const dataPtr = NULL;  // bad data pointer
1786   const void (*funcPtr)(void);  // bad function pointer
1787 
1788 #if defined(PPC64) && !defined(ABI_ELFv2)
1789   struct FunctionDescriptor functionDescriptor;
1790 
1791   functionDescriptor.set_entry((address) 0xF);
1792   funcPtr = (const void(*)()) &functionDescriptor;
1793 #else
1794   funcPtr = (const void(*)()) 0xF;
1795 #endif
1796 
1797   // Keep this in sync with test/hotspot/jtreg/runtime/ErrorHandling/ErrorHandler.java
1798   // which tests cases 1 thru 13.
1799   // Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java.
1800   // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java.
1801   // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java.
1802   // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
1803 
1804   // We try to grab Threads_lock to keep ThreadsSMRSupport::print_info_on()
1805   // from racing with Threads::add() or Threads::remove() as we
1806   // generate the hs_err_pid file. This makes our ErrorHandling tests
1807   // more stable.
1808   if (!Threads_lock->owned_by_self()) {
1809     Threads_lock->try_lock();
1810     // The VM is going to die so no need to unlock Thread_lock.
1811   }
1812 
1813   switch (how) {
1814     case  1: vmassert(str == NULL, "expected null"); break;
1815     case  2: vmassert(num == 1023 && *str == 'X',
1816                       "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1817     case  3: guarantee(str == NULL, "expected null"); break;
1818     case  4: guarantee(num == 1023 && *str == 'X',
1819                        "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1820     case  5: fatal("expected null"); break;
1821     case  6: fatal("num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1822     case  7: fatal("%s%s#    %s%s#    %s%s#    %s%s#    %s%s#    "
1823                    "%s%s#    %s%s#    %s%s#    %s%s#    %s%s#    "
1824                    "%s%s#    %s%s#    %s%s#    %s%s#    %s",
1825                    msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1826                    msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1827                    msg, eol, msg, eol, msg, eol, msg, eol, msg); break;
1828     case  8: vm_exit_out_of_memory(num, OOM_MALLOC_ERROR, "ChunkPool::allocate"); break;
1829     case  9: ShouldNotCallThis(); break;
1830     case 10: ShouldNotReachHere(); break;
1831     case 11: Unimplemented(); break;
1832     // There's no guarantee the bad data pointer will crash us
1833     // so "break" out to the ShouldNotReachHere().
1834     case 12: *dataPtr = '\0'; break;
1835     // There's no guarantee the bad function pointer will crash us
1836     // so "break" out to the ShouldNotReachHere().
1837     case 13: (*funcPtr)(); break;
1838     case 14: crash_with_segfault(); break;
1839     case 15: crash_with_sigfpe(); break;
1840     case 16: {
1841       ThreadsListHandle tlh;
1842       fatal("Force crash with an active ThreadsListHandle.");
1843     }
1844     case 17: {
1845       ThreadsListHandle tlh;
1846       {
1847         ThreadsListHandle tlh2;
1848         fatal("Force crash with a nested ThreadsListHandle.");
1849       }
1850     }
1851 
1852     default: tty->print_cr("ERROR: %d: unexpected test_num value.", how);
1853   }
1854   tty->print_cr("VMError::controlled_crash: survived intentional crash. Did you suppress the assert?");
1855   ShouldNotReachHere();
1856 }
1857 #endif // !PRODUCT