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