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 #ifndef SHARE_VM_RUNTIME_JNIHANDLES_HPP
  26 #define SHARE_VM_RUNTIME_JNIHANDLES_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "runtime/handles.hpp"
  30 
  31 class JNIHandleBlock;
  32 
  33 
  34 // Interface for creating and resolving local/global JNI handles
  35 
  36 class JNIHandles : AllStatic {
  37   friend class VMStructs;
  38  private:
  39   static JNIHandleBlock* _global_handles;             // First global handle block
  40   static JNIHandleBlock* _weak_global_handles;        // First weak global handle block
  41   static oop _deleted_handle;                         // Sentinel marking deleted handles
  42 
  43   inline static bool is_jweak(jobject handle);
  44   inline static oop& jobject_ref(jobject handle); // NOT jweak!
  45   inline static oop& jweak_ref(jobject handle);
  46 
  47   template<bool external_guard> inline static oop guard_value(oop value);
  48   template<bool external_guard> inline static oop resolve_impl(jobject handle);
  49   template<bool external_guard> static oop resolve_jweak(jweak handle);
  50 
  51   // This method is not inlined in order to avoid circular includes between
  52   // this header file and thread.hpp.
  53   static bool current_thread_in_native();
  54 
  55  public:
  56   // Low tag bit in jobject used to distinguish a jweak.  jweak is
  57   // type equivalent to jobject, but there are places where we need to
  58   // be able to distinguish jweak values from other jobjects, and
  59   // is_weak_global_handle is unsuitable for performance reasons.  To
  60   // provide such a test we add weak_tag_value to the (aligned) byte
  61   // address designated by the jobject to produce the corresponding
  62   // jweak.  Accessing the value of a jobject must account for it
  63   // being a possibly offset jweak.
  64   static const uintptr_t weak_tag_size = 1;
  65   static const uintptr_t weak_tag_alignment = (1u << weak_tag_size);
  66   static const uintptr_t weak_tag_mask = weak_tag_alignment - 1;
  67   static const int weak_tag_value = 1;
  68 
  69   // Resolve handle into oop
  70   inline static oop resolve(jobject handle);
  71   // Resolve externally provided handle into oop with some guards
  72   inline static oop resolve_external_guard(jobject handle);
  73   // Resolve handle into oop, result guaranteed not to be null
  74   inline static oop resolve_non_null(jobject handle);
  75 
  76   // Local handles
  77   static jobject make_local(oop obj);
  78   static jobject make_local(JNIEnv* env, oop obj);    // Fast version when env is known
  79   static jobject make_local(Thread* thread, oop obj); // Even faster version when current thread is known
  80   inline static void destroy_local(jobject handle);
  81 
  82   // Global handles
  83   static jobject make_global(Handle  obj);
  84   static void destroy_global(jobject handle);
  85 
  86   // Weak global handles
  87   static jobject make_weak_global(Handle obj);
  88   static void destroy_weak_global(jobject handle);
  89   static bool is_global_weak_cleared(jweak handle); // Test jweak without resolution
  90 
  91   // Sentinel marking deleted handles in block. Note that we cannot store NULL as
  92   // the sentinel, since clearing weak global JNI refs are done by storing NULL in
  93   // the handle. The handle may not be reused before destroy_weak_global is called.
  94   static oop deleted_handle()   { return _deleted_handle; }
  95 
  96   // Initialization
  97   static void initialize();
  98 
  99   // Debugging
 100   static void print_on(outputStream* st);
 101   static void print()           { print_on(tty); }
 102   static void verify();
 103   static bool is_local_handle(Thread* thread, jobject handle);
 104   static bool is_frame_handle(JavaThread* thr, jobject obj);
 105   static bool is_global_handle(jobject handle);
 106   static bool is_weak_global_handle(jobject handle);
 107   static long global_handle_memory_usage();
 108   static long weak_global_handle_memory_usage();
 109 
 110   // Garbage collection support(global handles only, local handles are traversed from thread)
 111   // Traversal of regular global handles
 112   static void oops_do(OopClosure* f);
 113   // Traversal of weak global handles. Unreachable oops are cleared.
 114   static void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f);
 115   // Traversal of weak global handles.
 116   static void weak_oops_do(OopClosure* f);
 117 };
 118 
 119 
 120 
 121 // JNI handle blocks holding local/global JNI handles
 122 
 123 class JNIHandleBlock : public CHeapObj<mtInternal> {
 124   friend class VMStructs;
 125   friend class CppInterpreter;
 126 
 127  private:
 128   enum SomeConstants {
 129     block_size_in_oops  = 32                    // Number of handles per handle block
 130   };
 131 
 132   oop             _handles[block_size_in_oops]; // The handles
 133   int             _top;                         // Index of next unused handle
 134   JNIHandleBlock* _next;                        // Link to next block
 135 
 136   // The following instance variables are only used by the first block in a chain.
 137   // Having two types of blocks complicates the code and the space overhead in negligible.
 138   JNIHandleBlock* _last;                        // Last block in use
 139   JNIHandleBlock* _pop_frame_link;              // Block to restore on PopLocalFrame call
 140   oop*            _free_list;                   // Handle free list
 141   int             _allocate_before_rebuild;     // Number of blocks to allocate before rebuilding free list
 142 
 143   // Check JNI, "planned capacity" for current frame (or push/ensure)
 144   size_t          _planned_capacity;
 145 
 146   #ifndef PRODUCT
 147   JNIHandleBlock* _block_list_link;             // Link for list below
 148   static JNIHandleBlock* _block_list;           // List of all allocated blocks (for debugging only)
 149   #endif
 150 
 151   static JNIHandleBlock* _block_free_list;      // Free list of currently unused blocks
 152   static int      _blocks_allocated;            // For debugging/printing
 153 
 154   // Fill block with bad_handle values
 155   void zap() NOT_DEBUG_RETURN;
 156 
 157   // Free list computation
 158   void rebuild_free_list();
 159 
 160   // No more handles in the both the current and following blocks
 161   void clear() { _top = 0; }
 162 
 163  public:
 164   // Handle allocation
 165   jobject allocate_handle(oop obj);
 166 
 167   // Release Handle
 168   void release_handle(jobject);
 169 
 170   // Block allocation and block free list management
 171   static JNIHandleBlock* allocate_block(Thread* thread = NULL);
 172   static void release_block(JNIHandleBlock* block, Thread* thread = NULL);
 173 
 174   // JNI PushLocalFrame/PopLocalFrame support
 175   JNIHandleBlock* pop_frame_link() const          { return _pop_frame_link; }
 176   void set_pop_frame_link(JNIHandleBlock* block)  { _pop_frame_link = block; }
 177 
 178   // Stub generator support
 179   static int top_offset_in_bytes()                { return offset_of(JNIHandleBlock, _top); }
 180 
 181   // Garbage collection support
 182   // Traversal of regular handles
 183   void oops_do(OopClosure* f);
 184   // Traversal of weak handles. Unreachable oops are cleared.
 185   void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f);
 186 
 187   // Checked JNI support
 188   void set_planned_capacity(size_t planned_capacity) { _planned_capacity = planned_capacity; }
 189   const size_t get_planned_capacity() { return _planned_capacity; }
 190   const size_t get_number_of_live_handles();
 191 
 192   // Debugging
 193   bool chain_contains(jobject handle) const;    // Does this block or following blocks contain handle
 194   bool contains(jobject handle) const;          // Does this block contain handle
 195   int length() const;                           // Length of chain starting with this block
 196   long memory_usage() const;
 197   #ifndef PRODUCT
 198   static bool any_contains(jobject handle);     // Does any block currently in use contain handle
 199   static void print_statistics();
 200   #endif
 201 };
 202 
 203 inline bool JNIHandles::is_jweak(jobject handle) {
 204   STATIC_ASSERT(weak_tag_size == 1);
 205   STATIC_ASSERT(weak_tag_value == 1);
 206   return (reinterpret_cast<uintptr_t>(handle) & weak_tag_mask) != 0;
 207 }
 208 
 209 inline oop& JNIHandles::jobject_ref(jobject handle) {
 210   assert(!is_jweak(handle), "precondition");
 211   return *reinterpret_cast<oop*>(handle);
 212 }
 213 
 214 inline oop& JNIHandles::jweak_ref(jobject handle) {
 215   assert(is_jweak(handle), "precondition");
 216   char* ptr = reinterpret_cast<char*>(handle) - weak_tag_value;
 217   return *reinterpret_cast<oop*>(ptr);
 218 }
 219 
 220 // external_guard is true if called from resolve_external_guard.
 221 // Treat deleted (and possibly zapped) as NULL for external_guard,
 222 // else as (asserted) error.
 223 template<bool external_guard>
 224 inline oop JNIHandles::guard_value(oop value) {
 225   if (!external_guard) {
 226     assert(value != deleted_handle(), "Used a deleted global handle");
 227   } else if (value == deleted_handle()) {
 228     value = NULL;
 229   }
 230   return value;
 231 }
 232 
 233 // external_guard is true if called from resolve_external_guard.
 234 template<bool external_guard>
 235 inline oop JNIHandles::resolve_impl(jobject handle) {
 236   assert(handle != NULL, "precondition");
 237   assert(!current_thread_in_native(), "must not be in native");
 238   oop result;
 239   if (is_jweak(handle)) {       // Unlikely
 240     result = resolve_jweak<external_guard>(handle);
 241   } else {
 242     result = jobject_ref(handle);
 243     // Construction of jobjects canonicalize a null value into a null
 244     // jobject, so for non-jweak the pointee should never be null.
 245     assert(external_guard || result != NULL,
 246            "Invalid value read from jni handle");
 247     result = guard_value<external_guard>(result);
 248   }
 249   return result;
 250 }
 251 
 252 inline oop JNIHandles::resolve(jobject handle) {
 253   oop result = NULL;
 254   if (handle != NULL) {
 255     result = resolve_impl<false /* external_guard */ >(handle);
 256   }
 257   return result;
 258 }
 259 
 260 // Resolve some erroneous cases to NULL, rather than treating them as
 261 // possibly unchecked errors.  In particular, deleted handles are
 262 // treated as NULL (though a deleted and later reallocated handle
 263 // isn't detected).
 264 inline oop JNIHandles::resolve_external_guard(jobject handle) {
 265   oop result = NULL;
 266   if (handle != NULL) {
 267     result = resolve_impl<true /* external_guard */ >(handle);
 268   }
 269   return result;
 270 }
 271 
 272 inline oop JNIHandles::resolve_non_null(jobject handle) {
 273   assert(handle != NULL, "JNI handle should not be null");
 274   oop result = resolve_impl<false /* external_guard */ >(handle);
 275   assert(result != NULL, "NULL read from jni handle");
 276   return result;
 277 }
 278 
 279 inline void JNIHandles::destroy_local(jobject handle) {
 280   if (handle != NULL) {
 281     jobject_ref(handle) = deleted_handle();
 282   }
 283 }
 284 
 285 #endif // SHARE_VM_RUNTIME_JNIHANDLES_HPP