1 /*
   2  * Copyright (c) 1997, 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_HANDLES_HPP
  26 #define SHARE_VM_RUNTIME_HANDLES_HPP
  27 
  28 #include "oops/oop.hpp"
  29 #include "oops/oopsHierarchy.hpp"
  30 
  31 class InstanceKlass;
  32 class Klass;
  33 
  34 //------------------------------------------------------------------------------------------------------------------------
  35 // In order to preserve oops during garbage collection, they should be
  36 // allocated and passed around via Handles within the VM. A handle is
  37 // simply an extra indirection allocated in a thread local handle area.
  38 //
  39 // A handle is a ValueObj, so it can be passed around as a value, can
  40 // be used as a parameter w/o using &-passing, and can be returned as a
  41 // return value.
  42 //
  43 // oop parameters and return types should be Handles whenever feasible.
  44 //
  45 // Handles are declared in a straight-forward manner, e.g.
  46 //
  47 //   oop obj = ...;
  48 //   Handle h2(thread, obj);      // allocate a new handle in thread
  49 //   Handle h3;                   // declare handle only, no allocation occurs
  50 //   ...
  51 //   h3 = h1;                     // make h3 refer to same indirection as h1
  52 //   oop obj2 = h2();             // get handle value
  53 //   h1->print();                 // invoking operation on oop
  54 //
  55 // Handles are specialized for different oop types to provide extra type
  56 // information and avoid unnecessary casting. For each oop type xxxOop
  57 // there is a corresponding handle called xxxHandle.
  58 
  59 //------------------------------------------------------------------------------------------------------------------------
  60 // Base class for all handles. Provides overloading of frequently
  61 // used operators for ease of use.
  62 
  63 class Handle VALUE_OBJ_CLASS_SPEC {
  64  private:
  65   oop* _handle;
  66 
  67  protected:
  68   oop     obj() const                            { return _handle == NULL ? (oop)NULL : *_handle; }
  69   oop     non_null_obj() const                   { assert(_handle != NULL, "resolving NULL handle"); return *_handle; }
  70 
  71  public:
  72   // Constructors
  73   Handle()                                       { _handle = NULL; }
  74   Handle(Thread* thread, oop obj);
  75 
  76   // General access
  77   oop     operator () () const                   { return obj(); }
  78   oop     operator -> () const                   { return non_null_obj(); }
  79   bool    operator == (oop o) const              { return obj() == o; }
  80   bool    operator == (const Handle& h) const          { return obj() == h.obj(); }
  81 
  82   // Null checks
  83   bool    is_null() const                        { return _handle == NULL; }
  84   bool    not_null() const                       { return _handle != NULL; }
  85 
  86   // Debugging
  87   void    print()                                { obj()->print(); }
  88 
  89   // Direct interface, use very sparingly.
  90   // Used by JavaCalls to quickly convert handles and to create handles static data structures.
  91   // Constructor takes a dummy argument to prevent unintentional type conversion in C++.
  92   Handle(oop *handle, bool dummy)                { _handle = handle; }
  93 
  94   // Raw handle access. Allows easy duplication of Handles. This can be very unsafe
  95   // since duplicates is only valid as long as original handle is alive.
  96   oop* raw_value()                               { return _handle; }
  97   static oop raw_resolve(oop *handle)            { return handle == NULL ? (oop)NULL : *handle; }
  98 };
  99 
 100 // Specific Handles for different oop types
 101 #define DEF_HANDLE(type, is_a)                   \
 102   class type##Handle: public Handle {            \
 103    protected:                                    \
 104     type##Oop    obj() const                     { return (type##Oop)Handle::obj(); } \
 105     type##Oop    non_null_obj() const            { return (type##Oop)Handle::non_null_obj(); } \
 106                                                  \
 107    public:                                       \
 108     /* Constructors */                           \
 109     type##Handle ()                              : Handle()                 {} \
 110     type##Handle (Thread* thread, type##Oop obj) : Handle(thread, (oop)obj) { \
 111       assert(is_null() || ((oop)obj)->is_a(), "illegal type");                \
 112     }                                                                         \
 113     \
 114     /* Operators for ease of use */              \
 115     type##Oop    operator () () const            { return obj(); } \
 116     type##Oop    operator -> () const            { return non_null_obj(); } \
 117   };
 118 
 119 
 120 DEF_HANDLE(instance         , is_instance_noinline         )
 121 DEF_HANDLE(array            , is_array_noinline            )
 122 DEF_HANDLE(objArray         , is_objArray_noinline         )
 123 DEF_HANDLE(typeArray        , is_typeArray_noinline        )
 124 
 125 //------------------------------------------------------------------------------------------------------------------------
 126 
 127 // Metadata Handles.  Unlike oop Handles these are needed to prevent metadata
 128 // from being reclaimed by RedefineClasses.
 129 
 130 // Specific Handles for different oop types
 131 #define DEF_METADATA_HANDLE(name, type)          \
 132   class name##Handle;                            \
 133   class name##Handle : public StackObj {         \
 134     type*     _value;                            \
 135     Thread*   _thread;                           \
 136    protected:                                    \
 137     type*        obj() const                     { return _value; } \
 138     type*        non_null_obj() const            { assert(_value != NULL, "resolving NULL _value"); return _value; } \
 139                                                  \
 140    public:                                       \
 141     /* Constructors */                           \
 142     name##Handle () : _value(NULL), _thread(NULL) {}   \
 143     name##Handle (type* obj);                    \
 144     name##Handle (Thread* thread, type* obj);    \
 145                                                  \
 146     name##Handle (const name##Handle &h);        \
 147     name##Handle& operator=(const name##Handle &s); \
 148                                                  \
 149     /* Destructor */                             \
 150     ~name##Handle ();                            \
 151     void remove();                               \
 152                                                  \
 153     /* Operators for ease of use */              \
 154     type*        operator () () const            { return obj(); } \
 155     type*        operator -> () const            { return non_null_obj(); } \
 156                                                  \
 157     bool    operator == (type* o) const          { return obj() == o; } \
 158     bool    operator == (const name##Handle& h) const  { return obj() == h.obj(); } \
 159                                                  \
 160     /* Null checks */                            \
 161     bool    is_null() const                      { return _value == NULL; } \
 162     bool    not_null() const                     { return _value != NULL; } \
 163   };
 164 
 165 
 166 DEF_METADATA_HANDLE(method, Method)
 167 DEF_METADATA_HANDLE(constantPool, ConstantPool)
 168 
 169 // Writing this class explicitly, since DEF_METADATA_HANDLE(klass) doesn't
 170 // provide the necessary Klass* <-> Klass* conversions. This Klass
 171 // could be removed when we don't have the Klass* typedef anymore.
 172 class KlassHandle : public StackObj {
 173   Klass* _value;
 174  protected:
 175    Klass* obj() const          { return _value; }
 176    Klass* non_null_obj() const { assert(_value != NULL, "resolving NULL _value"); return _value; }
 177 
 178  public:
 179    KlassHandle()                                 : _value(NULL) {}
 180    KlassHandle(const Klass* obj)                 : _value(const_cast<Klass *>(obj)) {};
 181    KlassHandle(Thread* thread, const Klass* obj) : _value(const_cast<Klass *>(obj)) {};
 182 
 183    Klass* operator () () const { return obj(); }
 184    Klass* operator -> () const { return non_null_obj(); }
 185 
 186    bool operator == (Klass* o) const             { return obj() == o; }
 187    bool operator == (const KlassHandle& h) const { return obj() == h.obj(); }
 188 
 189     bool is_null() const  { return _value == NULL; }
 190     bool not_null() const { return _value != NULL; }
 191 };
 192 
 193 class instanceKlassHandle : public KlassHandle {
 194  public:
 195   /* Constructors */
 196   instanceKlassHandle () : KlassHandle() {}
 197   instanceKlassHandle (const Klass* k) : KlassHandle(k) {
 198     assert(k == NULL || is_instanceKlass(k), "illegal type");
 199   }
 200   instanceKlassHandle (Thread* thread, const Klass* k) : KlassHandle(thread, k) {
 201     assert(k == NULL || is_instanceKlass(k), "illegal type");
 202   }
 203   /* Access to klass part */
 204   InstanceKlass*       operator () () const { return (InstanceKlass*)obj(); }
 205   InstanceKlass*       operator -> () const { return (InstanceKlass*)obj(); }
 206 
 207   debug_only(bool is_instanceKlass(const Klass* k));
 208 };
 209 
 210 
 211 //------------------------------------------------------------------------------------------------------------------------
 212 // Thread local handle area
 213 class HandleArea: public Arena {
 214   friend class HandleMark;
 215   friend class NoHandleMark;
 216   friend class ResetNoHandleMark;
 217 #ifdef ASSERT
 218   int _handle_mark_nesting;
 219   int _no_handle_mark_nesting;
 220 #endif
 221   HandleArea* _prev;          // link to outer (older) area
 222  public:
 223   // Constructor
 224   HandleArea(HandleArea* prev) : Arena(mtThread, Chunk::tiny_size) {
 225     debug_only(_handle_mark_nesting    = 0);
 226     debug_only(_no_handle_mark_nesting = 0);
 227     _prev = prev;
 228   }
 229 
 230   // Handle allocation
 231  private:
 232   oop* real_allocate_handle(oop obj) {
 233 #ifdef ASSERT
 234     oop* handle = (oop*) (UseMallocOnly ? internal_malloc_4(oopSize) : Amalloc_4(oopSize));
 235 #else
 236     oop* handle = (oop*) Amalloc_4(oopSize);
 237 #endif
 238     *handle = obj;
 239     return handle;
 240   }
 241  public:
 242 #ifdef ASSERT
 243   oop* allocate_handle(oop obj);
 244 #else
 245   oop* allocate_handle(oop obj) { return real_allocate_handle(obj); }
 246 #endif
 247 
 248   // Garbage collection support
 249   void oops_do(OopClosure* f);
 250 
 251   // Number of handles in use
 252   size_t used() const     { return Arena::used() / oopSize; }
 253 
 254   debug_only(bool no_handle_mark_active() { return _no_handle_mark_nesting > 0; })
 255 };
 256 
 257 
 258 //------------------------------------------------------------------------------------------------------------------------
 259 // Handles are allocated in a (growable) thread local handle area. Deallocation
 260 // is managed using a HandleMark. It should normally not be necessary to use
 261 // HandleMarks manually.
 262 //
 263 // A HandleMark constructor will record the current handle area top, and the
 264 // destructor will reset the top, destroying all handles allocated in between.
 265 // The following code will therefore NOT work:
 266 //
 267 //   Handle h;
 268 //   {
 269 //     HandleMark hm;
 270 //     h = Handle(THREAD, obj);
 271 //   }
 272 //   h()->print();       // WRONG, h destroyed by HandleMark destructor.
 273 //
 274 // If h has to be preserved, it can be converted to an oop or a local JNI handle
 275 // across the HandleMark boundary.
 276 
 277 // The base class of HandleMark should have been StackObj but we also heap allocate
 278 // a HandleMark when a thread is created. The operator new is for this special case.
 279 
 280 class HandleMark {
 281  private:
 282   Thread *_thread;              // thread that owns this mark
 283   HandleArea *_area;            // saved handle area
 284   Chunk *_chunk;                // saved arena chunk
 285   char *_hwm, *_max;            // saved arena info
 286   size_t _size_in_bytes;        // size of handle area
 287   // Link to previous active HandleMark in thread
 288   HandleMark* _previous_handle_mark;
 289 
 290   void initialize(Thread* thread);                // common code for constructors
 291   void set_previous_handle_mark(HandleMark* mark) { _previous_handle_mark = mark; }
 292   HandleMark* previous_handle_mark() const        { return _previous_handle_mark; }
 293 
 294   size_t size_in_bytes() const { return _size_in_bytes; }
 295  public:
 296   HandleMark();                            // see handles_inline.hpp
 297   HandleMark(Thread* thread)                      { initialize(thread); }
 298   ~HandleMark();
 299 
 300   // Functions used by HandleMarkCleaner
 301   // called in the constructor of HandleMarkCleaner
 302   void push();
 303   // called in the destructor of HandleMarkCleaner
 304   void pop_and_restore();
 305   // overloaded operators
 306   void* operator new(size_t size) throw();
 307   void* operator new [](size_t size) throw();
 308   void operator delete(void* p);
 309   void operator delete[](void* p);
 310 };
 311 
 312 //------------------------------------------------------------------------------------------------------------------------
 313 // A NoHandleMark stack object will verify that no handles are allocated
 314 // in its scope. Enabled in debug mode only.
 315 
 316 class NoHandleMark: public StackObj {
 317  public:
 318 #ifdef ASSERT
 319   NoHandleMark();
 320   ~NoHandleMark();
 321 #else
 322   NoHandleMark()  {}
 323   ~NoHandleMark() {}
 324 #endif
 325 };
 326 
 327 
 328 class ResetNoHandleMark: public StackObj {
 329   int _no_handle_mark_nesting;
 330  public:
 331 #ifdef ASSERT
 332   ResetNoHandleMark();
 333   ~ResetNoHandleMark();
 334 #else
 335   ResetNoHandleMark()  {}
 336   ~ResetNoHandleMark() {}
 337 #endif
 338 };
 339 
 340 #endif // SHARE_VM_RUNTIME_HANDLES_HPP