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