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