1 /*
   2  * Copyright (c) 1997, 2025, 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 #include "cds/archiveHeapLoader.hpp"
  26 #include "cds/cdsConfig.hpp"
  27 #include "cds/dynamicArchive.hpp"
  28 #include "cds/heapShared.hpp"
  29 #include "cds/metaspaceShared.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderDataGraph.hpp"
  32 #include "classfile/javaClasses.hpp"
  33 #include "classfile/stringTable.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/systemDictionary.hpp"
  36 #include "classfile/vmClasses.hpp"
  37 #include "classfile/vmSymbols.hpp"
  38 #include "code/codeBehaviours.hpp"
  39 #include "code/codeCache.hpp"
  40 #include "compiler/oopMap.hpp"
  41 #include "gc/shared/collectedHeap.inline.hpp"
  42 #include "gc/shared/gcArguments.hpp"
  43 #include "gc/shared/gcConfig.hpp"
  44 #include "gc/shared/gcLogPrecious.hpp"
  45 #include "gc/shared/gcTraceTime.inline.hpp"
  46 #include "gc/shared/oopStorageSet.hpp"
  47 #include "gc/shared/plab.hpp"
  48 #include "gc/shared/stringdedup/stringDedup.hpp"
  49 #include "gc/shared/tlab_globals.hpp"
  50 #include "logging/log.hpp"
  51 #include "logging/logStream.hpp"
  52 #include "memory/memoryReserver.hpp"
  53 #include "memory/metadataFactory.hpp"
  54 #include "memory/metaspaceClosure.hpp"
  55 #include "memory/metaspaceCounters.hpp"
  56 #include "memory/metaspaceUtils.hpp"
  57 #include "memory/oopFactory.hpp"
  58 #include "memory/resourceArea.hpp"
  59 #include "memory/universe.hpp"
  60 #include "oops/compressedOops.hpp"
  61 #include "oops/instanceKlass.hpp"
  62 #include "oops/instanceMirrorKlass.hpp"
  63 #include "oops/klass.inline.hpp"
  64 #include "oops/objArrayOop.inline.hpp"
  65 #include "oops/objLayout.hpp"
  66 #include "oops/oop.inline.hpp"
  67 #include "oops/oopHandle.inline.hpp"
  68 #include "oops/typeArrayKlass.hpp"
  69 #include "prims/resolvedMethodTable.hpp"
  70 #include "runtime/arguments.hpp"
  71 #include "runtime/atomic.hpp"
  72 #include "runtime/cpuTimeCounters.hpp"
  73 #include "runtime/flags/jvmFlagLimit.hpp"
  74 #include "runtime/handles.inline.hpp"
  75 #include "runtime/init.hpp"
  76 #include "runtime/java.hpp"
  77 #include "runtime/javaThread.hpp"
  78 #include "runtime/jniHandles.hpp"
  79 #include "runtime/threads.hpp"
  80 #include "runtime/timerTrace.hpp"
  81 #include "sanitizers/leak.hpp"
  82 #include "services/memoryService.hpp"
  83 #include "utilities/align.hpp"
  84 #include "utilities/autoRestore.hpp"
  85 #include "utilities/debug.hpp"
  86 #include "utilities/formatBuffer.hpp"
  87 #include "utilities/macros.hpp"
  88 #include "utilities/ostream.hpp"
  89 #include "utilities/preserveException.hpp"
  90 
  91 // A helper class for caching a Method* when the user of the cache
  92 // only cares about the latest version of the Method*. This cache safely
  93 // interacts with the RedefineClasses API.
  94 class LatestMethodCache {
  95   // We save the InstanceKlass* and the idnum of Method* in order to get
  96   // the current Method*.
  97   InstanceKlass*        _klass;
  98   int                   _method_idnum;
  99 
 100  public:
 101   LatestMethodCache()   { _klass = nullptr; _method_idnum = -1; }
 102 
 103   void init(JavaThread* current, InstanceKlass* ik, const char* method,
 104             Symbol* signature, bool is_static);
 105   Method* get_method();
 106 };
 107 
 108 static LatestMethodCache _finalizer_register_cache;         // Finalizer.register()
 109 static LatestMethodCache _loader_addClass_cache;            // ClassLoader.addClass()
 110 static LatestMethodCache _throw_illegal_access_error_cache; // Unsafe.throwIllegalAccessError()
 111 static LatestMethodCache _throw_no_such_method_error_cache; // Unsafe.throwNoSuchMethodError()
 112 static LatestMethodCache _do_stack_walk_cache;              // AbstractStackWalker.doStackWalk()
 113 static LatestMethodCache _is_substitutable_cache;           // ValueObjectMethods.isSubstitutable()
 114 static LatestMethodCache _value_object_hash_code_cache;     // ValueObjectMethods.valueObjectHashCode()
 115 
 116 // Known objects
 117 TypeArrayKlass* Universe::_typeArrayKlasses[T_LONG+1] = { nullptr /*, nullptr...*/ };
 118 ObjArrayKlass* Universe::_objectArrayKlass            = nullptr;
 119 Klass* Universe::_fillerArrayKlass                    = nullptr;
 120 OopHandle Universe::_basic_type_mirrors[T_VOID+1];
 121 #if INCLUDE_CDS_JAVA_HEAP
 122 int Universe::_archived_basic_type_mirror_indices[T_VOID+1];
 123 #endif
 124 
 125 OopHandle Universe::_main_thread_group;
 126 OopHandle Universe::_system_thread_group;
 127 OopHandle Universe::_the_empty_class_array;
 128 OopHandle Universe::_the_null_string;
 129 OopHandle Universe::_the_min_jint_string;
 130 
 131 OopHandle Universe::_the_null_sentinel;
 132 
 133 // _out_of_memory_errors is an objArray
 134 enum OutOfMemoryInstance { _oom_java_heap,
 135                            _oom_c_heap,
 136                            _oom_metaspace,
 137                            _oom_class_metaspace,
 138                            _oom_array_size,
 139                            _oom_gc_overhead_limit,
 140                            _oom_realloc_objects,
 141                            _oom_count };
 142 
 143 OopHandle Universe::_out_of_memory_errors;
 144 OopHandle Universe:: _class_init_stack_overflow_error;
 145 OopHandle Universe::_delayed_stack_overflow_error_message;
 146 OopHandle Universe::_preallocated_out_of_memory_error_array;
 147 volatile jint Universe::_preallocated_out_of_memory_error_avail_count = 0;
 148 
 149 // Message details for OOME objects, preallocate these objects since they could be
 150 // used when throwing OOME, we should try to avoid further allocation in such case
 151 OopHandle Universe::_msg_metaspace;
 152 OopHandle Universe::_msg_class_metaspace;
 153 
 154 OopHandle Universe::_reference_pending_list;
 155 
 156 Array<Klass*>* Universe::_the_array_interfaces_array = nullptr;
 157 
 158 long Universe::verify_flags                           = Universe::Verify_All;
 159 
 160 Array<int>* Universe::_the_empty_int_array            = nullptr;
 161 Array<u2>* Universe::_the_empty_short_array           = nullptr;
 162 Array<Klass*>* Universe::_the_empty_klass_array     = nullptr;
 163 Array<InstanceKlass*>* Universe::_the_empty_instance_klass_array  = nullptr;
 164 Array<Method*>* Universe::_the_empty_method_array   = nullptr;
 165 
 166 uintx Universe::_the_array_interfaces_bitmap = 0;
 167 uintx Universe::_the_empty_klass_bitmap      = 0;
 168 
 169 // These variables are guarded by FullGCALot_lock.
 170 debug_only(OopHandle Universe::_fullgc_alot_dummy_array;)
 171 debug_only(int Universe::_fullgc_alot_dummy_next = 0;)
 172 
 173 // Heap
 174 int             Universe::_verify_count = 0;
 175 
 176 // Oop verification (see MacroAssembler::verify_oop)
 177 uintptr_t       Universe::_verify_oop_mask = 0;
 178 uintptr_t       Universe::_verify_oop_bits = (uintptr_t) -1;
 179 
 180 int             Universe::_base_vtable_size = 0;
 181 bool            Universe::_bootstrapping = false;
 182 bool            Universe::_module_initialized = false;
 183 bool            Universe::_fully_initialized = false;
 184 
 185 OopStorage*     Universe::_vm_weak = nullptr;
 186 OopStorage*     Universe::_vm_global = nullptr;
 187 
 188 CollectedHeap*  Universe::_collectedHeap = nullptr;
 189 
 190 // These are the exceptions that are always created and are guatanteed to exist.
 191 // If possible, they can be stored as CDS archived objects to speed up AOT code.
 192 class BuiltinException {
 193   OopHandle _instance;
 194   CDS_JAVA_HEAP_ONLY(int _archived_root_index;)
 195 
 196 public:
 197   BuiltinException() : _instance() {
 198     CDS_JAVA_HEAP_ONLY(_archived_root_index = 0);
 199   }
 200 
 201   void init_if_empty(Symbol* symbol, TRAPS) {
 202     if (_instance.is_empty()) {
 203       Klass* k = SystemDictionary::resolve_or_fail(symbol, true, CHECK);
 204       oop obj = InstanceKlass::cast(k)->allocate_instance(CHECK);
 205       _instance = OopHandle(Universe::vm_global(), obj);
 206     }
 207   }
 208 
 209   oop instance() {
 210     return _instance.resolve();
 211   }
 212 
 213 #if INCLUDE_CDS_JAVA_HEAP
 214   void store_in_cds() {
 215     _archived_root_index = HeapShared::archive_exception_instance(instance());
 216   }
 217 
 218   void load_from_cds() {
 219     if (_archived_root_index >= 0) {
 220       oop obj = HeapShared::get_root(_archived_root_index);
 221       assert(obj != nullptr, "must be");
 222       _instance = OopHandle(Universe::vm_global(), obj);
 223     }
 224   }
 225 
 226   void serialize(SerializeClosure *f) {
 227     f->do_int(&_archived_root_index);
 228   }
 229 #endif
 230 };
 231 
 232 static BuiltinException _null_ptr_exception;
 233 static BuiltinException _arithmetic_exception;
 234 static BuiltinException _internal_error;
 235 static BuiltinException _array_index_out_of_bounds_exception;
 236 static BuiltinException _array_store_exception;
 237 static BuiltinException _class_cast_exception;
 238 
 239 objArrayOop Universe::the_empty_class_array ()  {
 240   return (objArrayOop)_the_empty_class_array.resolve();
 241 }
 242 
 243 oop Universe::main_thread_group()                 { return _main_thread_group.resolve(); }
 244 void Universe::set_main_thread_group(oop group)   { _main_thread_group = OopHandle(vm_global(), group); }
 245 
 246 oop Universe::system_thread_group()               { return _system_thread_group.resolve(); }
 247 void Universe::set_system_thread_group(oop group) { _system_thread_group = OopHandle(vm_global(), group); }
 248 
 249 oop Universe::the_null_string()                   { return _the_null_string.resolve(); }
 250 oop Universe::the_min_jint_string()               { return _the_min_jint_string.resolve(); }
 251 
 252 oop Universe::null_ptr_exception_instance()       { return _null_ptr_exception.instance(); }
 253 oop Universe::arithmetic_exception_instance()     { return _arithmetic_exception.instance(); }
 254 oop Universe::internal_error_instance()           { return _internal_error.instance(); }
 255 oop Universe::array_index_out_of_bounds_exception_instance() { return _array_index_out_of_bounds_exception.instance(); }
 256 oop Universe::array_store_exception_instance()    { return _array_store_exception.instance(); }
 257 oop Universe::class_cast_exception_instance()     { return _class_cast_exception.instance(); }
 258 
 259 oop Universe::the_null_sentinel()                 { return _the_null_sentinel.resolve(); }
 260 
 261 oop Universe::int_mirror()                        { return check_mirror(_basic_type_mirrors[T_INT].resolve()); }
 262 oop Universe::float_mirror()                      { return check_mirror(_basic_type_mirrors[T_FLOAT].resolve()); }
 263 oop Universe::double_mirror()                     { return check_mirror(_basic_type_mirrors[T_DOUBLE].resolve()); }
 264 oop Universe::byte_mirror()                       { return check_mirror(_basic_type_mirrors[T_BYTE].resolve()); }
 265 oop Universe::bool_mirror()                       { return check_mirror(_basic_type_mirrors[T_BOOLEAN].resolve()); }
 266 oop Universe::char_mirror()                       { return check_mirror(_basic_type_mirrors[T_CHAR].resolve()); }
 267 oop Universe::long_mirror()                       { return check_mirror(_basic_type_mirrors[T_LONG].resolve()); }
 268 oop Universe::short_mirror()                      { return check_mirror(_basic_type_mirrors[T_SHORT].resolve()); }
 269 oop Universe::void_mirror()                       { return check_mirror(_basic_type_mirrors[T_VOID].resolve()); }
 270 
 271 oop Universe::java_mirror(BasicType t) {
 272   assert((uint)t < T_VOID+1, "range check");
 273   assert(!is_reference_type(t), "sanity");
 274   return check_mirror(_basic_type_mirrors[t].resolve());
 275 }
 276 
 277 void Universe::basic_type_classes_do(KlassClosure *closure) {
 278   for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
 279     closure->do_klass(_typeArrayKlasses[i]);
 280   }
 281   // We don't do the following because it will confuse JVMTI.
 282   // _fillerArrayKlass is used only by GC, which doesn't need to see
 283   // this klass from basic_type_classes_do().
 284   //
 285   // closure->do_klass(_fillerArrayKlass);
 286 }
 287 
 288 void Universe::metaspace_pointers_do(MetaspaceClosure* it) {
 289   it->push(&_fillerArrayKlass);
 290   for (int i = 0; i < T_LONG+1; i++) {
 291     it->push(&_typeArrayKlasses[i]);
 292   }
 293   it->push(&_objectArrayKlass);
 294 
 295   it->push(&_the_empty_int_array);
 296   it->push(&_the_empty_short_array);
 297   it->push(&_the_empty_klass_array);
 298   it->push(&_the_empty_instance_klass_array);
 299   it->push(&_the_empty_method_array);
 300   it->push(&_the_array_interfaces_array);
 301 }
 302 
 303 #if INCLUDE_CDS_JAVA_HEAP
 304 void Universe::set_archived_basic_type_mirror_index(BasicType t, int index) {
 305   assert(CDSConfig::is_dumping_heap(), "sanity");
 306   assert(!is_reference_type(t), "sanity");
 307   _archived_basic_type_mirror_indices[t] = index;
 308 }
 309 
 310 void Universe::archive_exception_instances() {
 311   _null_ptr_exception.store_in_cds();
 312   _arithmetic_exception.store_in_cds();
 313   _internal_error.store_in_cds();
 314   _array_index_out_of_bounds_exception.store_in_cds();
 315   _array_store_exception.store_in_cds();
 316   _class_cast_exception.store_in_cds();
 317 }
 318 
 319 void Universe::load_archived_object_instances() {
 320   if (ArchiveHeapLoader::is_in_use()) {
 321     for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 322       int index = _archived_basic_type_mirror_indices[i];
 323       if (!is_reference_type((BasicType)i) && index >= 0) {
 324         oop mirror_oop = HeapShared::get_root(index);
 325         assert(mirror_oop != nullptr, "must be");
 326         _basic_type_mirrors[i] = OopHandle(vm_global(), mirror_oop);
 327       }
 328     }
 329 
 330     _null_ptr_exception.load_from_cds();
 331     _arithmetic_exception.load_from_cds();
 332     _internal_error.load_from_cds();
 333     _array_index_out_of_bounds_exception.load_from_cds();
 334     _array_store_exception.load_from_cds();
 335     _class_cast_exception.load_from_cds();
 336   }
 337 }
 338 #endif
 339 
 340 void Universe::serialize(SerializeClosure* f) {
 341 
 342 #if INCLUDE_CDS_JAVA_HEAP
 343   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 344     f->do_int(&_archived_basic_type_mirror_indices[i]);
 345     // if f->reading(): We can't call HeapShared::get_root() yet, as the heap
 346     // contents may need to be relocated. _basic_type_mirrors[i] will be
 347     // updated later in Universe::load_archived_object_instances().
 348   }
 349   _null_ptr_exception.serialize(f);
 350   _arithmetic_exception.serialize(f);
 351   _internal_error.serialize(f);
 352   _array_index_out_of_bounds_exception.serialize(f);
 353   _array_store_exception.serialize(f);
 354   _class_cast_exception.serialize(f);
 355 #endif
 356 
 357   f->do_ptr(&_fillerArrayKlass);
 358   for (int i = 0; i < T_LONG+1; i++) {
 359     f->do_ptr(&_typeArrayKlasses[i]);
 360   }
 361 
 362   f->do_ptr(&_objectArrayKlass);
 363   f->do_ptr(&_the_array_interfaces_array);
 364   f->do_ptr(&_the_empty_int_array);
 365   f->do_ptr(&_the_empty_short_array);
 366   f->do_ptr(&_the_empty_method_array);
 367   f->do_ptr(&_the_empty_klass_array);
 368   f->do_ptr(&_the_empty_instance_klass_array);
 369 }
 370 
 371 
 372 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
 373   if (size < alignment || size % alignment != 0) {
 374     vm_exit_during_initialization(
 375       err_msg("Size of %s (%zu bytes) must be aligned to %zu bytes", name, size, alignment));
 376   }
 377 }
 378 
 379 static void initialize_basic_type_klass(Klass* k, TRAPS) {
 380   Klass* ok = vmClasses::Object_klass();
 381 #if INCLUDE_CDS
 382   if (CDSConfig::is_using_archive()) {
 383     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 384     assert(k->super() == ok, "u3");
 385     if (k->is_instance_klass()) {
 386       InstanceKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), nullptr, CHECK);
 387     } else {
 388       ArrayKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), CHECK);
 389     }
 390   } else
 391 #endif
 392   {
 393     k->initialize_supers(ok, nullptr, CHECK);
 394   }
 395   k->append_to_sibling_list();
 396 }
 397 
 398 void Universe::genesis(TRAPS) {
 399   ResourceMark rm(THREAD);
 400   HandleMark   hm(THREAD);
 401 
 402   // Explicit null checks are needed if these offsets are not smaller than the page size
 403   if (UseCompactObjectHeaders) {
 404     assert(oopDesc::mark_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 405            "Mark offset is expected to be less than the page size");
 406   } else {
 407     assert(oopDesc::klass_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 408            "Klass offset is expected to be less than the page size");
 409   }
 410   assert(arrayOopDesc::length_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 411          "Array length offset is expected to be less than the page size");
 412 
 413   { AutoModifyRestore<bool> temporarily(_bootstrapping, true);
 414 
 415     java_lang_Class::allocate_fixup_lists();
 416 
 417     // determine base vtable size; without that we cannot create the array klasses
 418     compute_base_vtable_size();
 419 
 420     if (!CDSConfig::is_using_archive()) {
 421       // Initialization of the fillerArrayKlass must come before regular
 422       // int-TypeArrayKlass so that the int-Array mirror points to the
 423       // int-TypeArrayKlass.
 424       _fillerArrayKlass = TypeArrayKlass::create_klass(T_INT, "[Ljdk/internal/vm/FillerElement;", CHECK);
 425       for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
 426         _typeArrayKlasses[i] = TypeArrayKlass::create_klass((BasicType)i, CHECK);
 427       }
 428 
 429       ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
 430 
 431       _the_array_interfaces_array     = MetadataFactory::new_array<Klass*>(null_cld, 2, nullptr, CHECK);
 432       _the_empty_int_array            = MetadataFactory::new_array<int>(null_cld, 0, CHECK);
 433       _the_empty_short_array          = MetadataFactory::new_array<u2>(null_cld, 0, CHECK);
 434       _the_empty_method_array         = MetadataFactory::new_array<Method*>(null_cld, 0, CHECK);
 435       _the_empty_klass_array          = MetadataFactory::new_array<Klass*>(null_cld, 0, CHECK);
 436       _the_empty_instance_klass_array = MetadataFactory::new_array<InstanceKlass*>(null_cld, 0, CHECK);
 437     }
 438 
 439     vmSymbols::initialize();
 440 
 441     SystemDictionary::initialize(CHECK);
 442 
 443     // Create string constants
 444     oop s = StringTable::intern("null", CHECK);
 445     _the_null_string = OopHandle(vm_global(), s);
 446     s = StringTable::intern("-2147483648", CHECK);
 447     _the_min_jint_string = OopHandle(vm_global(), s);
 448 
 449 
 450 #if INCLUDE_CDS
 451     if (CDSConfig::is_using_archive()) {
 452       // Verify shared interfaces array.
 453       assert(_the_array_interfaces_array->at(0) ==
 454              vmClasses::Cloneable_klass(), "u3");
 455       assert(_the_array_interfaces_array->at(1) ==
 456              vmClasses::Serializable_klass(), "u3");
 457 
 458     } else
 459 #endif
 460     {
 461       // Set up shared interfaces array.  (Do this before supers are set up.)
 462       _the_array_interfaces_array->at_put(0, vmClasses::Cloneable_klass());
 463       _the_array_interfaces_array->at_put(1, vmClasses::Serializable_klass());
 464     }
 465 
 466     _the_array_interfaces_bitmap = Klass::compute_secondary_supers_bitmap(_the_array_interfaces_array);
 467     _the_empty_klass_bitmap      = Klass::compute_secondary_supers_bitmap(_the_empty_klass_array);
 468 
 469     initialize_basic_type_klass(_fillerArrayKlass, CHECK);
 470 
 471     initialize_basic_type_klass(boolArrayKlass(), CHECK);
 472     initialize_basic_type_klass(charArrayKlass(), CHECK);
 473     initialize_basic_type_klass(floatArrayKlass(), CHECK);
 474     initialize_basic_type_klass(doubleArrayKlass(), CHECK);
 475     initialize_basic_type_klass(byteArrayKlass(), CHECK);
 476     initialize_basic_type_klass(shortArrayKlass(), CHECK);
 477     initialize_basic_type_klass(intArrayKlass(), CHECK);
 478     initialize_basic_type_klass(longArrayKlass(), CHECK);
 479 
 480     assert(_fillerArrayKlass != intArrayKlass(),
 481            "Internal filler array klass should be different to int array Klass");
 482   } // end of core bootstrapping
 483 
 484   {
 485     Handle tns = java_lang_String::create_from_str("<null_sentinel>", CHECK);
 486     _the_null_sentinel = OopHandle(vm_global(), tns());
 487   }
 488 
 489   // Create a handle for reference_pending_list
 490   _reference_pending_list = OopHandle(vm_global(), nullptr);
 491 
 492   // Maybe this could be lifted up now that object array can be initialized
 493   // during the bootstrapping.
 494 
 495   // OLD
 496   // Initialize _objectArrayKlass after core bootstraping to make
 497   // sure the super class is set up properly for _objectArrayKlass.
 498   // ---
 499   // NEW
 500   // Since some of the old system object arrays have been converted to
 501   // ordinary object arrays, _objectArrayKlass will be loaded when
 502   // SystemDictionary::initialize(CHECK); is run. See the extra check
 503   // for Object_klass_loaded in objArrayKlassKlass::allocate_objArray_klass_impl.
 504   {
 505     Klass* oak = vmClasses::Object_klass()->array_klass(CHECK);
 506     _objectArrayKlass = ObjArrayKlass::cast(oak);
 507   }
 508   // OLD
 509   // Add the class to the class hierarchy manually to make sure that
 510   // its vtable is initialized after core bootstrapping is completed.
 511   // ---
 512   // New
 513   // Have already been initialized.
 514   _objectArrayKlass->append_to_sibling_list();
 515 
 516   #ifdef ASSERT
 517   if (FullGCALot) {
 518     // Allocate an array of dummy objects.
 519     // We'd like these to be at the bottom of the old generation,
 520     // so that when we free one and then collect,
 521     // (almost) the whole heap moves
 522     // and we find out if we actually update all the oops correctly.
 523     // But we can't allocate directly in the old generation,
 524     // so we allocate wherever, and hope that the first collection
 525     // moves these objects to the bottom of the old generation.
 526     int size = FullGCALotDummies * 2;
 527 
 528     objArrayOop    naked_array = oopFactory::new_objArray(vmClasses::Object_klass(), size, CHECK);
 529     objArrayHandle dummy_array(THREAD, naked_array);
 530     int i = 0;
 531     while (i < size) {
 532         // Allocate dummy in old generation
 533       oop dummy = vmClasses::Object_klass()->allocate_instance(CHECK);
 534       dummy_array->obj_at_put(i++, dummy);
 535     }
 536     {
 537       // Only modify the global variable inside the mutex.
 538       // If we had a race to here, the other dummy_array instances
 539       // and their elements just get dropped on the floor, which is fine.
 540       MutexLocker ml(THREAD, FullGCALot_lock);
 541       if (_fullgc_alot_dummy_array.is_empty()) {
 542         _fullgc_alot_dummy_array = OopHandle(vm_global(), dummy_array());
 543       }
 544     }
 545     assert(i == ((objArrayOop)_fullgc_alot_dummy_array.resolve())->length(), "just checking");
 546   }
 547   #endif
 548 }
 549 
 550 void Universe::initialize_basic_type_mirrors(TRAPS) {
 551 #if INCLUDE_CDS_JAVA_HEAP
 552     if (CDSConfig::is_using_archive() &&
 553         ArchiveHeapLoader::is_in_use() &&
 554         _basic_type_mirrors[T_INT].resolve() != nullptr) {
 555       assert(ArchiveHeapLoader::can_use(), "Sanity");
 556 
 557       // check that all basic type mirrors are mapped also
 558       for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 559         if (!is_reference_type((BasicType)i)) {
 560           oop m = _basic_type_mirrors[i].resolve();
 561           assert(m != nullptr, "archived mirrors should not be null");
 562         }
 563       }
 564     } else
 565       // _basic_type_mirrors[T_INT], etc, are null if archived heap is not mapped.
 566 #endif
 567     {
 568       for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 569         BasicType bt = (BasicType)i;
 570         if (!is_reference_type(bt)) {
 571           oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
 572           _basic_type_mirrors[i] = OopHandle(vm_global(), m);
 573         }
 574         CDS_JAVA_HEAP_ONLY(_archived_basic_type_mirror_indices[i] = -1);
 575       }
 576     }
 577     if (CDSConfig::is_dumping_heap()) {
 578       HeapShared::init_scratch_objects_for_basic_type_mirrors(CHECK);
 579     }
 580 }
 581 
 582 void Universe::fixup_mirrors(TRAPS) {
 583   // Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly,
 584   // but we cannot do that for classes created before java.lang.Class is loaded. Here we simply
 585   // walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note
 586   // that the number of objects allocated at this point is very small.
 587   assert(vmClasses::Class_klass_loaded(), "java.lang.Class should be loaded");
 588   HandleMark hm(THREAD);
 589 
 590   if (!CDSConfig::is_using_archive()) {
 591     // Cache the start of the static fields
 592     InstanceMirrorKlass::init_offset_of_static_fields();
 593   }
 594 
 595   GrowableArray <Klass*>* list = java_lang_Class::fixup_mirror_list();
 596   int list_length = list->length();
 597   for (int i = 0; i < list_length; i++) {
 598     Klass* k = list->at(i);
 599     assert(k->is_klass(), "List should only hold classes");
 600     java_lang_Class::fixup_mirror(k, CATCH);
 601   }
 602   delete java_lang_Class::fixup_mirror_list();
 603   java_lang_Class::set_fixup_mirror_list(nullptr);
 604 }
 605 
 606 #define assert_pll_locked(test) \
 607   assert(Heap_lock->test(), "Reference pending list access requires lock")
 608 
 609 #define assert_pll_ownership() assert_pll_locked(owned_by_self)
 610 
 611 oop Universe::reference_pending_list() {
 612   if (Thread::current()->is_VM_thread()) {
 613     assert_pll_locked(is_locked);
 614   } else {
 615     assert_pll_ownership();
 616   }
 617   return _reference_pending_list.resolve();
 618 }
 619 
 620 void Universe::clear_reference_pending_list() {
 621   assert_pll_ownership();
 622   _reference_pending_list.replace(nullptr);
 623 }
 624 
 625 bool Universe::has_reference_pending_list() {
 626   assert_pll_ownership();
 627   return _reference_pending_list.peek() != nullptr;
 628 }
 629 
 630 oop Universe::swap_reference_pending_list(oop list) {
 631   assert_pll_locked(is_locked);
 632   return _reference_pending_list.xchg(list);
 633 }
 634 
 635 #undef assert_pll_locked
 636 #undef assert_pll_ownership
 637 
 638 static void reinitialize_vtables() {
 639   // The vtables are initialized by starting at java.lang.Object and
 640   // initializing through the subclass links, so that the super
 641   // classes are always initialized first.
 642   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
 643     Klass* sub = iter.klass();
 644     sub->vtable().initialize_vtable();
 645   }
 646 }
 647 
 648 static void reinitialize_itables() {
 649 
 650   class ReinitTableClosure : public KlassClosure {
 651    public:
 652     void do_klass(Klass* k) {
 653       if (k->is_instance_klass()) {
 654          InstanceKlass::cast(k)->itable().initialize_itable();
 655       }
 656     }
 657   };
 658 
 659   MutexLocker mcld(ClassLoaderDataGraph_lock);
 660   ReinitTableClosure cl;
 661   ClassLoaderDataGraph::classes_do(&cl);
 662 }
 663 
 664 bool Universe::on_page_boundary(void* addr) {
 665   return is_aligned(addr, os::vm_page_size());
 666 }
 667 
 668 // the array of preallocated errors with backtraces
 669 objArrayOop Universe::preallocated_out_of_memory_errors() {
 670   return (objArrayOop)_preallocated_out_of_memory_error_array.resolve();
 671 }
 672 
 673 objArrayOop Universe::out_of_memory_errors() { return (objArrayOop)_out_of_memory_errors.resolve(); }
 674 
 675 oop Universe::out_of_memory_error_java_heap() {
 676   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_java_heap));
 677 }
 678 
 679 oop Universe::out_of_memory_error_java_heap_without_backtrace() {
 680   return out_of_memory_errors()->obj_at(_oom_java_heap);
 681 }
 682 
 683 oop Universe::out_of_memory_error_c_heap() {
 684   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_c_heap));
 685 }
 686 
 687 oop Universe::out_of_memory_error_metaspace() {
 688   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_metaspace));
 689 }
 690 
 691 oop Universe::out_of_memory_error_class_metaspace() {
 692   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_class_metaspace));
 693 }
 694 
 695 oop Universe::out_of_memory_error_array_size() {
 696   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_array_size));
 697 }
 698 
 699 oop Universe::out_of_memory_error_gc_overhead_limit() {
 700   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_gc_overhead_limit));
 701 }
 702 
 703 oop Universe::out_of_memory_error_realloc_objects() {
 704   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_realloc_objects));
 705 }
 706 
 707 oop Universe::class_init_out_of_memory_error()         { return out_of_memory_errors()->obj_at(_oom_java_heap); }
 708 oop Universe::class_init_stack_overflow_error()        { return _class_init_stack_overflow_error.resolve(); }
 709 oop Universe::delayed_stack_overflow_error_message()   { return _delayed_stack_overflow_error_message.resolve(); }
 710 
 711 
 712 bool Universe::should_fill_in_stack_trace(Handle throwable) {
 713   // never attempt to fill in the stack trace of preallocated errors that do not have
 714   // backtrace. These errors are kept alive forever and may be "re-used" when all
 715   // preallocated errors with backtrace have been consumed. Also need to avoid
 716   // a potential loop which could happen if an out of memory occurs when attempting
 717   // to allocate the backtrace.
 718   objArrayOop preallocated_oom = out_of_memory_errors();
 719   for (int i = 0; i < _oom_count; i++) {
 720     if (throwable() == preallocated_oom->obj_at(i)) {
 721       return false;
 722     }
 723   }
 724   return true;
 725 }
 726 
 727 
 728 oop Universe::gen_out_of_memory_error(oop default_err) {
 729   // generate an out of memory error:
 730   // - if there is a preallocated error and stack traces are available
 731   //   (j.l.Throwable is initialized), then return the preallocated
 732   //   error with a filled in stack trace, and with the message
 733   //   provided by the default error.
 734   // - otherwise, return the default error, without a stack trace.
 735   int next;
 736   if ((_preallocated_out_of_memory_error_avail_count > 0) &&
 737       vmClasses::Throwable_klass()->is_initialized()) {
 738     next = (int)Atomic::add(&_preallocated_out_of_memory_error_avail_count, -1);
 739     assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");
 740   } else {
 741     next = -1;
 742   }
 743   if (next < 0) {
 744     // all preallocated errors have been used.
 745     // return default
 746     return default_err;
 747   } else {
 748     JavaThread* current = JavaThread::current();
 749     Handle default_err_h(current, default_err);
 750     // get the error object at the slot and set set it to null so that the
 751     // array isn't keeping it alive anymore.
 752     Handle exc(current, preallocated_out_of_memory_errors()->obj_at(next));
 753     assert(exc() != nullptr, "slot has been used already");
 754     preallocated_out_of_memory_errors()->obj_at_put(next, nullptr);
 755 
 756     // use the message from the default error
 757     oop msg = java_lang_Throwable::message(default_err_h());
 758     assert(msg != nullptr, "no message");
 759     java_lang_Throwable::set_message(exc(), msg);
 760 
 761     // populate the stack trace and return it.
 762     java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
 763     return exc();
 764   }
 765 }
 766 
 767 bool Universe::is_out_of_memory_error_metaspace(oop ex_obj) {
 768   return java_lang_Throwable::message(ex_obj) == _msg_metaspace.resolve();
 769 }
 770 
 771 bool Universe::is_out_of_memory_error_class_metaspace(oop ex_obj) {
 772   return java_lang_Throwable::message(ex_obj) == _msg_class_metaspace.resolve();
 773 }
 774 
 775 // Setup preallocated OutOfMemoryError errors
 776 void Universe::create_preallocated_out_of_memory_errors(TRAPS) {
 777   InstanceKlass* ik = vmClasses::OutOfMemoryError_klass();
 778   objArrayOop oa = oopFactory::new_objArray(ik, _oom_count, CHECK);
 779   objArrayHandle oom_array(THREAD, oa);
 780 
 781   for (int i = 0; i < _oom_count; i++) {
 782     oop oom_obj = ik->allocate_instance(CHECK);
 783     oom_array->obj_at_put(i, oom_obj);
 784   }
 785   _out_of_memory_errors = OopHandle(vm_global(), oom_array());
 786 
 787   Handle msg = java_lang_String::create_from_str("Java heap space", CHECK);
 788   java_lang_Throwable::set_message(oom_array->obj_at(_oom_java_heap), msg());
 789 
 790   msg = java_lang_String::create_from_str("C heap space", CHECK);
 791   java_lang_Throwable::set_message(oom_array->obj_at(_oom_c_heap), msg());
 792 
 793   msg = java_lang_String::create_from_str("Metaspace", CHECK);
 794   _msg_metaspace = OopHandle(vm_global(), msg());
 795   java_lang_Throwable::set_message(oom_array->obj_at(_oom_metaspace), msg());
 796 
 797   msg = java_lang_String::create_from_str("Compressed class space", CHECK);
 798   _msg_class_metaspace = OopHandle(vm_global(), msg());
 799   java_lang_Throwable::set_message(oom_array->obj_at(_oom_class_metaspace), msg());
 800 
 801   msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK);
 802   java_lang_Throwable::set_message(oom_array->obj_at(_oom_array_size), msg());
 803 
 804   msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK);
 805   java_lang_Throwable::set_message(oom_array->obj_at(_oom_gc_overhead_limit), msg());
 806 
 807   msg = java_lang_String::create_from_str("Java heap space: failed reallocation of scalar replaced objects", CHECK);
 808   java_lang_Throwable::set_message(oom_array->obj_at(_oom_realloc_objects), msg());
 809 
 810   // Setup the array of errors that have preallocated backtrace
 811   int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
 812   objArrayOop instance = oopFactory::new_objArray(ik, len, CHECK);
 813   _preallocated_out_of_memory_error_array = OopHandle(vm_global(), instance);
 814   objArrayHandle preallocated_oom_array(THREAD, instance);
 815 
 816   for (int i=0; i<len; i++) {
 817     oop err = ik->allocate_instance(CHECK);
 818     Handle err_h(THREAD, err);
 819     java_lang_Throwable::allocate_backtrace(err_h, CHECK);
 820     preallocated_oom_array->obj_at_put(i, err_h());
 821   }
 822   _preallocated_out_of_memory_error_avail_count = (jint)len;
 823 }
 824 
 825 intptr_t Universe::_non_oop_bits = 0;
 826 
 827 void* Universe::non_oop_word() {
 828   // Neither the high bits nor the low bits of this value is allowed
 829   // to look like (respectively) the high or low bits of a real oop.
 830   //
 831   // High and low are CPU-specific notions, but low always includes
 832   // the low-order bit.  Since oops are always aligned at least mod 4,
 833   // setting the low-order bit will ensure that the low half of the
 834   // word will never look like that of a real oop.
 835   //
 836   // Using the OS-supplied non-memory-address word (usually 0 or -1)
 837   // will take care of the high bits, however many there are.
 838 
 839   if (_non_oop_bits == 0) {
 840     _non_oop_bits = (intptr_t)os::non_memory_address_word() | 1;
 841   }
 842 
 843   return (void*)_non_oop_bits;
 844 }
 845 
 846 bool Universe::contains_non_oop_word(void* p) {
 847   return *(void**)p == non_oop_word();
 848 }
 849 
 850 static void initialize_global_behaviours() {
 851   DefaultICProtectionBehaviour* protection_behavior = new DefaultICProtectionBehaviour();
 852   // Ignore leak of DefaultICProtectionBehaviour. It is overriden by some GC implementations and the
 853   // pointer is leaked once.
 854   LSAN_IGNORE_OBJECT(protection_behavior);
 855   CompiledICProtectionBehaviour::set_current(protection_behavior);
 856 }
 857 
 858 jint universe_init() {
 859   assert(!Universe::_fully_initialized, "called after initialize_vtables");
 860   guarantee(1 << LogHeapWordSize == sizeof(HeapWord),
 861          "LogHeapWordSize is incorrect.");
 862   guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");
 863   guarantee(sizeof(oop) % sizeof(HeapWord) == 0,
 864             "oop size is not not a multiple of HeapWord size");
 865 
 866   TraceTime timer("Genesis", TRACETIME_LOG(Info, startuptime));
 867 
 868   initialize_global_behaviours();
 869 
 870   GCLogPrecious::initialize();
 871 
 872   // Initialize CPUTimeCounters object, which must be done before creation of the heap.
 873   CPUTimeCounters::initialize();
 874 
 875   ObjLayout::initialize();
 876 
 877 #ifdef _LP64
 878   MetaspaceShared::adjust_heap_sizes_for_dumping();
 879 #endif // _LP64
 880 
 881   GCConfig::arguments()->initialize_heap_sizes();
 882 
 883   jint status = Universe::initialize_heap();
 884   if (status != JNI_OK) {
 885     return status;
 886   }
 887 
 888   Universe::initialize_tlab();
 889 
 890   Metaspace::global_initialize();
 891   // Initialize performance counters for metaspaces
 892   MetaspaceCounters::initialize_performance_counters();
 893 
 894   // Checks 'AfterMemoryInit' constraints.
 895   if (!JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterMemoryInit)) {
 896     return JNI_EINVAL;
 897   }
 898 
 899   ClassLoaderData::init_null_class_loader_data();
 900 
 901 #if INCLUDE_CDS
 902   DynamicArchive::check_for_dynamic_dump();
 903   if (CDSConfig::is_using_archive()) {
 904     // Read the data structures supporting the shared spaces (shared
 905     // system dictionary, symbol table, etc.)
 906     MetaspaceShared::initialize_shared_spaces();
 907   }
 908   if (CDSConfig::is_dumping_archive()) {
 909     MetaspaceShared::prepare_for_dumping();
 910   }
 911 #endif
 912 
 913   SymbolTable::create_table();
 914   StringTable::create_table();
 915 
 916   if (strlen(VerifySubSet) > 0) {
 917     Universe::initialize_verify_flags();
 918   }
 919 
 920   ResolvedMethodTable::create_table();
 921 
 922   return JNI_OK;
 923 }
 924 
 925 jint Universe::initialize_heap() {
 926   assert(_collectedHeap == nullptr, "Heap already created");
 927   _collectedHeap = GCConfig::arguments()->create_heap();
 928 
 929   log_info(gc)("Using %s", _collectedHeap->name());
 930   return _collectedHeap->initialize();
 931 }
 932 
 933 void Universe::initialize_tlab() {
 934   ThreadLocalAllocBuffer::set_max_size(Universe::heap()->max_tlab_size());
 935   PLAB::startup_initialization();
 936   if (UseTLAB) {
 937     ThreadLocalAllocBuffer::startup_initialization();
 938   }
 939 }
 940 
 941 ReservedHeapSpace Universe::reserve_heap(size_t heap_size, size_t alignment) {
 942 
 943   assert(alignment <= Arguments::conservative_max_heap_alignment(),
 944          "actual alignment %zu must be within maximum heap alignment %zu",
 945          alignment, Arguments::conservative_max_heap_alignment());
 946 
 947   size_t total_reserved = align_up(heap_size, alignment);
 948   assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),
 949       "heap size is too big for compressed oops");
 950 
 951   size_t page_size = os::vm_page_size();
 952   if (UseLargePages && is_aligned(alignment, os::large_page_size())) {
 953     page_size = os::large_page_size();
 954   } else {
 955     // Parallel is the only collector that might opt out of using large pages
 956     // for the heap.
 957     assert(!UseLargePages || UseParallelGC , "Wrong alignment to use large pages");
 958   }
 959 
 960   // Now create the space.
 961   ReservedHeapSpace rhs = HeapReserver::reserve(total_reserved, alignment, page_size, AllocateHeapAt);
 962 
 963   if (!rhs.is_reserved()) {
 964     vm_exit_during_initialization(
 965       err_msg("Could not reserve enough space for %zu KB object heap",
 966               total_reserved/K));
 967   }
 968 
 969   assert(total_reserved == rhs.size(),    "must be exactly of required size");
 970   assert(is_aligned(rhs.base(),alignment),"must be exactly of required alignment");
 971 
 972   assert(markWord::encode_pointer_as_mark(rhs.base()).decode_pointer() == rhs.base(),
 973       "area must be distinguishable from marks for mark-sweep");
 974   assert(markWord::encode_pointer_as_mark(&rhs.base()[rhs.size()]).decode_pointer() ==
 975       &rhs.base()[rhs.size()],
 976       "area must be distinguishable from marks for mark-sweep");
 977 
 978   // We are good.
 979 
 980   if (AllocateHeapAt != nullptr) {
 981     log_info(gc,heap)("Successfully allocated Java heap at location %s", AllocateHeapAt);
 982   }
 983 
 984   if (UseCompressedOops) {
 985     CompressedOops::initialize(rhs);
 986   }
 987 
 988   Universe::calculate_verify_data((HeapWord*)rhs.base(), (HeapWord*)rhs.end());
 989 
 990   return rhs;
 991 }
 992 
 993 OopStorage* Universe::vm_weak() {
 994   return Universe::_vm_weak;
 995 }
 996 
 997 OopStorage* Universe::vm_global() {
 998   return Universe::_vm_global;
 999 }
