1 /* 2 * Copyright (c) 1998, 2018, 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 "precompiled.hpp" 26 #include "gc/shared/oopStorage.inline.hpp" 27 #include "logging/log.hpp" 28 #include "memory/iterator.hpp" 29 #include "oops/access.inline.hpp" 30 #include "oops/oop.inline.hpp" 31 #include "runtime/handles.inline.hpp" 32 #include "runtime/jniHandles.inline.hpp" 33 #include "runtime/mutexLocker.hpp" 34 #include "runtime/thread.inline.hpp" 35 #include "utilities/align.hpp" 36 #include "utilities/debug.hpp" 37 38 OopStorage* JNIHandles::_global_handles = NULL; 39 OopStorage* JNIHandles::_weak_global_handles = NULL; 40 41 OopStorage* JNIHandles::global_handles() { 42 assert(_global_handles != NULL, "Uninitialized JNI global handles"); 43 return _global_handles; 44 } 45 46 OopStorage* JNIHandles::weak_global_handles() { 47 assert(_weak_global_handles != NULL, "Uninitialized JNI weak global handles"); 48 return _weak_global_handles; 49 } 50 51 52 jobject JNIHandles::make_local(oop obj) { 53 if (obj == NULL) { 54 return NULL; // ignore null handles 55 } else { 56 Thread* thread = Thread::current(); 57 assert(oopDesc::is_oop(obj), "not an oop"); 58 assert(!current_thread_in_native(), "must not be in native"); 59 return thread->active_handles()->allocate_handle(obj); 60 } 61 } 62 63 64 // optimized versions 65 66 jobject JNIHandles::make_local(Thread* thread, oop obj) { 67 if (obj == NULL) { 68 return NULL; // ignore null handles 69 } else { 70 assert(oopDesc::is_oop(obj), "not an oop"); 71 assert(thread->is_Java_thread(), "not a Java thread"); 72 assert(!current_thread_in_native(), "must not be in native"); 73 return thread->active_handles()->allocate_handle(obj); 74 } 75 } 76 77 78 jobject JNIHandles::make_local(JNIEnv* env, oop obj) { 79 if (obj == NULL) { 80 return NULL; // ignore null handles 81 } else { 82 JavaThread* thread = JavaThread::thread_from_jni_environment(env); 83 assert(oopDesc::is_oop(obj), "not an oop"); 84 assert(!current_thread_in_native(), "must not be in native"); 85 return thread->active_handles()->allocate_handle(obj); 86 } 87 } 88 89 90 static void report_handle_allocation_failure(AllocFailType alloc_failmode, 91 const char* handle_kind) { 92 if (alloc_failmode == AllocFailStrategy::EXIT_OOM) { 93 // Fake size value, since we don't know the min allocation size here. 94 vm_exit_out_of_memory(sizeof(oop), OOM_MALLOC_ERROR, 95 "Cannot create %s JNI handle", handle_kind); 96 } else { 97 assert(alloc_failmode == AllocFailStrategy::RETURN_NULL, "invariant"); 98 } 99 } 100 101 jobject JNIHandles::make_global(Handle obj, AllocFailType alloc_failmode) { 102 assert(!Universe::heap()->is_gc_active(), "can't extend the root set during GC"); 103 assert(!current_thread_in_native(), "must not be in native"); 104 jobject res = NULL; 105 if (!obj.is_null()) { 106 // ignore null handles 107 assert(oopDesc::is_oop(obj()), "not an oop"); 108 oop* ptr = global_handles()->allocate(); 109 // Return NULL on allocation failure. 110 if (ptr != NULL) { 111 assert(*ptr == NULL, "invariant"); 112 RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, obj()); 113 res = reinterpret_cast<jobject>(ptr); 114 } else { 115 report_handle_allocation_failure(alloc_failmode, "global"); 116 } 117 } else { 118 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 119 } 120 121 return res; 122 } 123 124 125 jobject JNIHandles::make_weak_global(Handle obj, AllocFailType alloc_failmode) { 126 assert(!Universe::heap()->is_gc_active(), "can't extend the root set during GC"); 127 assert(!current_thread_in_native(), "must not be in native"); 128 jobject res = NULL; 129 if (!obj.is_null()) { 130 // ignore null handles 131 assert(oopDesc::is_oop(obj()), "not an oop"); 132 oop* ptr = weak_global_handles()->allocate(); 133 // Return NULL on allocation failure. 134 if (ptr != NULL) { 135 assert(*ptr == NULL, "invariant"); 136 RootAccess<ON_PHANTOM_OOP_REF>::oop_store(ptr, obj()); 137 char* tptr = reinterpret_cast<char*>(ptr) + weak_tag_value; 138 res = reinterpret_cast<jobject>(tptr); 139 } else { 140 report_handle_allocation_failure(alloc_failmode, "weak global"); 141 } 142 } else { 143 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 144 } 145 return res; 146 } 147 148 // Resolve some erroneous cases to NULL, rather than treating them as 149 // possibly unchecked errors. In particular, deleted handles are 150 // treated as NULL (though a deleted and later reallocated handle 151 // isn't detected). 152 oop JNIHandles::resolve_external_guard(jobject handle) { 153 oop result = NULL; 154 if (handle != NULL) { 155 result = resolve_impl<true /* external_guard */ >(handle); 156 } 157 return result; 158 } 159 160 oop JNIHandles::resolve_jweak(jweak handle) { 161 assert(handle != NULL, "precondition"); 162 assert(is_jweak(handle), "precondition"); 163 return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(jweak_ptr(handle)); 164 } 165 166 bool JNIHandles::is_global_weak_cleared(jweak handle) { 167 assert(handle != NULL, "precondition"); 168 assert(is_jweak(handle), "not a weak handle"); 169 oop* oop_ptr = jweak_ptr(handle); 170 oop value = RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(oop_ptr); 171 return value == NULL; 172 } 173 174 void JNIHandles::destroy_global(jobject handle) { 175 if (handle != NULL) { 176 assert(!is_jweak(handle), "wrong method for detroying jweak"); 177 oop* oop_ptr = jobject_ptr(handle); 178 RootAccess<IN_CONCURRENT_ROOT>::oop_store(oop_ptr, (oop)NULL); 179 global_handles()->release(oop_ptr); 180 } 181 } 182 183 184 void JNIHandles::destroy_weak_global(jobject handle) { 185 if (handle != NULL) { 186 assert(is_jweak(handle), "JNI handle not jweak"); 187 oop* oop_ptr = jweak_ptr(handle); 188 RootAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_ptr, (oop)NULL); 189 weak_global_handles()->release(oop_ptr); 190 } 191 } 192 193 194 void JNIHandles::oops_do(OopClosure* f) { 195 global_handles()->oops_do(f); 196 } 197 198 199 void JNIHandles::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f) { 200 weak_global_handles()->weak_oops_do(is_alive, f); 201 } 202 203 204 void JNIHandles::weak_oops_do(OopClosure* f) { 205 weak_global_handles()->weak_oops_do(f); 206 } 207 208 209 void JNIHandles::initialize() { 210 _global_handles = new OopStorage("JNI Global", 211 JNIGlobalAlloc_lock, 212 JNIGlobalActive_lock); 213 _weak_global_handles = new OopStorage("JNI Weak", 214 JNIWeakAlloc_lock, 215 JNIWeakActive_lock); 216 } 217 218 219 inline bool is_storage_handle(const OopStorage* storage, const oop* ptr) { 220 return storage->allocation_status(ptr) == OopStorage::ALLOCATED_ENTRY; 221 } 222 223 224 jobjectRefType JNIHandles::handle_type(Thread* thread, jobject handle) { 225 assert(handle != NULL, "precondition"); 226 jobjectRefType result = JNIInvalidRefType; 227 if (is_jweak(handle)) { 228 if (is_storage_handle(weak_global_handles(), jweak_ptr(handle))) { 229 result = JNIWeakGlobalRefType; 230 } 231 } else { 232 switch (global_handles()->allocation_status(jobject_ptr(handle))) { 233 case OopStorage::ALLOCATED_ENTRY: 234 result = JNIGlobalRefType; 235 break; 236 237 case OopStorage::UNALLOCATED_ENTRY: 238 break; // Invalid global handle 239 240 case OopStorage::INVALID_ENTRY: 241 // Not in global storage. Might be a local handle. 242 if (is_local_handle(thread, handle) || 243 (thread->is_Java_thread() && 244 is_frame_handle((JavaThread*)thread, handle))) { 245 result = JNILocalRefType; 246 } 247 break; 248 249 default: 250 ShouldNotReachHere(); 251 } 252 } 253 return result; 254 } 255 256 257 bool JNIHandles::is_local_handle(Thread* thread, jobject handle) { 258 assert(handle != NULL, "precondition"); 259 JNIHandleBlock* block = thread->active_handles(); 260 261 // Look back past possible native calls to jni_PushLocalFrame. 262 while (block != NULL) { 263 if (block->chain_contains(handle)) { 264 return true; 265 } 266 block = block->pop_frame_link(); 267 } 268 return false; 269 } 270 271 272 // Determine if the handle is somewhere in the current thread's stack. 273 // We easily can't isolate any particular stack frame the handle might 274 // come from, so we'll check the whole stack. 275 276 bool JNIHandles::is_frame_handle(JavaThread* thr, jobject handle) { 277 assert(handle != NULL, "precondition"); 278 // If there is no java frame, then this must be top level code, such 279 // as the java command executable, in which case, this type of handle 280 // is not permitted. 281 return (thr->has_last_Java_frame() && 282 (void*)handle < (void*)thr->stack_base() && 283 (void*)handle >= (void*)thr->last_Java_sp()); 284 } 285 286 287 bool JNIHandles::is_global_handle(jobject handle) { 288 assert(handle != NULL, "precondition"); 289 return !is_jweak(handle) && is_storage_handle(global_handles(), jobject_ptr(handle)); 290 } 291 292 293 bool JNIHandles::is_weak_global_handle(jobject handle) { 294 assert(handle != NULL, "precondition"); 295 return is_jweak(handle) && is_storage_handle(weak_global_handles(), jweak_ptr(handle)); 296 } 297 298 size_t JNIHandles::global_handle_memory_usage() { 299 return global_handles()->total_memory_usage(); 300 } 301 302 size_t JNIHandles::weak_global_handle_memory_usage() { 303 return weak_global_handles()->total_memory_usage(); 304 } 305 306 307 // We assume this is called at a safepoint: no lock is needed. 308 void JNIHandles::print_on(outputStream* st) { 309 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 310 311 st->print_cr("JNI global refs: " SIZE_FORMAT ", weak refs: " SIZE_FORMAT, 312 global_handles()->allocation_count(), 313 weak_global_handles()->allocation_count()); 314 st->cr(); 315 st->flush(); 316 } 317 318 class VerifyJNIHandles: public OopClosure { 319 public: 320 virtual void do_oop(oop* root) { 321 (*root)->verify(); 322 } 323 virtual void do_oop(narrowOop* root) { ShouldNotReachHere(); } 324 }; 325 326 void JNIHandles::verify() { 327 VerifyJNIHandles verify_handle; 328 329 oops_do(&verify_handle); 330 weak_oops_do(&verify_handle); 331 } 332 333 // This method is implemented here to avoid circular includes between 334 // jniHandles.hpp and thread.hpp. 335 bool JNIHandles::current_thread_in_native() { 336 Thread* thread = Thread::current(); 337 return (thread->is_Java_thread() && 338 JavaThread::current()->thread_state() == _thread_in_native); 339 } 340 341 342 void jni_handles_init() { 343 JNIHandles::initialize(); 344 } 345 346 347 int JNIHandleBlock::_blocks_allocated = 0; 348 JNIHandleBlock* JNIHandleBlock::_block_free_list = NULL; 349 #ifndef PRODUCT 350 JNIHandleBlock* JNIHandleBlock::_block_list = NULL; 351 #endif 352 353 354 #ifdef ASSERT 355 void JNIHandleBlock::zap() { 356 // Zap block values 357 _top = 0; 358 for (int index = 0; index < block_size_in_oops; index++) { 359 // NOT using Access here; just bare clobbering to NULL, since the 360 // block no longer contains valid oops. 361 _handles[index] = NULL; 362 } 363 } 364 #endif // ASSERT 365 366 JNIHandleBlock* JNIHandleBlock::allocate_block(Thread* thread) { 367 assert(thread == NULL || thread == Thread::current(), "sanity check"); 368 JNIHandleBlock* block; 369 // Check the thread-local free list for a block so we don't 370 // have to acquire a mutex. 371 if (thread != NULL && thread->free_handle_block() != NULL) { 372 block = thread->free_handle_block(); 373 thread->set_free_handle_block(block->_next); 374 } 375 else { 376 // locking with safepoint checking introduces a potential deadlock: 377 // - we would hold JNIHandleBlockFreeList_lock and then Threads_lock 378 // - another would hold Threads_lock (jni_AttachCurrentThread) and then 379 // JNIHandleBlockFreeList_lock (JNIHandleBlock::allocate_block) 380 MutexLockerEx ml(JNIHandleBlockFreeList_lock, 381 Mutex::_no_safepoint_check_flag); 382 if (_block_free_list == NULL) { 383 // Allocate new block 384 block = new JNIHandleBlock(); 385 _blocks_allocated++; 386 block->zap(); 387 #ifndef PRODUCT 388 // Link new block to list of all allocated blocks 389 block->_block_list_link = _block_list; 390 _block_list = block; 391 #endif 392 } else { 393 // Get block from free list 394 block = _block_free_list; 395 _block_free_list = _block_free_list->_next; 396 } 397 } 398 block->_top = 0; 399 block->_next = NULL; 400 block->_pop_frame_link = NULL; 401 block->_planned_capacity = block_size_in_oops; 402 // _last, _free_list & _allocate_before_rebuild initialized in allocate_handle 403 debug_only(block->_last = NULL); 404 debug_only(block->_free_list = NULL); 405 debug_only(block->_allocate_before_rebuild = -1); 406 return block; 407 } 408 409 410 void JNIHandleBlock::release_block(JNIHandleBlock* block, Thread* thread) { 411 assert(thread == NULL || thread == Thread::current(), "sanity check"); 412 JNIHandleBlock* pop_frame_link = block->pop_frame_link(); 413 // Put returned block at the beginning of the thread-local free list. 414 // Note that if thread == NULL, we use it as an implicit argument that 415 // we _don't_ want the block to be kept on the free_handle_block. 416 // See for instance JavaThread::exit(). 417 if (thread != NULL ) { 418 block->zap(); 419 JNIHandleBlock* freelist = thread->free_handle_block(); 420 block->_pop_frame_link = NULL; 421 thread->set_free_handle_block(block); 422 423 // Add original freelist to end of chain 424 if ( freelist != NULL ) { 425 while ( block->_next != NULL ) block = block->_next; 426 block->_next = freelist; 427 } 428 block = NULL; 429 } 430 if (block != NULL) { 431 // Return blocks to free list 432 // locking with safepoint checking introduces a potential deadlock: 433 // - we would hold JNIHandleBlockFreeList_lock and then Threads_lock 434 // - another would hold Threads_lock (jni_AttachCurrentThread) and then 435 // JNIHandleBlockFreeList_lock (JNIHandleBlock::allocate_block) 436 MutexLockerEx ml(JNIHandleBlockFreeList_lock, 437 Mutex::_no_safepoint_check_flag); 438 while (block != NULL) { 439 block->zap(); 440 JNIHandleBlock* next = block->_next; 441 block->_next = _block_free_list; 442 _block_free_list = block; 443 block = next; 444 } 445 } 446 if (pop_frame_link != NULL) { 447 // As a sanity check we release blocks pointed to by the pop_frame_link. 448 // This should never happen (only if PopLocalFrame is not called the 449 // correct number of times). 450 release_block(pop_frame_link, thread); 451 } 452 } 453 454 455 void JNIHandleBlock::oops_do(OopClosure* f) { 456 JNIHandleBlock* current_chain = this; 457 // Iterate over chain of blocks, followed by chains linked through the 458 // pop frame links. 459 while (current_chain != NULL) { 460 for (JNIHandleBlock* current = current_chain; current != NULL; 461 current = current->_next) { 462 assert(current == current_chain || current->pop_frame_link() == NULL, 463 "only blocks first in chain should have pop frame link set"); 464 for (int index = 0; index < current->_top; index++) { 465 oop* root = &(current->_handles)[index]; 466 oop value = *root; 467 // traverse heap pointers only, not deleted handles or free list 468 // pointers 469 if (value != NULL && Universe::heap()->is_in_reserved(value)) { 470 f->do_oop(root); 471 } 472 } 473 // the next handle block is valid only if current block is full 474 if (current->_top < block_size_in_oops) { 475 break; 476 } 477 } 478 current_chain = current_chain->pop_frame_link(); 479 } 480 } 481 482 483 jobject JNIHandleBlock::allocate_handle(oop obj) { 484 assert(Universe::heap()->is_in_reserved(obj), "sanity check"); 485 if (_top == 0) { 486 // This is the first allocation or the initial block got zapped when 487 // entering a native function. If we have any following blocks they are 488 // not valid anymore. 489 for (JNIHandleBlock* current = _next; current != NULL; 490 current = current->_next) { 491 assert(current->_last == NULL, "only first block should have _last set"); 492 assert(current->_free_list == NULL, 493 "only first block should have _free_list set"); 494 if (current->_top == 0) { 495 // All blocks after the first clear trailing block are already cleared. 496 #ifdef ASSERT 497 for (current = current->_next; current != NULL; current = current->_next) { 498 assert(current->_top == 0, "trailing blocks must already be cleared"); 499 } 500 #endif 501 break; 502 } 503 current->_top = 0; 504 current->zap(); 505 } 506 // Clear initial block 507 _free_list = NULL; 508 _allocate_before_rebuild = 0; 509 _last = this; 510 zap(); 511 } 512 513 // Try last block 514 if (_last->_top < block_size_in_oops) { 515 oop* handle = &(_last->_handles)[_last->_top++]; 516 RootAccess<AS_DEST_NOT_INITIALIZED>::oop_store(handle, obj); 517 return (jobject) handle; 518 } 519 520 // Try free list 521 if (_free_list != NULL) { 522 oop* handle = _free_list; 523 _free_list = (oop*) *_free_list; 524 RootAccess<AS_DEST_NOT_INITIALIZED>::oop_store(handle, obj); 525 return (jobject) handle; 526 } 527 // Check if unused block follow last 528 if (_last->_next != NULL) { 529 // update last and retry 530 _last = _last->_next; 531 return allocate_handle(obj); 532 } 533 534 // No space available, we have to rebuild free list or expand 535 if (_allocate_before_rebuild == 0) { 536 rebuild_free_list(); // updates _allocate_before_rebuild counter 537 } else { 538 // Append new block 539 Thread* thread = Thread::current(); 540 Handle obj_handle(thread, obj); 541 // This can block, so we need to preserve obj across call. 542 _last->_next = JNIHandleBlock::allocate_block(thread); 543 _last = _last->_next; 544 _allocate_before_rebuild--; 545 obj = obj_handle(); 546 } 547 return allocate_handle(obj); // retry 548 } 549 550 void JNIHandleBlock::rebuild_free_list() { 551 assert(_allocate_before_rebuild == 0 && _free_list == NULL, "just checking"); 552 int free = 0; 553 int blocks = 0; 554 for (JNIHandleBlock* current = this; current != NULL; current = current->_next) { 555 for (int index = 0; index < current->_top; index++) { 556 oop* handle = &(current->_handles)[index]; 557 if (*handle == NULL) { 558 // this handle was cleared out by a delete call, reuse it 559 *handle = (oop) _free_list; 560 _free_list = handle; 561 free++; 562 } 563 } 564 // we should not rebuild free list if there are unused handles at the end 565 assert(current->_top == block_size_in_oops, "just checking"); 566 blocks++; 567 } 568 // Heuristic: if more than half of the handles are free we rebuild next time 569 // as well, otherwise we append a corresponding number of new blocks before 570 // attempting a free list rebuild again. 571 int total = blocks * block_size_in_oops; 572 int extra = total - 2*free; 573 if (extra > 0) { 574 // Not as many free handles as we would like - compute number of new blocks to append 575 _allocate_before_rebuild = (extra + block_size_in_oops - 1) / block_size_in_oops; 576 } 577 } 578 579 580 bool JNIHandleBlock::contains(jobject handle) const { 581 return ((jobject)&_handles[0] <= handle && handle<(jobject)&_handles[_top]); 582 } 583 584 585 bool JNIHandleBlock::chain_contains(jobject handle) const { 586 for (JNIHandleBlock* current = (JNIHandleBlock*) this; current != NULL; current = current->_next) { 587 if (current->contains(handle)) { 588 return true; 589 } 590 } 591 return false; 592 } 593 594 595 size_t JNIHandleBlock::length() const { 596 size_t result = 1; 597 for (JNIHandleBlock* current = _next; current != NULL; current = current->_next) { 598 result++; 599 } 600 return result; 601 } 602 603 class CountJNIHandleClosure: public OopClosure { 604 private: 605 int _count; 606 public: 607 CountJNIHandleClosure(): _count(0) {} 608 virtual void do_oop(oop* ooph) { _count++; } 609 virtual void do_oop(narrowOop* unused) { ShouldNotReachHere(); } 610 int count() { return _count; } 611 }; 612 613 const size_t JNIHandleBlock::get_number_of_live_handles() { 614 CountJNIHandleClosure counter; 615 oops_do(&counter); 616 return counter.count(); 617 } 618 619 // This method is not thread-safe, i.e., must be called while holding a lock on the 620 // structure. 621 size_t JNIHandleBlock::memory_usage() const { 622 return length() * sizeof(JNIHandleBlock); 623 } 624 625 626 #ifndef PRODUCT 627 628 bool JNIHandles::is_local_handle(jobject handle) { 629 return JNIHandleBlock::any_contains(handle); 630 } 631 632 bool JNIHandleBlock::any_contains(jobject handle) { 633 assert(handle != NULL, "precondition"); 634 for (JNIHandleBlock* current = _block_list; current != NULL; current = current->_block_list_link) { 635 if (current->contains(handle)) { 636 return true; 637 } 638 } 639 return false; 640 } 641 642 void JNIHandleBlock::print_statistics() { 643 int used_blocks = 0; 644 int free_blocks = 0; 645 int used_handles = 0; 646 int free_handles = 0; 647 JNIHandleBlock* block = _block_list; 648 while (block != NULL) { 649 if (block->_top > 0) { 650 used_blocks++; 651 } else { 652 free_blocks++; 653 } 654 used_handles += block->_top; 655 free_handles += (block_size_in_oops - block->_top); 656 block = block->_block_list_link; 657 } 658 tty->print_cr("JNIHandleBlocks statistics"); 659 tty->print_cr("- blocks allocated: %d", used_blocks + free_blocks); 660 tty->print_cr("- blocks in use: %d", used_blocks); 661 tty->print_cr("- blocks free: %d", free_blocks); 662 tty->print_cr("- handles in use: %d", used_handles); 663 tty->print_cr("- handles free: %d", free_handles); 664 } 665 666 #endif