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/vmSymbols.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/arguments.hpp"
35 #include "runtime/handles.inline.hpp"
36 #include "runtime/javaCalls.hpp"
37 #include "runtime/javaThread.inline.hpp"
38 #include "runtime/jniHandles.inline.hpp"
39 #include "runtime/mutexLocker.hpp"
40 #include "utilities/align.hpp"
41 #include "utilities/debug.hpp"
42
43 OopStorage* JNIHandles::global_handles() {
44 return _global_handles;
45 }
46
47 OopStorage* JNIHandles::weak_global_handles() {
48 return _weak_global_handles;
49 }
50
51 // Serviceability agent support.
52 OopStorage* JNIHandles::_global_handles = nullptr;
53 OopStorage* JNIHandles::_weak_global_handles = nullptr;
54
55 void jni_handles_init() {
56 JNIHandles::_global_handles = OopStorageSet::create_strong("JNI Global", mtInternal);
57 JNIHandles::_weak_global_handles = OopStorageSet::create_weak("JNI Weak", mtInternal);
58 }
59
60 jobject JNIHandles::make_local(oop obj) {
61 return make_local(JavaThread::current(), obj);
62 }
63
64 // Used by NewLocalRef which requires null on out-of-memory
65 jobject JNIHandles::make_local(JavaThread* thread, oop obj, AllocFailType alloc_failmode) {
66 if (obj == nullptr) {
67 return nullptr; // ignore null handles
68 } else {
69 assert(oopDesc::is_oop(obj), "not an oop");
70 assert(!current_thread_in_native(), "must not be in native");
71 STATIC_ASSERT(TypeTag::local == 0);
72 return thread->active_handles()->allocate_handle(thread, obj, alloc_failmode);
73 }
74 }
75
76 static void report_handle_allocation_failure(AllocFailType alloc_failmode,
77 const char* handle_kind) {
78 if (alloc_failmode == AllocFailStrategy::EXIT_OOM) {
79 // Fake size value, since we don't know the min allocation size here.
80 vm_exit_out_of_memory(sizeof(oop), OOM_MALLOC_ERROR,
81 "Cannot create %s JNI handle", handle_kind);
82 } else {
83 assert(alloc_failmode == AllocFailStrategy::RETURN_NULL, "invariant");
84 }
85 }
86
87 jobject JNIHandles::make_global(Handle obj, AllocFailType alloc_failmode) {
88 assert(!Universe::heap()->is_stw_gc_active(), "can't extend the root set during GC pause");
89 assert(!current_thread_in_native(), "must not be in native");
90 jobject res = nullptr;
91 if (!obj.is_null()) {
92 // ignore null handles
93 assert(oopDesc::is_oop(obj()), "not an oop");
94 oop* ptr = global_handles()->allocate();
95 // Return null on allocation failure.
96 if (ptr != nullptr) {
97 assert(NativeAccess<AS_NO_KEEPALIVE>::oop_load(ptr) == oop(nullptr), "invariant");
98 NativeAccess<>::oop_store(ptr, obj());
99 char* tptr = reinterpret_cast<char*>(ptr) + TypeTag::global;
100 res = reinterpret_cast<jobject>(tptr);
101 } else {
102 report_handle_allocation_failure(alloc_failmode, "global");
103 }
104 }
105
106 return res;
107 }
108
109 jweak JNIHandles::make_weak_global(Handle obj, AllocFailType alloc_failmode) {
110 assert(!Universe::heap()->is_stw_gc_active(), "can't extend the root set during GC pause");
111 assert(!current_thread_in_native(), "must not be in native");
112 jweak res = nullptr;
113 if (!obj.is_null()) {
114 // ignore null handles
115 assert(oopDesc::is_oop(obj()), "not an oop");
116 oop* ptr = weak_global_handles()->allocate();
117 // Return nullptr on allocation failure.
118 if (ptr != nullptr) {
119 assert(NativeAccess<AS_NO_KEEPALIVE>::oop_load(ptr) == oop(nullptr), "invariant");
120 NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(ptr, obj());
121 char* tptr = reinterpret_cast<char*>(ptr) + TypeTag::weak_global;
122 res = reinterpret_cast<jweak>(tptr);
123 } else {
124 report_handle_allocation_failure(alloc_failmode, "weak global");
125 }
126 }
127 return res;
128 }
129
130 // Resolve some erroneous cases to null, rather than treating them as
131 // possibly unchecked errors. In particular, deleted handles are
132 // treated as null (though a deleted and later reallocated handle
133 // isn't detected).
134 oop JNIHandles::resolve_external_guard(jobject handle) {
135 oop result = nullptr;
136 if (handle != nullptr) {
137 result = resolve_impl<DECORATORS_NONE, true /* external_guard */>(handle);
138 }
139 return result;
140 }
141
142 bool JNIHandles::is_weak_global_cleared(jweak handle) {
143 assert(handle != nullptr, "precondition");
144 oop* oop_ptr = weak_global_ptr(handle);
145 oop value = NativeAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(oop_ptr);
146 return value == nullptr;
147 }
148
149 void JNIHandles::destroy_global(jobject handle) {
150 if (handle != nullptr) {
151 oop* oop_ptr = global_ptr(handle);
152 NativeAccess<>::oop_store(oop_ptr, (oop)nullptr);
153 global_handles()->release(oop_ptr);
154 }
155 }
156
157
158 void JNIHandles::destroy_weak_global(jweak handle) {
159 if (handle != nullptr) {
160 oop* oop_ptr = weak_global_ptr(handle);
161 NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_ptr, (oop)nullptr);
162 weak_global_handles()->release(oop_ptr);
163 }
164 }
165
166
167 void JNIHandles::oops_do(OopClosure* f) {
168 global_handles()->oops_do(f);
169 }
170
171
172 void JNIHandles::weak_oops_do(OopClosure* f) {
173 weak_global_handles()->weak_oops_do(f);
174 }
175
176 bool JNIHandles::is_global_storage(const OopStorage* storage) {
177 return _global_handles == storage;
178 }
179
180 inline bool is_storage_handle(const OopStorage* storage, const oop* ptr) {
181 return storage->allocation_status(ptr) == OopStorage::ALLOCATED_ENTRY;
182 }
183
184
185 jobjectRefType JNIHandles::handle_type(JavaThread* thread, jobject handle) {
186 assert(handle != nullptr, "precondition");
187 jobjectRefType result = JNIInvalidRefType;
188 if (is_weak_global_tagged(handle)) {
189 if (is_storage_handle(weak_global_handles(), weak_global_ptr(handle))) {
190 result = JNIWeakGlobalRefType;
191 }
192 } else if (is_global_tagged(handle)) {
193 switch (global_handles()->allocation_status(global_ptr(handle))) {
194 case OopStorage::ALLOCATED_ENTRY:
195 result = JNIGlobalRefType;
196 break;
197
198 case OopStorage::UNALLOCATED_ENTRY:
199 break; // Invalid global handle
200
201 default:
202 ShouldNotReachHere();
203 }
204 } else if (is_local_handle(thread, handle) || is_frame_handle(thread, handle)) {
205 // Not in global storage. Might be a local handle.
206 result = JNILocalRefType;
207 }
208 return result;
209 }
210
211
212 bool JNIHandles::is_local_handle(JavaThread* thread, jobject handle) {
213 assert(handle != nullptr, "precondition");
214 JNIHandleBlock* block = thread->active_handles();
215
216 // Look back past possible native calls to jni_PushLocalFrame.
217 while (block != nullptr) {
218 if (block->chain_contains(handle)) {
219 return true;
220 }
221 block = block->pop_frame_link();
222 }
223 return false;
224 }
225
226
227 // Determine if the handle is somewhere in the current thread's stack.
228 // We easily can't isolate any particular stack frame the handle might
229 // come from, so we'll check the whole stack.
230
231 bool JNIHandles::is_frame_handle(JavaThread* thr, jobject handle) {
232 assert(handle != nullptr, "precondition");
233 // If there is no java frame, then this must be top level code, such
234 // as the java command executable, in which case, this type of handle
235 // is not permitted.
236 return (thr->has_last_Java_frame() &&
237 thr->is_in_stack_range_incl((address)handle, (address)thr->last_Java_sp()));
238 }
239
240
241 bool JNIHandles::is_global_handle(jobject handle) {
242 assert(handle != nullptr, "precondition");
243 return is_global_tagged(handle) && is_storage_handle(global_handles(), global_ptr(handle));
244 }
245
246
247 bool JNIHandles::is_weak_global_handle(jobject handle) {
248 assert(handle != nullptr, "precondition");
249 return is_weak_global_tagged(handle) && is_storage_handle(weak_global_handles(), weak_global_ptr(handle));
250 }
251
252 // We assume this is called at a safepoint: no lock is needed.
253 void JNIHandles::print_on(outputStream* st) {
254 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
255
256 st->print_cr("JNI global refs: %zu, weak refs: %zu",
257 global_handles()->allocation_count(),
258 weak_global_handles()->allocation_count());
259 st->cr();
260 st->flush();
261 }
262
263 void JNIHandles::print() { print_on(tty); }
264
265 class VerifyJNIHandles: public OopClosure {
266 public:
267 virtual void do_oop(oop* root) {
268 guarantee(oopDesc::is_oop_or_null(RawAccess<>::oop_load(root)), "Invalid oop");
269 }
270 virtual void do_oop(narrowOop* root) { ShouldNotReachHere(); }
271 };
272
273 void JNIHandles::verify() {
274 VerifyJNIHandles verify_handle;
275
276 oops_do(&verify_handle);
277 weak_oops_do(&verify_handle);
278 }
279
280 // This method is implemented here to avoid circular includes between
281 // jniHandles.hpp and thread.hpp.
282 bool JNIHandles::current_thread_in_native() {
283 Thread* thread = Thread::current();
284 return (thread->is_Java_thread() &&
285 JavaThread::cast(thread)->thread_state() == _thread_in_native);
286 }
287
288 bool JNIHandles::is_same_object(jobject handle1, jobject handle2) {
289 oop obj1 = resolve_no_keepalive(handle1);
290 oop obj2 = resolve_no_keepalive(handle2);
291
292 bool ret = obj1 == obj2;
293
294 if (!ret && Arguments::is_valhalla_enabled()) {
295 if (obj1 != nullptr && obj2 != nullptr &&
296 obj1->klass() == obj2->klass() && obj1->klass()->is_inline_klass()) {
297 // The two references are different, they are not null and they are both inline types,
298 // a full substitutability test is required, calling ValueObjectMethods.isSubstitutable()
299 // (similarly to InterpreterRuntime::is_substitutable).
300 // The jobjects must be re-resolved as the no-keepalive variants are not safe to use
301 // with the Java upcall.
302 JavaThread* THREAD = JavaThread::current();
303 Handle ha(THREAD, resolve_non_null(handle1));
304 Handle hb(THREAD, resolve_non_null(handle2));
305 JavaValue result(T_BOOLEAN);
306 JavaCallArguments args;
307 args.push_oop(ha);
308 args.push_oop(hb);
309 methodHandle method(THREAD, Universe::is_substitutable_method());
310 JavaCalls::call(&result, method, &args, THREAD);
311 Exceptions::wrap_exception_in_internal_error("Internal error in substitutability test", CHECK_false);
312
313 ret = result.get_jboolean();
314 }
315 }
316
317 return ret;
318 }
319
320
321 int JNIHandleBlock::_blocks_allocated = 0;
322
323 static inline bool is_tagged_free_list(uintptr_t value) {
324 return (value & 1u) != 0;
325 }
326
327 static inline uintptr_t tag_free_list(uintptr_t value) {
328 return value | 1u;
329 }
330
331 static inline uintptr_t untag_free_list(uintptr_t value) {
332 return value & ~(uintptr_t)1u;
333 }
334
335 // There is a freelist of handles running through the JNIHandleBlock
336 // with a tagged next pointer, distinguishing these next pointers from
337 // oops. The freelist handling currently relies on the size of oops
338 // being the same as a native pointer. If this ever changes, then
339 // this freelist handling must change too.
340 STATIC_ASSERT(sizeof(oop) == sizeof(uintptr_t));
341
342 #ifdef ASSERT
343 void JNIHandleBlock::zap() {
344 // Zap block values
345 _top = 0;
346 for (int index = 0; index < block_size_in_oops; index++) {
347 // NOT using Access here; just bare clobbering to null, since the
348 // block no longer contains valid oops.
349 _handles[index] = 0;
350 }
351 }
352 #endif // ASSERT
353
354 JNIHandleBlock* JNIHandleBlock::allocate_block(JavaThread* thread, AllocFailType alloc_failmode) {
355 // The VM thread can allocate a handle block in behalf of another thread during a safepoint.
356 assert(thread == nullptr || thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
357 "sanity check");
358 JNIHandleBlock* block;
359 // Check the thread-local free list for a block so we don't
360 // have to acquire a mutex.
361 if (thread != nullptr && thread->free_handle_block() != nullptr) {
362 block = thread->free_handle_block();
363 thread->set_free_handle_block(block->_next);
364 } else {
365 // Allocate new block
366 if (alloc_failmode == AllocFailStrategy::RETURN_NULL) {
367 block = new (std::nothrow) JNIHandleBlock();
368 if (block == nullptr) {
369 return nullptr;
370 }
371 } else {
372 block = new JNIHandleBlock();
373 }
374 AtomicAccess::inc(&_blocks_allocated);
375 block->zap();
376 }
377 block->_top = 0;
378 block->_next = nullptr;
379 block->_pop_frame_link = nullptr;
380 // _last, _free_list & _allocate_before_rebuild initialized in allocate_handle
381 DEBUG_ONLY(block->_last = nullptr);
382 DEBUG_ONLY(block->_free_list = nullptr);
383 DEBUG_ONLY(block->_allocate_before_rebuild = -1);
384 return block;
385 }
386
387
388 void JNIHandleBlock::release_block(JNIHandleBlock* block, JavaThread* thread) {
389 assert(thread == nullptr || thread == Thread::current(), "sanity check");
390 JNIHandleBlock* pop_frame_link = block->pop_frame_link();
391 // Put returned block at the beginning of the thread-local free list.
392 // Note that if thread == nullptr, we use it as an implicit argument that
393 // we _don't_ want the block to be kept on the free_handle_block.
394 // See for instance JavaThread::exit().
395 if (thread != nullptr ) {
396 block->zap();
397 JNIHandleBlock* freelist = thread->free_handle_block();
398 block->_pop_frame_link = nullptr;
399 thread->set_free_handle_block(block);
400
401 // Add original freelist to end of chain
402 if ( freelist != nullptr ) {
403 while ( block->_next != nullptr ) block = block->_next;
404 block->_next = freelist;
405 }
406 block = nullptr;
407 } else {
408 DEBUG_ONLY(block->set_pop_frame_link(nullptr));
409 while (block != nullptr) {
410 JNIHandleBlock* next = block->_next;
411 AtomicAccess::dec(&_blocks_allocated);
412 assert(block->pop_frame_link() == nullptr, "pop_frame_link should be null");
413 delete block;
414 block = next;
415 }
416 }
417 if (pop_frame_link != nullptr) {
418 // As a sanity check we release blocks pointed to by the pop_frame_link.
419 // This should never happen (only if PopLocalFrame is not called the
420 // correct number of times).
421 release_block(pop_frame_link, thread);
422 }
423 }
424
425
426 void JNIHandleBlock::oops_do(OopClosure* f) {
427 JNIHandleBlock* current_chain = this;
428 // Iterate over chain of blocks, followed by chains linked through the
429 // pop frame links.
430 while (current_chain != nullptr) {
431 for (JNIHandleBlock* current = current_chain; current != nullptr;
432 current = current->_next) {
433 assert(current == current_chain || current->pop_frame_link() == nullptr,
434 "only blocks first in chain should have pop frame link set");
435 for (int index = 0; index < current->_top; index++) {
436 uintptr_t* addr = &(current->_handles)[index];
437 uintptr_t value = *addr;
438 // traverse heap pointers only, not deleted handles or free list
439 // pointers
440 if (value != 0 && !is_tagged_free_list(value)) {
441 oop* root = (oop*)addr;
442 f->do_oop(root);
443 }
444 }
445 // the next handle block is valid only if current block is full
446 if (current->_top < block_size_in_oops) {
447 break;
448 }
449 }
450 current_chain = current_chain->pop_frame_link();
451 }
452 }
453
454
455 jobject JNIHandleBlock::allocate_handle(JavaThread* caller, oop obj, AllocFailType alloc_failmode) {
456 assert(Universe::heap()->is_in(obj), "sanity check");
457 if (_top == 0) {
458 // This is the first allocation or the initial block got zapped when
459 // entering a native function. If we have any following blocks they are
460 // not valid anymore.
461 for (JNIHandleBlock* current = _next; current != nullptr;
462 current = current->_next) {
463 assert(current->_last == nullptr, "only first block should have _last set");
464 assert(current->_free_list == nullptr,
465 "only first block should have _free_list set");
466 if (current->_top == 0) {
467 // All blocks after the first clear trailing block are already cleared.
468 #ifdef ASSERT
469 for (current = current->_next; current != nullptr; current = current->_next) {
470 assert(current->_top == 0, "trailing blocks must already be cleared");
471 }
472 #endif
473 break;
474 }
475 current->_top = 0;
476 current->zap();
477 }
478 // Clear initial block
479 _free_list = nullptr;
480 _allocate_before_rebuild = 0;
481 _last = this;
482 zap();
483 }
484
485 // Try last block
486 if (_last->_top < block_size_in_oops) {
487 oop* handle = (oop*)&(_last->_handles)[_last->_top++];
488 *handle = obj;
489 return (jobject) handle;
490 }
491
492 // Try free list
493 if (_free_list != nullptr) {
494 oop* handle = (oop*)_free_list;
495 _free_list = (uintptr_t*) untag_free_list(*_free_list);
496 *handle = obj;
497 return (jobject) handle;
498 }
499 // Check if unused block follow last
500 if (_last->_next != nullptr) {
501 // update last and retry
502 _last = _last->_next;
503 return allocate_handle(caller, obj, alloc_failmode);
504 }
505
506 // No space available, we have to rebuild free list or expand
507 if (_allocate_before_rebuild == 0) {
508 rebuild_free_list(); // updates _allocate_before_rebuild counter
509 } else {
510 _last->_next = JNIHandleBlock::allocate_block(caller, alloc_failmode);
511 if (_last->_next == nullptr) {
512 return nullptr;
513 }
514 _last = _last->_next;
515 _allocate_before_rebuild--;
516 }
517 return allocate_handle(caller, obj, alloc_failmode); // retry
518 }
519
520 void JNIHandleBlock::rebuild_free_list() {
521 assert(_allocate_before_rebuild == 0 && _free_list == nullptr, "just checking");
522 int free = 0;
523 int blocks = 0;
524 for (JNIHandleBlock* current = this; current != nullptr; current = current->_next) {
525 for (int index = 0; index < current->_top; index++) {
526 uintptr_t* handle = &(current->_handles)[index];
527 if (*handle == 0) {
528 // this handle was cleared out by a delete call, reuse it
529 *handle = _free_list == nullptr ? 0 : tag_free_list((uintptr_t)_free_list);
530 _free_list = handle;
531 free++;
532 }
533 }
534 // we should not rebuild free list if there are unused handles at the end
535 assert(current->_top == block_size_in_oops, "just checking");
536 blocks++;
537 }
538 // Heuristic: if more than half of the handles are free we rebuild next time
539 // as well, otherwise we append a corresponding number of new blocks before
540 // attempting a free list rebuild again.
541 int total = blocks * block_size_in_oops;
542 int extra = total - 2*free;
543 if (extra > 0) {
544 // Not as many free handles as we would like - compute number of new blocks to append
545 _allocate_before_rebuild = (extra + block_size_in_oops - 1) / block_size_in_oops;
546 }
547 }
548
549
550 bool JNIHandleBlock::contains(jobject handle) const {
551 return ((jobject)&_handles[0] <= handle && handle<(jobject)&_handles[_top]);
552 }
553
554
555 bool JNIHandleBlock::chain_contains(jobject handle) const {
556 for (JNIHandleBlock* current = (JNIHandleBlock*) this; current != nullptr; current = current->_next) {
557 if (current->contains(handle)) {
558 return true;
559 }
560 }
561 return false;
562 }