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