rev 55555 : [mq]: nestegg

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