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(110, "(printing stack bounds)" )
 459 
 460      if (_verbose) {
 461        st->print("Stack: ");
 462 
 463        address stack_top;
 464        size_t stack_size;
 465 
 466        if (_thread) {
 467           stack_top = _thread->stack_base();
 468           stack_size = _thread->stack_size();
 469        } else {
 470           stack_top = os::current_stack_base();
 471           stack_size = os::current_stack_size();
 472        }
 473 
 474        address stack_bottom = stack_top - stack_size;
 475        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", stack_bottom, stack_top);
 476 
 477        frame fr = _context ? os::fetch_frame_from_context(_context)
 478                            : os::current_frame();
 479 
 480        if (fr.sp()) {
 481          st->print(",  sp=" PTR_FORMAT, fr.sp());
 482          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 483          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 484        }
 485 
 486        st->cr();
 487      }
 488 
 489   STEP(120, "(printing native stack)" )
 490 
 491      if (_verbose) {
 492        frame fr = _context ? os::fetch_frame_from_context(_context)
 493                            : os::current_frame();
 494 
 495        // see if it's a valid frame
 496        if (fr.pc()) {
 497           st->print_cr("Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)");
 498 
 499           int count = 0;
 500 
 501           while (count++ < StackPrintLimit) {
 502              fr.print_on_error(st, buf, sizeof(buf));
 503              st->cr();
 504              if (os::is_first_C_frame(&fr)) break;
 505              fr = os::get_sender_for_C_frame(&fr);
 506           }
 507 
 508           if (count > StackPrintLimit) {
 509              st->print_cr("...<more frames>...");
 510           }
 511 
 512           st->cr();
 513        }
 514      }
 515 
 516   STEP(130, "(printing Java stack)" )
 517 
 518      if (_verbose && _thread && _thread->is_Java_thread()) {
 519        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
 520      }
 521 
 522   STEP(135, "(printing target Java thread stack)" )
 523 
 524      // printing Java thread stack trace if it is involved in GC crash
 525      if (_verbose && (_thread->is_Named_thread())) {
 526        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
 527        if (jt != NULL) {
 528          st->print_cr("JavaThread " PTR_FORMAT " (nid = " UINTX_FORMAT ") was being processed", jt, jt->osthread()->thread_id());
 529          print_stack_trace(st, jt, buf, sizeof(buf), true);
 530        }
 531      }
 532 
 533   STEP(140, "(printing VM operation)" )
 534 
 535      if (_verbose && _thread && _thread->is_VM_thread()) {
 536         VMThread* t = (VMThread*)_thread;
 537         VM_Operation* op = t->vm_operation();
 538         if (op) {
 539           op->print_on_error(st);
 540           st->cr();
 541           st->cr();
 542         }
 543      }
 544 
 545   STEP(150, "(printing current compile task)" )
 546 
 547      if (_verbose && _thread && _thread->is_Compiler_thread()) {
 548         CompilerThread* t = (CompilerThread*)_thread;
 549         if (t->task()) {
 550            st->cr();
 551            st->print_cr("Current CompileTask:");
 552            t->task()->print_line_on_error(st, buf, sizeof(buf));
 553            st->cr();
 554         }
 555      }
 556 
 557   STEP(160, "(printing process)" )
 558 
 559      if (_verbose) {
 560        st->cr();
 561        st->print_cr("---------------  P R O C E S S  ---------------");
 562        st->cr();
 563      }
 564 
 565   STEP(170, "(printing all threads)" )
 566 
 567      // all threads
 568      if (_verbose && _thread) {
 569        Threads::print_on_error(st, _thread, buf, sizeof(buf));
 570        st->cr();
 571      }
 572 
 573   STEP(175, "(printing VM state)" )
 574 
 575      if (_verbose) {
 576        // Safepoint state
 577        st->print("VM state:");
 578 
 579        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
 580        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
 581        else st->print("not at safepoint");
 582 
 583        // Also see if error occurred during initialization or shutdown
 584        if (!Universe::is_fully_initialized()) {
 585          st->print(" (not fully initialized)");
 586        } else if (VM_Exit::vm_exited()) {
 587          st->print(" (shutting down)");
 588        } else {
 589          st->print(" (normal execution)");
 590        }
 591        st->cr();
 592        st->cr();
 593      }
 594 
 595   STEP(180, "(printing owned locks on error)" )
 596 
 597      // mutexes/monitors that currently have an owner
 598      if (_verbose) {
 599        print_owned_locks_on_error(st);
 600        st->cr();
 601      }
 602 
 603   STEP(190, "(printing heap information)" )
 604 
 605      if (_verbose && Universe::is_fully_initialized()) {
 606        // print heap information before vm abort
 607        Universe::print_on(st);
 608        st->cr();
 609      }
 610 
 611   STEP(200, "(printing dynamic libraries)" )
 612 
 613      if (_verbose) {
 614        // dynamic libraries, or memory map
 615        os::print_dll_info(st);
 616        st->cr();
 617      }
 618 
 619   STEP(210, "(printing VM options)" )
 620 
 621      if (_verbose) {
 622        // VM options
 623        Arguments::print_on(st);
 624        st->cr();
 625      }
 626 
 627   STEP(220, "(printing environment variables)" )
 628 
 629      if (_verbose) {
 630        os::print_environment_variables(st, env_list, buf, sizeof(buf));
 631        st->cr();
 632      }
 633 
 634   STEP(225, "(printing signal handlers)" )
 635 
 636      if (_verbose) {
 637        os::print_signal_handlers(st, buf, sizeof(buf));
 638        st->cr();
 639      }
 640 
 641   STEP(230, "" )
 642 
 643      if (_verbose) {
 644        st->cr();
 645        st->print_cr("---------------  S Y S T E M  ---------------");
 646        st->cr();
 647      }
 648 
 649   STEP(240, "(printing OS information)" )
 650 
 651      if (_verbose) {
 652        os::print_os_info(st);
 653        st->cr();
 654      }
 655 
 656   STEP(250, "(printing CPU info)" )
 657      if (_verbose) {
 658        os::print_cpu_info(st);
 659        st->cr();
 660      }
 661 
 662   STEP(260, "(printing memory info)" )
 663 
 664      if (_verbose) {
 665        os::print_memory_info(st);
 666        st->cr();
 667      }
 668 
 669   STEP(270, "(printing internal vm info)" )
 670 
 671      if (_verbose) {
 672        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
 673        st->cr();
 674      }
 675 
 676   STEP(280, "(printing date and time)" )
 677 
 678      if (_verbose) {
 679        os::print_date_and_time(st);
 680        st->cr();
 681      }
 682 
 683   END
 684 
 685 # undef BEGIN
 686 # undef STEP
 687 # undef END
 688 }
 689 
 690 VMError* volatile VMError::first_error = NULL;
 691 volatile jlong VMError::first_error_tid = -1;
 692 
 693 void VMError::report_and_die() {
 694   // Don't allocate large buffer on stack
 695   static char buffer[O_BUFLEN];
 696 
 697   // An error could happen before tty is initialized or after it has been
 698   // destroyed. Here we use a very simple unbuffered fdStream for printing.
 699   // Only out.print_raw() and out.print_raw_cr() should be used, as other
 700   // printing methods need to allocate large buffer on stack. To format a
 701   // string, use jio_snprintf() with a static buffer or use staticBufferStream.
 702   static fdStream out(defaultStream::output_fd());
 703 
 704   // How many errors occurred in error handler when reporting first_error.
 705   static int recursive_error_count;
 706 
 707   // We will first print a brief message to standard out (verbose = false),
 708   // then save detailed information in log file (verbose = true).
 709   static bool out_done = false;         // done printing to standard out
 710   static bool log_done = false;         // done saving error log
 711   static fdStream log;                  // error log
 712 
 713   if (SuppressFatalErrorMessage) {
 714       os::abort();
 715   }
 716   jlong mytid = os::current_thread_id();
 717   if (first_error == NULL &&
 718       Atomic::cmpxchg_ptr(this, &first_error, NULL) == NULL) {
 719 
 720     // first time
 721     first_error_tid = mytid;
 722     set_error_reported();
 723 
 724     if (ShowMessageBoxOnError) {
 725       show_message_box(buffer, sizeof(buffer));
 726 
 727       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
 728       // WatcherThread can kill JVM if the error handler hangs.
 729       ShowMessageBoxOnError = false;
 730     }
 731 
 732     // reset signal handlers or exception filter; make sure recursive crashes
 733     // are handled properly.
 734     reset_signal_handlers();
 735 
 736   } else {
 737     // If UseOsErrorReporting we call this for each level of the call stack
 738     // while searching for the exception handler.  Only the first level needs
 739     // to be reported.
 740     if (UseOSErrorReporting && log_done) return;
 741 
 742     // This is not the first error, see if it happened in a different thread
 743     // or in the same thread during error reporting.
 744     if (first_error_tid != mytid) {
 745       jio_snprintf(buffer, sizeof(buffer),
 746                    "[thread " INT64_FORMAT " also had an error]",
 747                    mytid);
 748       out.print_raw_cr(buffer);
 749 
 750       // error reporting is not MT-safe, block current thread
 751       os::infinite_sleep();
 752 
 753     } else {
 754       if (recursive_error_count++ > 30) {
 755         out.print_raw_cr("[Too many errors, abort]");
 756         os::die();
 757       }
 758 
 759       jio_snprintf(buffer, sizeof(buffer),
 760                    "[error occurred during error reporting %s, id 0x%x]",
 761                    first_error ? first_error->_current_step_info : "",
 762                    _id);
 763       if (log.is_open()) {
 764         log.cr();
 765         log.print_raw_cr(buffer);
 766         log.cr();
 767       } else {
 768         out.cr();
 769         out.print_raw_cr(buffer);
 770         out.cr();
 771       }
 772     }
 773   }
 774 
 775   // print to screen
 776   if (!out_done) {
 777     first_error->_verbose = false;
 778 
 779     staticBufferStream sbs(buffer, sizeof(buffer), &out);
 780     first_error->report(&sbs);
 781 
 782     out_done = true;
 783 
 784     first_error->_current_step = 0;         // reset current_step
 785     first_error->_current_step_info = "";   // reset current_step string
 786   }
 787 
 788   // print to error log file
 789   if (!log_done) {
 790     first_error->_verbose = true;
 791 
 792     // see if log file is already open
 793     if (!log.is_open()) {
 794       // open log file
 795       int fd = -1;
 796 
 797       if (ErrorFile != NULL) {
 798         bool copy_ok =
 799           Arguments::copy_expand_pid(ErrorFile, strlen(ErrorFile), buffer, sizeof(buffer));
 800         if (copy_ok) {
 801           fd = open(buffer, O_WRONLY | O_CREAT | O_TRUNC, 0666);
 802         }
 803       }
 804 
 805       if (fd == -1) {
 806         const char *cwd = os::get_current_directory(buffer, sizeof(buffer));
 807         size_t len = strlen(cwd);
 808         // either user didn't specify, or the user's location failed,
 809         // so use the default name in the current directory
 810         jio_snprintf(&buffer[len], sizeof(buffer)-len, "%shs_err_pid%u.log",
 811                      os::file_separator(), os::current_process_id());
 812         fd = open(buffer, O_WRONLY | O_CREAT | O_TRUNC, 0666);
 813       }
 814 
 815       if (fd == -1) {
 816         // try temp directory
 817         const char * tmpdir = os::get_temp_directory();
 818         jio_snprintf(buffer, sizeof(buffer), "%s%shs_err_pid%u.log",
 819                      tmpdir, os::file_separator(), os::current_process_id());
 820         fd = open(buffer, O_WRONLY | O_CREAT | O_TRUNC, 0666);
 821       }
 822 
 823       if (fd != -1) {
 824         out.print_raw("# An error report file with more information is saved as:\n# ");
 825         out.print_raw_cr(buffer);
 826         os::set_error_file(buffer);
 827 
 828         log.set_fd(fd);
 829       } else {
 830         out.print_raw_cr("# Can not save log file, dump to screen..");
 831         log.set_fd(defaultStream::output_fd());
 832       }
 833     }
 834 
 835     staticBufferStream sbs(buffer, O_BUFLEN, &log);
 836     first_error->report(&sbs);
 837     first_error->_current_step = 0;         // reset current_step
 838     first_error->_current_step_info = "";   // reset current_step string
 839 
 840     if (log.fd() != defaultStream::output_fd()) {
 841       close(log.fd());
 842     }
 843 
 844     log.set_fd(-1);
 845     log_done = true;
 846   }
 847 
 848 
 849   static bool skip_OnError = false;
 850   if (!skip_OnError && OnError && OnError[0]) {
 851     skip_OnError = true;
 852 
 853     out.print_raw_cr("#");
 854     out.print_raw   ("# -XX:OnError=\"");
 855     out.print_raw   (OnError);
 856     out.print_raw_cr("\"");
 857 
 858     char* cmd;
 859     const char* ptr = OnError;
 860     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
 861       out.print_raw   ("#   Executing ");
 862 #if defined(LINUX)
 863       out.print_raw   ("/bin/sh -c ");
 864 #elif defined(SOLARIS)
 865       out.print_raw   ("/usr/bin/sh -c ");
 866 #endif
 867       out.print_raw   ("\"");
 868       out.print_raw   (cmd);
 869       out.print_raw_cr("\" ...");
 870 
 871       os::fork_and_exec(cmd);
 872     }
 873 
 874     // done with OnError
 875     OnError = NULL;
 876   }
 877 
 878   static bool skip_bug_url = false;
 879   if (!skip_bug_url) {
 880     skip_bug_url = true;
 881 
 882     out.print_raw_cr("#");
 883     print_bug_submit_message(&out, _thread);
 884   }
 885 
 886   if (!UseOSErrorReporting) {
 887     // os::abort() will call abort hooks, try it first.
 888     static bool skip_os_abort = false;
 889     if (!skip_os_abort) {
 890       skip_os_abort = true;
 891       os::abort();
 892     }
 893 
 894     // if os::abort() doesn't abort, try os::die();
 895     os::die();
 896   }
 897 }
 898 
 899 /*
 900  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
 901  * ensures utilities such as jmap can observe the process is a consistent state.
 902  */
 903 class VM_ReportJavaOutOfMemory : public VM_Operation {
 904  private:
 905   VMError *_err;
 906  public:
 907   VM_ReportJavaOutOfMemory(VMError *err) { _err = err; }
 908   VMOp_Type type() const                 { return VMOp_ReportJavaOutOfMemory; }
 909   void doit();
 910 };
 911 
 912 void VM_ReportJavaOutOfMemory::doit() {
 913   // Don't allocate large buffer on stack
 914   static char buffer[O_BUFLEN];
 915 
 916   tty->print_cr("#");
 917   tty->print_cr("# java.lang.OutOfMemoryError: %s", _err->message());
 918   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
 919 
 920   // make heap parsability
 921   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
 922 
 923   char* cmd;
 924   const char* ptr = OnOutOfMemoryError;
 925   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
 926     tty->print("#   Executing ");
 927 #if defined(LINUX)
 928     tty->print  ("/bin/sh -c ");
 929 #elif defined(SOLARIS)
 930     tty->print  ("/usr/bin/sh -c ");
 931 #endif
 932     tty->print_cr("\"%s\"...", cmd);
 933 
 934     os::fork_and_exec(cmd);
 935   }
 936 }
 937 
 938 void VMError::report_java_out_of_memory() {
 939   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
 940     MutexLocker ml(Heap_lock);
 941     VM_ReportJavaOutOfMemory op(this);
 942     VMThread::execute(&op);
 943   }
 944 }