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