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