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