1 /*
2  * Copyright (c) 2003, 2019, 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 "precompiled.hpp"
26 #include "jvm.h"
27 #include "code/codeCache.hpp"
28 #include "compiler/compileBroker.hpp"
29 #include "compiler/disassembler.hpp"
30 #include "gc/shared/gcConfig.hpp"
31 #include "logging/logConfiguration.hpp"
32 #include "jfr/jfrEvents.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "prims/whitebox.hpp"
35 #include "runtime/arguments.hpp"
36 #include "runtime/atomic.hpp"
37 #include "runtime/frame.inline.hpp"
38 #include "runtime/init.hpp"
39 #include "runtime/os.hpp"
40 #include "runtime/thread.inline.hpp"
41 #include "runtime/threadSMR.hpp"
42 #include "runtime/vmThread.hpp"
43 #include "runtime/vmOperations.hpp"
44 #include "runtime/vm_version.hpp"
45 #include "runtime/flags/jvmFlag.hpp"
46 #include "services/memTracker.hpp"
47 #include "utilities/debug.hpp"
48 #include "utilities/decoder.hpp"
49 #include "utilities/defaultStream.hpp"
50 #include "utilities/errorReporter.hpp"
51 #include "utilities/events.hpp"
52 #include "utilities/vmError.hpp"
53 #include "utilities/macros.hpp"
54 #if INCLUDE_JFR
55 #include "jfr/jfr.hpp"
56 #endif
57 
58 #ifndef PRODUCT
59 #include <signal.h>
60 #endif // PRODUCT
61 
62 bool VMError::_error_reported = false;
63 
64 // call this when the VM is dying--it might loosen some asserts
is_error_reported()65 bool VMError::is_error_reported() { return _error_reported; }
66 
67 // returns an address which is guaranteed to generate a SIGSEGV on read,
68 // for test purposes, which is not NULL and contains bits in every word
get_segfault_address()69 void* VMError::get_segfault_address() {
70   return (void*)
71 #ifdef _LP64
72     0xABC0000000000ABCULL;
73 #else
74     0x00000ABC;
75 #endif
76 }
77 
78 // List of environment variables that should be reported in error log file.
79 const char *env_list[] = {
80   // All platforms
81   "JAVA_HOME", "JRE_HOME", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH",
82   "JAVA_COMPILER", "PATH", "USERNAME",
83 
84   // Env variables that are defined on Solaris/Linux/BSD
85   "LD_LIBRARY_PATH", "LD_PRELOAD", "SHELL", "DISPLAY",
86   "HOSTTYPE", "OSTYPE", "ARCH", "MACHTYPE",
87   "LANG", "LC_ALL", "LC_CTYPE", "TZ",
88 
89   // defined on Linux
90   "LD_ASSUME_KERNEL", "_JAVA_SR_SIGNUM",
91 
92   // defined on Darwin
93   "DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH",
94   "DYLD_FRAMEWORK_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH",
95   "DYLD_INSERT_LIBRARIES",
96 
97   // defined on Windows
98   "OS", "PROCESSOR_IDENTIFIER", "_ALT_JAVA_HOME_DIR",
99 
100   (const char *)0
101 };
102 
103 // A simple parser for -XX:OnError, usage:
104 //  ptr = OnError;
105 //  while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr) != NULL)
106 //     ... ...
next_OnError_command(char * buf,int buflen,const char ** ptr)107 static char* next_OnError_command(char* buf, int buflen, const char** ptr) {
108   if (ptr == NULL || *ptr == NULL) return NULL;
109 
110   const char* cmd = *ptr;
111 
112   // skip leading blanks or ';'
113   while (*cmd == ' ' || *cmd == ';') cmd++;
114 
115   if (*cmd == '\0') return NULL;
116 
117   const char * cmdend = cmd;
118   while (*cmdend != '\0' && *cmdend != ';') cmdend++;
119 
120   Arguments::copy_expand_pid(cmd, cmdend - cmd, buf, buflen);
121 
122   *ptr = (*cmdend == '\0' ? cmdend : cmdend + 1);
123   return buf;
124 }
125 
print_bug_submit_message(outputStream * out,Thread * thread)126 static void print_bug_submit_message(outputStream *out, Thread *thread) {
127   if (out == NULL) return;
128   const char *url = Arguments::java_vendor_url_bug();
129   if (url == NULL || *url == '\0')
130     url = JDK_Version::runtime_vendor_vm_bug_url();
131   if (url != NULL && *url != '\0') {
132     out->print_raw_cr("# If you would like to submit a bug report, please visit:");
133     out->print_raw   ("#   ");
134     out->print_raw_cr(url);
135   }
136   // If the crash is in native code, encourage user to submit a bug to the
137   // provider of that code.
138   if (thread && thread->is_Java_thread() &&
139       !thread->is_hidden_from_external_view()) {
140     JavaThread* jt = (JavaThread*)thread;
141     if (jt->thread_state() == _thread_in_native) {
142       out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug.");
143     }
144   }
145   out->print_raw_cr("#");
146 }
147 
148 bool VMError::coredump_status;
149 char VMError::coredump_message[O_BUFLEN];
150 
record_coredump_status(const char * message,bool status)151 void VMError::record_coredump_status(const char* message, bool status) {
152   coredump_status = status;
153   strncpy(coredump_message, message, sizeof(coredump_message));
154   coredump_message[sizeof(coredump_message)-1] = 0;
155 }
156 
157 // Return a string to describe the error
error_string(char * buf,int buflen)158 char* VMError::error_string(char* buf, int buflen) {
159   char signame_buf[64];
160   const char *signame = os::exception_name(_id, signame_buf, sizeof(signame_buf));
161 
162   if (signame) {
163     jio_snprintf(buf, buflen,
164                  "%s (0x%x) at pc=" PTR_FORMAT ", pid=%d, tid=" UINTX_FORMAT,
165                  signame, _id, _pc,
166                  os::current_process_id(), os::current_thread_id());
167   } else if (_filename != NULL && _lineno > 0) {
168     // skip directory names
169     char separator = os::file_separator()[0];
170     const char *p = strrchr(_filename, separator);
171     int n = jio_snprintf(buf, buflen,
172                          "Internal Error at %s:%d, pid=%d, tid=" UINTX_FORMAT,
173                          p ? p + 1 : _filename, _lineno,
174                          os::current_process_id(), os::current_thread_id());
175     if (n >= 0 && n < buflen && _message) {
176       if (strlen(_detail_msg) > 0) {
177         jio_snprintf(buf + n, buflen - n, "%s%s: %s",
178         os::line_separator(), _message, _detail_msg);
179       } else {
180         jio_snprintf(buf + n, buflen - n, "%sError: %s",
181                      os::line_separator(), _message);
182       }
183     }
184   } else {
185     jio_snprintf(buf, buflen,
186                  "Internal Error (0x%x), pid=%d, tid=" UINTX_FORMAT,
187                  _id, os::current_process_id(), os::current_thread_id());
188   }
189 
190   return buf;
191 }
192 
print_stack_trace(outputStream * st,JavaThread * jt,char * buf,int buflen,bool verbose)193 void VMError::print_stack_trace(outputStream* st, JavaThread* jt,
194                                 char* buf, int buflen, bool verbose) {
195 #ifdef ZERO
196   if (jt->zero_stack()->sp() && jt->top_zero_frame()) {
197     // StackFrameStream uses the frame anchor, which may not have
198     // been set up.  This can be done at any time in Zero, however,
199     // so if it hasn't been set up then we just set it up now and
200     // clear it again when we're done.
201     bool has_last_Java_frame = jt->has_last_Java_frame();
202     if (!has_last_Java_frame)
203       jt->set_last_Java_frame();
204     st->print("Java frames:");
205     st->cr();
206 
207     // Print the frames
208     StackFrameStream sfs(jt);
209     for(int i = 0; !sfs.is_done(); sfs.next(), i++) {
210       sfs.current()->zero_print_on_error(i, st, buf, buflen);
211       st->cr();
212     }
213 
214     // Reset the frame anchor if necessary
215     if (!has_last_Java_frame)
216       jt->reset_last_Java_frame();
217   }
218 #else
219   if (jt->has_last_Java_frame()) {
220     st->print_cr("Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)");
221     for(StackFrameStream sfs(jt); !sfs.is_done(); sfs.next()) {
222       sfs.current()->print_on_error(st, buf, buflen, verbose);
223       st->cr();
224     }
225   }
226 #endif // ZERO
227 }
228 
print_native_stack(outputStream * st,frame fr,Thread * t,char * buf,int buf_size)229 void VMError::print_native_stack(outputStream* st, frame fr, Thread* t, char* buf, int buf_size) {
230 
231   // see if it's a valid frame
232   if (fr.pc()) {
233     st->print_cr("Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)");
234 
235     int count = 0;
236     while (count++ < StackPrintLimit) {
237       fr.print_on_error(st, buf, buf_size);
238       if (fr.pc()) { // print source file and line, if available
239         char buf[128];
240         int line_no;
241         if (Decoder::get_source_info(fr.pc(), buf, sizeof(buf), &line_no)) {
242           st->print("  (%s:%d)", buf, line_no);
243         }
244       }
245       st->cr();
246       // Compiled code may use EBP register on x86 so it looks like
247       // non-walkable C frame. Use frame.sender() for java frames.
248       if (t && t->is_Java_thread()) {
249         // Catch very first native frame by using stack address.
250         // For JavaThread stack_base and stack_size should be set.
251         if (!t->on_local_stack((address)(fr.real_fp() + 1))) {
252           break;
253         }
254         if (fr.is_java_frame() || fr.is_native_frame() || fr.is_runtime_frame()) {
255           RegisterMap map((JavaThread*)t, false); // No update
256           fr = fr.sender(&map);
257         } else {
258           // is_first_C_frame() does only simple checks for frame pointer,
259           // it will pass if java compiled code has a pointer in EBP.
260           if (os::is_first_C_frame(&fr)) break;
261           fr = os::get_sender_for_C_frame(&fr);
262         }
263       } else {
264         if (os::is_first_C_frame(&fr)) break;
265         fr = os::get_sender_for_C_frame(&fr);
266       }
267     }
268 
269     if (count > StackPrintLimit) {
270       st->print_cr("...<more frames>...");
271     }
272 
273     st->cr();
274   }
275 }
276 
print_oom_reasons(outputStream * st)277 static void print_oom_reasons(outputStream* st) {
278   st->print_cr("# Possible reasons:");
279   st->print_cr("#   The system is out of physical RAM or swap space");
280   if (UseCompressedOops) {
281     st->print_cr("#   The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap");
282   }
283   if (LogBytesPerWord == 2) {
284     st->print_cr("#   In 32 bit mode, the process size limit was hit");
285   }
286   st->print_cr("# Possible solutions:");
287   st->print_cr("#   Reduce memory load on the system");
288   st->print_cr("#   Increase physical memory or swap space");
289   st->print_cr("#   Check if swap backing store is full");
290   if (LogBytesPerWord == 2) {
291     st->print_cr("#   Use 64 bit Java on a 64 bit OS");
292   }
293   st->print_cr("#   Decrease Java heap size (-Xmx/-Xms)");
294   st->print_cr("#   Decrease number of Java threads");
295   st->print_cr("#   Decrease Java thread stack sizes (-Xss)");
296   st->print_cr("#   Set larger code cache with -XX:ReservedCodeCacheSize=");
297   if (UseCompressedOops) {
298     switch (Universe::narrow_oop_mode()) {
299       case Universe::UnscaledNarrowOop:
300         st->print_cr("#   JVM is running with Unscaled Compressed Oops mode in which the Java heap is");
301         st->print_cr("#     placed in the first 4GB address space. The Java Heap base address is the");
302         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
303         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 4GB virtual address.");
304         break;
305       case Universe::ZeroBasedNarrowOop:
306         st->print_cr("#   JVM is running with Zero Based Compressed Oops mode in which the Java heap is");
307         st->print_cr("#     placed in the first 32GB address space. The Java Heap base address is the");
308         st->print_cr("#     maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress");
309         st->print_cr("#     to set the Java Heap base and to place the Java Heap above 32GB virtual address.");
310         break;
311       default:
312         break;
313     }
314   }
315   st->print_cr("# This output file may be truncated or incomplete.");
316 }
317 
report_vm_version(outputStream * st,char * buf,int buflen)318 static void report_vm_version(outputStream* st, char* buf, int buflen) {
319    // VM version
320    st->print_cr("#");
321    JDK_Version::current().to_string(buf, buflen);
322    const char* runtime_name = JDK_Version::runtime_name() != NULL ?
323                                 JDK_Version::runtime_name() : "";
324    const char* runtime_version = JDK_Version::runtime_version() != NULL ?
325                                    JDK_Version::runtime_version() : "";
326    const char* vendor_version = JDK_Version::runtime_vendor_version() != NULL ?
327                                   JDK_Version::runtime_vendor_version() : "";
328    const char* jdk_debug_level = Abstract_VM_Version::printable_jdk_debug_level() != NULL ?
329                                    Abstract_VM_Version::printable_jdk_debug_level() : "";
330 
331    st->print_cr("# JRE version: %s%s%s (%s) (%sbuild %s)", runtime_name,
332                 (*vendor_version != '\0') ? " " : "", vendor_version,
333                 buf, jdk_debug_level, runtime_version);
334 
335    // This is the long version with some default settings added
336    st->print_cr("# Java VM: %s%s%s (%s%s, %s%s%s%s%s, %s, %s)",
337                  Abstract_VM_Version::vm_name(),
338                 (*vendor_version != '\0') ? " " : "", vendor_version,
339                  jdk_debug_level,
340                  Abstract_VM_Version::vm_release(),
341                  Abstract_VM_Version::vm_info_string(),
342                  TieredCompilation ? ", tiered" : "",
343 #if INCLUDE_JVMCI
344                  EnableJVMCI ? ", jvmci" : "",
345                  UseJVMCICompiler ? ", jvmci compiler" : "",
346 #else
347                  "", "",
348 #endif
349                  UseCompressedOops ? ", compressed oops" : "",
350                  GCConfig::hs_err_name(),
351                  Abstract_VM_Version::vm_platform_string()
352                );
353 }
354 
355 // This is the main function to report a fatal error. Only one thread can
356 // call this function, so we don't need to worry about MT-safety. But it's
357 // possible that the error handler itself may crash or die on an internal
358 // error, for example, when the stack/heap is badly damaged. We must be
359 // able to handle recursive errors that happen inside error handler.
360 //
361 // Error reporting is done in several steps. If a crash or internal error
362 // occurred when reporting an error, the nested signal/exception handler
363 // can skip steps that are already (or partially) done. Error reporting will
364 // continue from the next step. This allows us to retrieve and print
365 // information that may be unsafe to get after a fatal error. If it happens,
366 // you may find nested report_and_die() frames when you look at the stack
367 // in a debugger.
368 //
369 // In general, a hang in error handler is much worse than a crash or internal
370 // error, as it's harder to recover from a hang. Deadlock can happen if we
371 // try to grab a lock that is already owned by current thread, or if the
372 // owner is blocked forever (e.g. in os::infinite_sleep()). If possible, the
373 // error handler and all the functions it called should avoid grabbing any
374 // lock. An important thing to notice is that memory allocation needs a lock.
375 //
376 // We should avoid using large stack allocated buffers. Many errors happen
377 // when stack space is already low. Making things even worse is that there
378 // could be nested report_and_die() calls on stack (see above). Only one
379 // thread can report error, so large buffers are statically allocated in data
380 // segment.
381 
382 int          VMError::_current_step;
383 const char*  VMError::_current_step_info;
384 
385 volatile jlong VMError::_reporting_start_time = -1;
386 volatile bool VMError::_reporting_did_timeout = false;
387 volatile jlong VMError::_step_start_time = -1;
388 volatile bool VMError::_step_did_timeout = false;
389 
390 // Helper, return current timestamp for timeout handling.
get_current_timestamp()391 jlong VMError::get_current_timestamp() {
392   return os::javaTimeNanos();
393 }
394 // Factor to translate the timestamp to seconds.
395 #define TIMESTAMP_TO_SECONDS_FACTOR (1000 * 1000 * 1000)
396 
record_reporting_start_time()397 void VMError::record_reporting_start_time() {
398   const jlong now = get_current_timestamp();
399   Atomic::store(now, &_reporting_start_time);
400 }
401 
get_reporting_start_time()402 jlong VMError::get_reporting_start_time() {
403   return Atomic::load(&_reporting_start_time);
404 }
405 
record_step_start_time()406 void VMError::record_step_start_time() {
407   const jlong now = get_current_timestamp();
408   Atomic::store(now, &_step_start_time);
409 }
410 
get_step_start_time()411 jlong VMError::get_step_start_time() {
412   return Atomic::load(&_step_start_time);
413 }
414 
report(outputStream * st,bool _verbose)415 void VMError::report(outputStream* st, bool _verbose) {
416 
417 # define BEGIN if (_current_step == 0) { _current_step = __LINE__;
418 # define STEP(s) } if (_current_step < __LINE__) { _current_step = __LINE__; _current_step_info = s; \
419   record_step_start_time(); _step_did_timeout = false;
420 # define END }
421 
422   // don't allocate large buffer on stack
423   static char buf[O_BUFLEN];
424 
425   BEGIN
426 
427   STEP("printing fatal error message")
428 
429     st->print_cr("#");
430     if (should_report_bug(_id)) {
431       st->print_cr("# A fatal error has been detected by the Java Runtime Environment:");
432     } else {
433       st->print_cr("# There is insufficient memory for the Java "
434                    "Runtime Environment to continue.");
435     }
436 
437 #ifndef PRODUCT
438   // Error handler self tests
439 
440   // test secondary error handling. Test it twice, to test that resetting
441   // error handler after a secondary crash works.
442   STEP("test secondary crash 1")
443     if (_verbose && TestCrashInErrorHandler != 0) {
444       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
445         TestCrashInErrorHandler);
446       controlled_crash(TestCrashInErrorHandler);
447     }
448 
449   STEP("test secondary crash 2")
450     if (_verbose && TestCrashInErrorHandler != 0) {
451       st->print_cr("Will crash now (TestCrashInErrorHandler=" UINTX_FORMAT ")...",
452         TestCrashInErrorHandler);
453       controlled_crash(TestCrashInErrorHandler);
454     }
455 
456   // TestUnresponsiveErrorHandler: We want to test both step timeouts and global timeout.
457   // Step to global timeout ratio is 4:1, so in order to be absolutely sure we hit the
458   // global timeout, let's execute the timeout step five times.
459   // See corresponding test in test/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java
460   #define TIMEOUT_TEST_STEP STEP("test unresponsive error reporting step") \
461     if (_verbose && TestUnresponsiveErrorHandler) { os::infinite_sleep(); }
462   TIMEOUT_TEST_STEP
463   TIMEOUT_TEST_STEP
464   TIMEOUT_TEST_STEP
465   TIMEOUT_TEST_STEP
466   TIMEOUT_TEST_STEP
467 
468   STEP("test safefetch in error handler")
469     // test whether it is safe to use SafeFetch32 in Crash Handler. Test twice
470     // to test that resetting the signal handler works correctly.
471     if (_verbose && TestSafeFetchInErrorHandler) {
472       st->print_cr("Will test SafeFetch...");
473       if (CanUseSafeFetch32()) {
474         int* const invalid_pointer = (int*) get_segfault_address();
475         const int x = 0x76543210;
476         int i1 = SafeFetch32(invalid_pointer, x);
477         int i2 = SafeFetch32(invalid_pointer, x);
478         if (i1 == x && i2 == x) {
479           st->print_cr("SafeFetch OK."); // Correctly deflected and returned default pattern
480         } else {
481           st->print_cr("??");
482         }
483       } else {
484         st->print_cr("not possible; skipped.");
485       }
486     }
487 #endif // PRODUCT
488 
489   STEP("printing type of error")
490 
491      switch(static_cast<unsigned int>(_id)) {
492        case OOM_MALLOC_ERROR:
493        case OOM_MMAP_ERROR:
494          if (_size) {
495            st->print("# Native memory allocation ");
496            st->print((_id == (int)OOM_MALLOC_ERROR) ? "(malloc) failed to allocate " :
497                                                  "(mmap) failed to map ");
498            jio_snprintf(buf, sizeof(buf), SIZE_FORMAT, _size);
499            st->print("%s", buf);
500            st->print(" bytes");
501            if (strlen(_detail_msg) > 0) {
502              st->print(" for ");
503              st->print("%s", _detail_msg);
504            }
505            st->cr();
506          } else {
507            if (strlen(_detail_msg) > 0) {
508              st->print("# ");
509              st->print_cr("%s", _detail_msg);
510            }
511          }
512          // In error file give some solutions
513          if (_verbose) {
514            print_oom_reasons(st);
515          } else {
516            return;  // that's enough for the screen
517          }
518          break;
519        case INTERNAL_ERROR:
520        default:
521          break;
522      }
523 
524   STEP("printing exception/signal name")
525 
526      st->print_cr("#");
527      st->print("#  ");
528      // Is it an OS exception/signal?
529      if (os::exception_name(_id, buf, sizeof(buf))) {
530        st->print("%s", buf);
531        st->print(" (0x%x)", _id);                // signal number
532        st->print(" at pc=" PTR_FORMAT, p2i(_pc));
533        if (_siginfo != NULL && os::signal_sent_by_kill(_siginfo)) {
534          st->print(" (sent by kill)");
535        }
536      } else {
537        if (should_report_bug(_id)) {
538          st->print("Internal Error");
539        } else {
540          st->print("Out of Memory Error");
541        }
542        if (_filename != NULL && _lineno > 0) {
543 #ifdef PRODUCT
544          // In product mode chop off pathname?
545          char separator = os::file_separator()[0];
546          const char *p = strrchr(_filename, separator);
547          const char *file = p ? p+1 : _filename;
548 #else
549          const char *file = _filename;
550 #endif
551          st->print(" (%s:%d)", file, _lineno);
552        } else {
553          st->print(" (0x%x)", _id);
554        }
555      }
556 
557   STEP("printing current thread and pid")
558 
559      // process id, thread id
560      st->print(", pid=%d", os::current_process_id());
561      st->print(", tid=" UINTX_FORMAT, os::current_thread_id());
562      st->cr();
563 
564   STEP("printing error message")
565 
566      if (should_report_bug(_id)) {  // already printed the message.
567        // error message
568        if (strlen(_detail_msg) > 0) {
569          st->print_cr("#  %s: %s", _message ? _message : "Error", _detail_msg);
570        } else if (_message) {
571          st->print_cr("#  Error: %s", _message);
572        }
573      }
574 
575   STEP("printing Java version string")
576 
577      report_vm_version(st, buf, sizeof(buf));
578 
579   STEP("printing problematic frame")
580 
581      // Print current frame if we have a context (i.e. it's a crash)
582      if (_context) {
583        st->print_cr("# Problematic frame:");
584        st->print("# ");
585        frame fr = os::fetch_frame_from_context(_context);
586        fr.print_on_error(st, buf, sizeof(buf));
587        st->cr();
588        st->print_cr("#");
589      }
590 
591   STEP("printing core file information")
592     st->print("# ");
593     if (CreateCoredumpOnCrash) {
594       if (coredump_status) {
595         st->print("Core dump will be written. Default location: %s", coredump_message);
596       } else {
597         st->print("No core dump will be written. %s", coredump_message);
598       }
599     } else {
600       st->print("CreateCoredumpOnCrash turned off, no core file dumped");
601     }
602     st->cr();
603     st->print_cr("#");
604 
605   STEP("printing bug submit message")
606 
607      if (should_submit_bug_report(_id) && _verbose) {
608        print_bug_submit_message(st, _thread);
609      }
610 
611   STEP("printing summary")
612 
613      if (_verbose) {
614        st->cr();
615        st->print_cr("---------------  S U M M A R Y ------------");
616        st->cr();
617      }
618 
619   STEP("printing VM option summary")
620 
621      if (_verbose) {
622        // VM options
623        Arguments::print_summary_on(st);
624        st->cr();
625      }
626 
627   STEP("printing summary machine and OS info")
628 
629      if (_verbose) {
630        os::print_summary_info(st, buf, sizeof(buf));
631      }
632 
633 
634   STEP("printing date and time")
635 
636      if (_verbose) {
637        os::print_date_and_time(st, buf, sizeof(buf));
638      }
639 
640   STEP("printing thread")
641 
642      if (_verbose) {
643        st->cr();
644        st->print_cr("---------------  T H R E A D  ---------------");
645        st->cr();
646      }
647 
648   STEP("printing current thread")
649 
650      // current thread
651      if (_verbose) {
652        if (_thread) {
653          st->print("Current thread (" PTR_FORMAT "):  ", p2i(_thread));
654          _thread->print_on_error(st, buf, sizeof(buf));
655          st->cr();
656        } else {
657          st->print_cr("Current thread is native thread");
658        }
659        st->cr();
660      }
661 
662   STEP("printing current compile task")
663 
664      if (_verbose && _thread && _thread->is_Compiler_thread()) {
665         CompilerThread* t = (CompilerThread*)_thread;
666         if (t->task()) {
667            st->cr();
668            st->print_cr("Current CompileTask:");
669            t->task()->print_line_on_error(st, buf, sizeof(buf));
670            st->cr();
671         }
672      }
673 
674 
675   STEP("printing stack bounds")
676 
677      if (_verbose) {
678        st->print("Stack: ");
679 
680        address stack_top;
681        size_t stack_size;
682 
683        if (_thread) {
684           stack_top = _thread->stack_base();
685           stack_size = _thread->stack_size();
686        } else {
687           stack_top = os::current_stack_base();
688           stack_size = os::current_stack_size();
689        }
690 
691        address stack_bottom = stack_top - stack_size;
692        st->print("[" PTR_FORMAT "," PTR_FORMAT "]", p2i(stack_bottom), p2i(stack_top));
693 
694        frame fr = _context ? os::fetch_frame_from_context(_context)
695                            : os::current_frame();
696 
697        if (fr.sp()) {
698          st->print(",  sp=" PTR_FORMAT, p2i(fr.sp()));
699          size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024);
700          st->print(",  free space=" SIZE_FORMAT "k", free_stack_size);
701        }
702 
703        st->cr();
704      }
705 
706   STEP("printing native stack")
707 
708    if (_verbose) {
709      if (os::platform_print_native_stack(st, _context, buf, sizeof(buf))) {
710        // We have printed the native stack in platform-specific code
711        // Windows/x64 needs special handling.
712      } else {
713        frame fr = _context ? os::fetch_frame_from_context(_context)
714                            : os::current_frame();
715 
716        print_native_stack(st, fr, _thread, buf, sizeof(buf));
717      }
718    }
719 
720   STEP("printing Java stack")
721 
722      if (_verbose && _thread && _thread->is_Java_thread()) {
723        print_stack_trace(st, (JavaThread*)_thread, buf, sizeof(buf));
724      }
725 
726   STEP("printing target Java thread stack")
727 
728      // printing Java thread stack trace if it is involved in GC crash
729      if (_verbose && _thread && (_thread->is_Named_thread())) {
730        JavaThread*  jt = ((NamedThread *)_thread)->processed_thread();
731        if (jt != NULL) {
732          st->print_cr("JavaThread " PTR_FORMAT " (nid = %d) was being processed", p2i(jt), jt->osthread()->thread_id());
733          print_stack_trace(st, jt, buf, sizeof(buf), true);
734        }
735      }
736 
737   STEP("printing siginfo")
738 
739      // signal no, signal code, address that caused the fault
740      if (_verbose && _siginfo) {
741        st->cr();
742        os::print_siginfo(st, _siginfo);
743        st->cr();
744      }
745 
746   STEP("CDS archive access warning")
747 
748      // Print an explicit hint if we crashed on access to the CDS archive.
749      if (_verbose && _siginfo) {
750        check_failing_cds_access(st, _siginfo);
751        st->cr();
752      }
753 
754   STEP("printing register info")
755 
756      // decode register contents if possible
757      if (_verbose && _context && Universe::is_fully_initialized()) {
758        os::print_register_info(st, _context);
759        st->cr();
760      }
761 
762   STEP("printing registers, top of stack, instructions near pc")
763 
764      // registers, top of stack, instructions near pc
765      if (_verbose && _context) {
766        os::print_context(st, _context);
767        st->cr();
768      }
769 
770   STEP("inspecting top of stack")
771 
772      // decode stack contents if possible
773      if (_verbose && _context && Universe::is_fully_initialized()) {
774        frame fr = os::fetch_frame_from_context(_context);
775        const int slots = 8;
776        const intptr_t *start = fr.sp();
777        const intptr_t *end = start + slots;
778        if (is_aligned(start, sizeof(intptr_t)) && os::is_readable_range(start, end)) {
779          st->print_cr("Stack slot to memory mapping:");
780          for (int i = 0; i < slots; ++i) {
781            st->print("stack at sp + %d slots: ", i);
782            os::print_location(st, *(start + i));
783          }
784        }
785        st->cr();
786      }
787 
788   STEP("printing code blob if possible")
789 
790      if (_verbose && _context) {
791        CodeBlob* cb = CodeCache::find_blob(_pc);
792        if (cb != NULL) {
793          if (Interpreter::contains(_pc)) {
794            // The interpreter CodeBlob is very large so try to print the codelet instead.
795            InterpreterCodelet* codelet = Interpreter::codelet_containing(_pc);
796            if (codelet != NULL) {
797              codelet->print_on(st);
798              Disassembler::decode(codelet->code_begin(), codelet->code_end(), st);
799            }
800          } else {
801            StubCodeDesc* desc = StubCodeDesc::desc_for(_pc);
802            if (desc != NULL) {
803              desc->print_on(st);
804              Disassembler::decode(desc->begin(), desc->end(), st);
805            } else if (_thread != NULL) {
806              // Disassembling nmethod will incur resource memory allocation,
807              // only do so when thread is valid.
808              ResourceMark rm(_thread);
809              Disassembler::decode(cb, st);
810              st->cr();
811            }
812          }
813        }
814      }
815 
816   STEP("printing VM operation")
817 
818      if (_verbose && _thread && _thread->is_VM_thread()) {
819         VMThread* t = (VMThread*)_thread;
820         VM_Operation* op = t->vm_operation();
821         if (op) {
822           op->print_on_error(st);
823           st->cr();
824           st->cr();
825         }
826      }
827 
828   STEP("printing process")
829 
830      if (_verbose) {
831        st->cr();
832        st->print_cr("---------------  P R O C E S S  ---------------");
833        st->cr();
834      }
835 
836 #ifndef _WIN32
837   STEP("printing user info")
838 
839      if (ExtensiveErrorReports && _verbose) {
840        os::Posix::print_user_info(st);
841      }
842 #endif
843 
844   STEP("printing all threads")
845 
846      // all threads
847      if (_verbose && _thread) {
848        Threads::print_on_error(st, _thread, buf, sizeof(buf));
849        st->cr();
850      }
851 
852   STEP("printing VM state")
853 
854      if (_verbose) {
855        // Safepoint state
856        st->print("VM state:");
857 
858        if (SafepointSynchronize::is_synchronizing()) st->print("synchronizing");
859        else if (SafepointSynchronize::is_at_safepoint()) st->print("at safepoint");
860        else st->print("not at safepoint");
861 
862        // Also see if error occurred during initialization or shutdown
863        if (!Universe::is_fully_initialized()) {
864          st->print(" (not fully initialized)");
865        } else if (VM_Exit::vm_exited()) {
866          st->print(" (shutting down)");
867        } else {
868          st->print(" (normal execution)");
869        }
870        st->cr();
871        st->cr();
872      }
873 
874   STEP("printing owned locks on error")
875 
876      // mutexes/monitors that currently have an owner
877      if (_verbose) {
878        print_owned_locks_on_error(st);
879        st->cr();
880      }
881 
882   STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
883 
884      if (_verbose && Exceptions::has_exception_counts()) {
885        st->print_cr("OutOfMemory and StackOverflow Exception counts:");
886        Exceptions::print_exception_counts_on_error(st);
887        st->cr();
888      }
889 
890   STEP("printing compressed oops mode")
891 
892      if (_verbose && UseCompressedOops) {
893        Universe::print_compressed_oops_mode(st);
894        if (UseCompressedClassPointers) {
895          Metaspace::print_compressed_class_space(st);
896        }
897        st->cr();
898      }
899 
900   STEP("printing heap information")
901 
902      if (_verbose && Universe::is_fully_initialized()) {
903        Universe::heap()->print_on_error(st);
904        st->cr();
905        st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
906        st->cr();
907      }
908 
909   STEP("printing metaspace information")
910 
911      if (_verbose && Universe::is_fully_initialized()) {
912        st->print_cr("Metaspace:");
913        MetaspaceUtils::print_basic_report(st, 0);
914      }
915 
916   STEP("printing code cache information")
917 
918      if (_verbose && Universe::is_fully_initialized()) {
919        // print code cache information before vm abort
920        CodeCache::print_summary(st);
921        st->cr();
922      }
923 
924   STEP("printing ring buffers")
925 
926      if (_verbose) {
927        Events::print_all(st);
928        st->cr();
929      }
930 
931   STEP("printing dynamic libraries")
932 
933      if (_verbose) {
934        // dynamic libraries, or memory map
935        os::print_dll_info(st);
936        st->cr();
937      }
938 
939   STEP("printing native decoder state")
940 
941      if (_verbose) {
942        Decoder::print_state_on(st);
943        st->cr();
944      }
945 
946   STEP("printing VM options")
947 
948      if (_verbose) {
949        // VM options
950        Arguments::print_on(st);
951        st->cr();
952      }
953 
954   STEP("printing flags")
955 
956     if (_verbose) {
957       JVMFlag::printFlags(
958         st,
959         true, // with comments
960         false, // no ranges
961         true); // skip defaults
962       st->cr();
963     }
964 
965   STEP("printing warning if internal testing API used")
966 
967      if (WhiteBox::used()) {
968        st->print_cr("Unsupported internal testing APIs have been used.");
969        st->cr();
970      }
971 
972   STEP("printing log configuration")
973     if (_verbose){
974       st->print_cr("Logging:");
975       LogConfiguration::describe_current_configuration(st);
976       st->cr();
977     }
978 
979   STEP("printing all environment variables")
980 
981      if (_verbose) {
982        os::print_environment_variables(st, env_list);
983        st->cr();
984      }
985 
986   STEP("printing signal handlers")
987 
988      if (_verbose) {
989        os::print_signal_handlers(st, buf, sizeof(buf));
990        st->cr();
991      }
992 
993   STEP("Native Memory Tracking")
994      if (_verbose) {
995        MemTracker::error_report(st);
996      }
997 
998   STEP("printing system")
999 
1000      if (_verbose) {
1001        st->cr();
1002        st->print_cr("---------------  S Y S T E M  ---------------");
1003        st->cr();
1004      }
1005 
1006   STEP("printing OS information")
1007 
1008      if (_verbose) {
1009        os::print_os_info(st);
1010        st->cr();
1011      }
1012 
1013   STEP("printing CPU info")
1014      if (_verbose) {
1015        os::print_cpu_info(st, buf, sizeof(buf));
1016        st->cr();
1017      }
1018 
1019   STEP("printing memory info")
1020 
1021      if (_verbose) {
1022        os::print_memory_info(st);
1023        st->cr();
1024      }
1025 
1026   STEP("printing internal vm info")
1027 
1028      if (_verbose) {
1029        st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
1030        st->cr();
1031      }
1032 
1033   // print a defined marker to show that error handling finished correctly.
1034   STEP("printing end marker")
1035 
1036      if (_verbose) {
1037        st->print_cr("END.");
1038      }
1039 
1040   END
1041 
1042 # undef BEGIN
1043 # undef STEP
1044 # undef END
1045 }
1046 
1047 // Report for the vm_info_cmd. This prints out the information above omitting
1048 // crash and thread specific information.  If output is added above, it should be added
1049 // here also, if it is safe to call during a running process.
print_vm_info(outputStream * st)1050 void VMError::print_vm_info(outputStream* st) {
1051 
1052   char buf[O_BUFLEN];
1053   report_vm_version(st, buf, sizeof(buf));
1054 
1055   // STEP("printing summary")
1056 
1057   st->cr();
1058   st->print_cr("---------------  S U M M A R Y ------------");
1059   st->cr();
1060 
1061   // STEP("printing VM option summary")
1062 
1063   // VM options
1064   Arguments::print_summary_on(st);
1065   st->cr();
1066 
1067   // STEP("printing summary machine and OS info")
1068 
1069   os::print_summary_info(st, buf, sizeof(buf));
1070 
1071   // STEP("printing date and time")
1072 
1073   os::print_date_and_time(st, buf, sizeof(buf));
1074 
1075   // Skip: STEP("printing thread")
1076 
1077   // STEP("printing process")
1078 
1079   st->cr();
1080   st->print_cr("---------------  P R O C E S S  ---------------");
1081   st->cr();
1082 
1083   // STEP("printing number of OutOfMemoryError and StackOverflow exceptions")
1084 
1085   if (Exceptions::has_exception_counts()) {
1086     st->print_cr("OutOfMemory and StackOverflow Exception counts:");
1087     Exceptions::print_exception_counts_on_error(st);
1088     st->cr();
1089   }
1090 
1091   // STEP("printing compressed oops mode")
1092 
1093   if (UseCompressedOops) {
1094     Universe::print_compressed_oops_mode(st);
1095     if (UseCompressedClassPointers) {
1096       Metaspace::print_compressed_class_space(st);
1097     }
1098     st->cr();
1099   }
1100 
1101   // STEP("printing heap information")
1102 
1103   if (Universe::is_fully_initialized()) {
1104     MutexLocker hl(Heap_lock);
1105     Universe::heap()->print_on_error(st);
1106     st->cr();
1107     st->print_cr("Polling page: " INTPTR_FORMAT, p2i(os::get_polling_page()));
1108     st->cr();
1109   }
1110 
1111   // STEP("printing metaspace information")
1112 
1113   if (Universe::is_fully_initialized()) {
1114     st->print_cr("Metaspace:");
1115     MetaspaceUtils::print_basic_report(st, 0);
1116   }
1117 
1118   // STEP("printing code cache information")
1119 
1120   if (Universe::is_fully_initialized()) {
1121     // print code cache information before vm abort
1122     CodeCache::print_summary(st);
1123     st->cr();
1124   }
1125 
1126   // STEP("printing ring buffers")
1127 
1128   Events::print_all(st);
1129   st->cr();
1130 
1131   // STEP("printing dynamic libraries")
1132 
1133   // dynamic libraries, or memory map
1134   os::print_dll_info(st);
1135   st->cr();
1136 
1137   // STEP("printing VM options")
1138 
1139   // VM options
1140   Arguments::print_on(st);
1141   st->cr();
1142 
1143   // STEP("printing warning if internal testing API used")
1144 
1145   if (WhiteBox::used()) {
1146     st->print_cr("Unsupported internal testing APIs have been used.");
1147     st->cr();
1148   }
1149 
1150   // STEP("printing log configuration")
1151   st->print_cr("Logging:");
1152   LogConfiguration::describe(st);
1153   st->cr();
1154 
1155   // STEP("printing all environment variables")
1156 
1157   os::print_environment_variables(st, env_list);
1158   st->cr();
1159 
1160   // STEP("printing signal handlers")
1161 
1162   os::print_signal_handlers(st, buf, sizeof(buf));
1163   st->cr();
1164 
1165   // STEP("Native Memory Tracking")
1166 
1167   MemTracker::error_report(st);
1168 
1169   // STEP("printing system")
1170 
1171   st->cr();
1172   st->print_cr("---------------  S Y S T E M  ---------------");
1173   st->cr();
1174 
1175   // STEP("printing OS information")
1176 
1177   os::print_os_info(st);
1178   st->cr();
1179 
1180   // STEP("printing CPU info")
1181 
1182   os::print_cpu_info(st, buf, sizeof(buf));
1183   st->cr();
1184 
1185   // STEP("printing memory info")
1186 
1187   os::print_memory_info(st);
1188   st->cr();
1189 
1190   // STEP("printing internal vm info")
1191 
1192   st->print_cr("vm_info: %s", Abstract_VM_Version::internal_vm_info_string());
1193   st->cr();
1194 
1195   // print a defined marker to show that error handling finished correctly.
1196   // STEP("printing end marker")
1197 
1198   st->print_cr("END.");
1199 }
1200 
1201 volatile intptr_t VMError::first_error_tid = -1;
1202 
1203 /** Expand a pattern into a buffer starting at pos and open a file using constructed path */
expand_and_open(const char * pattern,char * buf,size_t buflen,size_t pos)1204 static int expand_and_open(const char* pattern, char* buf, size_t buflen, size_t pos) {
1205   int fd = -1;
1206   if (Arguments::copy_expand_pid(pattern, strlen(pattern), &buf[pos], buflen - pos)) {
1207     // the O_EXCL flag will cause the open to fail if the file exists
1208     fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0666);
1209   }
1210   return fd;
1211 }
1212 
1213 /**
1214  * Construct file name for a log file and return it's file descriptor.
1215  * Name and location depends on pattern, default_pattern params and access
1216  * permissions.
1217  */
prepare_log_file(const char * pattern,const char * default_pattern,char * buf,size_t buflen)1218 static int prepare_log_file(const char* pattern, const char* default_pattern, char* buf, size_t buflen) {
1219   int fd = -1;
1220 
1221   // If possible, use specified pattern to construct log file name
1222   if (pattern != NULL) {
1223     fd = expand_and_open(pattern, buf, buflen, 0);
1224   }
1225 
1226   // Either user didn't specify, or the user's location failed,
1227   // so use the default name in the current directory
1228   if (fd == -1) {
1229     const char* cwd = os::get_current_directory(buf, buflen);
1230     if (cwd != NULL) {
1231       size_t pos = strlen(cwd);
1232       int fsep_len = jio_snprintf(&buf[pos], buflen-pos, "%s", os::file_separator());
1233       pos += fsep_len;
1234       if (fsep_len > 0) {
1235         fd = expand_and_open(default_pattern, buf, buflen, pos);
1236       }
1237     }
1238   }
1239 
1240    // try temp directory if it exists.
1241    if (fd == -1) {
1242      const char* tmpdir = os::get_temp_directory();
1243      if (tmpdir != NULL && strlen(tmpdir) > 0) {
1244        int pos = jio_snprintf(buf, buflen, "%s%s", tmpdir, os::file_separator());
1245        if (pos > 0) {
1246          fd = expand_and_open(default_pattern, buf, buflen, pos);
1247        }
1248      }
1249    }
1250 
1251   return fd;
1252 }
1253 
1254 int         VMError::_id;
1255 const char* VMError::_message;
1256 char        VMError::_detail_msg[1024];
1257 Thread*     VMError::_thread;
1258 address     VMError::_pc;
1259 void*       VMError::_siginfo;
1260 void*       VMError::_context;
1261 const char* VMError::_filename;
1262 int         VMError::_lineno;
1263 size_t      VMError::_size;
1264 
report_and_die(Thread * thread,unsigned int sig,address pc,void * siginfo,void * context,const char * detail_fmt,...)1265 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo,
1266                              void* context, const char* detail_fmt, ...)
1267 {
1268   va_list detail_args;
1269   va_start(detail_args, detail_fmt);
1270   report_and_die(sig, NULL, detail_fmt, detail_args, thread, pc, siginfo, context, NULL, 0, 0);
1271   va_end(detail_args);
1272 }
1273 
report_and_die(Thread * thread,unsigned int sig,address pc,void * siginfo,void * context)1274 void VMError::report_and_die(Thread* thread, unsigned int sig, address pc, void* siginfo, void* context)
1275 {
1276   report_and_die(thread, sig, pc, siginfo, context, "%s", "");
1277 }
1278 
report_and_die(const char * message,const char * detail_fmt,...)1279 void VMError::report_and_die(const char* message, const char* detail_fmt, ...)
1280 {
1281   va_list detail_args;
1282   va_start(detail_args, detail_fmt);
1283   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, NULL, NULL, NULL, NULL, NULL, 0, 0);
1284   va_end(detail_args);
1285 }
1286 
report_and_die(const char * message)1287 void VMError::report_and_die(const char* message)
1288 {
1289   report_and_die(message, "%s", "");
1290 }
1291 
report_and_die(Thread * thread,void * context,const char * filename,int lineno,const char * message,const char * detail_fmt,va_list detail_args)1292 void VMError::report_and_die(Thread* thread, void* context, const char* filename, int lineno, const char* message,
1293                              const char* detail_fmt, va_list detail_args)
1294 {
1295   report_and_die(INTERNAL_ERROR, message, detail_fmt, detail_args, thread, NULL, NULL, context, filename, lineno, 0);
1296 }
1297 
report_and_die(Thread * thread,const char * filename,int lineno,size_t size,VMErrorType vm_err_type,const char * detail_fmt,va_list detail_args)1298 void VMError::report_and_die(Thread* thread, const char* filename, int lineno, size_t size,
1299                              VMErrorType vm_err_type, const char* detail_fmt, va_list detail_args) {
1300   report_and_die(vm_err_type, NULL, detail_fmt, detail_args, thread, NULL, NULL, NULL, filename, lineno, size);
1301 }
1302 
report_and_die(int id,const char * message,const char * detail_fmt,va_list detail_args,Thread * thread,address pc,void * siginfo,void * context,const char * filename,int lineno,size_t size)1303 void VMError::report_and_die(int id, const char* message, const char* detail_fmt, va_list detail_args,
1304                              Thread* thread, address pc, void* siginfo, void* context, const char* filename,
1305                              int lineno, size_t size)
1306 {
1307   // A single scratch buffer to be used from here on.
1308   // Do not rely on it being preserved across function calls.
1309   static char buffer[O_BUFLEN];
1310 
1311   // File descriptor to tty to print an error summary to.
1312   // Hard wired to stdout; see JDK-8215004 (compatibility concerns).
1313   static const int fd_out = 1; // stdout
1314 
1315   // File descriptor to the error log file.
1316   static int fd_log = -1;
1317 
1318 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
1319   // Disarm assertion poison page, since from this point on we do not need this mechanism anymore and it may
1320   // cause problems in error handling during native OOM, see JDK-8227275.
1321   disarm_assert_poison();
1322 #endif
1323 
1324   // Use local fdStream objects only. Do not use global instances whose initialization
1325   // relies on dynamic initialization (see JDK-8214975). Do not rely on these instances
1326   // to carry over into recursions or invocations from other threads.
1327   fdStream out(fd_out);
1328   out.set_scratch_buffer(buffer, sizeof(buffer));
1329 
1330   // Depending on the re-entrance depth at this point, fd_log may be -1 or point to an open hs-err file.
1331   fdStream log(fd_log);
1332   log.set_scratch_buffer(buffer, sizeof(buffer));
1333 
1334   // How many errors occurred in error handler when reporting first_error.
1335   static int recursive_error_count;
1336 
1337   // We will first print a brief message to standard out (verbose = false),
1338   // then save detailed information in log file (verbose = true).
1339   static bool out_done = false;         // done printing to standard out
1340   static bool log_done = false;         // done saving error log
1341   static bool transmit_report_done = false; // done error reporting
1342 
1343   if (SuppressFatalErrorMessage) {
1344       os::abort(CreateCoredumpOnCrash);
1345   }
1346   intptr_t mytid = os::current_thread_id();
1347   if (first_error_tid == -1 &&
1348       Atomic::cmpxchg(mytid, &first_error_tid, (intptr_t)-1) == -1) {
1349 
1350     // Initialize time stamps to use the same base.
1351     out.time_stamp().update_to(1);
1352     log.time_stamp().update_to(1);
1353 
1354     _id = id;
1355     _message = message;
1356     _thread = thread;
1357     _pc = pc;
1358     _siginfo = siginfo;
1359     _context = context;
1360     _filename = filename;
1361     _lineno = lineno;
1362     _size = size;
1363     jio_vsnprintf(_detail_msg, sizeof(_detail_msg), detail_fmt, detail_args);
1364 
1365     // first time
1366     _error_reported = true;
1367 
1368     reporting_started();
1369     record_reporting_start_time();
1370 
1371     if (ShowMessageBoxOnError || PauseAtExit) {
1372       show_message_box(buffer, sizeof(buffer));
1373 
1374       // User has asked JVM to abort. Reset ShowMessageBoxOnError so the
1375       // WatcherThread can kill JVM if the error handler hangs.
1376       ShowMessageBoxOnError = false;
1377     }
1378 
1379     os::check_dump_limit(buffer, sizeof(buffer));
1380 
1381     // reset signal handlers or exception filter; make sure recursive crashes
1382     // are handled properly.
1383     reset_signal_handlers();
1384 
1385     EventShutdown e;
1386     if (e.should_commit()) {
1387       e.set_reason("VM Error");
1388       e.commit();
1389     }
1390 
1391     JFR_ONLY(Jfr::on_vm_shutdown(true);)
1392 
1393   } else {
1394     // If UseOsErrorReporting we call this for each level of the call stack
1395     // while searching for the exception handler.  Only the first level needs
1396     // to be reported.
1397     if (UseOSErrorReporting && log_done) return;
1398 
1399     // This is not the first error, see if it happened in a different thread
1400     // or in the same thread during error reporting.
1401     if (first_error_tid != mytid) {
1402       char msgbuf[64];
1403       jio_snprintf(msgbuf, sizeof(msgbuf),
1404                    "[thread " INTX_FORMAT " also had an error]",
1405                    mytid);
1406       out.print_raw_cr(msgbuf);
1407 
1408       // error reporting is not MT-safe, block current thread
1409       os::infinite_sleep();
1410 
1411     } else {
1412       if (recursive_error_count++ > 30) {
1413         out.print_raw_cr("[Too many errors, abort]");
1414         os::die();
1415       }
1416 
1417       outputStream* const st = log.is_open() ? &log : &out;
1418       st->cr();
1419 
1420       // Timeout handling.
1421       if (_step_did_timeout) {
1422         // The current step had a timeout. Lets continue reporting with the next step.
1423         st->print_raw("[timeout occurred during error reporting in step \"");
1424         st->print_raw(_current_step_info);
1425         st->print_cr("\"] after " INT64_FORMAT " s.",
1426                      (int64_t)
1427                      ((get_current_timestamp() - _step_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1428       } else if (_reporting_did_timeout) {
1429         // We hit ErrorLogTimeout. Reporting will stop altogether. Let's wrap things
1430         // up, the process is about to be stopped by the WatcherThread.
1431         st->print_cr("------ Timeout during error reporting after " INT64_FORMAT " s. ------",
1432                      (int64_t)
1433                      ((get_current_timestamp() - _reporting_start_time) / TIMESTAMP_TO_SECONDS_FACTOR));
1434         st->flush();
1435         // Watcherthread is about to call os::die. Lets just wait.
1436         os::infinite_sleep();
1437       } else {
1438         // Crash or assert during error reporting. Lets continue reporting with the next step.
1439         stringStream ss(buffer, sizeof(buffer));
1440         // Note: this string does get parsed by a number of jtreg tests,
1441         // see hotspot/jtreg/runtime/ErrorHandling.
1442         ss.print("[error occurred during error reporting (%s), id 0x%x",
1443                    _current_step_info, id);
1444         char signal_name[64];
1445         if (os::exception_name(id, signal_name, sizeof(signal_name))) {
1446           ss.print(", %s (0x%x) at pc=" PTR_FORMAT, signal_name, id, p2i(pc));
1447         } else {
1448           if (should_report_bug(id)) {
1449             ss.print(", Internal Error (%s:%d)",
1450               filename == NULL ? "??" : filename, lineno);
1451           } else {
1452             ss.print(", Out of Memory Error (%s:%d)",
1453               filename == NULL ? "??" : filename, lineno);
1454           }
1455         }
1456         ss.print("]");
1457         st->print_raw_cr(buffer);
1458         st->cr();
1459       }
1460     }
1461   }
1462 
1463   // Part 1: print an abbreviated version (the '#' section) to stdout.
1464   if (!out_done) {
1465     // Suppress this output if we plan to print Part 2 to stdout too.
1466     // No need to have the "#" section twice.
1467     if (!(ErrorFileToStdout && out.fd() == 1)) {
1468       report(&out, false);
1469     }
1470 
1471     out_done = true;
1472 
1473     _current_step = 0;
1474     _current_step_info = "";
1475   }
1476 
1477   // Part 2: print a full error log file (optionally to stdout or stderr).
1478   // print to error log file
1479   if (!log_done) {
1480     // see if log file is already open
1481     if (!log.is_open()) {
1482       // open log file
1483       if (ErrorFileToStdout) {
1484         fd_log = 1;
1485       } else if (ErrorFileToStderr) {
1486         fd_log = 2;
1487       } else {
1488         fd_log = prepare_log_file(ErrorFile, "hs_err_pid%p.log", buffer, sizeof(buffer));
1489         if (fd_log != -1) {
1490           out.print_raw("# An error report file with more information is saved as:\n# ");
1491           out.print_raw_cr(buffer);
1492 
1493         } else {
1494           out.print_raw_cr("# Can not save log file, dump to screen..");
1495           fd_log = 1;
1496           /* Error reporting currently needs dumpfile.
1497            * Maybe implement direct streaming in the future.*/
1498           transmit_report_done = true;
1499         }
1500       }
1501       log.set_fd(fd_log);
1502     }
1503 
1504     report(&log, true);
1505     log_done = true;
1506     _current_step = 0;
1507     _current_step_info = "";
1508 
1509     // Run error reporting to determine whether or not to report the crash.
1510     if (!transmit_report_done && should_report_bug(_id)) {
1511       transmit_report_done = true;
1512       const int fd2 = ::dup(log.fd());
1513       if (fd2 != -1) {
1514         FILE* const hs_err = ::fdopen(fd2, "r");
1515         if (NULL != hs_err) {
1516           ErrorReporter er;
1517           er.call(hs_err, buffer, O_BUFLEN);
1518           ::fclose(hs_err);
1519         }
1520       }
1521     }
1522 
1523     if (fd_log > 3) {
1524       close(fd_log);
1525       fd_log = -1;
1526     }
1527 
1528     log.set_fd(-1);
1529   }
1530 
1531   if (PrintNMTStatistics) {
1532     fdStream fds(fd_out);
1533     MemTracker::final_report(&fds);
1534   }
1535 
1536   static bool skip_replay = ReplayCompiles; // Do not overwrite file during replay
1537   if (DumpReplayDataOnError && _thread && _thread->is_Compiler_thread() && !skip_replay) {
1538     skip_replay = true;
1539     ciEnv* env = ciEnv::current();
1540     if (env != NULL) {
1541       int fd = prepare_log_file(ReplayDataFile, "replay_pid%p.log", buffer, sizeof(buffer));
1542       if (fd != -1) {
1543         FILE* replay_data_file = os::open(fd, "w");
1544         if (replay_data_file != NULL) {
1545           fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1546           env->dump_replay_data_unsafe(&replay_data_stream);
1547           out.print_raw("#\n# Compiler replay data is saved as:\n# ");
1548           out.print_raw_cr(buffer);
1549         } else {
1550           int e = errno;
1551           out.print_raw("#\n# Can't open file to dump replay data. Error: ");
1552           out.print_raw_cr(os::strerror(e));
1553         }
1554       }
1555     }
1556   }
1557 
1558   static bool skip_bug_url = !should_submit_bug_report(_id);
1559   if (!skip_bug_url) {
1560     skip_bug_url = true;
1561 
1562     out.print_raw_cr("#");
1563     print_bug_submit_message(&out, _thread);
1564   }
1565 
1566   static bool skip_OnError = false;
1567   if (!skip_OnError && OnError && OnError[0]) {
1568     skip_OnError = true;
1569 
1570     // Flush output and finish logs before running OnError commands.
1571     ostream_abort();
1572 
1573     out.print_raw_cr("#");
1574     out.print_raw   ("# -XX:OnError=\"");
1575     out.print_raw   (OnError);
1576     out.print_raw_cr("\"");
1577 
1578     char* cmd;
1579     const char* ptr = OnError;
1580     while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1581       out.print_raw   ("#   Executing ");
1582 #if defined(LINUX) || defined(_ALLBSD_SOURCE)
1583       out.print_raw   ("/bin/sh -c ");
1584 #elif defined(SOLARIS)
1585       out.print_raw   ("/usr/bin/sh -c ");
1586 #elif defined(_WINDOWS)
1587       out.print_raw   ("cmd /C ");
1588 #endif
1589       out.print_raw   ("\"");
1590       out.print_raw   (cmd);
1591       out.print_raw_cr("\" ...");
1592 
1593       if (os::fork_and_exec(cmd) < 0) {
1594         out.print_cr("os::fork_and_exec failed: %s (%s=%d)",
1595                      os::strerror(errno), os::errno_name(errno), errno);
1596       }
1597     }
1598 
1599     // done with OnError
1600     OnError = NULL;
1601   }
1602 
1603   if (!UseOSErrorReporting) {
1604     // os::abort() will call abort hooks, try it first.
1605     static bool skip_os_abort = false;
1606     if (!skip_os_abort) {
1607       skip_os_abort = true;
1608       bool dump_core = should_report_bug(_id);
1609       os::abort(dump_core && CreateCoredumpOnCrash, _siginfo, _context);
1610     }
1611 
1612     // if os::abort() doesn't abort, try os::die();
1613     os::die();
1614   }
1615 }
1616 
1617 /*
1618  * OnOutOfMemoryError scripts/commands executed while VM is a safepoint - this
1619  * ensures utilities such as jmap can observe the process is a consistent state.
1620  */
1621 class VM_ReportJavaOutOfMemory : public VM_Operation {
1622  private:
1623   const char* _message;
1624  public:
VM_ReportJavaOutOfMemory(const char * message)1625   VM_ReportJavaOutOfMemory(const char* message) { _message = message; }
type() const1626   VMOp_Type type() const                        { return VMOp_ReportJavaOutOfMemory; }
1627   void doit();
1628 };
1629 
doit()1630 void VM_ReportJavaOutOfMemory::doit() {
1631   // Don't allocate large buffer on stack
1632   static char buffer[O_BUFLEN];
1633 
1634   tty->print_cr("#");
1635   tty->print_cr("# java.lang.OutOfMemoryError: %s", _message);
1636   tty->print_cr("# -XX:OnOutOfMemoryError=\"%s\"", OnOutOfMemoryError);
1637 
1638   // make heap parsability
1639   Universe::heap()->ensure_parsability(false);  // no need to retire TLABs
1640 
1641   char* cmd;
1642   const char* ptr = OnOutOfMemoryError;
1643   while ((cmd = next_OnError_command(buffer, sizeof(buffer), &ptr)) != NULL){
1644     tty->print("#   Executing ");
1645 #if defined(LINUX)
1646     tty->print  ("/bin/sh -c ");
1647 #elif defined(SOLARIS)
1648     tty->print  ("/usr/bin/sh -c ");
1649 #endif
1650     tty->print_cr("\"%s\"...", cmd);
1651 
1652     if (os::fork_and_exec(cmd, true) < 0) {
1653       tty->print_cr("os::fork_and_exec failed: %s (%s=%d)",
1654                      os::strerror(errno), os::errno_name(errno), errno);
1655     }
1656   }
1657 }
1658 
report_java_out_of_memory(const char * message)1659 void VMError::report_java_out_of_memory(const char* message) {
1660   if (OnOutOfMemoryError && OnOutOfMemoryError[0]) {
1661     MutexLocker ml(Heap_lock);
1662     VM_ReportJavaOutOfMemory op(message);
1663     VMThread::execute(&op);
1664   }
1665 }
1666 
show_message_box(char * buf,int buflen)1667 void VMError::show_message_box(char *buf, int buflen) {
1668   bool yes;
1669   do {
1670     error_string(buf, buflen);
1671     yes = os::start_debugging(buf,buflen);
1672   } while (yes);
1673 }
1674 
1675 // Timeout handling: check if a timeout happened (either a single step did
1676 // timeout or the whole of error reporting hit ErrorLogTimeout). Interrupt
1677 // the reporting thread if that is the case.
check_timeout()1678 bool VMError::check_timeout() {
1679 
1680   if (ErrorLogTimeout == 0) {
1681     return false;
1682   }
1683 
1684   // Do not check for timeouts if we still have a message box to show to the
1685   // user or if there are OnError handlers to be run.
1686   if (ShowMessageBoxOnError
1687       || (OnError != NULL && OnError[0] != '\0')
1688       || Arguments::abort_hook() != NULL) {
1689     return false;
1690   }
1691 
1692   const jlong reporting_start_time_l = get_reporting_start_time();
1693   const jlong now = get_current_timestamp();
1694   // Timestamp is stored in nanos.
1695   if (reporting_start_time_l > 0) {
1696     const jlong end = reporting_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR;
1697     if (end <= now) {
1698       _reporting_did_timeout = true;
1699       interrupt_reporting_thread();
1700       return true; // global timeout
1701     }
1702   }
1703 
1704   const jlong step_start_time_l = get_step_start_time();
1705   if (step_start_time_l > 0) {
1706     // A step times out after a quarter of the total timeout. Steps are mostly fast unless they
1707     // hang for some reason, so this simple rule allows for three hanging step and still
1708     // hopefully leaves time enough for the rest of the steps to finish.
1709     const jlong end = step_start_time_l + (jlong)ErrorLogTimeout * TIMESTAMP_TO_SECONDS_FACTOR / 4;
1710     if (end <= now) {
1711       _step_did_timeout = true;
1712       interrupt_reporting_thread();
1713       return false; // (Not a global timeout)
1714     }
1715   }
1716 
1717   return false;
1718 
1719 }
1720 
1721 #ifndef PRODUCT
1722 #if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140
1723 #pragma error_messages(off, SEC_NULL_PTR_DEREF)
1724 #endif
1725 typedef void (*voidfun_t)();
1726 // Crash with an authentic sigfpe
crash_with_sigfpe()1727 static void crash_with_sigfpe() {
1728   // generate a native synchronous SIGFPE where possible;
1729   // if that did not cause a signal (e.g. on ppc), just
1730   // raise the signal.
1731   volatile int x = 0;
1732   volatile int y = 1/x;
1733 #ifndef _WIN32
1734   // OSX implements raise(sig) incorrectly so we need to
1735   // explicitly target the current thread
1736   pthread_kill(pthread_self(), SIGFPE);
1737 #endif
1738 } // end: crash_with_sigfpe
1739 
1740 // crash with sigsegv at non-null address.
crash_with_segfault()1741 static void crash_with_segfault() {
1742 
1743   char* const crash_addr = (char*) VMError::get_segfault_address();
1744   *crash_addr = 'X';
1745 
1746 } // end: crash_with_segfault
1747 
test_error_handler()1748 void VMError::test_error_handler() {
1749   controlled_crash(ErrorHandlerTest);
1750 }
1751 
1752 // crash in a controlled way:
1753 // how can be one of:
1754 // 1,2 - asserts
1755 // 3,4 - guarantee
1756 // 5-7 - fatal
1757 // 8 - vm_exit_out_of_memory
1758 // 9 - ShouldNotCallThis
1759 // 10 - ShouldNotReachHere
1760 // 11 - Unimplemented
1761 // 12,13 - (not guaranteed) crashes
1762 // 14 - SIGSEGV
1763 // 15 - SIGFPE
controlled_crash(int how)1764 void VMError::controlled_crash(int how) {
1765   if (how == 0) return;
1766 
1767   // If asserts are disabled, use the corresponding guarantee instead.
1768   NOT_DEBUG(if (how <= 2) how += 2);
1769 
1770   const char* const str = "hello";
1771   const size_t      num = (size_t)os::vm_page_size();
1772 
1773   const char* const eol = os::line_separator();
1774   const char* const msg = "this message should be truncated during formatting";
1775   char * const dataPtr = NULL;  // bad data pointer
1776   const void (*funcPtr)(void);  // bad function pointer
1777 
1778 #if defined(PPC64) && !defined(ABI_ELFv2) && !defined(ZERO)
1779   struct FunctionDescriptor functionDescriptor;
1780 
1781   functionDescriptor.set_entry((address) 0xF);
1782   funcPtr = (const void(*)()) &functionDescriptor;
1783 #else
1784   funcPtr = (const void(*)()) 0xF;
1785 #endif
1786 
1787   // Keep this in sync with test/hotspot/jtreg/runtime/ErrorHandling/ErrorHandler.java
1788   // which tests cases 1 thru 13.
1789   // Case 14 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java.
1790   // Case 15 is tested by test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java.
1791   // Case 16 is tested by test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java.
1792   // Case 17 is tested by test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java.
1793 
1794   // We grab Threads_lock to keep ThreadsSMRSupport::print_info_on()
1795   // from racing with Threads::add() or Threads::remove() as we
1796   // generate the hs_err_pid file. This makes our ErrorHandling tests
1797   // more stable.
1798   MutexLockerEx ml(Threads_lock->owned_by_self() ? NULL : Threads_lock, Mutex::_no_safepoint_check_flag);
1799 
1800   switch (how) {
1801     case  1: vmassert(str == NULL, "expected null"); break;
1802     case  2: vmassert(num == 1023 && *str == 'X',
1803                       "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1804     case  3: guarantee(str == NULL, "expected null"); break;
1805     case  4: guarantee(num == 1023 && *str == 'X',
1806                        "num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1807     case  5: fatal("expected null"); break;
1808     case  6: fatal("num=" SIZE_FORMAT " str=\"%s\"", num, str); break;
1809     case  7: fatal("%s%s#    %s%s#    %s%s#    %s%s#    %s%s#    "
1810                    "%s%s#    %s%s#    %s%s#    %s%s#    %s%s#    "
1811                    "%s%s#    %s%s#    %s%s#    %s%s#    %s",
1812                    msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1813                    msg, eol, msg, eol, msg, eol, msg, eol, msg, eol,
1814                    msg, eol, msg, eol, msg, eol, msg, eol, msg); break;
1815     case  8: vm_exit_out_of_memory(num, OOM_MALLOC_ERROR, "ChunkPool::allocate"); break;
1816     case  9: ShouldNotCallThis(); break;
1817     case 10: ShouldNotReachHere(); break;
1818     case 11: Unimplemented(); break;
1819     // There's no guarantee the bad data pointer will crash us
1820     // so "break" out to the ShouldNotReachHere().
1821     case 12: *dataPtr = '\0'; break;
1822     // There's no guarantee the bad function pointer will crash us
1823     // so "break" out to the ShouldNotReachHere().
1824     case 13: (*funcPtr)(); break;
1825     case 14: crash_with_segfault(); break;
1826     case 15: crash_with_sigfpe(); break;
1827     case 16: {
1828       ThreadsListHandle tlh;
1829       fatal("Force crash with an active ThreadsListHandle.");
1830     }
1831     case 17: {
1832       ThreadsListHandle tlh;
1833       {
1834         ThreadsListHandle tlh2;
1835         fatal("Force crash with a nested ThreadsListHandle.");
1836       }
1837     }
1838 
1839     default: tty->print_cr("ERROR: %d: unexpected test_num value.", how);
1840   }
1841   tty->print_cr("VMError::controlled_crash: survived intentional crash. Did you suppress the assert?");
1842   ShouldNotReachHere();
1843 }
1844 #endif // !PRODUCT
1845 
1846