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