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