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