1000 
1001 void Universe::oopstorage_init() {
1002   Universe::_vm_global = OopStorageSet::create_strong("VM Global", mtInternal);
1003   Universe::_vm_weak = OopStorageSet::create_weak("VM Weak", mtInternal);
1004 }
1005 
1006 void universe_oopstorage_init() {
1007   Universe::oopstorage_init();
1008 }
1009 
1010 void LatestMethodCache::init(JavaThread* current, InstanceKlass* ik,
1011                              const char* method, Symbol* signature, bool is_static)
1012 {
1013   TempNewSymbol name = SymbolTable::new_symbol(method);
1014   Method* m = nullptr;
1015   // The klass must be linked before looking up the method.
1016   if (!ik->link_class_or_fail(current) ||
1017       ((m = ik->find_method(name, signature)) == nullptr) ||
1018       is_static != m->is_static()) {
1019     ResourceMark rm(current);
1020     // NoSuchMethodException doesn't actually work because it tries to run the
1021     // <init> function before java_lang_Class is linked. Print error and exit.
1022     vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",
1023                                  ik->name()->as_C_string(), method));
1024   }
1025 
1026   _klass = ik;
1027   _method_idnum = m->method_idnum();
1028   assert(_method_idnum >= 0, "sanity check");
1029 }
1030 
1031 Method* LatestMethodCache::get_method() {
1032   if (_klass == nullptr) {
1033     return nullptr;
1034   } else {
1035     Method* m = _klass->method_with_idnum(_method_idnum);
1036     assert(m != nullptr, "sanity check");
1037     return m;
1038   }
1039 }
1040 
1041 Method* Universe::finalizer_register_method()     { return _finalizer_register_cache.get_method(); }
1042 Method* Universe::loader_addClass_method()        { return _loader_addClass_cache.get_method(); }
1043 Method* Universe::throw_illegal_access_error()    { return _throw_illegal_access_error_cache.get_method(); }
1044 Method* Universe::throw_no_such_method_error()    { return _throw_no_such_method_error_cache.get_method(); }
1045 Method* Universe::do_stack_walk_method()          { return _do_stack_walk_cache.get_method(); }
1046 Method* Universe::is_substitutable_method()       { return _is_substitutable_cache.get_method(); }
1047 Method* Universe::value_object_hash_code_method() { return _value_object_hash_code_cache.get_method(); }
1048 
1049 void Universe::initialize_known_methods(JavaThread* current) {
1050   // Set up static method for registering finalizers
1051   _finalizer_register_cache.init(current,
1052                           vmClasses::Finalizer_klass(),
1053                           "register",
1054                           vmSymbols::object_void_signature(), true);
1055 
1056   _throw_illegal_access_error_cache.init(current,
1057                           vmClasses::internal_Unsafe_klass(),
1058                           "throwIllegalAccessError",
1059                           vmSymbols::void_method_signature(), true);
1060 
1061   _throw_no_such_method_error_cache.init(current,
1062                           vmClasses::internal_Unsafe_klass(),
1063                           "throwNoSuchMethodError",
1064                           vmSymbols::void_method_signature(), true);
1065 
1066   // Set up method for registering loaded classes in class loader vector
1067   _loader_addClass_cache.init(current,
1068                           vmClasses::ClassLoader_klass(),
1069                           "addClass",
1070                           vmSymbols::class_void_signature(), false);
1071 
1072   // Set up method for stack walking
1073   _do_stack_walk_cache.init(current,
1074                           vmClasses::AbstractStackWalker_klass(),
1075                           "doStackWalk",
1076                           vmSymbols::doStackWalk_signature(), false);
1077 
1078   // Set up substitutability testing
1079   ResourceMark rm(current);
1080   _is_substitutable_cache.init(current,
1081                           vmClasses::ValueObjectMethods_klass(),
1082                           vmSymbols::isSubstitutable_name()->as_C_string(),
1083                           vmSymbols::object_object_boolean_signature(), true);
1084   _value_object_hash_code_cache.init(current,
1085                           vmClasses::ValueObjectMethods_klass(),
1086                           vmSymbols::valueObjectHashCode_name()->as_C_string(),
1087                           vmSymbols::object_int_signature(), true);
1088 }
1089 
1090 void universe2_init() {
1091   EXCEPTION_MARK;
1092   Universe::genesis(CATCH);
1093 }
1094 
1095 // Set after initialization of the module runtime, call_initModuleRuntime
1096 void universe_post_module_init() {
1097   Universe::_module_initialized = true;
1098 }
1099 
1100 bool universe_post_init() {
1101   assert(!is_init_completed(), "Error: initialization not yet completed!");
1102   Universe::_fully_initialized = true;
1103   EXCEPTION_MARK;
1104   if (!CDSConfig::is_using_archive()) {
1105     reinitialize_vtables();
1106     reinitialize_itables();
1107   }
1108 
1109   HandleMark hm(THREAD);
1110   // Setup preallocated empty java.lang.Class array for Method reflection.
1111 
1112   objArrayOop the_empty_class_array = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_false);
1113   Universe::_the_empty_class_array = OopHandle(Universe::vm_global(), the_empty_class_array);
1114 
1115   // Setup preallocated OutOfMemoryError errors
1116   Universe::create_preallocated_out_of_memory_errors(CHECK_false);
1117 
1118   oop instance;
1119   // Setup preallocated cause message for delayed StackOverflowError
1120   if (StackReservedPages > 0) {
1121     instance = java_lang_String::create_oop_from_str("Delayed StackOverflowError due to ReservedStackAccess annotated method", CHECK_false);
1122     Universe::_delayed_stack_overflow_error_message = OopHandle(Universe::vm_global(), instance);
1123   }
1124 
1125   // Setup preallocated exceptions used for a cheap & dirty solution in compiler exception handling
1126   _null_ptr_exception.init_if_empty(vmSymbols::java_lang_NullPointerException(), CHECK_false);
1127   _arithmetic_exception.init_if_empty(vmSymbols::java_lang_ArithmeticException(), CHECK_false);
1128   _array_index_out_of_bounds_exception.init_if_empty(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK_false);
1129   _array_store_exception.init_if_empty(vmSymbols::java_lang_ArrayStoreException(), CHECK_false);
1130   _class_cast_exception.init_if_empty(vmSymbols::java_lang_ClassCastException(), CHECK_false);
1131 
1132   // Virtual Machine Error for when we get into a situation we can't resolve
1133   Klass* k = vmClasses::InternalError_klass();
1134   bool linked = InstanceKlass::cast(k)->link_class_or_fail(CHECK_false);
1135   if (!linked) {
1136      tty->print_cr("Unable to link/verify InternalError class");
1137      return false; // initialization failed
1138   }
1139   _internal_error.init_if_empty(vmSymbols::java_lang_InternalError(), CHECK_false);
1140 
1141   Handle msg = java_lang_String::create_from_str("/ by zero", CHECK_false);
1142   java_lang_Throwable::set_message(Universe::arithmetic_exception_instance(), msg());
1143 
1144   // Setup preallocated StackOverflowError for use with class initialization failure
1145   k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackOverflowError(), true, CHECK_false);
1146   instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
1147   Universe::_class_init_stack_overflow_error = OopHandle(Universe::vm_global(), instance);
1148 
1149   Universe::initialize_known_methods(THREAD);
1150 
1151   // This needs to be done before the first scavenge/gc, since
1152   // it's an input to soft ref clearing policy.
1153   {
1154     MutexLocker x(THREAD, Heap_lock);
1155     Universe::heap()->update_capacity_and_used_at_gc();
1156   }
1157 
1158   // ("weak") refs processing infrastructure initialization
1159   Universe::heap()->post_initialize();
1160 
1161   MemoryService::add_metaspace_memory_pools();
1162 
1163   MemoryService::set_universe_heap(Universe::heap());
1164 #if INCLUDE_CDS
1165   MetaspaceShared::post_initialize(CHECK_false);
1166 #endif
1167   return true;
1168 }
1169 
1170 
1171 void Universe::compute_base_vtable_size() {
1172   _base_vtable_size = ClassLoader::compute_Object_vtable();
1173 }
1174 
1175 void Universe::print_on(outputStream* st) {
1176   GCMutexLocker hl(Heap_lock); // Heap_lock might be locked by caller thread.
1177   st->print_cr("Heap");
1178   heap()->print_on(st);
1179 }
1180 
1181 void Universe::print_heap_at_SIGBREAK() {
1182   if (PrintHeapAtSIGBREAK) {
1183     print_on(tty);
1184     tty->cr();
1185     tty->flush();
1186   }
1187 }
1188 
1189 void Universe::initialize_verify_flags() {
1190   verify_flags = 0;
1191   const char delimiter[] = " ,";
1192 
1193   size_t length = strlen(VerifySubSet);
1194   char* subset_list = NEW_C_HEAP_ARRAY(char, length + 1, mtInternal);
1195   strncpy(subset_list, VerifySubSet, length + 1);
1196   char* save_ptr;
1197 
1198   char* token = strtok_r(subset_list, delimiter, &save_ptr);
1199   while (token != nullptr) {
1200     if (strcmp(token, "threads") == 0) {
1201       verify_flags |= Verify_Threads;
1202     } else if (strcmp(token, "heap") == 0) {
1203       verify_flags |= Verify_Heap;
1204     } else if (strcmp(token, "symbol_table") == 0) {
1205       verify_flags |= Verify_SymbolTable;
1206     } else if (strcmp(token, "string_table") == 0) {
1207       verify_flags |= Verify_StringTable;
1208     } else if (strcmp(token, "codecache") == 0) {
1209       verify_flags |= Verify_CodeCache;
1210     } else if (strcmp(token, "dictionary") == 0) {
1211       verify_flags |= Verify_SystemDictionary;
1212     } else if (strcmp(token, "classloader_data_graph") == 0) {
1213       verify_flags |= Verify_ClassLoaderDataGraph;
1214     } else if (strcmp(token, "metaspace") == 0) {
1215       verify_flags |= Verify_MetaspaceUtils;
1216     } else if (strcmp(token, "jni_handles") == 0) {
1217       verify_flags |= Verify_JNIHandles;
1218     } else if (strcmp(token, "codecache_oops") == 0) {
1219       verify_flags |= Verify_CodeCacheOops;
1220     } else if (strcmp(token, "resolved_method_table") == 0) {
1221       verify_flags |= Verify_ResolvedMethodTable;
1222     } else if (strcmp(token, "stringdedup") == 0) {
1223       verify_flags |= Verify_StringDedup;
1224     } else {
1225       vm_exit_during_initialization(err_msg("VerifySubSet: \'%s\' memory sub-system is unknown, please correct it", token));
1226     }
1227     token = strtok_r(nullptr, delimiter, &save_ptr);
1228   }
1229   FREE_C_HEAP_ARRAY(char, subset_list);
1230 }
1231 
1232 bool Universe::should_verify_subset(uint subset) {
1233   if (verify_flags & subset) {
1234     return true;
1235   }
1236   return false;
1237 }
1238 
1239 void Universe::verify(VerifyOption option, const char* prefix) {
1240   COMPILER2_PRESENT(
1241     assert(!DerivedPointerTable::is_active(),
1242          "DPT should not be active during verification "
1243          "(of thread stacks below)");
1244   )
1245 
1246   Thread* thread = Thread::current();
1247   ResourceMark rm(thread);
1248   HandleMark hm(thread);  // Handles created during verification can be zapped
1249   _verify_count++;
1250 
1251   FormatBuffer<> title("Verifying %s", prefix);
1252   GCTraceTime(Info, gc, verify) tm(title.buffer());
1253   if (should_verify_subset(Verify_Threads)) {
1254     log_debug(gc, verify)("Threads");
1255     Threads::verify();
1256   }
1257   if (should_verify_subset(Verify_Heap)) {
1258     log_debug(gc, verify)("Heap");
1259     heap()->verify(option);
1260   }
1261   if (should_verify_subset(Verify_SymbolTable)) {
1262     log_debug(gc, verify)("SymbolTable");
1263     SymbolTable::verify();
1264   }
1265   if (should_verify_subset(Verify_StringTable)) {
1266     log_debug(gc, verify)("StringTable");
1267     StringTable::verify();
1268   }
1269   if (should_verify_subset(Verify_CodeCache)) {
1270     log_debug(gc, verify)("CodeCache");
1271     CodeCache::verify();
1272   }
1273   if (should_verify_subset(Verify_SystemDictionary)) {
1274     log_debug(gc, verify)("SystemDictionary");
1275     SystemDictionary::verify();
1276   }
1277   if (should_verify_subset(Verify_ClassLoaderDataGraph)) {
1278     log_debug(gc, verify)("ClassLoaderDataGraph");
1279     ClassLoaderDataGraph::verify();
1280   }
1281   if (should_verify_subset(Verify_MetaspaceUtils)) {
1282     log_debug(gc, verify)("MetaspaceUtils");
1283     DEBUG_ONLY(MetaspaceUtils::verify();)
1284   }
1285   if (should_verify_subset(Verify_JNIHandles)) {
1286     log_debug(gc, verify)("JNIHandles");
1287     JNIHandles::verify();
1288   }
1289   if (should_verify_subset(Verify_CodeCacheOops)) {
1290     log_debug(gc, verify)("CodeCache Oops");
1291     CodeCache::verify_oops();
1292   }
1293   if (should_verify_subset(Verify_ResolvedMethodTable)) {
1294     log_debug(gc, verify)("ResolvedMethodTable Oops");
1295     ResolvedMethodTable::verify();
1296   }
1297   if (should_verify_subset(Verify_StringDedup)) {
1298     log_debug(gc, verify)("String Deduplication");
1299     StringDedup::verify();
1300   }
1301 }
1302 
1303 
1304 #ifndef PRODUCT
1305 void Universe::calculate_verify_data(HeapWord* low_boundary, HeapWord* high_boundary) {
1306   assert(low_boundary < high_boundary, "bad interval");
1307 
1308   // decide which low-order bits we require to be clear:
1309   size_t alignSize = MinObjAlignmentInBytes;
1310   size_t min_object_size = CollectedHeap::min_fill_size();
1311 
1312   // make an inclusive limit:
1313   uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;
1314   uintptr_t min = (uintptr_t)low_boundary;
1315   assert(min < max, "bad interval");
1316   uintptr_t diff = max ^ min;
1317 
1318   // throw away enough low-order bits to make the diff vanish
1319   uintptr_t mask = (uintptr_t)(-1);
1320   while ((mask & diff) != 0)
1321     mask <<= 1;
1322   uintptr_t bits = (min & mask);
1323   assert(bits == (max & mask), "correct mask");
1324   // check an intermediate value between min and max, just to make sure:
1325   assert(bits == ((min + (max-min)/2) & mask), "correct mask");
1326 
1327   // require address alignment, too:
1328   mask |= (alignSize - 1);
1329 
1330   if (!(_verify_oop_mask == 0 && _verify_oop_bits == (uintptr_t)-1)) {
1331     assert(_verify_oop_mask == mask && _verify_oop_bits == bits, "mask stability");
1332   }
1333   _verify_oop_mask = mask;
1334   _verify_oop_bits = bits;
1335 }
1336 
1337 void Universe::set_verify_data(uintptr_t mask, uintptr_t bits) {
1338   _verify_oop_mask = mask;
1339   _verify_oop_bits = bits;
1340 }
1341 
1342 // Oop verification (see MacroAssembler::verify_oop)
1343 
1344 uintptr_t Universe::verify_oop_mask() {
1345   return _verify_oop_mask;
1346 }
1347 
1348 uintptr_t Universe::verify_oop_bits() {
1349   return _verify_oop_bits;
1350 }
1351 
1352 uintptr_t Universe::verify_mark_mask() {
1353   return markWord::lock_mask_in_place;
1354 }
1355 
1356 uintptr_t Universe::verify_mark_bits() {
1357   intptr_t mask = verify_mark_mask();
1358   intptr_t bits = (intptr_t)markWord::prototype().value();
1359   assert((bits & ~mask) == 0, "no stray header bits");
1360   return bits;
1361 }
1362 #endif // PRODUCT
1363 
1364 #ifdef ASSERT
1365 // Release dummy object(s) at bottom of heap
1366 bool Universe::release_fullgc_alot_dummy() {
1367   MutexLocker ml(FullGCALot_lock);
1368   objArrayOop fullgc_alot_dummy_array = (objArrayOop)_fullgc_alot_dummy_array.resolve();
1369   if (fullgc_alot_dummy_array != nullptr) {
1370     if (_fullgc_alot_dummy_next >= fullgc_alot_dummy_array->length()) {
1371       // No more dummies to release, release entire array instead
1372       _fullgc_alot_dummy_array.release(Universe::vm_global());
1373       _fullgc_alot_dummy_array = OopHandle(); // null out OopStorage pointer.
1374       return false;
1375     }
1376 
1377     // Release dummy at bottom of old generation
1378     fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, nullptr);
1379   }
1380   return true;
1381 }
1382 
1383 bool Universe::is_stw_gc_active() {
1384   return heap()->is_stw_gc_active();
1385 }
1386 
1387 bool Universe::is_in_heap(const void* p) {
1388   return heap()->is_in(p);
1389 }
1390 
1391 #endif // ASSERT