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