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