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