1 /*
   2  * Copyright (c) 2003, 2015, 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 "compiler/compileBroker.hpp"
  28 #include "gc_interface/collectedHeap.hpp"
  29 #include "prims/whitebox.hpp"
  30 #include "runtime/arguments.hpp"
  31 #include "runtime/frame.inline.hpp"
  32 #include "runtime/init.hpp"
  33 #include "runtime/os.hpp"
  34 #include "runtime/thread.inline.hpp"
  35 #include "runtime/vmThread.hpp"
  36 #include "runtime/vm_operations.hpp"
  37 #include "services/memTracker.hpp"
  38 #include "utilities/debug.hpp"
  39 #include "utilities/decoder.hpp"
  40 #include "utilities/defaultStream.hpp"
  41 #include "utilities/errorReporter.hpp"
  42 #include "utilities/events.hpp"
  43 #include "utilities/top.hpp"
  44 #include "utilities/vmError.hpp"
  45 
  46 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  47 
  48 // List of environment variables that should be reported in error log file.
  49 const char *env_list[] = {
  50   // All platforms
  51   "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
  52   "JAVA_COMPILER", "PATH", "USERNAME",
  53 
  54   // Env variables that are defined on Solaris/Linux/BSD
  55   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
  56   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
  57 
  58   // defined on Linux
  59   "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
  60 
  61   // defined on Darwin
  62   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
  63   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
  64   "DYLD_INSERT_LIBRARIES",
  65 
  66   // defined on Windows
  67   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
  68 
  69   (const char *)0
  70 };
  71 
  72 // Fatal error handler for internal errors and crashes.
  73 //
  74 // The default behavior of fatal error handler is to print a brief message
  75 // to standard out (defaultStream::output_fd()), then save detailed information
  76 // into an error report file (hs_err_pid<pid>.log) and abort VM. If multiple
  77 // threads are having troubles at the same time, only one error is reported.
  78 // The thread that is reporting error will abort VM when it is done, all other
  79 // threads are blocked forever inside report_and_die().
  80 
  81 // Constructor for crashes
  82 VMError::VMError(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context) {
  83     _thread = thread;
  84     _id = sig;
  85     _pc   = pc;
  86     _siginfo = siginfo;
  87     _context = context;
  88 
  89     _verbose = false;
  90     _current_step = 0;
  91     _current_step_info = NULL;
  92 
  93     _message = NULL;
  94     _detail_msg = NULL;
  95     _filename = NULL;
  96     _lineno = 0;
  97 
  98     _size = 0;
  99 }
 100 
 101 // Constructor for internal errors
 102 VMError::VMError(Thread* thread, const char* filename, int lineno,
 103                  const char* message, const char * detail_msg)
 104 {
 105   _thread = thread;
 106   _id = INTERNAL_ERROR;     // Value that's not an OS exception/signal
 107   _filename = filename;
 108   _lineno = lineno;
 109   _message = message;
 110   _detail_msg = detail_msg;
 111 
 112   _verbose = false;
 113   _current_step = 0;
 114   _current_step_info = NULL;
 115 
 116   _pc = NULL;
 117   _siginfo = NULL;
 118   _context = NULL;
 119 
 120   _size = 0;
 121 }
 122 
 123 // Constructor for OOM errors
 124 VMError::VMError(Thread* thread, const char* filename, int lineno, size_t size,
 125                  VMErrorType vm_err_type, const char* message) {
 126     _thread = thread;
 127     _id = vm_err_type; // Value that's not an OS exception/signal
 128     _filename = filename;
 129     _lineno = lineno;
 130     _message = message;
 131     _detail_msg = NULL;
 132 
 133     _verbose = false;
 134     _current_step = 0;
 135     _current_step_info = NULL;
 136 
 137     _pc = NULL;
 138     _siginfo = NULL;
 139     _context = NULL;
 140 
 141     _size = size;
 142 }
 143 
 144 
 145 // Constructor for non-fatal errors
 146 VMError::VMError(const char* message) {
 147     _thread = NULL;
 148     _id = INTERNAL_ERROR;     // Value that's not an OS exception/signal
 149     _filename = NULL;
 150     _lineno = 0;
 151     _message = message;
 152     _detail_msg = NULL;
 153 
 154     _verbose = false;
 155     _current_step = 0;
 156     _current_step_info = NULL;
 157 
 158     _pc = NULL;
 159     _siginfo = NULL;
 160     _context = NULL;
 161 
 162     _size = 0;
 163 }
 164 
 165 // -XX:OnError=<string>, where <string> can be a list of commands, separated
 166 // by ';'. "%p" is replaced by current process id (pid); "%%" is replaced by
 167 // a single "%". Some examples:
 168 //
 169 // -XX:OnError="pmap %p"                // show memory map
 170 // -XX:OnError="gcore %p; dbx - %p"     // dump core and launch debugger
 171 // -XX:OnError="cat hs_err_pid%p.log | mail my_email@sun.com"
 172 // -XX:OnError="kill -9 %p"             // ?#!@#
 173 
 174 // A simple parser for -XX:OnError, usage:
 175 //  ptr = OnError;
 176 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
 177 //     ... ...
 178 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
 179   if (ptr == NULL || *ptr == NULL) return NULL;
 180 
 181   const char* cmd = *ptr;
 182 
 183   // skip leading blanks or ';'
 184   while (*cmd == ' ' || *cmd == ';') cmd++;
 185 
 186   if (*cmd == '\0') return NULL;
 187 
 188   const char * cmdend = cmd;
 189   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
 190 
 191   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
 192 
 193   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
 194   return buf;
 195 }
 196 
 197 
 198 static void print_bug_submit_message(outputStream *out, Thread *thread) {
 199   if (out == NULL) return;
 200   out->print_raw_cr("# If you would like to submit a bug report, please visit:");
 201   out->print_raw   ("#   ");
 202   out->print_raw_cr(Arguments::java_vendor_url_bug());
 203   // If the crash is in native code, encourage user to submit a bug to the
 204   // provider of that code.
 205   if (thread && thread->is_Java_thread() &&
 206       !thread->is_hidden_from_external_view()) {
 207     JavaThread* jt = (JavaThread*)thread;
 208     if (jt->thread_state() == _thread_in_native) {
 209       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
 210     }
 211   }
 212   out->print_raw_cr("#");
 213 }
 214 
 215 bool VMError::coredump_status;
 216 char VMError::coredump_message[O_BUFLEN];
 217 
 218 void VMError::report_coredump_status(const char* message, bool status) {
 219   coredump_status = status;
 220   strncpy(coredump_message, message, sizeof(coredump_message));
 221   coredump_message[sizeof(coredump_message)-1] = 0;
 222 }
 223 
 224 
 225 // Return a string to describe the error
 226 char* VMError::error_string(char* buf, int buflen) {
 227   char signame_buf[64];
 228   const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
 229 
 230   if (signame) {
 231     jio_snprintf(buf, buflen,
 232                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" INTPTR_FORMAT,
 233                  signame, _id, _pc,
 234                  os::current_process_id(), os::current_thread_id());
 235   } else if (_filename != NULL && _lineno > 0) {
 236     // skip directory names
 237     char separator = os::file_separator()[0];
 238     const char *p = strrchr(_filename, separator);
 239     int n = jio_snprintf(buf, buflen,
 240                          "Internal Error at %s:%d, pid=%d, tid=" INTPTR_FORMAT,
 241                          p ? p + 1 : _filename, _lineno,
 242                          os::current_process_id(), os::current_thread_id());
 243     if (n >= 0 && n < buflen && _message) {
 244       if (_detail_msg) {
 245         jio_snprintf(buf + n, buflen - n, "%s%s: %s",
 246                      os::line_separator(), _message, _detail_msg);
 247       } else {
 248         jio_snprintf(buf + n, buflen - n, "%sError: %s",
 249                      os::line_separator(), _message);
 250       }
 251     }
 252   } else {
 253     jio_snprintf(buf, buflen,
 254                  "Internal Error (0x%x), pid=%d, tid=" INTPTR_FORMAT,
 255                  _id, os::current_process_id(), os::current_thread_id());
 256   }
 257 
 258   return buf;
 259 }
 260 
 261 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
 262                                 char* buf, int buflen, bool verbose) {
 263 #ifdef ZERO
 264   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
 265     // StackFrameStream uses the frame anchor, which may not have
 266     // been set up.  This can be done at any time in Zero, however,
 267     // so if it hasn't been set up then we just set it up now and
 268     // clear it again when we're done.
 269     bool has_last_Java_frame = jt->has_last_Java_frame();
 270     if (!has_last_Java_frame)
 271       jt->set_last_Java_frame();
 272     st->print("Java frames:");
 273 
 274     // If the top frame is a Shark frame and the frame anchor isn't
 275     // set up then it's possible that the information in the frame
 276     // is garbage: it could be from a previous decache, or it could
 277     // simply have never been written.  So we print a warning...
 278     StackFrameStream sfs(jt);
 279     if (!has_last_Java_frame && !sfs.is_done()) {
 280       if (sfs.current()->zeroframe()->is_shark_frame()) {
 281         st->print(" (TOP FRAME MAY BE JUNK)");
 282       }
 283     }
 284     st->cr();
 285 
 286     // Print the frames
 287     for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
 288       sfs.current()->zero_print_on_error(i, st, buf, buflen);
 289       st->cr();
 290     }
 291 
 292     // Reset the frame anchor if necessary
 293     if (!has_last_Java_frame)
 294       jt->reset_last_Java_frame();
 295   }
 296 #else
 297   if (jt->has_last_Java_frame()) {
 298     st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
 299     for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
 300       sfs.current()->print_on_error(st, buf, buflen, verbose);
 301       st->cr();
 302     }
 303   }
 304 #endif // ZERO
 305 }
 306 
 307 // This is the main function to report a fatal error. Only one thread can
 308 // call this function, so we don't need to worry about MT-safety. But it's
 309 // possible that the error handler itself may crash or die on an internal
 310 // error, for example, when the stack/heap is badly damaged. We must be
 311 // able to handle recursive errors that happen inside error handler.
 312 //
 313 // Error reporting is done in several steps. If a crash or internal error
 314 // occurred when reporting an error, the nested signal/exception handler
 315 // can skip steps that are already (or partially) done. Error reporting will
 316 // continue from the next step. This allows us to retrieve and print
 317 // information that may be unsafe to get after a fatal error. If it happens,
 318 // you may find nested report_and_die() frames when you look at the stack
 319 // in a debugger.
 320 //
 321 // In general, a hang in error handler is much worse than a crash or internal
 322 // error, as it's harder to recover from a hang. Deadlock can happen if we
 323 // try to grab a lock that is already owned by current thread, or if the
 324 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 325 // error handler and all the functions it called should avoid grabbing any
 326 // lock. An important thing to notice is that memory allocation needs a lock.
 327 //
 328 // We should avoid using large stack allocated buffers. Many errors happen
 329 // when stack space is already low. Making things even worse is that there
 330 // could be nested report_and_die() calls on stack (see above). Only one
 331 // thread can report error, so large buffers are statically allocated in data
 332 // segment.
 333 
 334 void VMError::report(outputStream* st) {
 335 # define BEGIN if (_current_step == 0) { _current_step = 1;
 336 # define STEP(n, s) } if (_current_step < n) { _current_step = n; _current_step_info = s;
 337 # define END }
 338 
 339   // don't allocate large buffer on stack
 340   static char buf[O_BUFLEN];
 341 
 342   BEGIN
 343 
 344   STEP(10, "(printing fatal error message)")
 345 
 346     st->print_cr("#");
 347     if (should_report_bug(_id)) {
 348       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 349     } else {
 350       st->print_cr("# There is insufficient memory for the Java "
 351                    "Runtime Environment to continue.");
 352     }
 353 
 354   STEP(15, "(printing type of error)")
 355 
 356      switch(_id) {
 357        case OOM_MALLOC_ERROR:
 358        case OOM_MMAP_ERROR:
 359          if (_size) {
 360            st->print("# Native memory allocation ");
 361            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 362                                                  "(mmap) failed to map ");
 363            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
 364            st->print("%s", buf);
 365            st->print(" bytes");
 366            if (_message != NULL) {
 367              st->print(" for ");
 368              st->print("%s", _message);
 369            }
 370            st->cr();
 371          } else {
 372            if (_message != NULL)
 373              st->print("# ");
 374              st->print_cr("%s", _message);
 375          }
 376          // In error file give some solutions
 377          if (_verbose) {
 378            st->print_cr("# Possible reasons:");
 379            st->print_cr("#   The system is out of physical RAM or swap space");
 380            st->print_cr("#   In 32 bit mode, the process size limit was hit");
 381            st->print_cr("# Possible solutions:");
 382            st->print_cr("#   Reduce memory load on the system");
 383            st->print_cr("#   Increase physical memory or swap space");
 384            st->print_cr("#   Check if swap backing store is full");
 385            st->print_cr("#   Use 64 bit Java on a 64 bit OS");
 386            st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
 387            st->print_cr("#   Decrease number of Java threads");
 388            st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
 389            st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
 390            st->print_cr("# This output file may be truncated or incomplete.");
 391          } else {
 392            return;  // that's enough for the screen
 393          }
 394          break;
 395        case INTERNAL_ERROR:
 396        default:
 397          break;
 398      }
 399 
 400   STEP(20, "(printing exception/signal name)")
 401 
 402      st->print_cr("#");
 403      st->print("#  ");
 404      // Is it an OS exception/signal?
 405      if (os::exception_name(_id, buf, sizeof(buf))) {
 406        st->print("%s", buf);
 407        st->print(" (0x%x)", _id);                // signal number
 408        st->print(" at pc=" PTR_FORMAT, _pc);
 409      } else {
 410        if (should_report_bug(_id)) {
 411          st->print("Internal Error");
 412        } else {
 413          st->print("Out of Memory Error");
 414        }
 415        if (_filename != NULL && _lineno > 0) {
 416 #ifdef PRODUCT
 417          // In product mode chop off pathname?
 418          char separator = os::file_separator()[0];
 419          const char *p = strrchr(_filename, separator);
 420          const char *file = p ? p+1 : _filename;
 421 #else
 422          const char *file = _filename;
 423 #endif
 424          size_t len = strlen(file);
 425          size_t buflen = sizeof(buf);
 426 
 427          strncpy(buf, file, buflen);
 428          if (len + 10 < buflen) {
 429            sprintf(buf + len, ":%d", _lineno);
 430          }
 431          st->print(" (%s)", buf);
 432        } else {
 433          st->print(" (0x%x)", _id);
 434        }
 435      }
 436 
 437   STEP(30, "(printing current thread and pid)")
 438 
 439      // process id, thread id
 440      st->print(", pid=%d", os::current_process_id());
 441      st->print(", tid=" INTPTR_FORMAT, os::current_thread_id());
 442      st->cr();
 443 
 444   STEP(40, "(printing error message)")
 445 
 446      if (should_report_bug(_id)) {  // already printed the message.
 447        // error message
 448        if (_detail_msg) {
 449          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
 450        } else if (_message) {
 451          st->print_cr("#  Error: %s", _message);
 452        }
 453     }
 454 
 455   STEP(50, "(printing Java version string)")
 456 
 457      // VM version
 458      st->print_cr("#");
 459      JDK_Version::current().to_string(buf, sizeof(buf));
 460      const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 461                                   JDK_Version::runtime_name() : "";
 462      const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 463                                   JDK_Version::runtime_version() : "";
 464      st->print_cr("# JRE version: %s (%s) (build %s)", runtime_name, buf, runtime_version);
 465      st->print_cr("# Java VM: %s (%s %s %s %s)",
 466                    Abstract_VM_Version::vm_name(),
 467                    Abstract_VM_Version::vm_release(),
 468                    Abstract_VM_Version::vm_info_string(),
 469                    Abstract_VM_Version::vm_platform_string(),
 470                    UseCompressedOops ? "compressed oops" : ""
 471                  );
 472 
 473   STEP(60, "(printing problematic frame)")
 474 
 475      // Print current frame if we have a context (i.e. it's a crash)
 476      if (_context) {
 477        st->print_cr("# Problematic frame:");
 478        st->print("# ");
 479        frame fr = os::fetch_frame_from_context(_context);
 480        fr.print_on_error(st, buf, sizeof(buf));
 481        st->cr();
 482        st->print_cr("#");
 483      }
 484   STEP(63, "(printing core file information)")
 485     st->print("# ");
 486     if (coredump_status) {
 487       st->print("Core dump written. Default location: %s", coredump_message);
 488     } else {
 489       st->print("Failed to write core dump. %s", coredump_message);
 490     }
 491     st->cr();
 492     st->print_cr("#");
 493 
 494   STEP(65, "(printing bug submit message)")
 495 
 496      if (should_report_bug(_id) && _verbose) {
 497        print_bug_submit_message(st, _thread);
 498      }
 499 
 500   STEP(70, "(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(80, "(printing current thread)" )
 509 
 510      // current thread
 511      if (_verbose) {
 512        if (_thread) {
 513          st->print("Current thread (" PTR_FORMAT "):  ", _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(90, "(printing siginfo)" )
 523 
 524      // signal no, signal code, address that caused the fault
 525      if (_verbose && _siginfo) {
 526        os::print_siginfo(st, _siginfo);
 527        st->cr();
 528      }
 529 
 530   STEP(100, "(printing registers, top of stack, instructions near pc)")
 531 
 532      // registers, top of stack, instructions near pc
 533      if (_verbose && _context) {
 534        os::print_context(st, _context);
 535        st->cr();
 536      }
 537 
 538   STEP(105, "(printing register info)")
 539 
 540      // decode register contents if possible
 541      if (_verbose && _context && Universe::is_fully_initialized()) {
 542        os::print_register_info(st, _context);
 543        st->cr();
 544      }
 545 
 546   STEP(110, "(printing stack bounds)" )
 547 
 548      if (_verbose) {
 549        st->print("Stack: ");
 550 
 551        address stack_top;
 552        size_t stack_size;
 553 
 554        if (_thread) {
 555           stack_top = _thread->stack_base();
 556           stack_size = _thread->stack_size();
 557        } else {
 558           stack_top = os::current_stack_base();
 559           stack_size = os::current_stack_size();
 560        }
 561 
 562        address stack_bottom = stack_top - stack_size;
 563        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", stack_bottom, stack_top);
 564 
 565        frame fr = _context ? os::fetch_frame_from_context(_context)
 566                            : os::current_frame();
 567 
 568        if (fr.sp()) {
 569          st->print(",  sp=" PTR_FORMAT, fr.sp());
 570          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 571          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 572        }
 573 
 574        st->cr();
 575      }
 576 
 577   STEP(120, "(printing native stack)" )
 578 
 579    if (_verbose) {
 580      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
 581        // We have printed the native stack in platform-specific code
 582        // Windows/x64 needs special handling.
 583      } else {
 584        frame fr = _context ? os::fetch_frame_from_context(_context)
 585                            : os::current_frame();
 586 
 587        print_native_stack(st, fr, _thread, buf, sizeof(buf));
 588      }
 589    }
 590 
 591   STEP(130, "(printing Java stack)" )
 592 
 593      if (_verbose && _thread && _thread->is_Java_thread()) {
 594        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
 595      }
 596 
 597   STEP(135, "(printing target Java thread stack)" )
 598 
 599      // printing Java thread stack trace if it is involved in GC crash
 600      if (_verbose && _thread && (_thread->is_Named_thread())) {
 601        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
 602        if (jt != NULL) {
 603          st->print_cr("JavaThread " PTR_FORMAT " (nid = " UINTX_FORMAT ") was being processed", jt, jt->osthread()->thread_id());
 604          print_stack_trace(st, jt, buf, sizeof(buf), true);
 605        }
 606      }
 607 
 608   STEP(140, "(printing VM operation)" )
 609 
 610      if (_verbose && _thread && _thread->is_VM_thread()) {
 611         VMThread* t = (VMThread*)_thread;
 612         VM_Operation* op = t->vm_operation();
 613         if (op) {
 614           op->print_on_error(st);
 615           st->cr();
 616           st->cr();
 617         }
 618      }
 619 
 620   STEP(150, "(printing current compile task)" )
 621 
 622      if (_verbose && _thread && _thread->is_Compiler_thread()) {
 623         CompilerThread* t = (CompilerThread*)_thread;
 624         if (t->task()) {
 625            st->cr();
 626            st->print_cr("Current CompileTask:");
 627            t->task()->print_line_on_error(st, buf, sizeof(buf));
 628            st->cr();
 629         }
 630      }
 631 
 632   STEP(160, "(printing process)" )
 633 
 634      if (_verbose) {
 635        st->cr();
 636        st->print_cr("---------------  P R O C E S S  ---------------");
 637        st->cr();
 638      }
 639 
 640   STEP(170, "(printing all threads)" )
 641 
 642      // all threads
 643      if (_verbose && _thread) {
 644        Threads::print_on_error(st, _thread, buf, sizeof(buf));
 645        st->cr();
 646      }
 647 
 648   STEP(175, "(printing VM state)" )
 649 
 650      if (_verbose) {
 651        // Safepoint state
 652        st->print("VM state:");
 653 
 654        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
 655        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
 656        else st->print("not at safepoint");
 657 
 658        // Also see if error occurred during initialization or shutdown
 659        if (!Universe::is_fully_initialized()) {
 660          st->print(" (not fully initialized)");
 661        } else if (VM_Exit::vm_exited()) {
 662          st->print(" (shutting down)");
 663        } else {
 664          st->print(" (normal execution)");
 665        }
 666        st->cr();
 667        st->cr();
 668      }
 669 
 670   STEP(180, "(printing owned locks on error)" )
 671 
 672      // mutexes/monitors that currently have an owner
 673      if (_verbose) {
 674        print_owned_locks_on_error(st);
 675        st->cr();
 676      }
 677 
 678   STEP(190, "(printing heap information)" )
 679 
 680      if (_verbose && Universe::is_fully_initialized()) {
 681        Universe::heap()->print_on_error(st);
 682        st->cr();
 683 
 684        st->print_cr("Polling page: " INTPTR_FORMAT, os::get_polling_page());
 685        st->cr();
 686      }
 687 
 688   STEP(195, "(printing code cache information)" )
 689 
 690      if (_verbose && Universe::is_fully_initialized()) {
 691        // print code cache information before vm abort
 692        CodeCache::print_summary(st);
 693        st->cr();
 694      }
 695 
 696   STEP(200, "(printing ring buffers)" )
 697 
 698      if (_verbose) {
 699        Events::print_all(st);
 700        st->cr();
 701      }
 702 
 703   STEP(205, "(printing dynamic libraries)" )
 704 
 705      if (_verbose) {
 706        // dynamic libraries, or memory map
 707        os::print_dll_info(st);
 708        st->cr();
 709      }
 710 
 711   STEP(210, "(printing VM options)" )
 712 
 713      if (_verbose) {
 714        // VM options
 715        Arguments::print_on(st);
 716        st->cr();
 717      }
 718 
 719   STEP(215, "(printing warning if internal testing API used)" )
 720 
 721      if (WhiteBox::used()) {
 722        st->print_cr("Unsupported internal testing APIs have been used.");
 723        st->cr();
 724      }
 725 
 726   STEP(220, "(printing environment variables)" )
 727 
 728      if (_verbose) {
 729        os::print_environment_variables(st, env_list, buf, sizeof(buf));
 730        st->cr();
 731      }
 732 
 733   STEP(225, "(printing signal handlers)" )
 734 
 735      if (_verbose) {
 736        os::print_signal_handlers(st, buf, sizeof(buf));
 737        st->cr();
 738      }
 739 
 740   STEP(228, "(Native Memory Tracking)" )
 741      if (_verbose) {
 742        MemTracker::error_report(st);
 743      }
 744 
 745   STEP(230, "" )
 746 
 747      if (_verbose) {
 748        st->cr();
 749        st->print_cr("---------------  S Y S T E M  ---------------");
 750        st->cr();
 751      }
 752 
 753   STEP(240, "(printing OS information)" )
 754 
 755      if (_verbose) {
 756        os::print_os_info(st);
 757        st->cr();
 758      }
 759 
 760   STEP(250, "(printing CPU info)" )
 761      if (_verbose) {
 762        os::print_cpu_info(st);
 763        st->cr();
 764      }
 765 
 766   STEP(260, "(printing memory info)" )
 767 
 768      if (_verbose) {
 769        os::print_memory_info(st);
 770        st->cr();
 771      }
 772 
 773   STEP(270, "(printing internal vm info)" )
 774 
 775      if (_verbose) {
 776        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
 777        st->cr();
 778      }
 779 
 780   STEP(280, "(printing date and time)" )
 781 
 782      if (_verbose) {
 783        os::print_date_and_time(st);
 784        st->cr();
 785      }
 786 
 787   END
 788 
 789 # undef BEGIN
 790 # undef STEP
 791 # undef END
 792 }
 793 
 794 VMError* volatile VMError::first_error = NULL;
 795 volatile jlong VMError::first_error_tid = -1;
 796 
 797 // An error could happen before tty is initialized or after it has been
 798 // destroyed. Here we use a very simple unbuffered fdStream for printing.
 799 // Only out.print_raw() and out.print_raw_cr() should be used, as other
 800 // printing methods need to allocate large buffer on stack. To format a
 801 // string, use jio_snprintf() with a static buffer or use staticBufferStream.
 802 fdStream VMError::out(defaultStream::output_fd());
 803 fdStream VMError::log; // error log used by VMError::report_and_die()
 804 
 805 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
 806 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
 807   int fd = -1;
 808   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
 809     // the O_EXCL flag will cause the open to fail if the file exists
 810     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
 811   }
 812   return fd;
 813 }
 814 
 815 /**
 816  * Construct file name for a log file and return it's file descriptor.
 817  * Name and location depends on pattern, default_pattern params and access
 818  * permissions.
 819  */
 820 static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
 821   int fd = -1;
 822 
 823   // If possible, use specified pattern to construct log file name
 824   if (pattern != NULL) {
 825     fd = expand_and_open(pattern, buf, buflen, 0);
 826   }
 827 
 828   // Either user didn't specify, or the user's location failed,
 829   // so use the default name in the current directory
 830   if (fd == -1) {
 831     const char* cwd = os::get_current_directory(buf, buflen);
 832     if (cwd != NULL) {
 833       size_t pos = strlen(cwd);
 834       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
 835       pos += fsep_len;
 836       if (fsep_len > 0) {
 837         fd = expand_and_open(default_pattern, buf, buflen, pos);
 838       }
 839     }
 840   }
 841 
 842    // try temp directory if it exists.
 843    if (fd == -1) {
 844      const char* tmpdir = os::get_temp_directory();
 845      if (tmpdir != NULL && strlen(tmpdir) > 0) {
 846        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
 847        if (pos > 0) {
 848          fd = expand_and_open(default_pattern, buf, buflen, pos);
 849        }
 850      }
 851    }
 852 
 853   return fd;
 854 }
 855 
 856 void VMError::report_and_die() {
 857   // Don't allocate large buffer on stack
 858   static char buffer[O_BUFLEN];
 859 
 860   // How many errors occurred in error handler when reporting first_error.
 861   static int recursive_error_count;
 862 
 863   // We will first print a brief message to standard out (verbose = false),
 864   // then save detailed information in log file (verbose = true).
 865   static bool out_done = false;         // done printing to standard out
 866   static bool log_done = false;         // done saving error log
 867   static bool transmit_report_done = false; // done error reporting
 868 
 869   if (SuppressFatalErrorMessage) {
 870       os::abort();
 871   }
 872   jlong mytid = os::current_thread_id();
 873   if (first_error == NULL &&
 874       Atomic::cmpxchg_ptr(this, &first_error, NULL) == NULL) {
 875 
 876     // first time
 877     first_error_tid = mytid;
 878     set_error_reported();
 879 
 880     if (ShowMessageBoxOnError || PauseAtExit) {
 881       show_message_box(buffer, sizeof(buffer));
 882 
 883       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
 884       // WatcherThread can kill JVM if the error handler hangs.
 885       ShowMessageBoxOnError = false;
 886     }
 887 
 888     // Write a minidump on Windows, check core dump limits on Linux/Solaris
 889     os::check_or_create_dump(_siginfo, _context, buffer, sizeof(buffer));
 890 
 891     // reset signal handlers or exception filter; make sure recursive crashes
 892     // are handled properly.
 893     reset_signal_handlers();
 894 
 895   } else {
 896     // If UseOsErrorReporting we call this for each level of the call stack
 897     // while searching for the exception handler.  Only the first level needs
 898     // to be reported.
 899     if (UseOSErrorReporting && log_done) return;
 900 
 901     // This is not the first error, see if it happened in a different thread
 902     // or in the same thread during error reporting.
 903     if (first_error_tid != mytid) {
 904       char msgbuf[64];
 905       jio_snprintf(msgbuf, sizeof(msgbuf),
 906                    "[thread " INT64_FORMAT " also had an error]",
 907                    mytid);
 908       out.print_raw_cr(msgbuf);
 909 
 910       // error reporting is not MT-safe, block current thread
 911       os::infinite_sleep();
 912 
 913     } else {
 914       if (recursive_error_count++ > 30) {
 915         out.print_raw_cr("[Too many errors, abort]");
 916         os::die();
 917       }
 918 
 919       jio_snprintf(buffer, sizeof(buffer),
 920                    "[error occurred during error reporting %s, id 0x%x]",
 921                    first_error ? first_error->_current_step_info : "",
 922                    _id);
 923       if (log.is_open()) {
 924         log.cr();
 925         log.print_raw_cr(buffer);
 926         log.cr();
 927       } else {
 928         out.cr();
 929         out.print_raw_cr(buffer);
 930         out.cr();
 931       }
 932     }
 933   }
 934 
 935   // print to screen
 936   if (!out_done) {
 937     first_error->_verbose = false;
 938 
 939     staticBufferStream sbs(buffer, sizeof(buffer), &out);
 940     first_error->report(&sbs);
 941 
 942     out_done = true;
 943 
 944     first_error->_current_step = 0;         // reset current_step
 945     first_error->_current_step_info = "";   // reset current_step string
 946   }
 947 
 948   // print to error log file
 949   if (!log_done) {
 950     first_error->_verbose = true;
 951 
 952     // see if log file is already open
 953     if (!log.is_open()) {
 954       // open log file
 955       int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
 956       if (fd != -1) {
 957         out.print_raw("# An error report file with more information is saved as:\n# ");
 958         out.print_raw_cr(buffer);
 959 
 960         log.set_fd(fd);
 961       } else {
 962         out.print_raw_cr("# Can not save log file, dump to screen..");
 963         log.set_fd(defaultStream::output_fd());
 964         /* Error reporting currently needs dumpfile.
 965          * Maybe implement direct streaming in the future.*/
 966         transmit_report_done = true;
 967       }
 968     }
 969 
 970     staticBufferStream sbs(buffer, O_BUFLEN, &log);
 971     first_error->report(&sbs);
 972     first_error->_current_step = 0;         // reset current_step
 973     first_error->_current_step_info = "";   // reset current_step string
 974 
 975     // Run error reporting to determine whether or not to report the crash.
 976     if (!transmit_report_done && should_report_bug(first_error->_id)) {
 977       transmit_report_done = true;
 978       FILE* hs_err = os::open(log.fd(), "r");
 979       if (NULL != hs_err) {
 980         ErrorReporter er;
 981         er.call(hs_err, buffer, O_BUFLEN);
 982       }
 983     }
 984 
 985     if (log.fd() != defaultStream::output_fd()) {
 986       close(log.fd());
 987     }
 988 
 989     log.set_fd(-1);
 990     log_done = true;
 991   }
 992 
 993 
 994   static bool skip_OnError = false;
 995   if (!skip_OnError && OnError && OnError[0]) {
 996     skip_OnError = true;
 997 
 998     out.print_raw_cr("#");
 999     out.print_raw   ("# -XX:OnError=\"");
1000     out.print_raw   (OnError);
1001     out.print_raw_cr("\"");
1002 
1003     char* cmd;
1004     const char* ptr = OnError;
1005     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1006       out.print_raw   ("#   Executing ");
1007 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1008       out.print_raw   ("/bin/sh -c ");
1009 #elif defined(SOLARIS)
1010       out.print_raw   ("/usr/bin/sh -c ");
1011 #endif
1012       out.print_raw   ("\"");
1013       out.print_raw   (cmd);
1014       out.print_raw_cr("\" ...");
1015 
1016       if (os::fork_and_exec(cmd) < 0) {
1017         out.print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1018       }
1019     }
1020 
1021     // done with OnError
1022     OnError = NULL;
1023   }
1024 
1025   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1026   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1027     skip_replay = true;
1028     ciEnv* env = ciEnv::current();
1029     if (env != NULL) {
1030       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1031       if (fd != -1) {
1032         FILE* replay_data_file = os::open(fd, "w");
1033         if (replay_data_file != NULL) {
1034           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1035           env->dump_replay_data_unsafe(&replay_data_stream);
1036           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1037           out.print_raw_cr(buffer);
1038         } else {
1039           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1040           out.print_raw_cr(strerror(os::get_last_error()));
1041         }
1042       }
1043     }
1044   }
1045 
1046   static bool skip_bug_url = !should_report_bug(first_error->_id);
1047   if (!skip_bug_url) {
1048     skip_bug_url = true;
1049 
1050     out.print_raw_cr("#");
1051     print_bug_submit_message(&out, _thread);
1052   }
1053 
1054   if (!UseOSErrorReporting) {
1055     // os::abort() will call abort hooks, try it first.
1056     static bool skip_os_abort = false;
1057     if (!skip_os_abort) {
1058       skip_os_abort = true;
1059       bool dump_core = should_report_bug(first_error->_id);
1060       os::abort(dump_core);
1061     }
1062 
1063     // if os::abort() doesn't abort, try os::die();
1064     os::die();
1065   }
1066 }
1067 
1068 /*
1069  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1070  * ensures utilities such as jmap can observe the process is a consistent state.
1071  */
1072 class VM_ReportJavaOutOfMemory : public VM_Operation {
1073  private:
1074   VMError *_err;
1075  public:
1076   VM_ReportJavaOutOfMemory(VMError *err) { _err = err; }
1077   VMOp_Type type() const                 { return VMOp_ReportJavaOutOfMemory; }
1078   void doit();
1079 };
1080 
1081 void VM_ReportJavaOutOfMemory::doit() {
1082   // Don't allocate large buffer on stack
1083   static char buffer[O_BUFLEN];
1084 
1085   tty->print_cr("#");
1086   tty->print_cr("# java.lang.OutOfMemoryError: %s", _err->message());
1087   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1088 
1089   // make heap parsability
1090   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1091 
1092   char* cmd;
1093   const char* ptr = OnOutOfMemoryError;
1094   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1095     tty->print("#   Executing ");
1096 #if defined(LINUX)
1097     tty->print  ("/bin/sh -c ");
1098 #elif defined(SOLARIS)
1099     tty->print  ("/usr/bin/sh -c ");
1100 #endif
1101     tty->print_cr("\"%s\"...", cmd);
1102 
1103     if (os::fork_and_exec(cmd) < 0) {
1104       tty->print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1105     }
1106   }
1107 }
1108 
1109 void VMError::report_java_out_of_memory() {
1110   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1111     MutexLocker ml(Heap_lock);
1112     VM_ReportJavaOutOfMemory op(this);
1113     VMThread::execute(&op);
1114   }
1115 }