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