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