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