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