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