2
* Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
25
#include "precompiled.hpp"
26
#include "classfile/javaClasses.hpp"
27
#include "classfile/systemDictionary.hpp"
28
#include "classfile/vmClasses.hpp"
29
#include "classfile/vmSymbols.hpp"
30
#include "compiler/compileBroker.hpp"
31
#include "logging/log.hpp"
32
#include "logging/logStream.hpp"
33
#include "memory/resourceArea.hpp"
34
#include "memory/universe.hpp"
35
#include "oops/oop.inline.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 "runtime/threadCritical.hpp"
43
#include "runtime/atomic.hpp"
44
#include "utilities/events.hpp"
45
#include "utilities/exceptions.hpp"
47
// Limit exception message components to 64K (the same max as Symbols)
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");
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;
65
void ThreadShadow::clear_pending_exception() {
66
LogTarget(Debug, exceptions) lt;
67
if (_pending_exception != nullptr && lt.is_enabled()) {
70
ls.print("Thread::clear_pending_exception: cleared exception:");
71
_pending_exception->print_on(&ls);
73
_pending_exception = nullptr;
74
_exception_file = nullptr;
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();
86
// Implementation of Exceptions
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));
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);
100
vm_exit_during_initialization(h_name, message);
102
ShouldNotReachHere();
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");
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);
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);
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");
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(),
154
MAX_LEN, message ? message : "",
155
p2i(h_exception()), file, line, p2i(thread));
157
// for AbortVMOnException flag
158
Exceptions::debug_check_abort(h_exception, message);
160
// Check for special boot-strapping/compiler-thread handling
161
if (special_exception(thread, file, line, h_exception)) {
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();
170
if (h_exception->is_a(vmClasses::OutOfMemoryError_klass())) {
171
count_out_of_memory_exceptions(h_exception);
175
if (h_exception->is_a(vmClasses::LinkageError_klass())) {
176
Atomic::inc(&_linkage_errors, memory_order_relaxed);
179
assert(h_exception->is_a(vmClasses::Throwable_klass()), "exception is not a subclass of java/lang/Throwable");
181
// set the pending exception
182
thread->set_pending_exception(h_exception(), file, line);
185
Events::log_exception(thread, h_exception, message, file, line);
189
void Exceptions::_throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message,
190
Handle h_loader, Handle h_protection_domain) {
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, h_protection_domain);
196
_throw(thread, file, line, h_exception, message);
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, Handle h_protection_domain) {
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, h_protection_domain);
205
_throw(thread, file, line, h_exception, message);
208
void Exceptions::_throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause,
209
Handle h_loader, Handle h_protection_domain) {
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, h_protection_domain);
214
_throw(thread, file, line, h_exception, nullptr);
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);
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(thread, nullptr), Handle(thread, nullptr));
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(thread, nullptr), Handle(thread, nullptr));
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(thread, nullptr), Handle(thread, nullptr));
241
void Exceptions::throw_stack_overflow_exception(JavaThread* THREAD, const char* file, int line, const methodHandle& method) {
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);
251
// Increment counter for hs_err file reporting
252
Atomic::inc(&Exceptions::_stack_overflow_errors, memory_order_relaxed);
254
// if prior exception, throw that one instead
255
exception = Handle(THREAD, THREAD->pending_exception());
257
_throw(THREAD, file, line, exception);
260
void Exceptions::fthrow(JavaThread* thread, const char* file, int line, Symbol* h_name, const char* format, ...) {
261
const int max_msg_size = 1024;
263
va_start(ap, format);
264
char msg[max_msg_size];
265
os::vsnprintf(msg, max_msg_size, format, ap);
267
_throw_msg(thread, file, line, h_name, msg);
271
// Creates an exception oop, calls the <init> method with the given signature.
272
// and returns a Handle
273
Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
274
Symbol* signature, JavaCallArguments *args,
275
Handle h_loader, Handle h_protection_domain) {
276
assert(Universe::is_fully_initialized(),
277
"cannot be called during initialization");
278
assert(!thread->has_pending_exception(), "already has exception");
282
// Resolve exception klass, and check for pending exception below.
283
Klass* klass = SystemDictionary::resolve_or_fail(name, h_loader, h_protection_domain, true, thread);
285
if (!thread->has_pending_exception()) {
286
assert(klass != nullptr, "klass must exist");
287
h_exception = JavaCalls::construct_new_instance(InstanceKlass::cast(klass),
293
// Check if another exception was thrown in the process, if so rethrow that one
294
if (thread->has_pending_exception()) {
295
h_exception = Handle(thread, thread->pending_exception());
296
thread->clear_pending_exception();
301
// Creates an exception oop, calls the <init> method with the given signature.
302
// and returns a Handle
303
// Initializes the cause if cause non-null
304
Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
305
Symbol* signature, JavaCallArguments *args,
307
Handle h_loader, Handle h_protection_domain) {
308
Handle h_exception = new_exception(thread, name, signature, args, h_loader, h_protection_domain);
310
// Future: object initializer should take a cause argument
311
if (h_cause.not_null()) {
312
assert(h_cause->is_a(vmClasses::Throwable_klass()),
313
"exception cause is not a subclass of java/lang/Throwable");
314
JavaValue result1(T_OBJECT);
315
JavaCallArguments args1;
316
args1.set_receiver(h_exception);
317
args1.push_oop(h_cause);
318
JavaCalls::call_virtual(&result1, h_exception->klass(),
319
vmSymbols::initCause_name(),
320
vmSymbols::throwable_throwable_signature(),
325
// Check if another exception was thrown in the process, if so rethrow that one
326
if (thread->has_pending_exception()) {
327
h_exception = Handle(thread, thread->pending_exception());
328
thread->clear_pending_exception();
333
// Convenience method. Calls either the <init>() or <init>(Throwable) method when
334
// creating a new exception
335
Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
337
Handle h_loader, Handle h_protection_domain,
338
ExceptionMsgToUtf8Mode to_utf8_safe) {
339
JavaCallArguments args;
340
Symbol* signature = nullptr;
341
if (h_cause.is_null()) {
342
signature = vmSymbols::void_method_signature();
344
signature = vmSymbols::throwable_void_signature();
345
args.push_oop(h_cause);
347
return new_exception(thread, name, signature, &args, h_loader, h_protection_domain);
350
// Convenience method. Calls either the <init>() or <init>(String) method when
351
// creating a new exception
352
Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
353
const char* message, Handle h_cause,
354
Handle h_loader, Handle h_protection_domain,
355
ExceptionMsgToUtf8Mode to_utf8_safe) {
356
JavaCallArguments args;
357
Symbol* signature = nullptr;
358
if (message == nullptr) {
359
signature = vmSymbols::void_method_signature();
361
// There should be no pending exception. The caller is responsible for not calling
362
// this with a pending exception.
363
Handle incoming_exception;
364
if (thread->has_pending_exception()) {
365
incoming_exception = Handle(thread, thread->pending_exception());
366
thread->clear_pending_exception();
367
ResourceMark rm(thread);
368
assert(incoming_exception.is_null(), "Pending exception while throwing %s %s", name->as_C_string(), message);
371
if (to_utf8_safe == safe_to_utf8) {
372
// Make a java UTF8 string.
373
msg = java_lang_String::create_from_str(message, thread);
375
// Make a java string keeping the encoding scheme of the original string.
376
msg = java_lang_String::create_from_platform_dependent_str(message, thread);
378
// If we get an exception from the allocation, prefer that to
379
// the exception we are trying to build, or the pending exception (in product mode)
380
if (thread->has_pending_exception()) {
381
Handle exception(thread, thread->pending_exception());
382
thread->clear_pending_exception();
385
if (incoming_exception.not_null()) {
386
return incoming_exception;
389
signature = vmSymbols::string_void_signature();
391
return new_exception(thread, name, signature, &args, h_cause, h_loader, h_protection_domain);
394
// Another convenience method that creates handles for null class loaders and
395
// protection domains and null causes.
396
// If the last parameter 'to_utf8_mode' is safe_to_utf8,
397
// it means we can safely ignore the encoding scheme of the message string and
398
// convert it directly to a java UTF8 string. Otherwise, we need to take the
399
// encoding scheme of the string into account. One thing we should do at some
400
// point is to push this flag down to class java_lang_String since other
401
// classes may need similar functionalities.
402
Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
404
ExceptionMsgToUtf8Mode to_utf8_safe) {
406
Handle h_loader(thread, nullptr);
407
Handle h_prot(thread, nullptr);
408
Handle h_cause(thread, nullptr);
409
return Exceptions::new_exception(thread, name, message, h_cause, h_loader,
410
h_prot, to_utf8_safe);
413
// invokedynamic uses wrap_dynamic_exception for:
414
// - bootstrap method resolution
415
// - post call to MethodHandleNatives::linkCallSite
416
// dynamically computed constant uses wrap_dynamic_exception for:
417
// - bootstrap method resolution
418
// - post call to MethodHandleNatives::linkDynamicConstant
419
void Exceptions::wrap_dynamic_exception(bool is_indy, JavaThread* THREAD) {
420
if (THREAD->has_pending_exception()) {
421
bool log_indy = log_is_enabled(Debug, methodhandles, indy) && is_indy;
422
bool log_condy = log_is_enabled(Debug, methodhandles, condy) && !is_indy;
423
LogStreamHandle(Debug, methodhandles, indy) lsh_indy;
424
LogStreamHandle(Debug, methodhandles, condy) lsh_condy;
425
LogStream* ls = nullptr;
428
} else if (log_condy) {
431
oop exception = THREAD->pending_exception();
433
// See the "Linking Exceptions" section for the invokedynamic instruction
435
if (exception->is_a(vmClasses::Error_klass())) {
436
// Pass through an Error, including BootstrapMethodError, any other form
437
// of linkage error, or say OutOfMemoryError
439
ResourceMark rm(THREAD);
440
ls->print_cr("bootstrap method invocation wraps BSME around " PTR_FORMAT, p2i(exception));
441
exception->print_on(ls);
446
// Otherwise wrap the exception in a BootstrapMethodError
448
ResourceMark rm(THREAD);
449
ls->print_cr("%s throws BSME for " PTR_FORMAT, is_indy ? "invokedynamic" : "dynamic constant", p2i(exception));
450
exception->print_on(ls);
452
Handle nested_exception(THREAD, exception);
453
THREAD->clear_pending_exception();
454
THROW_CAUSE(vmSymbols::java_lang_BootstrapMethodError(), nested_exception)
458
// Exception counting for hs_err file
459
volatile int Exceptions::_stack_overflow_errors = 0;
460
volatile int Exceptions::_linkage_errors = 0;
461
volatile int Exceptions::_out_of_memory_error_java_heap_errors = 0;
462
volatile int Exceptions::_out_of_memory_error_metaspace_errors = 0;
463
volatile int Exceptions::_out_of_memory_error_class_metaspace_errors = 0;
465
void Exceptions::count_out_of_memory_exceptions(Handle exception) {
466
if (Universe::is_out_of_memory_error_metaspace(exception())) {
467
Atomic::inc(&_out_of_memory_error_metaspace_errors, memory_order_relaxed);
468
} else if (Universe::is_out_of_memory_error_class_metaspace(exception())) {
469
Atomic::inc(&_out_of_memory_error_class_metaspace_errors, memory_order_relaxed);
471
// everything else reported as java heap OOM
472
Atomic::inc(&_out_of_memory_error_java_heap_errors, memory_order_relaxed);
476
static void print_oom_count(outputStream* st, const char *err, int count) {
478
st->print_cr("OutOfMemoryError %s=%d", err, count);
482
bool Exceptions::has_exception_counts() {
483
return (_stack_overflow_errors + _out_of_memory_error_java_heap_errors +
484
_out_of_memory_error_metaspace_errors + _out_of_memory_error_class_metaspace_errors) > 0;
487
void Exceptions::print_exception_counts_on_error(outputStream* st) {
488
print_oom_count(st, "java_heap_errors", _out_of_memory_error_java_heap_errors);
489
print_oom_count(st, "metaspace_errors", _out_of_memory_error_metaspace_errors);
490
print_oom_count(st, "class_metaspace_errors", _out_of_memory_error_class_metaspace_errors);
491
if (_stack_overflow_errors > 0) {
492
st->print_cr("StackOverflowErrors=%d", _stack_overflow_errors);
494
if (_linkage_errors > 0) {
495
st->print_cr("LinkageErrors=%d", _linkage_errors);
499
// Implementation of ExceptionMark
501
ExceptionMark::ExceptionMark(JavaThread* thread) {
502
assert(thread == JavaThread::current(), "must be");
504
check_no_pending_exception();
507
ExceptionMark::ExceptionMark() {
508
_thread = JavaThread::current();
509
check_no_pending_exception();
512
inline void ExceptionMark::check_no_pending_exception() {
513
if (_thread->has_pending_exception()) {
514
oop exception = _thread->pending_exception();
515
_thread->clear_pending_exception(); // Needed to avoid infinite recursion
517
fatal("ExceptionMark constructor expects no pending exceptions");
522
ExceptionMark::~ExceptionMark() {
523
if (_thread->has_pending_exception()) {
524
Handle exception(_thread, _thread->pending_exception());
525
_thread->clear_pending_exception(); // Needed to avoid infinite recursion
526
if (is_init_completed()) {
528
fatal("ExceptionMark destructor expects no pending exceptions");
530
vm_exit_during_initialization(exception);
535
// ----------------------------------------------------------------------------------------
537
// caller frees value_string if necessary
538
void Exceptions::debug_check_abort(const char *value_string, const char* message) {
539
if (AbortVMOnException != nullptr && value_string != nullptr &&
540
strstr(value_string, AbortVMOnException)) {
541
if (AbortVMOnExceptionMessage == nullptr || (message != nullptr &&
542
strstr(message, AbortVMOnExceptionMessage))) {
543
if (message == nullptr) {
544
fatal("Saw %s, aborting", value_string);
546
fatal("Saw %s: %s, aborting", value_string, message);
552
void Exceptions::debug_check_abort(Handle exception, const char* message) {
553
if (AbortVMOnException != nullptr) {
554
debug_check_abort_helper(exception, message);
558
void Exceptions::debug_check_abort_helper(Handle exception, const char* message) {
560
if (message == nullptr && exception->is_a(vmClasses::Throwable_klass())) {
561
oop msg = java_lang_Throwable::message(exception());
562
if (msg != nullptr) {
563
message = java_lang_String::as_utf8_string(msg);
566
debug_check_abort(exception()->klass()->external_name(), message);
569
// for logging exceptions
570
void Exceptions::log_exception(Handle exception, const char* message) {
572
const char* detail_message = java_lang_Throwable::message_as_utf8(exception());
573
if (detail_message != nullptr) {
574
log_info(exceptions)("Exception <%.*s: %.*s>\n thrown in %.*s",
575
MAX_LEN, exception->print_value_string(),
576
MAX_LEN, detail_message,
579
log_info(exceptions)("Exception <%.*s>\n thrown in %.*s",
580
MAX_LEN, exception->print_value_string(),