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