Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/runtime/jniHandles.cpp
32285 views
/*1* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/systemDictionary.hpp"26#include "memory/iterator.hpp"27#include "oops/oop.inline.hpp"28#include "prims/jvmtiExport.hpp"29#include "runtime/jniHandles.hpp"30#include "runtime/mutexLocker.hpp"31#include "runtime/thread.inline.hpp"32#if INCLUDE_ALL_GCS33#include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"34#endif3536PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC3738JNIHandleBlock* JNIHandles::_global_handles = NULL;39JNIHandleBlock* JNIHandles::_weak_global_handles = NULL;40oop JNIHandles::_deleted_handle = NULL;414243jobject JNIHandles::make_local(oop obj) {44if (obj == NULL) {45return NULL; // ignore null handles46} else {47Thread* thread = Thread::current();48assert(Universe::heap()->is_in_reserved(obj), "sanity check");49return thread->active_handles()->allocate_handle(obj);50}51}525354// optimized versions5556jobject JNIHandles::make_local(Thread* thread, oop obj) {57if (obj == NULL) {58return NULL; // ignore null handles59} else {60assert(Universe::heap()->is_in_reserved(obj), "sanity check");61return thread->active_handles()->allocate_handle(obj);62}63}646566jobject JNIHandles::make_local(JNIEnv* env, oop obj) {67if (obj == NULL) {68return NULL; // ignore null handles69} else {70JavaThread* thread = JavaThread::thread_from_jni_environment(env);71assert(Universe::heap()->is_in_reserved(obj), "sanity check");72return thread->active_handles()->allocate_handle(obj);73}74}757677jobject JNIHandles::make_global(Handle obj) {78assert(!Universe::heap()->is_gc_active(), "can't extend the root set during GC");79jobject res = NULL;80if (!obj.is_null()) {81// ignore null handles82MutexLocker ml(JNIGlobalHandle_lock);83assert(Universe::heap()->is_in_reserved(obj()), "sanity check");84res = _global_handles->allocate_handle(obj());85} else {86CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());87}8889return res;90}9192jobject JNIHandles::make_weak_global(Handle obj) {93assert(!Universe::heap()->is_gc_active(), "can't extend the root set during GC");94jobject res = NULL;95if (!obj.is_null()) {96// ignore null handles97{98MutexLocker ml(JNIGlobalHandle_lock);99assert(Universe::heap()->is_in_reserved(obj()), "sanity check");100res = _weak_global_handles->allocate_handle(obj());101}102// Add weak tag.103assert(is_ptr_aligned(res, weak_tag_alignment), "invariant");104char* tptr = reinterpret_cast<char*>(res) + weak_tag_value;105res = reinterpret_cast<jobject>(tptr);106} else {107CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());108}109return res;110}111112template<bool external_guard>113oop JNIHandles::resolve_jweak(jweak handle) {114assert(is_jweak(handle), "precondition");115oop result = jweak_ref(handle);116result = guard_value<external_guard>(result);117#if INCLUDE_ALL_GCS118if (result != NULL && (UseG1GC || (UseShenandoahGC && ShenandoahSATBBarrier))) {119G1SATBCardTableModRefBS::enqueue(result);120}121#endif // INCLUDE_ALL_GCS122return result;123}124125template oop JNIHandles::resolve_jweak<true>(jweak);126template oop JNIHandles::resolve_jweak<false>(jweak);127128void JNIHandles::destroy_global(jobject handle) {129if (handle != NULL) {130assert(is_global_handle(handle), "Invalid delete of global JNI handle");131jobject_ref(handle) = deleted_handle();132}133}134135void JNIHandles::destroy_weak_global(jobject handle) {136if (handle != NULL) {137jweak_ref(handle) = deleted_handle();138}139}140141142void JNIHandles::oops_do(OopClosure* f) {143f->do_oop(&_deleted_handle);144_global_handles->oops_do(f);145}146147148void JNIHandles::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f) {149_weak_global_handles->weak_oops_do(is_alive, f);150}151152153void JNIHandles::weak_oops_do(OopClosure* f) {154AlwaysTrueClosure always_true;155weak_oops_do(&always_true, f);156}157158159void JNIHandles::initialize() {160_global_handles = JNIHandleBlock::allocate_block();161_weak_global_handles = JNIHandleBlock::allocate_block();162EXCEPTION_MARK;163// We will never reach the CATCH below since Exceptions::_throw will cause164// the VM to exit if an exception is thrown during initialization165Klass* k = SystemDictionary::Object_klass();166_deleted_handle = InstanceKlass::cast(k)->allocate_instance(CATCH);167}168169170bool JNIHandles::is_local_handle(Thread* thread, jobject handle) {171JNIHandleBlock* block = thread->active_handles();172173// Look back past possible native calls to jni_PushLocalFrame.174while (block != NULL) {175if (block->chain_contains(handle)) {176return true;177}178block = block->pop_frame_link();179}180return false;181}182183184// Determine if the handle is somewhere in the current thread's stack.185// We easily can't isolate any particular stack frame the handle might186// come from, so we'll check the whole stack.187188bool JNIHandles::is_frame_handle(JavaThread* thr, jobject obj) {189// If there is no java frame, then this must be top level code, such190// as the java command executable, in which case, this type of handle191// is not permitted.192return (thr->has_last_Java_frame() &&193(void*)obj < (void*)thr->stack_base() &&194(void*)obj >= (void*)thr->last_Java_sp());195}196197198bool JNIHandles::is_global_handle(jobject handle) {199return _global_handles->chain_contains(handle);200}201202203bool JNIHandles::is_weak_global_handle(jobject handle) {204return _weak_global_handles->chain_contains(handle);205}206207long JNIHandles::global_handle_memory_usage() {208return _global_handles->memory_usage();209}210211long JNIHandles::weak_global_handle_memory_usage() {212return _weak_global_handles->memory_usage();213}214215216class CountHandleClosure: public OopClosure {217private:218int _count;219public:220CountHandleClosure(): _count(0) {}221virtual void do_oop(oop* ooph) {222if (*ooph != JNIHandles::deleted_handle()) {223_count++;224}225}226virtual void do_oop(narrowOop* unused) { ShouldNotReachHere(); }227int count() { return _count; }228};229230// We assume this is called at a safepoint: no lock is needed.231void JNIHandles::print_on(outputStream* st) {232assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");233assert(_global_handles != NULL && _weak_global_handles != NULL,234"JNIHandles not initialized");235236CountHandleClosure global_handle_count;237oops_do(&global_handle_count);238weak_oops_do(&global_handle_count);239240st->print_cr("JNI global references: %d", global_handle_count.count());241st->cr();242st->flush();243}244245class VerifyHandleClosure: public OopClosure {246public:247virtual void do_oop(oop* root) {248(*root)->verify();249}250virtual void do_oop(narrowOop* root) { ShouldNotReachHere(); }251};252253void JNIHandles::verify() {254VerifyHandleClosure verify_handle;255256oops_do(&verify_handle);257weak_oops_do(&verify_handle);258}259260261262void jni_handles_init() {263JNIHandles::initialize();264}265266267int JNIHandleBlock::_blocks_allocated = 0;268JNIHandleBlock* JNIHandleBlock::_block_free_list = NULL;269#ifndef PRODUCT270JNIHandleBlock* JNIHandleBlock::_block_list = NULL;271#endif272273274void JNIHandleBlock::zap() {275// Zap block values276_top = 0;277for (int index = 0; index < block_size_in_oops; index++) {278_handles[index] = badJNIHandle;279}280}281282JNIHandleBlock* JNIHandleBlock::allocate_block(Thread* thread) {283assert(thread == NULL || thread == Thread::current(), "sanity check");284JNIHandleBlock* block;285// Check the thread-local free list for a block so we don't286// have to acquire a mutex.287if (thread != NULL && thread->free_handle_block() != NULL) {288block = thread->free_handle_block();289thread->set_free_handle_block(block->_next);290}291else {292// locking with safepoint checking introduces a potential deadlock:293// - we would hold JNIHandleBlockFreeList_lock and then Threads_lock294// - another would hold Threads_lock (jni_AttachCurrentThread) and then295// JNIHandleBlockFreeList_lock (JNIHandleBlock::allocate_block)296MutexLockerEx ml(JNIHandleBlockFreeList_lock,297Mutex::_no_safepoint_check_flag);298if (_block_free_list == NULL) {299// Allocate new block300block = new JNIHandleBlock();301_blocks_allocated++;302if (TraceJNIHandleAllocation) {303tty->print_cr("JNIHandleBlock " INTPTR_FORMAT " allocated (%d total blocks)",304block, _blocks_allocated);305}306if (ZapJNIHandleArea) block->zap();307#ifndef PRODUCT308// Link new block to list of all allocated blocks309block->_block_list_link = _block_list;310_block_list = block;311#endif312} else {313// Get block from free list314block = _block_free_list;315_block_free_list = _block_free_list->_next;316}317}318block->_top = 0;319block->_next = NULL;320block->_pop_frame_link = NULL;321block->_planned_capacity = block_size_in_oops;322// _last, _free_list & _allocate_before_rebuild initialized in allocate_handle323debug_only(block->_last = NULL);324debug_only(block->_free_list = NULL);325debug_only(block->_allocate_before_rebuild = -1);326return block;327}328329330void JNIHandleBlock::release_block(JNIHandleBlock* block, Thread* thread) {331assert(thread == NULL || thread == Thread::current(), "sanity check");332JNIHandleBlock* pop_frame_link = block->pop_frame_link();333// Put returned block at the beginning of the thread-local free list.334// Note that if thread == NULL, we use it as an implicit argument that335// we _don't_ want the block to be kept on the free_handle_block.336// See for instance JavaThread::exit().337if (thread != NULL ) {338if (ZapJNIHandleArea) block->zap();339JNIHandleBlock* freelist = thread->free_handle_block();340block->_pop_frame_link = NULL;341thread->set_free_handle_block(block);342343// Add original freelist to end of chain344if ( freelist != NULL ) {345while ( block->_next != NULL ) block = block->_next;346block->_next = freelist;347}348block = NULL;349}350if (block != NULL) {351// Return blocks to free list352// locking with safepoint checking introduces a potential deadlock:353// - we would hold JNIHandleBlockFreeList_lock and then Threads_lock354// - another would hold Threads_lock (jni_AttachCurrentThread) and then355// JNIHandleBlockFreeList_lock (JNIHandleBlock::allocate_block)356MutexLockerEx ml(JNIHandleBlockFreeList_lock,357Mutex::_no_safepoint_check_flag);358while (block != NULL) {359if (ZapJNIHandleArea) block->zap();360JNIHandleBlock* next = block->_next;361block->_next = _block_free_list;362_block_free_list = block;363block = next;364}365}366if (pop_frame_link != NULL) {367// As a sanity check we release blocks pointed to by the pop_frame_link.368// This should never happen (only if PopLocalFrame is not called the369// correct number of times).370release_block(pop_frame_link, thread);371}372}373374375void JNIHandleBlock::oops_do(OopClosure* f) {376JNIHandleBlock* current_chain = this;377// Iterate over chain of blocks, followed by chains linked through the378// pop frame links.379while (current_chain != NULL) {380for (JNIHandleBlock* current = current_chain; current != NULL;381current = current->_next) {382assert(current == current_chain || current->pop_frame_link() == NULL,383"only blocks first in chain should have pop frame link set");384for (int index = 0; index < current->_top; index++) {385oop* root = &(current->_handles)[index];386oop value = *root;387// traverse heap pointers only, not deleted handles or free list388// pointers389if (value != NULL && Universe::heap()->is_in_reserved(value)) {390f->do_oop(root);391}392}393// the next handle block is valid only if current block is full394if (current->_top < block_size_in_oops) {395break;396}397}398current_chain = current_chain->pop_frame_link();399}400}401402403void JNIHandleBlock::weak_oops_do(BoolObjectClosure* is_alive,404OopClosure* f) {405for (JNIHandleBlock* current = this; current != NULL; current = current->_next) {406assert(current->pop_frame_link() == NULL,407"blocks holding weak global JNI handles should not have pop frame link set");408for (int index = 0; index < current->_top; index++) {409oop* root = &(current->_handles)[index];410oop value = *root;411// traverse heap pointers only, not deleted handles or free list pointers412if (value != NULL && Universe::heap()->is_in_reserved(value)) {413if (is_alive->do_object_b(value)) {414// The weakly referenced object is alive, update pointer415f->do_oop(root);416} else {417// The weakly referenced object is not alive, clear the reference by storing NULL418if (TraceReferenceGC) {419tty->print_cr("Clearing JNI weak reference (" INTPTR_FORMAT ")", root);420}421*root = NULL;422}423}424}425// the next handle block is valid only if current block is full426if (current->_top < block_size_in_oops) {427break;428}429}430431/*432* JVMTI data structures may also contain weak oops. The iteration of them433* is placed here so that we don't need to add it to each of the collectors.434*/435JvmtiExport::weak_oops_do(is_alive, f);436}437438439jobject JNIHandleBlock::allocate_handle(oop obj) {440assert(Universe::heap()->is_in_reserved(obj), "sanity check");441if (_top == 0) {442// This is the first allocation or the initial block got zapped when443// entering a native function. If we have any following blocks they are444// not valid anymore.445for (JNIHandleBlock* current = _next; current != NULL;446current = current->_next) {447assert(current->_last == NULL, "only first block should have _last set");448assert(current->_free_list == NULL,449"only first block should have _free_list set");450current->_top = 0;451if (ZapJNIHandleArea) current->zap();452}453// Clear initial block454_free_list = NULL;455_allocate_before_rebuild = 0;456_last = this;457if (ZapJNIHandleArea) zap();458}459460// Try last block461if (_last->_top < block_size_in_oops) {462oop* handle = &(_last->_handles)[_last->_top++];463*handle = obj;464return (jobject) handle;465}466467// Try free list468if (_free_list != NULL) {469oop* handle = _free_list;470_free_list = (oop*) *_free_list;471*handle = obj;472return (jobject) handle;473}474// Check if unused block follow last475if (_last->_next != NULL) {476// update last and retry477_last = _last->_next;478return allocate_handle(obj);479}480481// No space available, we have to rebuild free list or expand482if (_allocate_before_rebuild == 0) {483rebuild_free_list(); // updates _allocate_before_rebuild counter484} else {485// Append new block486Thread* thread = Thread::current();487Handle obj_handle(thread, obj);488// This can block, so we need to preserve obj accross call.489_last->_next = JNIHandleBlock::allocate_block(thread);490_last = _last->_next;491_allocate_before_rebuild--;492obj = obj_handle();493}494return allocate_handle(obj); // retry495}496497498void JNIHandleBlock::rebuild_free_list() {499assert(_allocate_before_rebuild == 0 && _free_list == NULL, "just checking");500int free = 0;501int blocks = 0;502for (JNIHandleBlock* current = this; current != NULL; current = current->_next) {503for (int index = 0; index < current->_top; index++) {504oop* handle = &(current->_handles)[index];505if (*handle == JNIHandles::deleted_handle()) {506// this handle was cleared out by a delete call, reuse it507*handle = (oop) _free_list;508_free_list = handle;509free++;510}511}512// we should not rebuild free list if there are unused handles at the end513assert(current->_top == block_size_in_oops, "just checking");514blocks++;515}516// Heuristic: if more than half of the handles are free we rebuild next time517// as well, otherwise we append a corresponding number of new blocks before518// attempting a free list rebuild again.519int total = blocks * block_size_in_oops;520int extra = total - 2*free;521if (extra > 0) {522// Not as many free handles as we would like - compute number of new blocks to append523_allocate_before_rebuild = (extra + block_size_in_oops - 1) / block_size_in_oops;524}525if (TraceJNIHandleAllocation) {526tty->print_cr("Rebuild free list JNIHandleBlock " INTPTR_FORMAT " blocks=%d used=%d free=%d add=%d",527this, blocks, total-free, free, _allocate_before_rebuild);528}529}530531532bool JNIHandleBlock::contains(jobject handle) const {533return ((jobject)&_handles[0] <= handle && handle<(jobject)&_handles[_top]);534}535536537bool JNIHandleBlock::chain_contains(jobject handle) const {538for (JNIHandleBlock* current = (JNIHandleBlock*) this; current != NULL; current = current->_next) {539if (current->contains(handle)) {540return true;541}542}543return false;544}545546547int JNIHandleBlock::length() const {548int result = 1;549for (JNIHandleBlock* current = _next; current != NULL; current = current->_next) {550result++;551}552return result;553}554555const size_t JNIHandleBlock::get_number_of_live_handles() {556CountHandleClosure counter;557oops_do(&counter);558return counter.count();559}560561// This method is not thread-safe, i.e., must be called whule holding a lock on the562// structure.563long JNIHandleBlock::memory_usage() const {564return length() * sizeof(JNIHandleBlock);565}566567568#ifndef PRODUCT569570bool JNIHandleBlock::any_contains(jobject handle) {571for (JNIHandleBlock* current = _block_list; current != NULL; current = current->_block_list_link) {572if (current->contains(handle)) {573return true;574}575}576return false;577}578579void JNIHandleBlock::print_statistics() {580int used_blocks = 0;581int free_blocks = 0;582int used_handles = 0;583int free_handles = 0;584JNIHandleBlock* block = _block_list;585while (block != NULL) {586if (block->_top > 0) {587used_blocks++;588} else {589free_blocks++;590}591used_handles += block->_top;592free_handles += (block_size_in_oops - block->_top);593block = block->_block_list_link;594}595tty->print_cr("JNIHandleBlocks statistics");596tty->print_cr("- blocks allocated: %d", used_blocks + free_blocks);597tty->print_cr("- blocks in use: %d", used_blocks);598tty->print_cr("- blocks free: %d", free_blocks);599tty->print_cr("- handles in use: %d", used_handles);600tty->print_cr("- handles free: %d", free_handles);601}602603#endif604605606