2
* Copyright (c) 1998, 2023, 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 "gc/shared/collectedHeap.hpp"
27
#include "gc/shared/oopStorage.inline.hpp"
28
#include "gc/shared/oopStorageSet.hpp"
29
#include "logging/log.hpp"
30
#include "memory/iterator.hpp"
31
#include "memory/universe.hpp"
32
#include "oops/access.inline.hpp"
33
#include "oops/oop.inline.hpp"
34
#include "runtime/handles.inline.hpp"
35
#include "runtime/javaThread.inline.hpp"
36
#include "runtime/jniHandles.inline.hpp"
37
#include "runtime/mutexLocker.hpp"
38
#include "utilities/align.hpp"
39
#include "utilities/debug.hpp"
41
OopStorage* JNIHandles::global_handles() {
42
return _global_handles;
45
OopStorage* JNIHandles::weak_global_handles() {
46
return _weak_global_handles;
49
// Serviceability agent support.
50
OopStorage* JNIHandles::_global_handles = nullptr;
51
OopStorage* JNIHandles::_weak_global_handles = nullptr;
53
void jni_handles_init() {
54
JNIHandles::_global_handles = OopStorageSet::create_strong("JNI Global", mtInternal);
55
JNIHandles::_weak_global_handles = OopStorageSet::create_weak("JNI Weak", mtInternal);
58
jobject JNIHandles::make_local(oop obj) {
59
return make_local(JavaThread::current(), obj);
62
// Used by NewLocalRef which requires null on out-of-memory
63
jobject JNIHandles::make_local(JavaThread* thread, oop obj, AllocFailType alloc_failmode) {
65
return nullptr; // ignore null handles
67
assert(oopDesc::is_oop(obj), "not an oop");
68
assert(!current_thread_in_native(), "must not be in native");
69
STATIC_ASSERT(TypeTag::local == 0);
70
return thread->active_handles()->allocate_handle(thread, obj, alloc_failmode);
74
static void report_handle_allocation_failure(AllocFailType alloc_failmode,
75
const char* handle_kind) {
76
if (alloc_failmode == AllocFailStrategy::EXIT_OOM) {
77
// Fake size value, since we don't know the min allocation size here.
78
vm_exit_out_of_memory(sizeof(oop), OOM_MALLOC_ERROR,
79
"Cannot create %s JNI handle", handle_kind);
81
assert(alloc_failmode == AllocFailStrategy::RETURN_NULL, "invariant");
85
jobject JNIHandles::make_global(Handle obj, AllocFailType alloc_failmode) {
86
assert(!Universe::heap()->is_stw_gc_active(), "can't extend the root set during GC pause");
87
assert(!current_thread_in_native(), "must not be in native");
88
jobject res = nullptr;
90
// ignore null handles
91
assert(oopDesc::is_oop(obj()), "not an oop");
92
oop* ptr = global_handles()->allocate();
93
// Return null on allocation failure.
95
assert(NativeAccess<AS_NO_KEEPALIVE>::oop_load(ptr) == oop(nullptr), "invariant");
96
NativeAccess<>::oop_store(ptr, obj());
97
char* tptr = reinterpret_cast<char*>(ptr) + TypeTag::global;
98
res = reinterpret_cast<jobject>(tptr);
100
report_handle_allocation_failure(alloc_failmode, "global");
107
jweak JNIHandles::make_weak_global(Handle obj, AllocFailType alloc_failmode) {
108
assert(!Universe::heap()->is_stw_gc_active(), "can't extend the root set during GC pause");
109
assert(!current_thread_in_native(), "must not be in native");
111
if (!obj.is_null()) {
112
// ignore null handles
113
assert(oopDesc::is_oop(obj()), "not an oop");
114
oop* ptr = weak_global_handles()->allocate();
115
// Return nullptr on allocation failure.
116
if (ptr != nullptr) {
117
assert(NativeAccess<AS_NO_KEEPALIVE>::oop_load(ptr) == oop(nullptr), "invariant");
118
NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(ptr, obj());
119
char* tptr = reinterpret_cast<char*>(ptr) + TypeTag::weak_global;
120
res = reinterpret_cast<jweak>(tptr);
122
report_handle_allocation_failure(alloc_failmode, "weak global");
128
// Resolve some erroneous cases to null, rather than treating them as
129
// possibly unchecked errors. In particular, deleted handles are
130
// treated as null (though a deleted and later reallocated handle
132
oop JNIHandles::resolve_external_guard(jobject handle) {
133
oop result = nullptr;
134
if (handle != nullptr) {
135
result = resolve_impl<DECORATORS_NONE, true /* external_guard */>(handle);
140
bool JNIHandles::is_weak_global_cleared(jweak handle) {
141
assert(handle != nullptr, "precondition");
142
oop* oop_ptr = weak_global_ptr(handle);
143
oop value = NativeAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(oop_ptr);
144
return value == nullptr;
147
void JNIHandles::destroy_global(jobject handle) {
148
if (handle != nullptr) {
149
oop* oop_ptr = global_ptr(handle);
150
NativeAccess<>::oop_store(oop_ptr, (oop)nullptr);
151
global_handles()->release(oop_ptr);
156
void JNIHandles::destroy_weak_global(jweak handle) {
157
if (handle != nullptr) {
158
oop* oop_ptr = weak_global_ptr(handle);
159
NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_ptr, (oop)nullptr);
160
weak_global_handles()->release(oop_ptr);
165
void JNIHandles::oops_do(OopClosure* f) {
166
global_handles()->oops_do(f);
170
void JNIHandles::weak_oops_do(OopClosure* f) {
171
weak_global_handles()->weak_oops_do(f);
174
bool JNIHandles::is_global_storage(const OopStorage* storage) {
175
return _global_handles == storage;
178
inline bool is_storage_handle(const OopStorage* storage, const oop* ptr) {
179
return storage->allocation_status(ptr) == OopStorage::ALLOCATED_ENTRY;
183
jobjectRefType JNIHandles::handle_type(JavaThread* thread, jobject handle) {
184
assert(handle != nullptr, "precondition");
185
jobjectRefType result = JNIInvalidRefType;
186
if (is_weak_global_tagged(handle)) {
187
if (is_storage_handle(weak_global_handles(), weak_global_ptr(handle))) {
188
result = JNIWeakGlobalRefType;
190
} else if (is_global_tagged(handle)) {
191
switch (global_handles()->allocation_status(global_ptr(handle))) {
192
case OopStorage::ALLOCATED_ENTRY:
193
result = JNIGlobalRefType;
196
case OopStorage::UNALLOCATED_ENTRY:
197
break; // Invalid global handle
200
ShouldNotReachHere();
202
} else if (is_local_handle(thread, handle) || is_frame_handle(thread, handle)) {
203
// Not in global storage. Might be a local handle.
204
result = JNILocalRefType;
210
bool JNIHandles::is_local_handle(JavaThread* thread, jobject handle) {
211
assert(handle != nullptr, "precondition");
212
JNIHandleBlock* block = thread->active_handles();
214
// Look back past possible native calls to jni_PushLocalFrame.
215
while (block != nullptr) {
216
if (block->chain_contains(handle)) {
219
block = block->pop_frame_link();
225
// Determine if the handle is somewhere in the current thread's stack.
226
// We easily can't isolate any particular stack frame the handle might
227
// come from, so we'll check the whole stack.
229
bool JNIHandles::is_frame_handle(JavaThread* thr, jobject handle) {
230
assert(handle != nullptr, "precondition");
231
// If there is no java frame, then this must be top level code, such
232
// as the java command executable, in which case, this type of handle
234
return (thr->has_last_Java_frame() &&
235
thr->is_in_stack_range_incl((address)handle, (address)thr->last_Java_sp()));
239
bool JNIHandles::is_global_handle(jobject handle) {
240
assert(handle != nullptr, "precondition");
241
return is_global_tagged(handle) && is_storage_handle(global_handles(), global_ptr(handle));
245
bool JNIHandles::is_weak_global_handle(jobject handle) {
246
assert(handle != nullptr, "precondition");
247
return is_weak_global_tagged(handle) && is_storage_handle(weak_global_handles(), weak_global_ptr(handle));
250
// We assume this is called at a safepoint: no lock is needed.
251
void JNIHandles::print_on(outputStream* st) {
252
assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
254
st->print_cr("JNI global refs: " SIZE_FORMAT ", weak refs: " SIZE_FORMAT,
255
global_handles()->allocation_count(),
256
weak_global_handles()->allocation_count());
261
void JNIHandles::print() { print_on(tty); }
263
class VerifyJNIHandles: public OopClosure {
265
virtual void do_oop(oop* root) {
266
guarantee(oopDesc::is_oop_or_null(RawAccess<>::oop_load(root)), "Invalid oop");
268
virtual void do_oop(narrowOop* root) { ShouldNotReachHere(); }
271
void JNIHandles::verify() {
272
VerifyJNIHandles verify_handle;
274
oops_do(&verify_handle);
275
weak_oops_do(&verify_handle);
278
// This method is implemented here to avoid circular includes between
279
// jniHandles.hpp and thread.hpp.
280
bool JNIHandles::current_thread_in_native() {
281
Thread* thread = Thread::current();
282
return (thread->is_Java_thread() &&
283
JavaThread::cast(thread)->thread_state() == _thread_in_native);
286
int JNIHandleBlock::_blocks_allocated = 0;
288
static inline bool is_tagged_free_list(uintptr_t value) {
289
return (value & 1u) != 0;
292
static inline uintptr_t tag_free_list(uintptr_t value) {
296
static inline uintptr_t untag_free_list(uintptr_t value) {
297
return value & ~(uintptr_t)1u;
300
// There is a freelist of handles running through the JNIHandleBlock
301
// with a tagged next pointer, distinguishing these next pointers from
302
// oops. The freelist handling currently relies on the size of oops
303
// being the same as a native pointer. If this ever changes, then
304
// this freelist handling must change too.
305
STATIC_ASSERT(sizeof(oop) == sizeof(uintptr_t));
308
void JNIHandleBlock::zap() {
311
for (int index = 0; index < block_size_in_oops; index++) {
312
// NOT using Access here; just bare clobbering to null, since the
313
// block no longer contains valid oops.
319
JNIHandleBlock* JNIHandleBlock::allocate_block(JavaThread* thread, AllocFailType alloc_failmode) {
320
// The VM thread can allocate a handle block in behalf of another thread during a safepoint.
321
assert(thread == nullptr || thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
323
JNIHandleBlock* block;
324
// Check the thread-local free list for a block so we don't
325
// have to acquire a mutex.
326
if (thread != nullptr && thread->free_handle_block() != nullptr) {
327
block = thread->free_handle_block();
328
thread->set_free_handle_block(block->_next);
330
// Allocate new block
331
if (alloc_failmode == AllocFailStrategy::RETURN_NULL) {
332
block = new (std::nothrow) JNIHandleBlock();
333
if (block == nullptr) {
337
block = new JNIHandleBlock();
339
Atomic::inc(&_blocks_allocated);
343
block->_next = nullptr;
344
block->_pop_frame_link = nullptr;
345
// _last, _free_list & _allocate_before_rebuild initialized in allocate_handle
346
debug_only(block->_last = nullptr);
347
debug_only(block->_free_list = nullptr);
348
debug_only(block->_allocate_before_rebuild = -1);
353
void JNIHandleBlock::release_block(JNIHandleBlock* block, JavaThread* thread) {
354
assert(thread == nullptr || thread == Thread::current(), "sanity check");
355
JNIHandleBlock* pop_frame_link = block->pop_frame_link();
356
// Put returned block at the beginning of the thread-local free list.
357
// Note that if thread == nullptr, we use it as an implicit argument that
358
// we _don't_ want the block to be kept on the free_handle_block.
359
// See for instance JavaThread::exit().
360
if (thread != nullptr ) {
362
JNIHandleBlock* freelist = thread->free_handle_block();
363
block->_pop_frame_link = nullptr;
364
thread->set_free_handle_block(block);
366
// Add original freelist to end of chain
367
if ( freelist != nullptr ) {
368
while ( block->_next != nullptr ) block = block->_next;
369
block->_next = freelist;
373
DEBUG_ONLY(block->set_pop_frame_link(nullptr));
374
while (block != nullptr) {
375
JNIHandleBlock* next = block->_next;
376
Atomic::dec(&_blocks_allocated);
377
assert(block->pop_frame_link() == nullptr, "pop_frame_link should be null");
382
if (pop_frame_link != nullptr) {
383
// As a sanity check we release blocks pointed to by the pop_frame_link.
384
// This should never happen (only if PopLocalFrame is not called the
385
// correct number of times).
386
release_block(pop_frame_link, thread);
391
void JNIHandleBlock::oops_do(OopClosure* f) {
392
JNIHandleBlock* current_chain = this;
393
// Iterate over chain of blocks, followed by chains linked through the
395
while (current_chain != nullptr) {
396
for (JNIHandleBlock* current = current_chain; current != nullptr;
397
current = current->_next) {
398
assert(current == current_chain || current->pop_frame_link() == nullptr,
399
"only blocks first in chain should have pop frame link set");
400
for (int index = 0; index < current->_top; index++) {
401
uintptr_t* addr = &(current->_handles)[index];
402
uintptr_t value = *addr;
403
// traverse heap pointers only, not deleted handles or free list
405
if (value != 0 && !is_tagged_free_list(value)) {
406
oop* root = (oop*)addr;
410
// the next handle block is valid only if current block is full
411
if (current->_top < block_size_in_oops) {
415
current_chain = current_chain->pop_frame_link();
420
jobject JNIHandleBlock::allocate_handle(JavaThread* caller, oop obj, AllocFailType alloc_failmode) {
421
assert(Universe::heap()->is_in(obj), "sanity check");
423
// This is the first allocation or the initial block got zapped when
424
// entering a native function. If we have any following blocks they are
425
// not valid anymore.
426
for (JNIHandleBlock* current = _next; current != nullptr;
427
current = current->_next) {
428
assert(current->_last == nullptr, "only first block should have _last set");
429
assert(current->_free_list == nullptr,
430
"only first block should have _free_list set");
431
if (current->_top == 0) {
432
// All blocks after the first clear trailing block are already cleared.
434
for (current = current->_next; current != nullptr; current = current->_next) {
435
assert(current->_top == 0, "trailing blocks must already be cleared");
443
// Clear initial block
444
_free_list = nullptr;
445
_allocate_before_rebuild = 0;
451
if (_last->_top < block_size_in_oops) {
452
oop* handle = (oop*)&(_last->_handles)[_last->_top++];
454
return (jobject) handle;
458
if (_free_list != nullptr) {
459
oop* handle = (oop*)_free_list;
460
_free_list = (uintptr_t*) untag_free_list(*_free_list);
462
return (jobject) handle;
464
// Check if unused block follow last
465
if (_last->_next != nullptr) {
466
// update last and retry
467
_last = _last->_next;
468
return allocate_handle(caller, obj, alloc_failmode);
471
// No space available, we have to rebuild free list or expand
472
if (_allocate_before_rebuild == 0) {
473
rebuild_free_list(); // updates _allocate_before_rebuild counter
475
_last->_next = JNIHandleBlock::allocate_block(caller, alloc_failmode);
476
if (_last->_next == nullptr) {
479
_last = _last->_next;
480
_allocate_before_rebuild--;
482
return allocate_handle(caller, obj, alloc_failmode); // retry
485
void JNIHandleBlock::rebuild_free_list() {
486
assert(_allocate_before_rebuild == 0 && _free_list == nullptr, "just checking");
489
for (JNIHandleBlock* current = this; current != nullptr; current = current->_next) {
490
for (int index = 0; index < current->_top; index++) {
491
uintptr_t* handle = &(current->_handles)[index];
493
// this handle was cleared out by a delete call, reuse it
494
*handle = _free_list == nullptr ? 0 : tag_free_list((uintptr_t)_free_list);
499
// we should not rebuild free list if there are unused handles at the end
500
assert(current->_top == block_size_in_oops, "just checking");
503
// Heuristic: if more than half of the handles are free we rebuild next time
504
// as well, otherwise we append a corresponding number of new blocks before
505
// attempting a free list rebuild again.
506
int total = blocks * block_size_in_oops;
507
int extra = total - 2*free;
509
// Not as many free handles as we would like - compute number of new blocks to append
510
_allocate_before_rebuild = (extra + block_size_in_oops - 1) / block_size_in_oops;
515
bool JNIHandleBlock::contains(jobject handle) const {
516
return ((jobject)&_handles[0] <= handle && handle<(jobject)&_handles[_top]);
520
bool JNIHandleBlock::chain_contains(jobject handle) const {
521
for (JNIHandleBlock* current = (JNIHandleBlock*) this; current != nullptr; current = current->_next) {
522
if (current->contains(handle)) {