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