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