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