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 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
1331   // Disarm assertion poison page, since from this point on we do not need this mechanism anymore and it may
1332   // cause problems in error handling during native OOM, see JDK-8227275.
1333   disarm_assert_poison();
1334 #endif
1335 
1336   // Use local fdStream objects only. Do not use global instances whose initialization
1337   // relies on dynamic initialization (see JDK-8214975). Do not rely on these instances
1338   // to carry over into recursions or invocations from other threads.
1339   fdStream out(fd_out);
1340   out.set_scratch_buffer(buffer, sizeof(buffer));
1341 
1342   // Depending on the re-entrance depth at this point, fd_log may be -1 or point to an open hs-err file.
1343   fdStream log(fd_log);
1344   log.set_scratch_buffer(buffer, sizeof(buffer));
1345 
1346   // How many errors occurred in error handler when reporting first_error.
1347   static int recursive_error_count;
1348 
1349   // We will first print a brief message to standard out (verbose = false),
1350   // then save detailed information in log file (verbose = true).
1351   static bool out_done = false;         // done printing to standard out
1352   static bool log_done = false;         // done saving error log
1353 
1354   if (SuppressFatalErrorMessage) {
1355       os::abort(CreateCoredumpOnCrash);
1356   }
1357   intptr_t mytid = os::current_thread_id();
1358   if (_first_error_tid == -1 &&
1359       Atomic::cmpxchg(mytid, &_first_error_tid, (intptr_t)-1) == -1) {
1360 
1361     // Initialize time stamps to use the same base.
1362     out.time_stamp().update_to(1);
1363     log.time_stamp().update_to(1);
1364 
1365     _id = id;
1366     _message = message;
1367     _thread = thread;
1368     _pc = pc;
1369     _siginfo = siginfo;
1370     _context = context;
1371     _filename = filename;
1372     _lineno = lineno;
1373     _size = size;
1374     jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1375 
1376     // first time
1377     _error_reported = true;
1378 
1379     reporting_started();
1380     if (!TestUnresponsiveErrorHandler) {
1381       // Record reporting_start_time unless we're running the
1382       // TestUnresponsiveErrorHandler test. For that test we record
1383       // reporting_start_time at the beginning of the test.
1384       record_reporting_start_time();
1385     } else {
1386       out.print_raw_cr("Delaying recording reporting_start_time for TestUnresponsiveErrorHandler.");
1387     }
1388 
1389     if (ShowMessageBoxOnError || PauseAtExit) {
1390       show_message_box(buffer, sizeof(buffer));
1391 
1392       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1393       // WatcherThread can kill JVM if the error handler hangs.
1394       ShowMessageBoxOnError = false;
1395     }
1396 
1397     os::check_dump_limit(buffer, sizeof(buffer));
1398 
1399     // reset signal handlers or exception filter; make sure recursive crashes
1400     // are handled properly.
1401     reset_signal_handlers();
1402 
1403     EventShutdown e;
1404     if (e.should_commit()) {
1405       e.set_reason("VM Error");
1406       e.commit();
1407     }
1408 
1409     JFR_ONLY(Jfr::on_vm_shutdown(true);)
1410 
1411   } else {
1412     // If UseOsErrorReporting we call this for each level of the call stack
1413     // while searching for the exception handler.  Only the first level needs
1414     // to be reported.
1415     if (UseOSErrorReporting && log_done) return;
1416 
1417     // This is not the first error, see if it happened in a different thread
1418     // or in the same thread during error reporting.
1419     if (_first_error_tid != mytid) {
1420       char msgbuf[64];
1421       jio_snprintf(msgbuf, sizeof(msgbuf),
1422                    "[thread " INTX_FORMAT " also had an error]",
1423                    mytid);
1424       out.print_raw_cr(msgbuf);
1425 
1426       // error reporting is not MT-safe, block current thread
1427       os::infinite_sleep();
1428 
1429     } else {
1430       if (recursive_error_count++ > 30) {
1431         out.print_raw_cr("[Too many errors, abort]");
1432         os::die();
1433       }
1434 
1435       outputStream* const st = log.is_open() ? &log : &out;
1436       st->cr();
1437 
1438       // Timeout handling.
1439       if (_step_did_timeout) {
1440         // The current step had a timeout. Lets continue reporting with the next step.
1441         st->print_raw("[timeout occurred during error reporting in step \"");
1442         st->print_raw(_current_step_info);
1443         st->print_cr("\"] after " INT64_FORMAT " s.",
1444                      (int64_t)
1445                      ((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1446       } else if (_reporting_did_timeout) {
1447         // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1448         // up, the process is about to be stopped by the WatcherThread.
1449         st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1450                      (int64_t)
1451                      ((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1452         st->flush();
1453         // Watcherthread is about to call os::die. Lets just wait.
1454         os::infinite_sleep();
1455       } else {
1456         // Crash or assert during error reporting. Lets continue reporting with the next step.
1457         stringStream ss(buffer, sizeof(buffer));
1458         // Note: this string does get parsed by a number of jtreg tests,
1459         // see hotspot/jtreg/runtime/ErrorHandling.
1460         ss.print("[error occurred during error reporting (%s), id 0x%x",
1461                    _current_step_info, id);
1462         char signal_name[64];
1463         if (os::exception_name(id, signal_name, sizeof(signal_name))) {
1464           ss.print(", %s (0x%x) at pc=" PTR_FORMAT, signal_name, id, p2i(pc));
1465         } else {
1466           if (should_report_bug(id)) {
1467             ss.print(", Internal Error (%s:%d)",
1468               filename == NULL ? "??" : filename, lineno);
1469           } else {
1470             ss.print(", Out of Memory Error (%s:%d)",
1471               filename == NULL ? "??" : filename, lineno);
1472           }
1473         }
1474         ss.print("]");
1475         st->print_raw_cr(buffer);
1476         st->cr();
1477       }
1478     }
1479   }
1480 
1481   // Part 1: print an abbreviated version (the '#' section) to stdout.
1482   if (!out_done) {
1483     // Suppress this output if we plan to print Part 2 to stdout too.
1484     // No need to have the "#" section twice.
1485     if (!(ErrorFileToStdout && out.fd() == 1)) {
1486       report(&out, false);
1487     }
1488 
1489     out_done = true;
1490 
1491     _current_step = 0;
1492     _current_step_info = "";
1493   }
1494 
1495   // Part 2: print a full error log file (optionally to stdout or stderr).
1496   // print to error log file
1497   if (!log_done) {
1498     // see if log file is already open
1499     if (!log.is_open()) {
1500       // open log file
1501       if (ErrorFileToStdout) {
1502         fd_log = 1;
1503       } else if (ErrorFileToStderr) {
1504         fd_log = 2;
1505       } else {
1506         fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", true,
1507                  buffer, sizeof(buffer));
1508         if (fd_log != -1) {
1509           out.print_raw("# An error report file with more information is saved as:\n# ");
1510           out.print_raw_cr(buffer);
1511         } else {
1512           out.print_raw_cr("# Can not save log file, dump to screen..");
1513           fd_log = 1;
1514         }
1515       }
1516       log.set_fd(fd_log);
1517     }
1518 
1519     report(&log, true);
1520     log_done = true;
1521     _current_step = 0;
1522     _current_step_info = "";
1523 
1524     if (fd_log > 3) {
1525       close(fd_log);
1526       fd_log = -1;
1527     }
1528 
1529     log.set_fd(-1);
1530   }
1531 
1532   if (PrintNMTStatistics) {
1533     fdStream fds(fd_out);
1534     MemTracker::final_report(&fds);
1535   }
1536 
1537   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1538   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1539     skip_replay = true;
1540     ciEnv* env = ciEnv::current();
1541     if (env != NULL) {
1542       const bool overwrite = false; // We do not overwrite an existing replay file.
1543       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", overwrite, buffer, sizeof(buffer));
1544       if (fd != -1) {
1545         FILE* replay_data_file = os::open(fd, "w");
1546         if (replay_data_file != NULL) {
1547           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1548           env->dump_replay_data_unsafe(&replay_data_stream);
1549           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1550           out.print_raw_cr(buffer);
1551         } else {
1552           int e = errno;
1553           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1554           out.print_raw_cr(os::strerror(e));
1555         }
1556       }
1557     }
1558   }
1559 
1560   static bool skip_bug_url = !should_report_bug(_id);
1561   if (!skip_bug_url) {
1562     skip_bug_url = true;
1563 
1564     out.print_raw_cr("#");
1565     print_bug_submit_message(&out, _thread);
1566   }
1567 
1568   static bool skip_OnError = false;
1569   if (!skip_OnError && OnError && OnError[0]) {
1570     skip_OnError = true;
1571 
1572     // Flush output and finish logs before running OnError commands.
1573     ostream_abort();
1574 
1575     out.print_raw_cr("#");
1576     out.print_raw   ("# -XX:OnError=\"");
1577     out.print_raw   (OnError);
1578     out.print_raw_cr("\"");
1579 
1580     char* cmd;
1581     const char* ptr = OnError;
1582     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1583       out.print_raw   ("#   Executing ");
1584 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1585       out.print_raw   ("/bin/sh -c ");
1586 #elif defined(SOLARIS)
1587       out.print_raw   ("/usr/bin/sh -c ");
1588 #elif defined(_WINDOWS)
1589       out.print_raw   ("cmd /C ");
1590 #endif
1591       out.print_raw   ("\"");
1592       out.print_raw   (cmd);
1593       out.print_raw_cr("\" ...");
1594 
1595       if (os::fork_and_exec(cmd) < 0) {
1596         out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1597                      os::strerror(errno), os::errno_name(errno), errno);
1598       }
1599     }
1600 
1601     // done with OnError
1602     OnError = NULL;
1603   }
1604 
1605   if (!UseOSErrorReporting) {
1606     // os::abort() will call abort hooks, try it first.
1607     static bool skip_os_abort = false;
1608     if (!skip_os_abort) {
1609       skip_os_abort = true;
1610       bool dump_core = should_report_bug(_id);
1611       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1612     }
1613 
1614     // if os::abort() doesn't abort, try os::die();
1615     os::die();
1616   }
1617 }
1618 
1619 /*
1620  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1621  * ensures utilities such as jmap can observe the process is a consistent state.
1622  */
1623 class VM_ReportJavaOutOfMemory : public VM_Operation {
1624  private:
1625   const char* _message;
1626  public:
1627   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1628   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1629   void doit();
1630 };
1631 
1632 void VM_ReportJavaOutOfMemory::doit() {
1633   // Don't allocate large buffer on stack
1634   static char buffer[O_BUFLEN];
1635 
1636   tty->print_cr("#");
1637   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1638   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1639 
1640   // make heap parsability
1641   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1642 
1643   char* cmd;
1644   const char* ptr = OnOutOfMemoryError;
1645   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1646     tty->print("#   Executing ");
1647 #if defined(LINUX)
1648     tty->print  ("/bin/sh -c ");
1649 #elif defined(SOLARIS)
1650     tty->print  ("/usr/bin/sh -c ");
1651 #endif
1652     tty->print_cr("\"%s\"...", cmd);
1653 
1654     if (os::fork_and_exec(cmd, true) < 0) {
1655       tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1656                      os::strerror(errno), os::errno_name(errno), errno);
1657     }
1658   }
1659 }
1660 
1661 void VMError::report_java_out_of_memory(const char* message) {
1662   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1663     MutexLocker ml(Heap_lock);
1664     VM_ReportJavaOutOfMemory op(message);
1665     VMThread::execute(&op);
1666   }
1667 }
1668 
1669 void VMError::show_message_box(char *buf, int buflen) {
1670   bool yes;
1671   do {
1672     error_string(buf, buflen);
1673     yes = os::start_debugging(buf,buflen);
1674   } while (yes);
1675 }
1676 
1677 // Timeout handling: check if a timeout happened (either a single step did
1678 // timeout or the whole of error reporting hit ErrorLogTimeout). Interrupt
1679 // the reporting thread if that is the case.
1680 bool VMError::check_timeout() {
1681 
1682   if (ErrorLogTimeout == 0) {
1683     return false;
1684   }
1685 
1686   // Do not check for timeouts if we still have a message box to show to the
1687   // user or if there are OnError handlers to be run.
1688   if (ShowMessageBoxOnError
1689       || (OnError != NULL && OnError[0] != '\0')
1690       || Arguments::abort_hook() != NULL) {
1691     return false;
1692   }
1693 
1694   const jlong reporting_start_time_l = get_reporting_start_time();
1695   const jlong now = get_current_timestamp();
1696   // Timestamp is stored in nanos.
1697   if (reporting_start_time_l > 0) {
1698     const jlong end = reporting_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1699     if (end <= now && !_reporting_did_timeout) {
1700       // We hit ErrorLogTimeout and we haven't interrupted the reporting
1701       // thread yet.
1702       _reporting_did_timeout = true;
1703       interrupt_reporting_thread();
1704       return true; // global timeout
1705     }
1706   }
1707 
1708   const jlong step_start_time_l = get_step_start_time();
1709   if (step_start_time_l > 0) {
1710     // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1711     // hang for some reason, so this simple rule allows for three hanging step and still
1712     // hopefully leaves time enough for the rest of the steps to finish.
1713     const jlong end = step_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4;
1714     if (end <= now && !_step_did_timeout) {
1715       // The step timed out and we haven't interrupted the reporting
1716       // thread yet.
1717       _step_did_timeout = true;
1718       interrupt_reporting_thread();
1719       return false; // (Not a global timeout)
1720     }
1721   }
1722 
1723   return false;
1724 
1725 }
1726 
1727 #ifndef PRODUCT
1728 #if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140
1729 #pragma error_messages(off, SEC_NULL_PTR_DEREF)
1730 #endif
1731 typedef void (*voidfun_t)();
1732 // Crash with an authentic sigfpe
1733 static void crash_with_sigfpe() {
1734   // generate a native synchronous SIGFPE where possible;
1735   // if that did not cause a signal (e.g. on ppc), just
1736   // raise the signal.
1737   volatile int x = 0;
1738   volatile int y = 1/x;
1739 #ifndef _WIN32
1740   // OSX implements raise(sig) incorrectly so we need to
1741   // explicitly target the current thread
1742   pthread_kill(pthread_self(), SIGFPE);
1743 #endif
1744 } // end: crash_with_sigfpe
1745 
1746 // crash with sigsegv at non-null address.
1747 static void crash_with_segfault() {
1748 
1749   char* const crash_addr = (char*) VMError::get_segfault_address();
1750   *crash_addr = 'X';
1751 
1752 } // end: crash_with_segfault
1753 
1754 void VMError::test_error_handler() {
1755   controlled_crash(ErrorHandlerTest);
1756 }
1757 
1758 // crash in a controlled way:
1759 // how can be one of:
1760 // 1,2 - asserts
1761 // 3,4 - guarantee
1762 // 5-7 - fatal
1763 // 8 - vm_exit_out_of_memory
1764 // 9 - ShouldNotCallThis
1765 // 10 - ShouldNotReachHere
1766 // 11 - Unimplemented
1767 // 12,13 - (not guaranteed) crashes
1768 // 14 - SIGSEGV
1769 // 15 - SIGFPE
1770 void VMError::controlled_crash(int how) {
1771   if (how == 0) return;
1772 
1773   // If asserts are disabled, use the corresponding guarantee instead.
1774   NOT_DEBUG(if (how <= 2) how += 2);
1775 
1776   const char* const str = "hello";
1777   const size_t      num = (size_t)os::vm_page_size();
1778 
1779   const char* const eol = os::line_separator();
1780   const char* const msg = "this message should be truncated during formatting";
1781   char * const dataPtr = NULL;  // bad data pointer
1782   const void (*funcPtr)(void);  // bad function pointer
1783 
1784 #if defined(PPC64) && !defined(ABI_ELFv2)
1785   struct FunctionDescriptor functionDescriptor;
1786 
1787   functionDescriptor.set_entry((address) 0xF);
1788   funcPtr = (const void(*)()) &functionDescriptor;
1789 #else
1790   funcPtr = (const void(*)()) 0xF;
1791 #endif
1792 
1793   // Keep this in sync with test/hotspot/jtreg/runtime/ErrorHandling/ErrorHandler.java
1794   // which tests cases 1 thru 13.
1795   // Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java.
1796   // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java.
1797   // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java.
1798   // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
1799 
1800   // We try to grab Threads_lock to keep ThreadsSMRSupport::print_info_on()
1801   // from racing with Threads::add() or Threads::remove() as we
1802   // generate the hs_err_pid file. This makes our ErrorHandling tests
1803   // more stable.
1804   if (!Threads_lock->owned_by_self()) {
1805     Threads_lock->try_lock();
1806     // The VM is going to die so no need to unlock Thread_lock.
1807   }
1808 
1809   switch (how) {
1810     case  1: vmassert(str == NULL, "expected null"); break;
1811     case  2: vmassert(num == 1023 && *str == 'X',
1812                       "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1813     case  3: guarantee(str == NULL, "expected null"); break;
1814     case  4: guarantee(num == 1023 && *str == 'X',
1815                        "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1816     case  5: fatal("expected null"); break;
1817     case  6: fatal("num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1818     case  7: fatal("%s%s#    %s%s#    %s%s#    %s%s#    %s%s#    "
1819                    "%s%s#    %s%s#    %s%s#    %s%s#    %s%s#    "
1820                    "%s%s#    %s%s#    %s%s#    %s%s#    %s",
1821                    msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1822                    msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1823                    msg, eol, msg, eol, msg, eol, msg, eol, msg); break;
1824     case  8: vm_exit_out_of_memory(num, OOM_MALLOC_ERROR, "ChunkPool::allocate"); break;
1825     case  9: ShouldNotCallThis(); break;
1826     case 10: ShouldNotReachHere(); break;
1827     case 11: Unimplemented(); break;
1828     // There's no guarantee the bad data pointer will crash us
1829     // so "break" out to the ShouldNotReachHere().
1830     case 12: *dataPtr = '\0'; break;
1831     // There's no guarantee the bad function pointer will crash us
1832     // so "break" out to the ShouldNotReachHere().
1833     case 13: (*funcPtr)(); break;
1834     case 14: crash_with_segfault(); break;
1835     case 15: crash_with_sigfpe(); break;
1836     case 16: {
1837       ThreadsListHandle tlh;
1838       fatal("Force crash with an active ThreadsListHandle.");
1839     }
1840     case 17: {
1841       ThreadsListHandle tlh;
1842       {
1843         ThreadsListHandle tlh2;
1844         fatal("Force crash with a nested ThreadsListHandle.");
1845       }
1846     }
1847 
1848     default: tty->print_cr("ERROR: %d: unexpected test_num value.", how);
1849   }
1850   tty->print_cr("VMError::controlled_crash: survived intentional crash. Did you suppress the assert?");
1851   ShouldNotReachHere();
1852 }
1853 #endif // !PRODUCT