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