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