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