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