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