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