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