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