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