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