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