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