1 /*
  2  * Copyright (c) 1997, 2023, 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_MEMORY_UNIVERSE_HPP
 26 #define SHARE_MEMORY_UNIVERSE_HPP
 27 
 28 #include "gc/shared/verifyOption.hpp"
 29 #include "oops/array.hpp"
 30 #include "oops/oopHandle.hpp"
 31 #include "runtime/handles.hpp"
 32 #include "utilities/growableArray.hpp"
 33 
 34 // Universe is a name space holding known system classes and objects in the VM.
 35 //
 36 // Loaded classes are accessible through the SystemDictionary.
 37 //
 38 // The object heap is allocated and accessed through Universe, and various allocation
 39 // support is provided. Allocation by the interpreter and compiled code is done inline
 40 // and bails out to Scavenge::invoke_and_allocate.
 41 
 42 class CollectedHeap;
 43 class DeferredObjAllocEvent;
 44 class OopStorage;
 45 class ReservedHeapSpace;
 46 class SerializeClosure;
 47 
 48 // A helper class for caching a Method* when the user of the cache
 49 // only cares about the latest version of the Method*.  This cache safely
 50 // interacts with the RedefineClasses API.
 51 
 52 class LatestMethodCache : public CHeapObj<mtClass> {
 53   // We save the Klass* and the idnum of Method* in order to get
 54   // the current cached Method*.
 55  private:
 56   Klass*                _klass;
 57   int                   _method_idnum;
 58 
 59  public:
 60   LatestMethodCache()   { _klass = nullptr; _method_idnum = -1; }
 61   ~LatestMethodCache()  { _klass = nullptr; _method_idnum = -1; }
 62 
 63   void   init(Klass* k, Method* m);
 64   Klass* klass() const           { return _klass; }
 65   int    method_idnum() const    { return _method_idnum; }
 66 
 67   Method* get_method();
 68 
 69   // CDS support.  Replace the klass in this with the archive version
 70   // could use this for Enhanced Class Redefinition also.
 71   void serialize(SerializeClosure* f);
 72   void metaspace_pointers_do(MetaspaceClosure* it);
 73 };
 74 
 75 class Universe: AllStatic {
 76   // Ugh.  Universe is much too friendly.
 77   friend class MarkSweep;
 78   friend class oopDesc;
 79   friend class ClassLoader;
 80   friend class SystemDictionary;
 81   friend class ReservedHeapSpace;
 82   friend class VMStructs;
 83   friend class VM_PopulateDumpSharedSpace;
 84   friend class Metaspace;
 85   friend class MetaspaceShared;
 86   friend class vmClasses;
 87 
 88   friend jint  universe_init();
 89   friend void  universe2_init();
 90   friend bool  universe_post_init();
 91   friend void  universe_post_module_init();
 92 
 93  private:
 94   // Known classes in the VM
 95   static Klass* _typeArrayKlassObjs[T_LONG+1];
 96   static Klass* _objectArrayKlassObj;
 97   // Special int-Array that represents filler objects that are used by GC to overwrite
 98   // dead objects. References to them are generally an error.
 99   static Klass* _fillerArrayKlassObj;
100 
101   // Known objects in the VM
102   static OopHandle    _main_thread_group;             // Reference to the main thread group object
103   static OopHandle    _system_thread_group;           // Reference to the system thread group object
104 
105   static OopHandle    _the_empty_class_array;         // Canonicalized obj array of type java.lang.Class
106   static OopHandle    _the_null_string;               // A cache of "null" as a Java string
107   static OopHandle    _the_min_jint_string;           // A cache of "-2147483648" as a Java string
108 
109   static OopHandle    _the_null_sentinel;             // A unique object pointer unused except as a sentinel for null.
110 
111   // preallocated error objects (no backtrace)
112   static OopHandle    _out_of_memory_errors;
113   static OopHandle    _class_init_stack_overflow_error;
114 
115   // preallocated cause message for delayed StackOverflowError
116   static OopHandle    _delayed_stack_overflow_error_message;
117 
118   static LatestMethodCache* _finalizer_register_cache; // static method for registering finalizable objects
119   static LatestMethodCache* _loader_addClass_cache;    // method for registering loaded classes in class loader vector
120   static LatestMethodCache* _throw_illegal_access_error_cache; // Unsafe.throwIllegalAccessError() method
121   static LatestMethodCache* _throw_no_such_method_error_cache; // Unsafe.throwNoSuchMethodError() method
122   static LatestMethodCache* _do_stack_walk_cache;      // method for stack walker callback
123 
124   static Array<int>*            _the_empty_int_array;            // Canonicalized int array
125   static Array<u2>*             _the_empty_short_array;          // Canonicalized short array
126   static Array<Klass*>*         _the_empty_klass_array;          // Canonicalized klass array
127   static Array<InstanceKlass*>* _the_empty_instance_klass_array; // Canonicalized instance klass array
128   static Array<Method*>*        _the_empty_method_array;         // Canonicalized method array
129 
130   static Array<Klass*>*  _the_array_interfaces_array;
131 
132   // array of preallocated error objects with backtrace
133   static OopHandle     _preallocated_out_of_memory_error_array;
134 
135   // number of preallocated error objects available for use
136   static volatile jint _preallocated_out_of_memory_error_avail_count;
137 
138   // preallocated message detail strings for error objects
139   static OopHandle _msg_metaspace;
140   static OopHandle _msg_class_metaspace;
141 
142   static OopHandle    _null_ptr_exception_instance;   // preallocated exception object
143   static OopHandle    _arithmetic_exception_instance; // preallocated exception object
144   static OopHandle    _virtual_machine_error_instance; // preallocated exception object
145 
146   static OopHandle    _array_index_oob_exception_instance; // preallocated exception object
147   static OopHandle    _array_store_exception_instance;     // preallocated exception object
148   static OopHandle    _class_cast_exception_instance;      // preallocated exception object
149 
150   // References waiting to be transferred to the ReferenceHandler
151   static OopHandle    _reference_pending_list;
152 
153   // The particular choice of collected heap.
154   static CollectedHeap* _collectedHeap;
155 
156   static intptr_t _non_oop_bits;
157 
158   // array of dummy objects used with +FullGCAlot
159   debug_only(static OopHandle   _fullgc_alot_dummy_array;)
160   debug_only(static int         _fullgc_alot_dummy_next;)
161 
162   // Compiler/dispatch support
163   static int  _base_vtable_size;                      // Java vtbl size of klass Object (in words)
164 
165   // Initialization
166   static bool _bootstrapping;                         // true during genesis
167   static bool _module_initialized;                    // true after call_initPhase2 called
168   static bool _fully_initialized;                     // true after universe_init and initialize_vtables called
169 
170   // the array of preallocated errors with backtraces
171   static objArrayOop  preallocated_out_of_memory_errors();
172 
173   static objArrayOop out_of_memory_errors();
174   // generate an out of memory error; if possible using an error with preallocated backtrace;
175   // otherwise return the given default error.
176   static oop        gen_out_of_memory_error(oop default_err);
177 
178   static OopStorage* _vm_weak;
179   static OopStorage* _vm_global;
180 
181   static jint initialize_heap();
182   static void initialize_tlab();
183   static void initialize_basic_type_mirrors(TRAPS);
184   static void fixup_mirrors(TRAPS);
185 
186   static void compute_base_vtable_size();             // compute vtable size of class Object
187 
188   static void genesis(TRAPS);                         // Create the initial world
189 
190   // Mirrors for primitive classes (created eagerly)
191   static oop check_mirror(oop m) {
192     assert(m != nullptr, "mirror not initialized");
193     return m;
194   }
195 
196   // Debugging
197   static int _verify_count;                           // number of verifies done
198   static long verify_flags;
199 
200   static uintptr_t _verify_oop_mask;
201   static uintptr_t _verify_oop_bits;
202 
203   // Table of primitive type mirrors, excluding T_OBJECT and T_ARRAY
204   // but including T_VOID, hence the index including T_VOID
205   static OopHandle _basic_type_mirrors[T_VOID+1];
206 
207 #if INCLUDE_CDS_JAVA_HEAP
208   // Each slot i stores an index that can be used to restore _basic_type_mirrors[i]
209   // from the archive heap using HeapShared::get_root(int)
210   static int _archived_basic_type_mirror_indices[T_VOID+1];
211 
212   static int _archived_null_ptr_exception_instance_index;
213   static int _archived_arithmetic_exception_instance_index;
214   static int _archived_virtual_machine_error_instance_index;
215   static int _archived_array_index_oob_exception_instance_index;
216   static int _archived_array_store_exception_instance_index;
217   static int _archived_class_cast_exception_instance_index;
218 #endif
219 
220  public:
221   static void calculate_verify_data(HeapWord* low_boundary, HeapWord* high_boundary) PRODUCT_RETURN;
222   static void set_verify_data(uintptr_t mask, uintptr_t bits) PRODUCT_RETURN;
223 
224   // Known classes in the VM
225   static Klass* boolArrayKlassObj()                 { return typeArrayKlassObj(T_BOOLEAN); }
226   static Klass* byteArrayKlassObj()                 { return typeArrayKlassObj(T_BYTE); }
227   static Klass* charArrayKlassObj()                 { return typeArrayKlassObj(T_CHAR); }
228   static Klass* intArrayKlassObj()                  { return typeArrayKlassObj(T_INT); }
229   static Klass* shortArrayKlassObj()                { return typeArrayKlassObj(T_SHORT); }
230   static Klass* longArrayKlassObj()                 { return typeArrayKlassObj(T_LONG); }
231   static Klass* floatArrayKlassObj()                { return typeArrayKlassObj(T_FLOAT); }
232   static Klass* doubleArrayKlassObj()               { return typeArrayKlassObj(T_DOUBLE); }
233 
234   static Klass* objectArrayKlassObj()               { return _objectArrayKlassObj; }
235 
236   static Klass* fillerArrayKlassObj()               { return _fillerArrayKlassObj; }
237 
238   static Klass* typeArrayKlassObj(BasicType t) {
239     assert((uint)t >= T_BOOLEAN, "range check for type: %s", type2name(t));
240     assert((uint)t < T_LONG+1,   "range check for type: %s", type2name(t));
241     assert(_typeArrayKlassObjs[t] != nullptr, "domain check");
242     return _typeArrayKlassObjs[t];
243   }
244 
245   // Known objects in the VM
246   static oop int_mirror();
247   static oop float_mirror();
248   static oop double_mirror();
249   static oop byte_mirror();
250   static oop bool_mirror();
251   static oop char_mirror();
252   static oop long_mirror();
253   static oop short_mirror();
254   static oop void_mirror();
255 
256   static oop java_mirror(BasicType t);
257 
258 #if INCLUDE_CDS_JAVA_HEAP
259   static void set_archived_basic_type_mirror_index(BasicType t, int index);
260   static void update_archived_basic_type_mirrors();
261 
262   static void set_archived_null_ptr_exception_instance_index(int index) {
263     _archived_null_ptr_exception_instance_index = index;
264   }
265   static void set_archived_arithmetic_exception_instance_index(int index) {
266     _archived_arithmetic_exception_instance_index = index;
267   }
268   static void set_archived_virtual_machine_error_instance_index(int index) {
269     _archived_virtual_machine_error_instance_index = index;
270   }
271   static void set_archived_array_index_oob_exception_instance_index(int index) {
272     _archived_array_index_oob_exception_instance_index = index;
273   }
274   static void set_archived_array_store_exception_instance_index(int index) {
275     _archived_array_store_exception_instance_index = index;
276   }
277   static void set_archived_class_cast_exception_instance_index(int index) {
278     _archived_class_cast_exception_instance_index = index;
279   }
280 
281   static void update_exception_instances();
282 #endif
283 
284   static oop      main_thread_group();
285   static void set_main_thread_group(oop group);
286 
287   static oop      system_thread_group();
288   static void set_system_thread_group(oop group);
289 
290   static objArrayOop  the_empty_class_array ();
291 
292   static oop          the_null_string();
293   static oop          the_min_jint_string();
294 
295   static oop          null_ptr_exception_instance();
296   static oop          arithmetic_exception_instance();
297   static oop          virtual_machine_error_instance();
298   static oop          vm_exception()                  { return virtual_machine_error_instance(); }
299 
300   static oop          array_index_oob_exception_instance();
301   static oop          array_store_exception_instance();
302   static oop          class_cast_exception_instance();
303 
304   static Array<Klass*>* the_array_interfaces_array()  { return _the_array_interfaces_array;   }
305   static Method*      finalizer_register_method()     { return _finalizer_register_cache->get_method(); }
306   static Method*      loader_addClass_method()        { return _loader_addClass_cache->get_method(); }
307 
308   static Method*      throw_illegal_access_error()    { return _throw_illegal_access_error_cache->get_method(); }
309   static Method*      throw_no_such_method_error()    { return _throw_no_such_method_error_cache->get_method(); }
310 
311   static Method*      do_stack_walk_method()          { return _do_stack_walk_cache->get_method(); }
312 
313   static oop          the_null_sentinel();
314   static address      the_null_sentinel_addr()        { return (address) &_the_null_sentinel;  }
315 
316   // Function to initialize these
317   static void initialize_known_methods(TRAPS);
318 
319   static void create_preallocated_out_of_memory_errors(TRAPS);
320 
321   // Reference pending list manipulation.  Access is protected by
322   // Heap_lock.  The getter, setter and predicate require the caller
323   // owns the lock.  Swap is used by parallel non-concurrent reference
324   // processing threads, where some higher level controller owns
325   // Heap_lock, so requires the lock is locked, but not necessarily by
326   // the current thread.
327   static oop          reference_pending_list();
328   static void         clear_reference_pending_list();
329   static bool         has_reference_pending_list();
330   static oop          swap_reference_pending_list(oop list);
331 
332   static Array<int>*             the_empty_int_array()    { return _the_empty_int_array; }
333   static Array<u2>*              the_empty_short_array()  { return _the_empty_short_array; }
334   static Array<Method*>*         the_empty_method_array() { return _the_empty_method_array; }
335   static Array<Klass*>*          the_empty_klass_array()  { return _the_empty_klass_array; }
336   static Array<InstanceKlass*>*  the_empty_instance_klass_array() { return _the_empty_instance_klass_array; }
337 
338   // OutOfMemoryError support. Returns an error with the required message. The returned error
339   // may or may not have a backtrace. If error has a backtrace then the stack trace is already
340   // filled in.
341   static oop out_of_memory_error_java_heap();
342   static oop out_of_memory_error_c_heap();
343   static oop out_of_memory_error_metaspace();
344   static oop out_of_memory_error_class_metaspace();
345   static oop out_of_memory_error_array_size();
346   static oop out_of_memory_error_gc_overhead_limit();
347   static oop out_of_memory_error_realloc_objects();
348 
349   // Throw default _out_of_memory_error_retry object as it will never propagate out of the VM
350   static oop out_of_memory_error_retry();
351   static oop delayed_stack_overflow_error_message();
352 
353   // Saved StackOverflowError and OutOfMemoryError for use when
354   // class initialization can't create ExceptionInInitializerError.
355   static oop class_init_stack_overflow_error();
356   static oop class_init_out_of_memory_error();
357 
358   // If it's a certain type of OOME object
359   static bool is_out_of_memory_error_metaspace(oop ex_obj);
360   static bool is_out_of_memory_error_class_metaspace(oop ex_obj);
361 
362   // The particular choice of collected heap.
363   static CollectedHeap* heap() { return _collectedHeap; }
364 
365   DEBUG_ONLY(static bool is_gc_active();)
366   DEBUG_ONLY(static bool is_in_heap(const void* p);)
367   DEBUG_ONLY(static bool is_in_heap_or_null(const void* p) { return p == nullptr || is_in_heap(p); })
368 
369   // Reserve Java heap and determine CompressedOops mode
370   static ReservedHeapSpace reserve_heap(size_t heap_size, size_t alignment);
371 
372   // Global OopStorages
373   static OopStorage* vm_weak();
374   static OopStorage* vm_global();
375   static void oopstorage_init();
376 
377   // Testers
378   static bool is_bootstrapping()                      { return _bootstrapping; }
379   static bool is_module_initialized()                 { return _module_initialized; }
380   static bool is_fully_initialized()                  { return _fully_initialized; }
381 
382   static bool        on_page_boundary(void* addr);
383   static bool        should_fill_in_stack_trace(Handle throwable);
384   static void check_alignment(uintx size, uintx alignment, const char* name);
385 
386   // CDS support
387   static void serialize(SerializeClosure* f);
388 
389   // Apply the closure to all klasses for basic types (classes not present in
390   // SystemDictionary).
391   static void basic_type_classes_do(KlassClosure* closure);
392   static void metaspace_pointers_do(MetaspaceClosure* it);
393 
394   // Debugging
395   enum VERIFY_FLAGS {
396     Verify_Threads = 1,
397     Verify_Heap = 2,
398     Verify_SymbolTable = 4,
399     Verify_StringTable = 8,
400     Verify_CodeCache = 16,
401     Verify_SystemDictionary = 32,
402     Verify_ClassLoaderDataGraph = 64,
403     Verify_MetaspaceUtils = 128,
404     Verify_JNIHandles = 256,
405     Verify_CodeCacheOops = 512,
406     Verify_ResolvedMethodTable = 1024,
407     Verify_StringDedup = 2048,
408     Verify_All = -1
409   };
410   static void initialize_verify_flags();
411   static bool should_verify_subset(uint subset);
412   static void verify(VerifyOption option, const char* prefix);
413   static void verify(const char* prefix) {
414     verify(VerifyOption::Default, prefix);
415   }
416   static void verify() {
417     verify("");
418   }
419 
420   static int  verify_count()       { return _verify_count; }
421   static void print_on(outputStream* st);
422   static void print_heap_at_SIGBREAK();
423 
424   // Change the number of dummy objects kept reachable by the full gc dummy
425   // array; this should trigger relocation in a sliding compaction collector.
426   debug_only(static bool release_fullgc_alot_dummy();)
427   // The non-oop pattern (see compiledIC.hpp, etc)
428   static void*         non_oop_word();
429   static bool contains_non_oop_word(void* p);
430 
431   // Oop verification (see MacroAssembler::verify_oop)
432   static uintptr_t verify_oop_mask()          PRODUCT_RETURN0;
433   static uintptr_t verify_oop_bits()          PRODUCT_RETURN0;
434   static uintptr_t verify_mark_bits()         PRODUCT_RETURN0;
435   static uintptr_t verify_mark_mask()         PRODUCT_RETURN0;
436 
437   // Compiler support
438   static int base_vtable_size()               { return _base_vtable_size; }
439 };
440 
441 #endif // SHARE_MEMORY_UNIVERSE_HPP