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