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