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