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