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