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