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