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