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