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