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