1 /*
  2  * Copyright (c) 1998, 2025, 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 "classfile/javaClasses.hpp"
 26 #include "classfile/systemDictionary.hpp"
 27 #include "classfile/vmClasses.hpp"
 28 #include "classfile/vmSymbols.hpp"
 29 #include "compiler/compileBroker.hpp"
 30 #include "logging/log.hpp"
 31 #include "logging/logStream.hpp"
 32 #include "memory/resourceArea.hpp"
 33 #include "memory/universe.hpp"
 34 #include "oops/oop.inline.hpp"
 35 #include "runtime/handles.inline.hpp"
 36 #include "runtime/init.hpp"
 37 #include "runtime/java.hpp"
 38 #include "runtime/javaCalls.hpp"
 39 #include "runtime/javaThread.hpp"
 40 #include "runtime/os.hpp"
 41 #include "runtime/atomic.hpp"
 42 #include "utilities/events.hpp"
 43 #include "utilities/exceptions.hpp"
 44 #include "utilities/utf8.hpp"
 45 
 46 // Limit exception message components to 64K (the same max as Symbols)
 47 #define MAX_LEN 65535
 48 
 49 // Implementation of ThreadShadow
 50 void check_ThreadShadow() {
 51   const ByteSize offset1 = byte_offset_of(ThreadShadow, _pending_exception);
 52   const ByteSize offset2 = Thread::pending_exception_offset();
 53   if (offset1 != offset2) fatal("ThreadShadow::_pending_exception is not positioned correctly");
 54 }
 55 
 56 
 57 void ThreadShadow::set_pending_exception(oop exception, const char* file, int line) {
 58   assert(exception != nullptr && oopDesc::is_oop(exception), "invalid exception oop");
 59   _pending_exception = exception;
 60   _exception_file    = file;
 61   _exception_line    = line;
 62 }
 63 
 64 void ThreadShadow::clear_pending_exception() {
 65   LogTarget(Debug, exceptions) lt;
 66   if (_pending_exception != nullptr && lt.is_enabled()) {
 67     ResourceMark rm;
 68     LogStream ls(lt);
 69     ls.print("Thread::clear_pending_exception: cleared exception:");
 70     _pending_exception->print_on(&ls);
 71   }
 72   _pending_exception = nullptr;
 73   _exception_file    = nullptr;
 74   _exception_line    = 0;
 75 }
 76 
 77 void ThreadShadow::clear_pending_nonasync_exception() {
 78   // Do not clear probable async exceptions.
 79   if ((_pending_exception->klass() != vmClasses::InternalError_klass() ||
 80        java_lang_InternalError::during_unsafe_access(_pending_exception) != JNI_TRUE)) {
 81     clear_pending_exception();
 82   }
 83 }
 84 
 85 void ThreadShadow::set_pending_preempted_exception() {
 86   assert(!has_pending_exception(), "");
 87   // We always install the same dummy exception since we only want
 88   // to use the TRAPS mechaninsm to bail out from all methods until
 89   // reaching the one using the CHECK_AND_CLEAR_PREEMPTED macro.
 90   set_pending_exception(Universe::preempted_exception_instance(), __FILE__, __LINE__);
 91 }
 92 
 93 void ThreadShadow::clear_pending_preempted_exception() {
 94   if (_pending_exception->klass() == vmClasses::PreemptedException_klass()) {
 95     clear_pending_exception();
 96   }
 97 }
 98 
 99 #ifdef ASSERT
100 void ThreadShadow::check_preempted_exception() {
101   assert(has_pending_exception(), "");
102   assert(pending_exception()->is_a(vmClasses::PreemptedException_klass()), "");
103 }
104 #endif
105 
106 // Implementation of Exceptions
107 
108 bool Exceptions::special_exception(JavaThread* thread, const char* file, int line, Handle h_exception, Symbol* h_name, const char* message) {
109   assert(h_exception.is_null() != (h_name == nullptr), "either exception (" PTR_FORMAT ") or "
110          "symbol (" PTR_FORMAT ") must be non-null but not both", p2i(h_exception()), p2i(h_name));
111 
112   // bootstrapping check
113   if (!Universe::is_fully_initialized()) {
114     if (h_exception.not_null()) {
115       vm_exit_during_initialization(h_exception);
116     } else if (h_name == nullptr) {
117       // at least an informative message.
118       vm_exit_during_initialization("Exception", message);
119     } else {
120       vm_exit_during_initialization(h_name, message);
121     }
122    ShouldNotReachHere();
123   }
124 
125 #ifdef ASSERT
126   // Check for trying to throw stack overflow before initialization is complete
127   // to prevent infinite recursion trying to initialize stack overflow without
128   // adequate stack space.
129   // This can happen with stress testing a large value of StackShadowPages
130   if (h_exception.not_null() && h_exception()->klass() == vmClasses::StackOverflowError_klass()) {
131     InstanceKlass* ik = InstanceKlass::cast(h_exception->klass());
132     assert(ik->is_initialized(),
133            "need to increase java_thread_min_stack_allowed calculation");
134   }
135 #endif // ASSERT
136 
137   if (h_exception.is_null() && !thread->can_call_java()) {
138     if (log_is_enabled(Info, exceptions)) {
139       ResourceMark rm(thread);
140       const char* exc_value = h_name != nullptr ? h_name->as_C_string() : "null";
141       log_info(exceptions)("Thread cannot call Java so instead of throwing exception <%.*s%s%.*s> (" PTR_FORMAT ") \n"
142                            "at [%s, line %d]\nfor thread " PTR_FORMAT ",\n"
143                            "throwing pre-allocated exception: %s",
144                            MAX_LEN, exc_value, message ? ": " : "",
145                            MAX_LEN, message ? message : "",
146                            p2i(h_exception()), file, line, p2i(thread),
147                            Universe::vm_exception()->print_value_string());
148     }
149     // We do not care what kind of exception we get for a thread which
150     // is compiling.  We just install a dummy exception object
151     thread->set_pending_exception(Universe::vm_exception(), file, line);
152     return true;
153   }
154 
155   return false;
156 }
157 
158 // This method should only be called from generated code,
159 // therefore the exception oop should be in the oopmap.
160 void Exceptions::_throw_oop(JavaThread* thread, const char* file, int line, oop exception) {
161   assert(exception != nullptr, "exception should not be null");
162   Handle h_exception(thread, exception);
163   _throw(thread, file, line, h_exception);
164 }
165 
166 void Exceptions::_throw(JavaThread* thread, const char* file, int line, Handle h_exception, const char* message) {
167   ResourceMark rm(thread);
168   assert(h_exception() != nullptr, "exception should not be null");
169 
170   // tracing (do this up front - so it works during boot strapping)
171   // Note, the print_value_string() argument is not called unless logging is enabled!
172   log_info(exceptions)("Exception <%.*s%s%.*s> (" PTR_FORMAT ") \n"
173                        "thrown [%s, line %d]\nfor thread " PTR_FORMAT,
174                        MAX_LEN, h_exception->print_value_string(),
175                        message ? ": " : "",
176                        MAX_LEN, message ? message : "",
177                        p2i(h_exception()), file, line, p2i(thread));
178   if (log_is_enabled(Info, exceptions, stacktrace)) {
179     log_exception_stacktrace(h_exception);
180   }
181 
182   // for AbortVMOnException flag
183   Exceptions::debug_check_abort(h_exception, message);
184 
185   // Check for special boot-strapping/compiler-thread handling
186   if (special_exception(thread, file, line, h_exception)) {
187     return;
188   }
189 
190   if (h_exception->is_a(vmClasses::VirtualMachineError_klass())) {
191     // Remove the ScopedValue bindings in case we got a virtual machine
192     // Error while we were trying to manipulate ScopedValue bindings.
193     thread->clear_scopedValueBindings();
194 
195     if (h_exception->is_a(vmClasses::OutOfMemoryError_klass())) {
196       count_out_of_memory_exceptions(h_exception);
197     }
198   }
199 
200   if (h_exception->is_a(vmClasses::LinkageError_klass())) {
201     Atomic::inc(&_linkage_errors, memory_order_relaxed);
202   }
203 
204   assert(h_exception->is_a(vmClasses::Throwable_klass()), "exception is not a subclass of java/lang/Throwable");
205 
206   // set the pending exception
207   thread->set_pending_exception(h_exception(), file, line);
208 
209   // vm log
210   Events::log_exception(thread, h_exception, message, file, line, MAX_LEN);
211 }
212 
213 
214 void Exceptions::_throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message,
215                             Handle h_loader) {
216   // Check for special boot-strapping/compiler-thread handling
217   if (special_exception(thread, file, line, Handle(), name, message)) return;
218   // Create and throw exception
219   Handle h_cause(thread, nullptr);
220   Handle h_exception = new_exception(thread, name, message, h_cause, h_loader);
221   _throw(thread, file, line, h_exception, message);
222 }
223 
224 void Exceptions::_throw_msg_cause(JavaThread* thread, const char* file, int line, Symbol* name, const char* message, Handle h_cause,
225                                   Handle h_loader) {
226   // Check for special boot-strapping/compiler-thread handling
227   if (special_exception(thread, file, line, Handle(), name, message)) return;
228   // Create and throw exception and init cause
229   Handle h_exception = new_exception(thread, name, message, h_cause, h_loader);
230   _throw(thread, file, line, h_exception, message);
231 }
232 
233 void Exceptions::_throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause,
234                               Handle h_loader) {
235   // Check for special boot-strapping/compiler-thread handling
236   if (special_exception(thread, file, line, Handle(), name)) return;
237   // Create and throw exception
238   Handle h_exception = new_exception(thread, name, h_cause, h_loader);
239   _throw(thread, file, line, h_exception, nullptr);
240 }
241 
242 void Exceptions::_throw_args(JavaThread* thread, const char* file, int line, Symbol* name, Symbol* signature, JavaCallArguments *args) {
243   // Check for special boot-strapping/compiler-thread handling
244   if (special_exception(thread, file, line, Handle(), name, nullptr)) return;
245   // Create and throw exception
246   Handle h_loader(thread, nullptr);
247   Handle h_prot(thread, nullptr);
248   Handle exception = new_exception(thread, name, signature, args, h_loader, h_prot);
249   _throw(thread, file, line, exception);
250 }
251 
252 
253 // Methods for default parameters.
254 // NOTE: These must be here (and not in the header file) because of include circularities.
255 void Exceptions::_throw_msg_cause(JavaThread* thread, const char* file, int line, Symbol* name, const char* message, Handle h_cause) {
256   _throw_msg_cause(thread, file, line, name, message, h_cause, Handle());
257 }
258 void Exceptions::_throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message) {
259   _throw_msg(thread, file, line, name, message, Handle());
260 }
261 void Exceptions::_throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause) {
262   _throw_cause(thread, file, line, name, h_cause, Handle());
263 }
264 
265 
266 void Exceptions::throw_stack_overflow_exception(JavaThread* THREAD, const char* file, int line, const methodHandle& method) {
267   Handle exception;
268   if (!THREAD->has_pending_exception()) {
269     InstanceKlass* k = vmClasses::StackOverflowError_klass();
270     oop e = k->allocate_instance(CHECK);
271     exception = Handle(THREAD, e);  // fill_in_stack trace does gc
272     assert(k->is_initialized(), "need to increase java_thread_min_stack_allowed calculation");
273     if (StackTraceInThrowable) {
274       java_lang_Throwable::fill_in_stack_trace(exception, method);
275     }
276     // Increment counter for hs_err file reporting
277     Atomic::inc(&Exceptions::_stack_overflow_errors, memory_order_relaxed);
278   } else {
279     // if prior exception, throw that one instead
280     exception = Handle(THREAD, THREAD->pending_exception());
281   }
282   _throw(THREAD, file, line, exception);
283 }
284 
285 // All callers are expected to have ensured that the incoming expanded format string
286 // will be within reasonable limits - specifically we will never hit the INT_MAX limit
287 // of os::vsnprintf when it tries to report how big a buffer is needed. Even so we
288 // further limit the formatted output to 1024 characters.
289 void Exceptions::fthrow(JavaThread* thread, const char* file, int line, Symbol* h_name, const char* format, ...) {
290   const int max_msg_size = 1024;
291   va_list ap;
292   va_start(ap, format);
293   char msg[max_msg_size];
294   int ret = os::vsnprintf(msg, max_msg_size, format, ap);
295   va_end(ap);
296 
297   // If ret == -1 then either there was a format conversion error, or the required buffer size
298   // exceeds INT_MAX and so couldn't be returned (undocumented behaviour of vsnprintf). Depending
299   // on the platform the buffer may be filled to its capacity (Linux), filled to the conversion
300   // that encountered the overflow (macOS), or is empty (Windows), so it is possible we
301   // have a truncated UTF-8 sequence. Similarly, if the buffer was too small and ret >= max_msg_size
302   // we may also have a truncated UTF-8 sequence. In such cases we need to fix the buffer so the UTF-8
303   // sequence is valid.
304   assert(ret != -1, "Caller should have ensured the incoming format string is size limited!");
305   if (ret == -1 || ret >= max_msg_size) {
306     int len = (int) strlen(msg);
307     if (len > 0) {
308       // Truncation will only happen if the buffer was filled by vsnprintf,
309       // otherwise vsnprintf already terminated filling it at a well-defined point.
310       // But as this is not a clearly specified area we will perform our own UTF8
311       // truncation anyway - though for those well-defined termination points it
312       // will be a no-op.
313       UTF8::truncate_to_legal_utf8((unsigned char*)msg, len + 1);
314     }
315   }
316   // UTF8::is_legal_utf8 should actually be called is_legal_utf8_class_name as the final
317   // parameter controls a check for a specific character appearing in the "name", which is only
318   // allowed for classfile versions <= 47. We pass `true` so that we allow such strings as this code
319   // know nothing about the actual string content.
320   assert(UTF8::is_legal_utf8((const unsigned char*)msg, strlen(msg), true), "must be");
321   _throw_msg(thread, file, line, h_name, msg);
322 }
323 
324 
325 // Creates an exception oop, calls the <init> method with the given signature.
326 // and returns a Handle
327 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
328                                  Symbol* signature, JavaCallArguments *args,
329                                  Handle h_loader) {
330   assert(Universe::is_fully_initialized(),
331     "cannot be called during initialization");
332   assert(!thread->has_pending_exception(), "already has exception");
333 
334   Handle h_exception;
335 
336   // Resolve exception klass, and check for pending exception below.
337   Klass* klass = SystemDictionary::resolve_or_fail(name, h_loader, true, thread);
338 
339   if (!thread->has_pending_exception()) {
340     assert(klass != nullptr, "klass must exist");
341     h_exception = JavaCalls::construct_new_instance(InstanceKlass::cast(klass),
342                                 signature,
343                                 args,
344                                 thread);
345   }
346 
347   // Check if another exception was thrown in the process, if so rethrow that one
348   if (thread->has_pending_exception()) {
349     h_exception = Handle(thread, thread->pending_exception());
350     thread->clear_pending_exception();
351   }
352   return h_exception;
353 }
354 
355 // Creates an exception oop, calls the <init> method with the given signature.
356 // and returns a Handle
357 // Initializes the cause if cause non-null
358 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
359                                  Symbol* signature, JavaCallArguments *args,
360                                  Handle h_cause,
361                                  Handle h_loader) {
362   Handle h_exception = new_exception(thread, name, signature, args, h_loader);
363 
364   // Future: object initializer should take a cause argument
365   if (h_cause.not_null()) {
366     assert(h_cause->is_a(vmClasses::Throwable_klass()),
367         "exception cause is not a subclass of java/lang/Throwable");
368     JavaValue result1(T_OBJECT);
369     JavaCallArguments args1;
370     args1.set_receiver(h_exception);
371     args1.push_oop(h_cause);
372     JavaCalls::call_virtual(&result1, h_exception->klass(),
373                                       vmSymbols::initCause_name(),
374                                       vmSymbols::throwable_throwable_signature(),
375                                       &args1,
376                                       thread);
377   }
378 
379   // Check if another exception was thrown in the process, if so rethrow that one
380   if (thread->has_pending_exception()) {
381     h_exception = Handle(thread, thread->pending_exception());
382     thread->clear_pending_exception();
383   }
384   return h_exception;
385 }
386 
387 // Convenience method. Calls either the <init>() or <init>(Throwable) method when
388 // creating a new exception
389 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
390                                  Handle h_cause,
391                                  Handle h_loader,
392                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
393   JavaCallArguments args;
394   Symbol* signature = nullptr;
395   if (h_cause.is_null()) {
396     signature = vmSymbols::void_method_signature();
397   } else {
398     signature = vmSymbols::throwable_void_signature();
399     args.push_oop(h_cause);
400   }
401   return new_exception(thread, name, signature, &args, h_loader);
402 }
403 
404 // Convenience method. Calls either the <init>() or <init>(String) method when
405 // creating a new exception
406 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
407                                  const char* message, Handle h_cause,
408                                  Handle h_loader,
409                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
410   JavaCallArguments args;
411   Symbol* signature = nullptr;
412   if (message == nullptr) {
413     signature = vmSymbols::void_method_signature();
414   } else {
415     // There should be no pending exception. The caller is responsible for not calling
416     // this with a pending exception.
417     Handle incoming_exception;
418     if (thread->has_pending_exception()) {
419       incoming_exception = Handle(thread, thread->pending_exception());
420       thread->clear_pending_exception();
421       ResourceMark rm(thread);
422       assert(incoming_exception.is_null(), "Pending exception while throwing %s %s", name->as_C_string(), message);
423     }
424     Handle msg;
425     if (to_utf8_safe == safe_to_utf8) {
426       // Make a java UTF8 string.
427       msg = java_lang_String::create_from_str(message, thread);
428     } else {
429       // Make a java string keeping the encoding scheme of the original string.
430       msg = java_lang_String::create_from_platform_dependent_str(message, thread);
431     }
432     // If we get an exception from the allocation, prefer that to
433     // the exception we are trying to build, or the pending exception (in product mode)
434     if (thread->has_pending_exception()) {
435       Handle exception(thread, thread->pending_exception());
436       thread->clear_pending_exception();
437       return exception;
438     }
439     if (incoming_exception.not_null()) {
440       return incoming_exception;
441     }
442     args.push_oop(msg);
443     signature = vmSymbols::string_void_signature();
444   }
445   return new_exception(thread, name, signature, &args, h_cause, h_loader);
446 }
447 
448 // Another convenience method that creates handles for null class loaders and null causes.
449 // If the last parameter 'to_utf8_mode' is safe_to_utf8,
450 // it means we can safely ignore the encoding scheme of the message string and
451 // convert it directly to a java UTF8 string. Otherwise, we need to take the
452 // encoding scheme of the string into account. One thing we should do at some
453 // point is to push this flag down to class java_lang_String since other
454 // classes may need similar functionalities.
455 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
456                                  const char* message,
457                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
458 
459   Handle h_loader;
460   Handle h_cause;
461   return Exceptions::new_exception(thread, name, message, h_cause, h_loader,
462                                    to_utf8_safe);
463 }
464 
465 // invokedynamic uses wrap_dynamic_exception for:
466 //    - bootstrap method resolution
467 //    - post call to MethodHandleNatives::linkCallSite
468 // dynamically computed constant uses wrap_dynamic_exception for:
469 //    - bootstrap method resolution
470 //    - post call to MethodHandleNatives::linkDynamicConstant
471 void Exceptions::wrap_dynamic_exception(bool is_indy, JavaThread* THREAD) {
472   if (THREAD->has_pending_exception()) {
473     bool log_indy = log_is_enabled(Debug, methodhandles, indy) && is_indy;
474     bool log_condy = log_is_enabled(Debug, methodhandles, condy) && !is_indy;
475     LogStreamHandle(Debug, methodhandles, indy) lsh_indy;
476     LogStreamHandle(Debug, methodhandles, condy) lsh_condy;
477     LogStream* ls = nullptr;
478     if (log_indy) {
479       ls = &lsh_indy;
480     } else if (log_condy) {
481       ls = &lsh_condy;
482     }
483     oop exception = THREAD->pending_exception();
484 
485     // See the "Linking Exceptions" section for the invokedynamic instruction
486     // in JVMS 6.5.
487     if (exception->is_a(vmClasses::Error_klass())) {
488       // Pass through an Error, including BootstrapMethodError, any other form
489       // of linkage error, or say OutOfMemoryError
490       if (ls != nullptr) {
491         ResourceMark rm(THREAD);
492         ls->print_cr("bootstrap method invocation wraps BSME around " PTR_FORMAT, p2i(exception));
493         exception->print_on(ls);
494       }
495       return;
496     }
497 
498     // Otherwise wrap the exception in a BootstrapMethodError
499     if (ls != nullptr) {
500       ResourceMark rm(THREAD);
501       ls->print_cr("%s throws BSME for " PTR_FORMAT, is_indy ? "invokedynamic" : "dynamic constant", p2i(exception));
502       exception->print_on(ls);
503     }
504     Handle nested_exception(THREAD, exception);
505     THREAD->clear_pending_exception();
506     THROW_CAUSE(vmSymbols::java_lang_BootstrapMethodError(), nested_exception)
507   }
508 }
509 
510 // Exception counting for hs_err file
511 volatile int Exceptions::_stack_overflow_errors = 0;
512 volatile int Exceptions::_linkage_errors = 0;
513 volatile int Exceptions::_out_of_memory_error_java_heap_errors = 0;
514 volatile int Exceptions::_out_of_memory_error_metaspace_errors = 0;
515 volatile int Exceptions::_out_of_memory_error_class_metaspace_errors = 0;
516 
517 void Exceptions::count_out_of_memory_exceptions(Handle exception) {
518   if (Universe::is_out_of_memory_error_metaspace(exception())) {
519      Atomic::inc(&_out_of_memory_error_metaspace_errors, memory_order_relaxed);
520   } else if (Universe::is_out_of_memory_error_class_metaspace(exception())) {
521      Atomic::inc(&_out_of_memory_error_class_metaspace_errors, memory_order_relaxed);
522   } else {
523      // everything else reported as java heap OOM
524      Atomic::inc(&_out_of_memory_error_java_heap_errors, memory_order_relaxed);
525   }
526 }
527 
528 static void print_oom_count(outputStream* st, const char *err, int count) {
529   if (count > 0) {
530     st->print_cr("OutOfMemoryError %s=%d", err, count);
531   }
532 }
533 
534 bool Exceptions::has_exception_counts() {
535   return (_stack_overflow_errors + _out_of_memory_error_java_heap_errors +
536          _out_of_memory_error_metaspace_errors + _out_of_memory_error_class_metaspace_errors) > 0;
537 }
538 
539 void Exceptions::print_exception_counts_on_error(outputStream* st) {
540   print_oom_count(st, "java_heap_errors", _out_of_memory_error_java_heap_errors);
541   print_oom_count(st, "metaspace_errors", _out_of_memory_error_metaspace_errors);
542   print_oom_count(st, "class_metaspace_errors", _out_of_memory_error_class_metaspace_errors);
543   if (_stack_overflow_errors > 0) {
544     st->print_cr("StackOverflowErrors=%d", _stack_overflow_errors);
545   }
546   if (_linkage_errors > 0) {
547     st->print_cr("LinkageErrors=%d", _linkage_errors);
548   }
549 }
550 
551 // Implementation of ExceptionMark
552 
553 ExceptionMark::ExceptionMark(JavaThread* thread) {
554   assert(thread == JavaThread::current(), "must be");
555   _thread  = thread;
556   check_no_pending_exception();
557 }
558 
559 ExceptionMark::ExceptionMark() {
560   _thread = JavaThread::current();
561   check_no_pending_exception();
562 }
563 
564 inline void ExceptionMark::check_no_pending_exception() {
565   if (_thread->has_pending_exception()) {
566     oop exception = _thread->pending_exception();
567     _thread->clear_pending_exception(); // Needed to avoid infinite recursion
568     ResourceMark rm;
569     exception->print();
570     fatal("ExceptionMark constructor expects no pending exceptions");
571   }
572 }
573 
574 
575 ExceptionMark::~ExceptionMark() {
576   if (_thread->has_pending_exception()) {
577     Handle exception(_thread, _thread->pending_exception());
578     _thread->clear_pending_exception(); // Needed to avoid infinite recursion
579     if (is_init_completed()) {
580       ResourceMark rm;
581       exception->print();
582       fatal("ExceptionMark destructor expects no pending exceptions");
583     } else {
584       vm_exit_during_initialization(exception);
585     }
586   }
587 }
588 
589 // ----------------------------------------------------------------------------------------
590 
591 // caller frees value_string if necessary
592 void Exceptions::debug_check_abort(const char *value_string, const char* message) {
593   if (AbortVMOnException != nullptr && value_string != nullptr &&
594       strstr(value_string, AbortVMOnException)) {
595     if (AbortVMOnExceptionMessage == nullptr || (message != nullptr &&
596         strstr(message, AbortVMOnExceptionMessage))) {
597       if (message == nullptr) {
598         fatal("Saw %s, aborting", value_string);
599       } else {
600         fatal("Saw %s: %s, aborting", value_string, message);
601       }
602     }
603   }
604 }
605 
606 void Exceptions::debug_check_abort(Handle exception, const char* message) {
607   if (AbortVMOnException != nullptr) {
608     debug_check_abort_helper(exception, message);
609   }
610 }
611 
612 void Exceptions::debug_check_abort_helper(Handle exception, const char* message) {
613   ResourceMark rm;
614   if (message == nullptr && exception->is_a(vmClasses::Throwable_klass())) {
615     oop msg = java_lang_Throwable::message(exception());
616     if (msg != nullptr) {
617       message = java_lang_String::as_utf8_string(msg);
618     }
619   }
620   debug_check_abort(exception()->klass()->external_name(), message);
621 }
622 
623 // for logging exceptions
624 void Exceptions::log_exception(Handle exception, const char* message) {
625   ResourceMark rm;
626   const char* detail_message = java_lang_Throwable::message_as_utf8(exception());
627   if (detail_message != nullptr) {
628     log_info(exceptions)("Exception <%.*s: %.*s>\n thrown in %.*s",
629                          MAX_LEN, exception->print_value_string(),
630                          MAX_LEN, detail_message,
631                          MAX_LEN, message);
632   } else {
633     log_info(exceptions)("Exception <%.*s>\n thrown in %.*s",
634                          MAX_LEN, exception->print_value_string(),
635                          MAX_LEN, message);
636   }
637 }
638 
639 // This is called from InterpreterRuntime::exception_handler_for_exception(), which is the only
640 // easy way to be notified in the VM that an _athrow bytecode has been executed. (The alternative
641 // would be to add hooks into the interpreter and compiler, for all platforms ...).
642 //
643 // Unfortunately, InterpreterRuntime::exception_handler_for_exception() is called for every level
644 // of the Java stack when looking for an exception handler. To avoid excessive output,
645 // we print the stack only when the bci points to an _athrow bytecode.
646 //
647 // NOTE: exceptions that are NOT thrown by _athrow are handled by Exceptions::special_exception()
648 // and Exceptions::_throw()).
649 void Exceptions::log_exception_stacktrace(Handle exception, methodHandle method, int bci) {
650   if (!method->is_native() && (Bytecodes::Code) *method->bcp_from(bci) == Bytecodes::_athrow) {
651     // TODO: try to find a way to avoid repeated stacktraces when an exception gets re-thrown
652     // by a finally block
653     log_exception_stacktrace(exception);
654   }
655 }
656 
657 // This should be called only from a live Java thread.
658 void Exceptions::log_exception_stacktrace(Handle exception) {
659   LogStreamHandle(Info, exceptions, stacktrace) st;
660   ResourceMark rm;
661   const char* detail_message = java_lang_Throwable::message_as_utf8(exception());
662   if (detail_message != nullptr) {
663     st.print_cr("Exception <%.*s: %.*s>",
664                 MAX_LEN, exception->print_value_string(),
665                 MAX_LEN, detail_message);
666   } else {
667     st.print_cr("Exception <%.*s>",
668                 MAX_LEN, exception->print_value_string());
669   }
670   JavaThread* t = JavaThread::current();
671   if (t->has_last_Java_frame()) {
672     t->print_active_stack_on(&st);
673   } else {
674     st.print_cr("(Cannot print stracktrace)");
675   }
676 }