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 NativeAccess<>::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 NativeAccess<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<DECORATORS_NONE, true /* external_guard */>(handle); 156 } 157 return result; 158 } 159 160 bool JNIHandles::is_global_weak_cleared(jweak handle) { 161 assert(handle != NULL, "precondition"); 162 assert(is_jweak(handle), "not a weak handle"); 163 oop* oop_ptr = jweak_ptr(handle); 164 oop value = NativeAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(oop_ptr); 165 return value == NULL; 166 } 167 168 void JNIHandles::destroy_global(jobject handle) { 169 if (handle != NULL) { 170 assert(!is_jweak(handle), "wrong method for detroying jweak"); 171 oop* oop_ptr = jobject_ptr(handle); 172 NativeAccess<>::oop_store(oop_ptr, (oop)NULL); 173 global_handles()->release(oop_ptr); 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 oop* oop_ptr = jweak_ptr(handle); 182 NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_ptr, (oop)NULL); 183 weak_global_handles()->release(oop_ptr); 184 } 185 } 186 187 188 void JNIHandles::oops_do(OopClosure* f) { 189 global_handles()->oops_do(f); 190 } 191 192 193 void JNIHandles::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f) { 194 weak_global_handles()->weak_oops_do(is_alive, f); 195 } 196 197 198 void JNIHandles::weak_oops_do(OopClosure* f) { 199 weak_global_handles()->weak_oops_do(f); 200 } 201 202 203 void JNIHandles::initialize() { 204 _global_handles = new OopStorage("JNI Global", 205 JNIGlobalAlloc_lock, 206 JNIGlobalActive_lock); 207 _weak_global_handles = new OopStorage("JNI Weak", 208 JNIWeakAlloc_lock, 209 JNIWeakActive_lock); 210 } 211 212 213 inline bool is_storage_handle(const OopStorage* storage, const oop* ptr) { 214 return storage->allocation_status(ptr) == OopStorage::ALLOCATED_ENTRY; 215 } 216 217 218 jobjectRefType JNIHandles::handle_type(Thread* thread, jobject handle) { 219 assert(handle != NULL, "precondition"); 220 jobjectRefType result = JNIInvalidRefType; 221 if (is_jweak(handle)) { 222 if (is_storage_handle(weak_global_handles(), jweak_ptr(handle))) { 223 result = JNIWeakGlobalRefType; 224 } 225 } else { 226 switch (global_handles()->allocation_status(jobject_ptr(handle))) { 227 case OopStorage::ALLOCATED_ENTRY: 228 result = JNIGlobalRefType; 229 break; 230 231 case OopStorage::UNALLOCATED_ENTRY: 232 break; // Invalid global handle 233 234 case OopStorage::INVALID_ENTRY: 235 // Not in global storage. Might be a local handle. 236 if (is_local_handle(thread, handle) || 237 (thread->is_Java_thread() && 238 is_frame_handle((JavaThread*)thread, handle))) { 239 result = JNILocalRefType; 240 } 241 break; 242 243 default: 244 ShouldNotReachHere(); 245 } 246 } 247 return result; 248 } 249 250 251 bool JNIHandles::is_local_handle(Thread* thread, jobject handle) { 252 assert(handle != NULL, "precondition"); 253 JNIHandleBlock* block = thread->active_handles(); 254 255 // Look back past possible native calls to jni_PushLocalFrame. 256 while (block != NULL) { 257 if (block->chain_contains(handle)) { 258 return true; 259 } 260 block = block->pop_frame_link(); 261 } 262 return false; 263 } 264 265 266 // Determine if the handle is somewhere in the current thread's stack. 267 // We easily can't isolate any particular stack frame the handle might 268 // come from, so we'll check the whole stack. 269 270 bool JNIHandles::is_frame_handle(JavaThread* thr, jobject handle) { 271 assert(handle != NULL, "precondition"); 272 // If there is no java frame, then this must be top level code, such 273 // as the java command executable, in which case, this type of handle 274 // is not permitted. 275 return (thr->has_last_Java_frame() && 276 (void*)handle < (void*)thr->stack_base() && 277 (void*)handle >= (void*)thr->last_Java_sp()); 278 } 279 280 281 bool JNIHandles::is_global_handle(jobject handle) { 282 assert(handle != NULL, "precondition"); 283 return !is_jweak(handle) && is_storage_handle(global_handles(), jobject_ptr(handle)); 284 } 285 286 287 bool JNIHandles::is_weak_global_handle(jobject handle) { 288 assert(handle != NULL, "precondition"); 289 return is_jweak(handle) && is_storage_handle(weak_global_handles(), jweak_ptr(handle)); 290 } 291 292 size_t JNIHandles::global_handle_memory_usage() { 293 return global_handles()->total_memory_usage(); 294 } 295 296 size_t JNIHandles::weak_global_handle_memory_usage() { 297 return weak_global_handles()->total_memory_usage(); 298 } 299 300 301 // We assume this is called at a safepoint: no lock is needed. 302 void JNIHandles::print_on(outputStream* st) { 303 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 304 305 st->print_cr("JNI global refs: " SIZE_FORMAT ", weak refs: " SIZE_FORMAT, 306 global_handles()->allocation_count(), 307 weak_global_handles()->allocation_count()); 308 st->cr(); 309 st->flush(); 310 } 311 312 class VerifyJNIHandles: public OopClosure { 313 public: 314 virtual void do_oop(oop* root) { 315 guarantee(oopDesc::is_oop_or_null(RawAccess<>::oop_load(root)), "Invalid oop"); 316 } 317 virtual void do_oop(narrowOop* root) { ShouldNotReachHere(); } 318 }; 319 320 void JNIHandles::verify() { 321 VerifyJNIHandles verify_handle; 322 323 oops_do(&verify_handle); 324 weak_oops_do(&verify_handle); 325 } 326 327 // This method is implemented here to avoid circular includes between 328 // jniHandles.hpp and thread.hpp. 329 bool JNIHandles::current_thread_in_native() { 330 Thread* thread = Thread::current(); 331 return (thread->is_Java_thread() && 332 JavaThread::current()->thread_state() == _thread_in_native); 333 } 334 335 336 void jni_handles_init() { 337 JNIHandles::initialize(); 338 } 339 340 341 int JNIHandleBlock::_blocks_allocated = 0; 342 JNIHandleBlock* JNIHandleBlock::_block_free_list = NULL; 343 #ifndef PRODUCT 344 JNIHandleBlock* JNIHandleBlock::_block_list = NULL; 345 #endif 346 347 348 #ifdef ASSERT 349 void JNIHandleBlock::zap() { 350 // Zap block values 351 _top = 0; 352 for (int index = 0; index < block_size_in_oops; index++) { 353 // NOT using Access here; just bare clobbering to NULL, since the 354 // block no longer contains valid oops. 355 _handles[index] = NULL; 356 } 357 } 358 #endif // ASSERT 359 360 JNIHandleBlock* JNIHandleBlock::allocate_block(Thread* thread) { 361 assert(thread == NULL || thread == Thread::current(), "sanity check"); 362 JNIHandleBlock* block; 363 // Check the thread-local free list for a block so we don't 364 // have to acquire a mutex. 365 if (thread != NULL && thread->free_handle_block() != NULL) { 366 block = thread->free_handle_block(); 367 thread->set_free_handle_block(block->_next); 368 } 369 else { 370 // locking with safepoint checking introduces a potential deadlock: 371 // - we would hold JNIHandleBlockFreeList_lock and then Threads_lock 372 // - another would hold Threads_lock (jni_AttachCurrentThread) and then 373 // JNIHandleBlockFreeList_lock (JNIHandleBlock::allocate_block) 374 MutexLockerEx ml(JNIHandleBlockFreeList_lock, 375 Mutex::_no_safepoint_check_flag); 376 if (_block_free_list == NULL) { 377 // Allocate new block 378 block = new JNIHandleBlock(); 379 _blocks_allocated++; 380 block->zap(); 381 #ifndef PRODUCT 382 // Link new block to list of all allocated blocks 383 block->_block_list_link = _block_list; 384 _block_list = block; 385 #endif 386 } else { 387 // Get block from free list 388 block = _block_free_list; 389 _block_free_list = _block_free_list->_next; 390 } 391 } 392 block->_top = 0; 393 block->_next = NULL; 394 block->_pop_frame_link = NULL; 395 block->_planned_capacity = block_size_in_oops; 396 // _last, _free_list & _allocate_before_rebuild initialized in allocate_handle 397 debug_only(block->_last = NULL); 398 debug_only(block->_free_list = NULL); 399 debug_only(block->_allocate_before_rebuild = -1); 400 return block; 401 } 402 403 404 void JNIHandleBlock::release_block(JNIHandleBlock* block, Thread* thread) { 405 assert(thread == NULL || thread == Thread::current(), "sanity check"); 406 JNIHandleBlock* pop_frame_link = block->pop_frame_link(); 407 // Put returned block at the beginning of the thread-local free list. 408 // Note that if thread == NULL, we use it as an implicit argument that 409 // we _don't_ want the block to be kept on the free_handle_block. 410 // See for instance JavaThread::exit(). 411 if (thread != NULL ) { 412 block->zap(); 413 JNIHandleBlock* freelist = thread->free_handle_block(); 414 block->_pop_frame_link = NULL; 415 thread->set_free_handle_block(block); 416 417 // Add original freelist to end of chain 418 if ( freelist != NULL ) { 419 while ( block->_next != NULL ) block = block->_next; 420 block->_next = freelist; 421 } 422 block = NULL; 423 } 424 if (block != NULL) { 425 // Return blocks to free list 426 // locking with safepoint checking introduces a potential deadlock: 427 // - we would hold JNIHandleBlockFreeList_lock and then Threads_lock 428 // - another would hold Threads_lock (jni_AttachCurrentThread) and then 429 // JNIHandleBlockFreeList_lock (JNIHandleBlock::allocate_block) 430 MutexLockerEx ml(JNIHandleBlockFreeList_lock, 431 Mutex::_no_safepoint_check_flag); 432 while (block != NULL) { 433 block->zap(); 434 JNIHandleBlock* next = block->_next; 435 block->_next = _block_free_list; 436 _block_free_list = block; 437 block = next; 438 } 439 } 440 if (pop_frame_link != NULL) { 441 // As a sanity check we release blocks pointed to by the pop_frame_link. 442 // This should never happen (only if PopLocalFrame is not called the 443 // correct number of times). 444 release_block(pop_frame_link, thread); 445 } 446 } 447 448 449 void JNIHandleBlock::oops_do(OopClosure* f) { 450 JNIHandleBlock* current_chain = this; 451 // Iterate over chain of blocks, followed by chains linked through the 452 // pop frame links. 453 while (current_chain != NULL) { 454 for (JNIHandleBlock* current = current_chain; current != NULL; 455 current = current->_next) { 456 assert(current == current_chain || current->pop_frame_link() == NULL, 457 "only blocks first in chain should have pop frame link set"); 458 for (int index = 0; index < current->_top; index++) { 459 oop* root = &(current->_handles)[index]; 460 oop value = *root; 461 // traverse heap pointers only, not deleted handles or free list 462 // pointers 463 if (value != NULL && Universe::heap()->is_in_reserved(value)) { 464 f->do_oop(root); 465 } 466 } 467 // the next handle block is valid only if current block is full 468 if (current->_top < block_size_in_oops) { 469 break; 470 } 471 } 472 current_chain = current_chain->pop_frame_link(); 473 } 474 } 475 476 477 jobject JNIHandleBlock::allocate_handle(oop obj) { 478 assert(Universe::heap()->is_in_reserved(obj), "sanity check"); 479 if (_top == 0) { 480 // This is the first allocation or the initial block got zapped when 481 // entering a native function. If we have any following blocks they are 482 // not valid anymore. 483 for (JNIHandleBlock* current = _next; current != NULL; 484 current = current->_next) { 485 assert(current->_last == NULL, "only first block should have _last set"); 486 assert(current->_free_list == NULL, 487 "only first block should have _free_list set"); 488 if (current->_top == 0) { 489 // All blocks after the first clear trailing block are already cleared. 490 #ifdef ASSERT 491 for (current = current->_next; current != NULL; current = current->_next) { 492 assert(current->_top == 0, "trailing blocks must already be cleared"); 493 } 494 #endif 495 break; 496 } 497 current->_top = 0; 498 current->zap(); 499 } 500 // Clear initial block 501 _free_list = NULL; 502 _allocate_before_rebuild = 0; 503 _last = this; 504 zap(); 505 } 506 507 // Try last block 508 if (_last->_top < block_size_in_oops) { 509 oop* handle = &(_last->_handles)[_last->_top++]; 510 NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, obj); 511 return (jobject) handle; 512 } 513 514 // Try free list 515 if (_free_list != NULL) { 516 oop* handle = _free_list; 517 _free_list = (oop*) *_free_list; 518 NativeAccess<IS_DEST_UNINITIALIZED>::oop_store(handle, obj); 519 return (jobject) handle; 520 } 521 // Check if unused block follow last 522 if (_last->_next != NULL) { 523 // update last and retry 524 _last = _last->_next; 525 return allocate_handle(obj); 526 } 527 528 // No space available, we have to rebuild free list or expand 529 if (_allocate_before_rebuild == 0) { 530 rebuild_free_list(); // updates _allocate_before_rebuild counter 531 } else { 532 // Append new block 533 Thread* thread = Thread::current(); 534 Handle obj_handle(thread, obj); 535 // This can block, so we need to preserve obj across call. 536 _last->_next = JNIHandleBlock::allocate_block(thread); 537 _last = _last->_next; 538 _allocate_before_rebuild--; 539 obj = obj_handle(); 540 } 541 return allocate_handle(obj); // retry 542 } 543 544 void JNIHandleBlock::rebuild_free_list() { 545 assert(_allocate_before_rebuild == 0 && _free_list == NULL, "just checking"); 546 int free = 0; 547 int blocks = 0; 548 for (JNIHandleBlock* current = this; current != NULL; current = current->_next) { 549 for (int index = 0; index < current->_top; index++) { 550 oop* handle = &(current->_handles)[index]; 551 if (*handle == NULL) { 552 // this handle was cleared out by a delete call, reuse it 553 *handle = (oop) _free_list; 554 _free_list = handle; 555 free++; 556 } 557 } 558 // we should not rebuild free list if there are unused handles at the end 559 assert(current->_top == block_size_in_oops, "just checking"); 560 blocks++; 561 } 562 // Heuristic: if more than half of the handles are free we rebuild next time 563 // as well, otherwise we append a corresponding number of new blocks before 564 // attempting a free list rebuild again. 565 int total = blocks * block_size_in_oops; 566 int extra = total - 2*free; 567 if (extra > 0) { 568 // Not as many free handles as we would like - compute number of new blocks to append 569 _allocate_before_rebuild = (extra + block_size_in_oops - 1) / block_size_in_oops; 570 } 571 } 572 573 574 bool JNIHandleBlock::contains(jobject handle) const { 575 return ((jobject)&_handles[0] <= handle && handle<(jobject)&_handles[_top]); 576 } 577 578 579 bool JNIHandleBlock::chain_contains(jobject handle) const { 580 for (JNIHandleBlock* current = (JNIHandleBlock*) this; current != NULL; current = current->_next) { 581 if (current->contains(handle)) { 582 return true; 583 } 584 } 585 return false; 586 } 587 588 589 size_t JNIHandleBlock::length() const { 590 size_t result = 1; 591 for (JNIHandleBlock* current = _next; current != NULL; current = current->_next) { 592 result++; 593 } 594 return result; 595 } 596 597 class CountJNIHandleClosure: public OopClosure { 598 private: 599 int _count; 600 public: 601 CountJNIHandleClosure(): _count(0) {} 602 virtual void do_oop(oop* ooph) { _count++; } 603 virtual void do_oop(narrowOop* unused) { ShouldNotReachHere(); } 604 int count() { return _count; } 605 }; 606 607 const size_t JNIHandleBlock::get_number_of_live_handles() { 608 CountJNIHandleClosure counter; 609 oops_do(&counter); 610 return counter.count(); 611 } 612 613 // This method is not thread-safe, i.e., must be called while holding a lock on the 614 // structure. 615 size_t JNIHandleBlock::memory_usage() const { 616 return length() * sizeof(JNIHandleBlock); 617 } 618 619 620 #ifndef PRODUCT 621 622 bool JNIHandles::is_local_handle(jobject handle) { 623 return JNIHandleBlock::any_contains(handle); 624 } 625 626 bool JNIHandleBlock::any_contains(jobject handle) { 627 assert(handle != NULL, "precondition"); 628 for (JNIHandleBlock* current = _block_list; current != NULL; current = current->_block_list_link) { 629 if (current->contains(handle)) { 630 return true; 631 } 632 } 633 return false; 634 } 635 636 void JNIHandleBlock::print_statistics() { 637 int used_blocks = 0; 638 int free_blocks = 0; 639 int used_handles = 0; 640 int free_handles = 0; 641 JNIHandleBlock* block = _block_list; 642 while (block != NULL) { 643 if (block->_top > 0) { 644 used_blocks++; 645 } else { 646 free_blocks++; 647 } 648 used_handles += block->_top; 649 free_handles += (block_size_in_oops - block->_top); 650 block = block->_block_list_link; 651 } 652 tty->print_cr("JNIHandleBlocks statistics"); 653 tty->print_cr("- blocks allocated: %d", used_blocks + free_blocks); 654 tty->print_cr("- blocks in use: %d", used_blocks); 655 tty->print_cr("- blocks free: %d", free_blocks); 656 tty->print_cr("- handles in use: %d", used_handles); 657 tty->print_cr("- handles free: %d", free_handles); 658 } 659 660 #endif