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