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