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