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