< prev index next >

src/share/vm/utilities/vmError.cpp

Print this page




  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::record_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


 340 // occurred when reporting an error, the nested signal/exception handler
 341 // can skip steps that are already (or partially) done. Error reporting will
 342 // continue from the next step. This allows us to retrieve and print
 343 // information that may be unsafe to get after a fatal error. If it happens,
 344 // you may find nested report_and_die() frames when you look at the stack
 345 // in a debugger.
 346 //
 347 // In general, a hang in error handler is much worse than a crash or internal
 348 // error, as it's harder to recover from a hang. Deadlock can happen if we
 349 // try to grab a lock that is already owned by current thread, or if the
 350 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 351 // error handler and all the functions it called should avoid grabbing any
 352 // lock. An important thing to notice is that memory allocation needs a lock.
 353 //
 354 // We should avoid using large stack allocated buffers. Many errors happen
 355 // when stack space is already low. Making things even worse is that there
 356 // could be nested report_and_die() calls on stack (see above). Only one
 357 // thread can report error, so large buffers are statically allocated in data
 358 // segment.
 359 
 360 void VMError::report(outputStream* st) {






 361 # define BEGIN if (_current_step == 0) { _current_step = 1;
 362 # define STEP(n, s) } if (_current_step < n) { _current_step = n; _current_step_info = s;
 363 # define END }
 364 
 365   // don't allocate large buffer on stack
 366   static char buf[O_BUFLEN];
 367 
 368   BEGIN
 369 
 370   STEP(10, "(printing fatal error message)")
 371 
 372     st->print_cr("#");
 373     if (should_report_bug(_id)) {
 374       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 375     } else {
 376       st->print_cr("# There is insufficient memory for the Java "
 377                    "Runtime Environment to continue.");
 378     }
 379 
 380 #ifndef PRODUCT
 381   // Error handler self tests
 382 
 383   // test secondary error handling. Test it twice, to test that resetting
 384   // error handler after a secondary crash works.
 385   STEP(20, "(test secondary crash 1)")
 386     if (_verbose && TestCrashInErrorHandler != 0) {
 387       st->print_cr("Will crash now (TestCrashInErrorHandler=%d)...",
 388         TestCrashInErrorHandler);
 389       controlled_crash(TestCrashInErrorHandler);
 390     }
 391 
 392   STEP(30, "(test secondary crash 2)")
 393     if (_verbose && TestCrashInErrorHandler != 0) {


 402     if (_verbose && TestSafeFetchInErrorHandler) {
 403       st->print_cr("Will test SafeFetch...");
 404       if (CanUseSafeFetch32()) {
 405         int* const invalid_pointer = (int*) get_segfault_address();
 406         const int x = 0x76543210;
 407         int i1 = SafeFetch32(invalid_pointer, x);
 408         int i2 = SafeFetch32(invalid_pointer, x);
 409         if (i1 == x && i2 == x) {
 410           st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
 411         } else {
 412           st->print_cr("??");
 413         }
 414       } else {
 415         st->print_cr("not possible; skipped.");
 416       }
 417     }
 418 #endif // PRODUCT
 419 
 420   STEP(50, "(printing type of error)")
 421 
 422      switch(_id) {
 423        case OOM_MALLOC_ERROR:
 424        case OOM_MMAP_ERROR:
 425          if (_size) {
 426            st->print("# Native memory allocation ");
 427            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 428                                                  "(mmap) failed to map ");
 429            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
 430            st->print("%s", buf);
 431            st->print(" bytes");
 432            if (_message != NULL) {
 433              st->print(" for ");
 434              st->print("%s", _message);
 435            }
 436            st->cr();
 437          } else {
 438            if (_message != NULL) {
 439              st->print("# ");
 440              st->print_cr("%s", _message);
 441            }
 442          }
 443          // In error file give some solutions
 444          if (_verbose) {
 445            print_oom_reasons(st);
 446          } else {
 447            return;  // that's enough for the screen
 448          }
 449          break;
 450        case INTERNAL_ERROR:
 451        default:
 452          break;
 453      }
 454 
 455   STEP(60, "(printing exception/signal name)")
 456 
 457      st->print_cr("#");
 458      st->print("#  ");
 459      // Is it an OS exception/signal?
 460      if (os::exception_name(_id, buf, sizeof(buf))) {
 461        st->print("%s", buf);
 462        st->print(" (0x%x)", _id);                // signal number
 463        st->print(" at pc=" PTR_FORMAT, _pc);
 464      } else {
 465        if (should_report_bug(_id)) {
 466          st->print("Internal Error");
 467        } else {
 468          st->print("Out of Memory Error");
 469        }
 470        if (_filename != NULL && _lineno > 0) {
 471 #ifdef PRODUCT
 472          // In product mode chop off pathname?
 473          char separator = os::file_separator()[0];
 474          const char *p = strrchr(_filename, separator);
 475          const char *file = p ? p+1 : _filename;
 476 #else
 477          const char *file = _filename;
 478 #endif
 479          st->print(" (%s:%d)", file, _lineno);
 480        } else {
 481          st->print(" (0x%x)", _id);
 482        }
 483      }
 484 
 485   STEP(70, "(printing current thread and pid)")
 486 
 487      // process id, thread id
 488      st->print(", pid=%d", os::current_process_id());
 489      st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
 490      st->cr();
 491 
 492   STEP(80, "(printing error message)")
 493 
 494      if (should_report_bug(_id)) {  // already printed the message.
 495        // error message
 496        if (_detail_msg) {
 497          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
 498        } else if (_message) {
 499          st->print_cr("#  Error: %s", _message);

 500        }
 501     }
 502 
 503   STEP(90, "(printing Java version string)")
 504 
 505      // VM version
 506      st->print_cr("#");
 507      JDK_Version::current().to_string(buf, sizeof(buf));
 508      const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 509                                   JDK_Version::runtime_name() : "";
 510      const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 511                                   JDK_Version::runtime_version() : "";
 512      st->print_cr("# JRE version: %s (%s) (build %s)", runtime_name, buf, runtime_version);
 513      // This is the long version with some default settings added
 514      st->print_cr("# Java VM: %s (%s, %s%s%s, %s, %s)",
 515                    Abstract_VM_Version::vm_name(),
 516                    Abstract_VM_Version::vm_release(),
 517                    Abstract_VM_Version::vm_info_string(),
 518                    TieredCompilation ? ", tiered" : "",
 519                    UseCompressedOops ? ", compressed oops" : "",
 520                    gc_mode(),
 521                    Abstract_VM_Version::vm_platform_string()
 522                  );
 523 
 524   STEP(100, "(printing problematic frame)")
 525 
 526      // Print current frame if we have a context (i.e. it's a crash)
 527      if (_context) {
 528        st->print_cr("# Problematic frame:");
 529        st->print("# ");
 530        frame fr = os::fetch_frame_from_context(_context);
 531        fr.print_on_error(st, buf, sizeof(buf));
 532        st->cr();
 533        st->print_cr("#");
 534      }
 535 
 536   STEP(110, "(printing core file information)")
 537     st->print("# ");
 538     if (CreateCoredumpOnCrash) {
 539       if (coredump_status) {
 540         st->print("Core dump will be written. Default location: %s", coredump_message);
 541       } else {
 542         st->print("No core dump will be written. %s", coredump_message);
 543       }
 544     } else {
 545       st->print("CreateCoredumpOnCrash turned off, no core file dumped");
 546     }
 547     st->cr();
 548     st->print_cr("#");
 549 
 550   STEP(120, "(printing bug submit message)")
 551 
 552      if (should_report_bug(_id) && _verbose) {
 553        print_bug_submit_message(st, _thread);
 554      }
 555 
 556   STEP(130, "(printing summary)" )
 557 
 558      if (_verbose) {
 559        st->cr();
 560        st->print_cr("---------------  S U M M A R Y ------------");
 561        st->cr();
 562      }
 563 
 564   STEP(140, "(printing VM option summary)" )
 565 
 566      if (_verbose) {
 567        // VM options
 568        Arguments::print_summary_on(st);
 569        st->cr();
 570      }
 571 
 572   STEP(150, "(printing summary machine and OS info)")
 573 


 577 
 578 
 579   STEP(160, "(printing date and time)" )
 580 
 581      if (_verbose) {
 582        os::print_date_and_time(st, buf, sizeof(buf));
 583      }
 584 
 585   STEP(170, "(printing thread)" )
 586 
 587      if (_verbose) {
 588        st->cr();
 589        st->print_cr("---------------  T H R E A D  ---------------");
 590        st->cr();
 591      }
 592 
 593   STEP(180, "(printing current thread)" )
 594 
 595      // current thread
 596      if (_verbose) {
 597        if (_thread) {
 598          st->print("Current thread (" PTR_FORMAT "):  ", _thread);
 599          _thread->print_on_error(st, buf, sizeof(buf));
 600          st->cr();
 601        } else {
 602          st->print_cr("Current thread is native thread");
 603        }
 604        st->cr();
 605      }
 606 
 607   STEP(190, "(printing current compile task)" )
 608 
 609      if (_verbose && _thread && _thread->is_Compiler_thread()) {
 610         CompilerThread* t = (CompilerThread*)_thread;
 611         if (t->task()) {
 612            st->cr();
 613            st->print_cr("Current CompileTask:");
 614            t->task()->print_line_on_error(st, buf, sizeof(buf));
 615            st->cr();
 616         }
 617      }
 618 
 619 
 620   STEP(200, "(printing stack bounds)" )
 621 
 622      if (_verbose) {
 623        st->print("Stack: ");
 624 
 625        address stack_top;
 626        size_t stack_size;
 627 
 628        if (_thread) {
 629           stack_top = _thread->stack_base();
 630           stack_size = _thread->stack_size();
 631        } else {
 632           stack_top = os::current_stack_base();
 633           stack_size = os::current_stack_size();
 634        }
 635 
 636        address stack_bottom = stack_top - stack_size;
 637        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", stack_bottom, stack_top);
 638 
 639        frame fr = _context ? os::fetch_frame_from_context(_context)
 640                            : os::current_frame();
 641 
 642        if (fr.sp()) {
 643          st->print(",  sp=" PTR_FORMAT, fr.sp());
 644          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 645          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 646        }
 647 
 648        st->cr();
 649      }
 650 
 651   STEP(210, "(printing native stack)" )
 652 
 653    if (_verbose) {
 654      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
 655        // We have printed the native stack in platform-specific code
 656        // Windows/x64 needs special handling.
 657      } else {
 658        frame fr = _context ? os::fetch_frame_from_context(_context)
 659                            : os::current_frame();
 660 
 661        print_native_stack(st, fr, _thread, buf, sizeof(buf));
 662      }
 663    }
 664 
 665   STEP(220, "(printing Java stack)" )
 666 
 667      if (_verbose && _thread && _thread->is_Java_thread()) {
 668        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
 669      }
 670 
 671   STEP(230, "(printing target Java thread stack)" )
 672 
 673      // printing Java thread stack trace if it is involved in GC crash
 674      if (_verbose && _thread && (_thread->is_Named_thread())) {
 675        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
 676        if (jt != NULL) {
 677          st->print_cr("JavaThread " PTR_FORMAT " (nid = " UINTX_FORMAT ") was being processed", jt, jt->osthread()->thread_id());
 678          print_stack_trace(st, jt, buf, sizeof(buf), true);
 679        }
 680      }
 681 
 682   STEP(240, "(printing siginfo)" )
 683 
 684      // signal no, signal code, address that caused the fault
 685      if (_verbose && _siginfo) {
 686        st->cr();
 687        os::print_siginfo(st, _siginfo);
 688        st->cr();
 689      }
 690 
 691   STEP(250, "(printing register info)")
 692 
 693      // decode register contents if possible
 694      if (_verbose && _context && Universe::is_fully_initialized()) {
 695        os::print_register_info(st, _context);
 696        st->cr();
 697      }
 698 
 699   STEP(260, "(printing registers, top of stack, instructions near pc)")
 700 
 701      // registers, top of stack, instructions near pc
 702      if (_verbose && _context) {
 703        os::print_context(st, _context);
 704        st->cr();
 705      }
 706 
 707   STEP(270, "(printing VM operation)" )
 708 
 709      if (_verbose && _thread && _thread->is_VM_thread()) {
 710         VMThread* t = (VMThread*)_thread;
 711         VM_Operation* op = t->vm_operation();
 712         if (op) {
 713           op->print_on_error(st);
 714           st->cr();
 715           st->cr();
 716         }
 717      }
 718 
 719   STEP(280, "(printing process)" )
 720 
 721      if (_verbose) {
 722        st->cr();
 723        st->print_cr("---------------  P R O C E S S  ---------------");
 724        st->cr();
 725      }
 726 
 727   STEP(290, "(printing all threads)" )
 728 
 729      // all threads
 730      if (_verbose && _thread) {
 731        Threads::print_on_error(st, _thread, buf, sizeof(buf));
 732        st->cr();
 733      }
 734 
 735   STEP(300, "(printing VM state)" )
 736 
 737      if (_verbose) {
 738        // Safepoint state
 739        st->print("VM state:");
 740 
 741        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
 742        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
 743        else st->print("not at safepoint");
 744 
 745        // Also see if error occurred during initialization or shutdown
 746        if (!Universe::is_fully_initialized()) {
 747          st->print(" (not fully initialized)");
 748        } else if (VM_Exit::vm_exited()) {
 749          st->print(" (shutting down)");
 750        } else {
 751          st->print(" (normal execution)");


 879 
 880      if (_verbose) {
 881        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
 882        st->cr();
 883      }
 884 
 885   // print a defined marker to show that error handling finished correctly.
 886   STEP(480, "(printing end marker)" )
 887 
 888      if (_verbose) {
 889        st->print_cr("END.");
 890      }
 891 
 892   END
 893 
 894 # undef BEGIN
 895 # undef STEP
 896 # undef END
 897 }
 898 
 899 VMError* volatile VMError::first_error = NULL;
 900 volatile jlong VMError::first_error_tid = -1;
 901 
 902 // An error could happen before tty is initialized or after it has been
 903 // destroyed. Here we use a very simple unbuffered fdStream for printing.
 904 // Only out.print_raw() and out.print_raw_cr() should be used, as other
 905 // printing methods need to allocate large buffer on stack. To format a
 906 // string, use jio_snprintf() with a static buffer or use staticBufferStream.
 907 fdStream VMError::out(defaultStream::output_fd());
 908 fdStream VMError::log; // error log used by VMError::report_and_die()
 909 
 910 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
 911 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
 912   int fd = -1;
 913   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
 914     // the O_EXCL flag will cause the open to fail if the file exists
 915     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
 916   }
 917   return fd;
 918 }
 919 


 941       if (fsep_len > 0) {
 942         fd = expand_and_open(default_pattern, buf, buflen, pos);
 943       }
 944     }
 945   }
 946 
 947    // try temp directory if it exists.
 948    if (fd == -1) {
 949      const char* tmpdir = os::get_temp_directory();
 950      if (tmpdir != NULL && strlen(tmpdir) > 0) {
 951        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
 952        if (pos > 0) {
 953          fd = expand_and_open(default_pattern, buf, buflen, pos);
 954        }
 955      }
 956    }
 957 
 958   return fd;
 959 }
 960 
 961 void VMError::report_and_die() {









































 962   // Don't allocate large buffer on stack
 963   static char buffer[O_BUFLEN];
 964 
 965   // How many errors occurred in error handler when reporting first_error.
 966   static int recursive_error_count;
 967 
 968   // We will first print a brief message to standard out (verbose = false),
 969   // then save detailed information in log file (verbose = true).
 970   static bool out_done = false;         // done printing to standard out
 971   static bool log_done = false;         // done saving error log
 972   static bool transmit_report_done = false; // done error reporting
 973 
 974   if (SuppressFatalErrorMessage) {
 975       os::abort(CreateCoredumpOnCrash);
 976   }
 977   jlong mytid = os::current_thread_id();
 978   if (first_error == NULL &&
 979       Atomic::cmpxchg_ptr(this, &first_error, NULL) == NULL) {
 980 
 981     // first time
 982     first_error_tid = mytid;
 983     set_error_reported();
 984 
 985     if (ShowMessageBoxOnError || PauseAtExit) {
 986       show_message_box(buffer, sizeof(buffer));



 987 
 988       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
 989       // WatcherThread can kill JVM if the error handler hangs.
 990       ShowMessageBoxOnError = false;
 991     }
 992 
 993     os::check_dump_limit(buffer, sizeof(buffer));
 994 
 995     // reset signal handlers or exception filter; make sure recursive crashes
 996     // are handled properly.
 997     reset_signal_handlers();
 998 
 999   } else {
1000     // If UseOsErrorReporting we call this for each level of the call stack
1001     // while searching for the exception handler.  Only the first level needs
1002     // to be reported.
1003     if (UseOSErrorReporting && log_done) return;
1004 
1005     // This is not the first error, see if it happened in a different thread
1006     // or in the same thread during error reporting.
1007     if (first_error_tid != mytid) {
1008       char msgbuf[64];
1009       jio_snprintf(msgbuf, sizeof(msgbuf),
1010                    "[thread " INT64_FORMAT " also had an error]",
1011                    mytid);
1012       out.print_raw_cr(msgbuf);
1013 
1014       // error reporting is not MT-safe, block current thread
1015       os::infinite_sleep();
1016 
1017     } else {
1018       if (recursive_error_count++ > 30) {
1019         out.print_raw_cr("[Too many errors, abort]");
1020         os::die();
1021       }
1022 
1023       jio_snprintf(buffer, sizeof(buffer),
1024                    "[error occurred during error reporting %s, id 0x%x]",
1025                    first_error ? first_error->_current_step_info : "",
1026                    _id);
1027       if (log.is_open()) {
1028         log.cr();
1029         log.print_raw_cr(buffer);
1030         log.cr();
1031       } else {
1032         out.cr();
1033         out.print_raw_cr(buffer);
1034         out.cr();
1035       }
1036     }
1037   }
1038 
1039   // print to screen
1040   if (!out_done) {
1041     first_error->_verbose = false;
1042 
1043     staticBufferStream sbs(buffer, sizeof(buffer), &out);
1044     first_error->report(&sbs);



1045 
1046     out_done = true;
1047 
1048     first_error->_current_step = 0;         // reset current_step
1049     first_error->_current_step_info = "";   // reset current_step string
1050   }
1051 
1052   // print to error log file
1053   if (!log_done) {
1054     first_error->_verbose = true;
1055 
1056     // see if log file is already open
1057     if (!log.is_open()) {
1058       // open log file
1059       int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1060       if (fd != -1) {
1061         out.print_raw("# An error report file with more information is saved as:\n# ");
1062         out.print_raw_cr(buffer);
1063 
1064         log.set_fd(fd);
1065       } else {
1066         out.print_raw_cr("# Can not save log file, dump to screen..");
1067         log.set_fd(defaultStream::output_fd());
1068         /* Error reporting currently needs dumpfile.
1069          * Maybe implement direct streaming in the future.*/
1070         transmit_report_done = true;
1071       }
1072     }
1073 
1074     staticBufferStream sbs(buffer, O_BUFLEN, &log);
1075     first_error->report(&sbs);
1076     first_error->_current_step = 0;         // reset current_step
1077     first_error->_current_step_info = "";   // reset current_step string



1078 
1079     // Run error reporting to determine whether or not to report the crash.
1080     if (!transmit_report_done && should_report_bug(first_error->_id)) {
1081       transmit_report_done = true;
1082       const int fd2 = ::dup(log.fd());
1083       FILE* const hs_err = ::fdopen(fd2, "r");
1084       if (NULL != hs_err) {
1085         ErrorReporter er;
1086         er.call(hs_err, buffer, O_BUFLEN);
1087       }
1088       ::fclose(hs_err);
1089     }
1090 
1091     if (log.fd() != defaultStream::output_fd()) {
1092       close(log.fd());
1093     }
1094 
1095     log.set_fd(-1);
1096     log_done = true;
1097   }
1098 
1099 
1100   static bool skip_OnError = false;


1112       out.print_raw   ("#   Executing ");
1113 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1114       out.print_raw   ("/bin/sh -c ");
1115 #elif defined(SOLARIS)
1116       out.print_raw   ("/usr/bin/sh -c ");
1117 #endif
1118       out.print_raw   ("\"");
1119       out.print_raw   (cmd);
1120       out.print_raw_cr("\" ...");
1121 
1122       if (os::fork_and_exec(cmd) < 0) {
1123         out.print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1124       }
1125     }
1126 
1127     // done with OnError
1128     OnError = NULL;
1129   }
1130 
1131   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1132   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1133     skip_replay = true;
1134     ciEnv* env = ciEnv::current();
1135     if (env != NULL) {
1136       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1137       if (fd != -1) {
1138         FILE* replay_data_file = os::open(fd, "w");
1139         if (replay_data_file != NULL) {
1140           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1141           env->dump_replay_data_unsafe(&replay_data_stream);
1142           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1143           out.print_raw_cr(buffer);
1144         } else {
1145           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1146           out.print_raw_cr(strerror(os::get_last_error()));
1147         }
1148       }
1149     }
1150   }
1151 
1152   static bool skip_bug_url = !should_report_bug(first_error->_id);
1153   if (!skip_bug_url) {
1154     skip_bug_url = true;
1155 
1156     out.print_raw_cr("#");
1157     print_bug_submit_message(&out, _thread);
1158   }
1159 
1160   if (!UseOSErrorReporting) {
1161     // os::abort() will call abort hooks, try it first.
1162     static bool skip_os_abort = false;
1163     if (!skip_os_abort) {
1164       skip_os_abort = true;
1165       bool dump_core = should_report_bug(first_error->_id);
1166       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1167     }
1168 
1169     // if os::abort() doesn't abort, try os::die();
1170     os::die();
1171   }
1172 }
1173 
1174 /*
1175  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1176  * ensures utilities such as jmap can observe the process is a consistent state.
1177  */
1178 class VM_ReportJavaOutOfMemory : public VM_Operation {
1179  private:
1180   VMError *_err;
1181  public:
1182   VM_ReportJavaOutOfMemory(VMError *err) { _err = err; }
1183   VMOp_Type type() const                 { return VMOp_ReportJavaOutOfMemory; }
1184   void doit();
1185 };
1186 
1187 void VM_ReportJavaOutOfMemory::doit() {
1188   // Don't allocate large buffer on stack
1189   static char buffer[O_BUFLEN];
1190 
1191   tty->print_cr("#");
1192   tty->print_cr("# java.lang.OutOfMemoryError: %s", _err->message());
1193   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1194 
1195   // make heap parsability
1196   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1197 
1198   char* cmd;
1199   const char* ptr = OnOutOfMemoryError;
1200   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1201     tty->print("#   Executing ");
1202 #if defined(LINUX)
1203     tty->print  ("/bin/sh -c ");
1204 #elif defined(SOLARIS)
1205     tty->print  ("/usr/bin/sh -c ");
1206 #endif
1207     tty->print_cr("\"%s\"...", cmd);
1208 
1209     if (os::fork_and_exec(cmd) < 0) {
1210       tty->print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1211     }
1212   }
1213 }
1214 
1215 void VMError::report_java_out_of_memory() {
1216   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1217     MutexLocker ml(Heap_lock);
1218     VM_ReportJavaOutOfMemory op(this);
1219     VMThread::execute(&op);
1220   }
1221 }


  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 // A simple parser for -XX:OnError, usage:
  75 //  ptr = OnError;
  76 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
  77 //     ... ...
  78 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
  79   if (ptr == NULL || *ptr == NULL) return NULL;
  80 
  81   const char* cmd = *ptr;
  82 
  83   // skip leading blanks or ';'
  84   while (*cmd == ' ' || *cmd == ';') cmd++;
  85 
  86   if (*cmd == '\0') return NULL;
  87 
  88   const char * cmdend = cmd;
  89   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
  90 
  91   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
  92 
  93   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
  94   return buf;
  95 }
  96 

  97 static void print_bug_submit_message(outputStream *out, Thread *thread) {
  98   if (out == NULL) return;
  99   out->print_raw_cr("# If you would like to submit a bug report, please visit:");
 100   out->print_raw   ("#   ");
 101   out->print_raw_cr(Arguments::java_vendor_url_bug());
 102   // If the crash is in native code, encourage user to submit a bug to the
 103   // provider of that code.
 104   if (thread && thread->is_Java_thread() &&
 105       !thread->is_hidden_from_external_view()) {
 106     JavaThread* jt = (JavaThread*)thread;
 107     if (jt->thread_state() == _thread_in_native) {
 108       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
 109     }
 110   }
 111   out->print_raw_cr("#");
 112 }
 113 
 114 bool VMError::coredump_status;
 115 char VMError::coredump_message[O_BUFLEN];
 116 
 117 void VMError::record_coredump_status(const char* message, bool status) {
 118   coredump_status = status;
 119   strncpy(coredump_message, message, sizeof(coredump_message));
 120   coredump_message[sizeof(coredump_message)-1] = 0;
 121 }
 122 

 123 // Return a string to describe the error
 124 char* VMError::error_string(char* buf, int buflen, int id, const char* message, const char* detail_fmt,
 125                             va_list detail_args, address pc, const char* filename, int lineno)
 126 {
 127   char signame_buf[64];
 128   const char *signame = os::exception_name(id, signame_buf, sizeof(signame_buf));
 129 
 130   if (signame) {
 131     jio_snprintf(buf, buflen,
 132                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
 133                  signame, id, pc,
 134                  os::current_process_id(), os::current_thread_id());
 135   } else if (filename != NULL && lineno > 0) {
 136     // skip directory names
 137     char separator = os::file_separator()[0];
 138     const char *p = strrchr(filename, separator);
 139     int n = jio_snprintf(buf, buflen,
 140                          "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
 141                          p ? p + 1 : filename, lineno,
 142                          os::current_process_id(), os::current_thread_id());
 143     if (n >= 0 && n < buflen && message) {
 144       if (detail_fmt) {
 145         int d = jio_snprintf(buf + n, buflen - n, "%s%s: ", os::line_separator(), message);
 146         if (d >= 0) {
 147           n += d;
 148           if (n < buflen) {
 149             jio_vsnprintf(buf + n, buflen - n, detail_fmt, detail_args);
 150           }
 151         }
 152       } else {
 153         jio_snprintf(buf + n, buflen - n, "%sError: %s",
 154                      os::line_separator(), message);
 155       }
 156     }
 157   } else {
 158     jio_snprintf(buf, buflen,
 159                  "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
 160                  id, os::current_process_id(), os::current_thread_id());
 161   }
 162 
 163   return buf;
 164 }
 165 
 166 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
 167                                 char* buf, int buflen, bool verbose) {
 168 #ifdef ZERO
 169   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
 170     // StackFrameStream uses the frame anchor, which may not have
 171     // been set up.  This can be done at any time in Zero, however,
 172     // so if it hasn't been set up then we just set it up now and
 173     // clear it again when we're done.
 174     bool has_last_Java_frame = jt->has_last_Java_frame();
 175     if (!has_last_Java_frame)
 176       jt->set_last_Java_frame();
 177     st->print("Java frames:");
 178 
 179     // If the top frame is a Shark frame and the frame anchor isn't
 180     // set up then it's possible that the information in the frame


 243 // occurred when reporting an error, the nested signal/exception handler
 244 // can skip steps that are already (or partially) done. Error reporting will
 245 // continue from the next step. This allows us to retrieve and print
 246 // information that may be unsafe to get after a fatal error. If it happens,
 247 // you may find nested report_and_die() frames when you look at the stack
 248 // in a debugger.
 249 //
 250 // In general, a hang in error handler is much worse than a crash or internal
 251 // error, as it's harder to recover from a hang. Deadlock can happen if we
 252 // try to grab a lock that is already owned by current thread, or if the
 253 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
 254 // error handler and all the functions it called should avoid grabbing any
 255 // lock. An important thing to notice is that memory allocation needs a lock.
 256 //
 257 // We should avoid using large stack allocated buffers. Many errors happen
 258 // when stack space is already low. Making things even worse is that there
 259 // could be nested report_and_die() calls on stack (see above). Only one
 260 // thread can report error, so large buffers are statically allocated in data
 261 // segment.
 262 
 263 int          VMError::_current_step;
 264 const char*  VMError::_current_step_info;
 265 int          VMError::_verbose;
 266 
 267 void VMError::report(outputStream* st, int id, const char* message, const char* detail_fmt,
 268                      va_list detail_args, Thread* thread, address pc, void* siginfo, void* context,
 269                      const char* filename, int lineno, size_t size) {
 270 # define BEGIN if (_current_step == 0) { _current_step = 1;
 271 # define STEP(n, s) } if (_current_step < n) { _current_step = n; _current_step_info = s;
 272 # define END }
 273 
 274   // don't allocate large buffer on stack
 275   static char buf[O_BUFLEN];
 276 
 277   BEGIN
 278 
 279   STEP(10, "(printing fatal error message)")
 280 
 281     st->print_cr("#");
 282     if (should_report_bug(id)) {
 283       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
 284     } else {
 285       st->print_cr("# There is insufficient memory for the Java "
 286                    "Runtime Environment to continue.");
 287     }
 288 
 289 #ifndef PRODUCT
 290   // Error handler self tests
 291 
 292   // test secondary error handling. Test it twice, to test that resetting
 293   // error handler after a secondary crash works.
 294   STEP(20, "(test secondary crash 1)")
 295     if (_verbose && TestCrashInErrorHandler != 0) {
 296       st->print_cr("Will crash now (TestCrashInErrorHandler=%d)...",
 297         TestCrashInErrorHandler);
 298       controlled_crash(TestCrashInErrorHandler);
 299     }
 300 
 301   STEP(30, "(test secondary crash 2)")
 302     if (_verbose && TestCrashInErrorHandler != 0) {


 311     if (_verbose && TestSafeFetchInErrorHandler) {
 312       st->print_cr("Will test SafeFetch...");
 313       if (CanUseSafeFetch32()) {
 314         int* const invalid_pointer = (int*) get_segfault_address();
 315         const int x = 0x76543210;
 316         int i1 = SafeFetch32(invalid_pointer, x);
 317         int i2 = SafeFetch32(invalid_pointer, x);
 318         if (i1 == x && i2 == x) {
 319           st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
 320         } else {
 321           st->print_cr("??");
 322         }
 323       } else {
 324         st->print_cr("not possible; skipped.");
 325       }
 326     }
 327 #endif // PRODUCT
 328 
 329   STEP(50, "(printing type of error)")
 330 
 331      switch(id) {
 332        case OOM_MALLOC_ERROR:
 333        case OOM_MMAP_ERROR:
 334          if (size) {
 335            st->print("# Native memory allocation ");
 336            st->print((id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
 337                                                  "(mmap) failed to map ");
 338            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, size);
 339            st->print("%s", buf);
 340            st->print(" bytes");
 341            if (detail_fmt != NULL) {
 342              st->print(" for ");
 343              st->vprint(detail_fmt, detail_args);
 344            }
 345            st->cr();
 346          } else {
 347            if (detail_fmt != NULL) {
 348              st->print("# ");
 349              st->vprint_cr(detail_fmt, detail_args);
 350            }
 351          }
 352          // In error file give some solutions
 353          if (_verbose) {
 354            print_oom_reasons(st);
 355          } else {
 356            return;  // that's enough for the screen
 357          }
 358          break;
 359        case INTERNAL_ERROR:
 360        default:
 361          break;
 362      }
 363 
 364   STEP(60, "(printing exception/signal name)")
 365 
 366      st->print_cr("#");
 367      st->print("#  ");
 368      // Is it an OS exception/signal?
 369      if (os::exception_name(id, buf, sizeof(buf))) {
 370        st->print("%s", buf);
 371        st->print(" (0x%x)", id);                // signal number
 372        st->print(" at pc=" PTR_FORMAT, pc);
 373      } else {
 374        if (should_report_bug(id)) {
 375          st->print("Internal Error");
 376        } else {
 377          st->print("Out of Memory Error");
 378        }
 379        if (filename != NULL && lineno > 0) {
 380 #ifdef PRODUCT
 381          // In product mode chop off pathname?
 382          char separator = os::file_separator()[0];
 383          const char *p = strrchr(filename, separator);
 384          const char *file = p ? p+1 : filename;
 385 #else
 386          const char *file = filename;
 387 #endif
 388          st->print(" (%s:%d)", file, lineno);
 389        } else {
 390          st->print(" (0x%x)", id);
 391        }
 392      }
 393 
 394   STEP(70, "(printing current thread and pid)")
 395 
 396      // process id, thread id
 397      st->print(", pid=%d", os::current_process_id());
 398      st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
 399      st->cr();
 400 
 401   STEP(80, "(printing error message)")
 402 
 403      if (should_report_bug(id)) {  // already printed the message.
 404        // error message
 405        if (detail_fmt) {
 406          st->print("#  %s: ", message ? message : "Error");
 407          st->vprint_cr(detail_fmt, detail_args);
 408        } else if (message) {
 409          st->print_cr("#  Error: %s", message);
 410        }
 411     }
 412 
 413   STEP(90, "(printing Java version string)")
 414 
 415      // VM version
 416      st->print_cr("#");
 417      JDK_Version::current().to_string(buf, sizeof(buf));
 418      const char* runtime_name = JDK_Version::runtime_name() != NULL ?
 419                                   JDK_Version::runtime_name() : "";
 420      const char* runtime_version = JDK_Version::runtime_version() != NULL ?
 421                                   JDK_Version::runtime_version() : "";
 422      st->print_cr("# JRE version: %s (%s) (build %s)", runtime_name, buf, runtime_version);
 423      // This is the long version with some default settings added
 424      st->print_cr("# Java VM: %s (%s, %s%s%s, %s, %s)",
 425                    Abstract_VM_Version::vm_name(),
 426                    Abstract_VM_Version::vm_release(),
 427                    Abstract_VM_Version::vm_info_string(),
 428                    TieredCompilation ? ", tiered" : "",
 429                    UseCompressedOops ? ", compressed oops" : "",
 430                    gc_mode(),
 431                    Abstract_VM_Version::vm_platform_string()
 432                  );
 433 
 434   STEP(100, "(printing problematic frame)")
 435 
 436      // Print current frame if we have a context (i.e. it's a crash)
 437      if (context) {
 438        st->print_cr("# Problematic frame:");
 439        st->print("# ");
 440        frame fr = os::fetch_frame_from_context(context);
 441        fr.print_on_error(st, buf, sizeof(buf));
 442        st->cr();
 443        st->print_cr("#");
 444      }
 445 
 446   STEP(110, "(printing core file information)")
 447     st->print("# ");
 448     if (CreateCoredumpOnCrash) {
 449       if (coredump_status) {
 450         st->print("Core dump will be written. Default location: %s", coredump_message);
 451       } else {
 452         st->print("No core dump will be written. %s", coredump_message);
 453       }
 454     } else {
 455       st->print("CreateCoredumpOnCrash turned off, no core file dumped");
 456     }
 457     st->cr();
 458     st->print_cr("#");
 459 
 460   STEP(120, "(printing bug submit message)")
 461 
 462      if (should_report_bug(id) && _verbose) {
 463        print_bug_submit_message(st, thread);
 464      }
 465 
 466   STEP(130, "(printing summary)" )
 467 
 468      if (_verbose) {
 469        st->cr();
 470        st->print_cr("---------------  S U M M A R Y ------------");
 471        st->cr();
 472      }
 473 
 474   STEP(140, "(printing VM option summary)" )
 475 
 476      if (_verbose) {
 477        // VM options
 478        Arguments::print_summary_on(st);
 479        st->cr();
 480      }
 481 
 482   STEP(150, "(printing summary machine and OS info)")
 483 


 487 
 488 
 489   STEP(160, "(printing date and time)" )
 490 
 491      if (_verbose) {
 492        os::print_date_and_time(st, buf, sizeof(buf));
 493      }
 494 
 495   STEP(170, "(printing thread)" )
 496 
 497      if (_verbose) {
 498        st->cr();
 499        st->print_cr("---------------  T H R E A D  ---------------");
 500        st->cr();
 501      }
 502 
 503   STEP(180, "(printing current thread)" )
 504 
 505      // current thread
 506      if (_verbose) {
 507        if (thread) {
 508          st->print("Current thread (" PTR_FORMAT "):  ", thread);
 509          thread->print_on_error(st, buf, sizeof(buf));
 510          st->cr();
 511        } else {
 512          st->print_cr("Current thread is native thread");
 513        }
 514        st->cr();
 515      }
 516 
 517   STEP(190, "(printing current compile task)" )
 518 
 519      if (_verbose && thread && thread->is_Compiler_thread()) {
 520         CompilerThread* t = (CompilerThread*)thread;
 521         if (t->task()) {
 522            st->cr();
 523            st->print_cr("Current CompileTask:");
 524            t->task()->print_line_on_error(st, buf, sizeof(buf));
 525            st->cr();
 526         }
 527      }
 528 
 529 
 530   STEP(200, "(printing stack bounds)" )
 531 
 532      if (_verbose) {
 533        st->print("Stack: ");
 534 
 535        address stack_top;
 536        size_t stack_size;
 537 
 538        if (thread) {
 539           stack_top = thread->stack_base();
 540           stack_size = thread->stack_size();
 541        } else {
 542           stack_top = os::current_stack_base();
 543           stack_size = os::current_stack_size();
 544        }
 545 
 546        address stack_bottom = stack_top - stack_size;
 547        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", stack_bottom, stack_top);
 548 
 549        frame fr = context ? os::fetch_frame_from_context(context)
 550                            : os::current_frame();
 551 
 552        if (fr.sp()) {
 553          st->print(",  sp=" PTR_FORMAT, fr.sp());
 554          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
 555          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
 556        }
 557 
 558        st->cr();
 559      }
 560 
 561   STEP(210, "(printing native stack)" )
 562 
 563    if (_verbose) {
 564      if (os::platform_print_native_stack(st, context, buf, sizeof(buf))) {
 565        // We have printed the native stack in platform-specific code
 566        // Windows/x64 needs special handling.
 567      } else {
 568        frame fr = context ? os::fetch_frame_from_context(context)
 569                           : os::current_frame();
 570 
 571        print_native_stack(st, fr, thread, buf, sizeof(buf));
 572      }
 573    }
 574 
 575   STEP(220, "(printing Java stack)" )
 576 
 577      if (_verbose && thread && thread->is_Java_thread()) {
 578        print_stack_trace(st, (JavaThread*)thread, buf, sizeof(buf));
 579      }
 580 
 581   STEP(230, "(printing target Java thread stack)" )
 582 
 583      // printing Java thread stack trace if it is involved in GC crash
 584      if (_verbose && thread && (thread->is_Named_thread())) {
 585        JavaThread*  jt = ((NamedThread *)thread)->processed_thread();
 586        if (jt != NULL) {
 587          st->print_cr("JavaThread " PTR_FORMAT " (nid = " UINTX_FORMAT ") was being processed", jt, jt->osthread()->thread_id());
 588          print_stack_trace(st, jt, buf, sizeof(buf), true);
 589        }
 590      }
 591 
 592   STEP(240, "(printing siginfo)" )
 593 
 594      // signal no, signal code, address that caused the fault
 595      if (_verbose && siginfo) {
 596        st->cr();
 597        os::print_siginfo(st, siginfo);
 598        st->cr();
 599      }
 600 
 601   STEP(250, "(printing register info)")
 602 
 603      // decode register contents if possible
 604      if (_verbose && context && Universe::is_fully_initialized()) {
 605        os::print_register_info(st, context);
 606        st->cr();
 607      }
 608 
 609   STEP(260, "(printing registers, top of stack, instructions near pc)")
 610 
 611      // registers, top of stack, instructions near pc
 612      if (_verbose && context) {
 613        os::print_context(st, context);
 614        st->cr();
 615      }
 616 
 617   STEP(270, "(printing VM operation)" )
 618 
 619      if (_verbose && thread && thread->is_VM_thread()) {
 620         VMThread* t = (VMThread*)thread;
 621         VM_Operation* op = t->vm_operation();
 622         if (op) {
 623           op->print_on_error(st);
 624           st->cr();
 625           st->cr();
 626         }
 627      }
 628 
 629   STEP(280, "(printing process)" )
 630 
 631      if (_verbose) {
 632        st->cr();
 633        st->print_cr("---------------  P R O C E S S  ---------------");
 634        st->cr();
 635      }
 636 
 637   STEP(290, "(printing all threads)" )
 638 
 639      // all threads
 640      if (_verbose && thread) {
 641        Threads::print_on_error(st, thread, buf, sizeof(buf));
 642        st->cr();
 643      }
 644 
 645   STEP(300, "(printing VM state)" )
 646 
 647      if (_verbose) {
 648        // Safepoint state
 649        st->print("VM state:");
 650 
 651        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
 652        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
 653        else st->print("not at safepoint");
 654 
 655        // Also see if error occurred during initialization or shutdown
 656        if (!Universe::is_fully_initialized()) {
 657          st->print(" (not fully initialized)");
 658        } else if (VM_Exit::vm_exited()) {
 659          st->print(" (shutting down)");
 660        } else {
 661          st->print(" (normal execution)");


 789 
 790      if (_verbose) {
 791        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
 792        st->cr();
 793      }
 794 
 795   // print a defined marker to show that error handling finished correctly.
 796   STEP(480, "(printing end marker)" )
 797 
 798      if (_verbose) {
 799        st->print_cr("END.");
 800      }
 801 
 802   END
 803 
 804 # undef BEGIN
 805 # undef STEP
 806 # undef END
 807 }
 808 

 809 volatile jlong VMError::first_error_tid = -1;
 810 
 811 // An error could happen before tty is initialized or after it has been
 812 // destroyed. Here we use a very simple unbuffered fdStream for printing.
 813 // Only out.print_raw() and out.print_raw_cr() should be used, as other
 814 // printing methods need to allocate large buffer on stack. To format a
 815 // string, use jio_snprintf() with a static buffer or use staticBufferStream.
 816 fdStream VMError::out(defaultStream::output_fd());
 817 fdStream VMError::log; // error log used by VMError::report_and_die()
 818 
 819 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
 820 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
 821   int fd = -1;
 822   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
 823     // the O_EXCL flag will cause the open to fail if the file exists
 824     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
 825   }
 826   return fd;
 827 }
 828 


 850       if (fsep_len > 0) {
 851         fd = expand_and_open(default_pattern, buf, buflen, pos);
 852       }
 853     }
 854   }
 855 
 856    // try temp directory if it exists.
 857    if (fd == -1) {
 858      const char* tmpdir = os::get_temp_directory();
 859      if (tmpdir != NULL && strlen(tmpdir) > 0) {
 860        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
 861        if (pos > 0) {
 862          fd = expand_and_open(default_pattern, buf, buflen, pos);
 863        }
 864      }
 865    }
 866 
 867   return fd;
 868 }
 869 
 870 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
 871                              void* context, const char* detail_fmt, ...)
 872 {
 873   va_list detail_args;
 874   va_start(detail_args, detail_fmt);
 875   report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
 876   va_end(detail_args);
 877 }
 878 
 879 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
 880 {
 881   report_and_die(thread, sig, pc, siginfo, context, "%s", "");
 882 }
 883 
 884 void VMError::report_and_die(const char* message, const char* detail_fmt, ...)
 885 {
 886   va_list detail_args;
 887   va_start(detail_args, detail_fmt);
 888   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, NULL, NULL, NULL, NULL, NULL, 0, 0);
 889   va_end(detail_args);
 890 }
 891 
 892 void VMError::report_and_die(const char* message)
 893 {
 894   report_and_die(message, "%s", "");
 895 }
 896 
 897 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, const char* message,
 898                              const char* detail_fmt, va_list detail_args)
 899 {
 900   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, 0);
 901 }
 902 
 903 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
 904                              VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
 905   report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
 906 }
 907 
 908 void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
 909                              Thread* thread, address pc, void* siginfo, void* context, const char* filename,
 910                              int lineno, size_t size)
 911 {
 912   // Don't allocate large buffer on stack
 913   static char buffer[O_BUFLEN];
 914 
 915   // How many errors occurred in error handler when reporting first_error.
 916   static int recursive_error_count;
 917 
 918   // We will first print a brief message to standard out (verbose = false),
 919   // then save detailed information in log file (verbose = true).
 920   static bool out_done = false;         // done printing to standard out
 921   static bool log_done = false;         // done saving error log
 922   static bool transmit_report_done = false; // done error reporting
 923 
 924   if (SuppressFatalErrorMessage) {
 925       os::abort(CreateCoredumpOnCrash);
 926   }
 927   jlong mytid = os::current_thread_id();
 928   if (first_error_tid == -1 &&
 929       Atomic::cmpxchg(mytid, &first_error_tid, -1) == -1) {
 930 
 931     // first time

 932     set_error_reported();
 933 
 934     if (ShowMessageBoxOnError || PauseAtExit) {
 935       va_list tmp_args;
 936       va_copy(tmp_args, detail_args);
 937       show_message_box(buffer, sizeof(buffer), id, message, detail_fmt, tmp_args, pc, filename, lineno);
 938       va_end(tmp_args);
 939 
 940       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
 941       // WatcherThread can kill JVM if the error handler hangs.
 942       ShowMessageBoxOnError = false;
 943     }
 944 
 945     os::check_dump_limit(buffer, sizeof(buffer));
 946 
 947     // reset signal handlers or exception filter; make sure recursive crashes
 948     // are handled properly.
 949     reset_signal_handlers();
 950 
 951   } else {
 952     // If UseOsErrorReporting we call this for each level of the call stack
 953     // while searching for the exception handler.  Only the first level needs
 954     // to be reported.
 955     if (UseOSErrorReporting && log_done) return;
 956 
 957     // This is not the first error, see if it happened in a different thread
 958     // or in the same thread during error reporting.
 959     if (first_error_tid != mytid) {
 960       char msgbuf[64];
 961       jio_snprintf(msgbuf, sizeof(msgbuf),
 962                    "[thread " INT64_FORMAT " also had an error]",
 963                    mytid);
 964       out.print_raw_cr(msgbuf);
 965 
 966       // error reporting is not MT-safe, block current thread
 967       os::infinite_sleep();
 968 
 969     } else {
 970       if (recursive_error_count++ > 30) {
 971         out.print_raw_cr("[Too many errors, abort]");
 972         os::die();
 973       }
 974 
 975       jio_snprintf(buffer, sizeof(buffer),
 976                    "[error occurred during error reporting %s, id 0x%x]",
 977                    _current_step_info, id);

 978       if (log.is_open()) {
 979         log.cr();
 980         log.print_raw_cr(buffer);
 981         log.cr();
 982       } else {
 983         out.cr();
 984         out.print_raw_cr(buffer);
 985         out.cr();
 986       }
 987     }
 988   }
 989 
 990   // print to screen
 991   if (!out_done) {
 992     _verbose = false;
 993 
 994     staticBufferStream sbs(buffer, sizeof(buffer), &out);
 995     va_list tmp_args;
 996     va_copy(tmp_args, detail_args);
 997     report(&sbs, id, message, detail_fmt, tmp_args, thread, pc, siginfo, context, filename, lineno, size);
 998     va_end(tmp_args);
 999 
1000     out_done = true;
1001 
1002     _current_step = 0;         // reset current_step
1003     _current_step_info = "";   // reset current_step string
1004   }
1005 
1006   // print to error log file
1007   if (!log_done) {
1008     _verbose = true;
1009 
1010     // see if log file is already open
1011     if (!log.is_open()) {
1012       // open log file
1013       int fd = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1014       if (fd != -1) {
1015         out.print_raw("# An error report file with more information is saved as:\n# ");
1016         out.print_raw_cr(buffer);
1017 
1018         log.set_fd(fd);
1019       } else {
1020         out.print_raw_cr("# Can not save log file, dump to screen..");
1021         log.set_fd(defaultStream::output_fd());
1022         /* Error reporting currently needs dumpfile.
1023          * Maybe implement direct streaming in the future.*/
1024         transmit_report_done = true;
1025       }
1026     }
1027 
1028     staticBufferStream sbs(buffer, O_BUFLEN, &log);
1029     va_list tmp_args;
1030     va_copy(tmp_args, detail_args);
1031     report(&sbs, id, message, detail_fmt, tmp_args, thread, pc, siginfo, context, filename, lineno, size);
1032     va_end(tmp_args);
1033     _current_step = 0;         // reset current_step
1034     _current_step_info = "";   // reset current_step string
1035 
1036     // Run error reporting to determine whether or not to report the crash.
1037     if (!transmit_report_done && should_report_bug(id)) {
1038       transmit_report_done = true;
1039       const int fd2 = ::dup(log.fd());
1040       FILE* const hs_err = ::fdopen(fd2, "r");
1041       if (NULL != hs_err) {
1042         ErrorReporter er;
1043         er.call(hs_err, buffer, O_BUFLEN);
1044       }
1045       ::fclose(hs_err);
1046     }
1047 
1048     if (log.fd() != defaultStream::output_fd()) {
1049       close(log.fd());
1050     }
1051 
1052     log.set_fd(-1);
1053     log_done = true;
1054   }
1055 
1056 
1057   static bool skip_OnError = false;


1069       out.print_raw   ("#   Executing ");
1070 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1071       out.print_raw   ("/bin/sh -c ");
1072 #elif defined(SOLARIS)
1073       out.print_raw   ("/usr/bin/sh -c ");
1074 #endif
1075       out.print_raw   ("\"");
1076       out.print_raw   (cmd);
1077       out.print_raw_cr("\" ...");
1078 
1079       if (os::fork_and_exec(cmd) < 0) {
1080         out.print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1081       }
1082     }
1083 
1084     // done with OnError
1085     OnError = NULL;
1086   }
1087 
1088   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1089   if (DumpReplayDataOnError && thread && thread->is_Compiler_thread() && !skip_replay) {
1090     skip_replay = true;
1091     ciEnv* env = ciEnv::current();
1092     if (env != NULL) {
1093       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1094       if (fd != -1) {
1095         FILE* replay_data_file = os::open(fd, "w");
1096         if (replay_data_file != NULL) {
1097           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1098           env->dump_replay_data_unsafe(&replay_data_stream);
1099           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1100           out.print_raw_cr(buffer);
1101         } else {
1102           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1103           out.print_raw_cr(strerror(os::get_last_error()));
1104         }
1105       }
1106     }
1107   }
1108 
1109   static bool skip_bug_url = !should_report_bug(id);
1110   if (!skip_bug_url) {
1111     skip_bug_url = true;
1112 
1113     out.print_raw_cr("#");
1114     print_bug_submit_message(&out, thread);
1115   }
1116 
1117   if (!UseOSErrorReporting) {
1118     // os::abort() will call abort hooks, try it first.
1119     static bool skip_os_abort = false;
1120     if (!skip_os_abort) {
1121       skip_os_abort = true;
1122       bool dump_core = should_report_bug(id);
1123       os::abort(dump_core && CreateCoredumpOnCrash, siginfo, context);
1124     }
1125 
1126     // if os::abort() doesn't abort, try os::die();
1127     os::die();
1128   }
1129 }
1130 
1131 /*
1132  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1133  * ensures utilities such as jmap can observe the process is a consistent state.
1134  */
1135 class VM_ReportJavaOutOfMemory : public VM_Operation {
1136  private:
1137   const char* _message;
1138  public:
1139   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
1140   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1141   void doit();
1142 };
1143 
1144 void VM_ReportJavaOutOfMemory::doit() {
1145   // Don't allocate large buffer on stack
1146   static char buffer[O_BUFLEN];
1147 
1148   tty->print_cr("#");
1149   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1150   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1151 
1152   // make heap parsability
1153   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1154 
1155   char* cmd;
1156   const char* ptr = OnOutOfMemoryError;
1157   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1158     tty->print("#   Executing ");
1159 #if defined(LINUX)
1160     tty->print  ("/bin/sh -c ");
1161 #elif defined(SOLARIS)
1162     tty->print  ("/usr/bin/sh -c ");
1163 #endif
1164     tty->print_cr("\"%s\"...", cmd);
1165 
1166     if (os::fork_and_exec(cmd) < 0) {
1167       tty->print_cr("os::fork_and_exec failed: %s (%d)", strerror(errno), errno);
1168     }
1169   }
1170 }
1171 
1172 void VMError::report_java_out_of_memory(const char* message) {
1173   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1174     MutexLocker ml(Heap_lock);
1175     VM_ReportJavaOutOfMemory op(message);
1176     VMThread::execute(&op);
1177   }
1178 }
< prev index next >