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