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