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