1 /*
   2  * Copyright (c) 1997, 2016, 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 "classfile/classLoader.hpp"
  27 #include "classfile/classLoaderData.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "classfile/stringTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/dependencies.hpp"
  34 #include "gc/shared/cardTableModRefBS.hpp"
  35 #include "gc/shared/collectedHeap.inline.hpp"
  36 #include "gc/shared/gcLocker.inline.hpp"
  37 #include "gc/shared/genCollectedHeap.hpp"
  38 #include "gc/shared/generation.hpp"
  39 #include "gc/shared/gcTraceTime.inline.hpp"
  40 #include "gc/shared/space.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "logging/log.hpp"
  43 #include "memory/filemap.hpp"
  44 #include "memory/metadataFactory.hpp"
  45 #include "memory/metaspaceShared.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "memory/universe.inline.hpp"
  50 #include "oops/constantPool.hpp"
  51 #include "oops/instanceClassLoaderKlass.hpp"
  52 #include "oops/instanceKlass.hpp"
  53 #include "oops/instanceMirrorKlass.hpp"
  54 #include "oops/instanceRefKlass.hpp"
  55 #include "oops/objArrayOop.inline.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "oops/typeArrayKlass.hpp"
  58 #include "runtime/arguments.hpp"
  59 #include "runtime/atomic.inline.hpp"
  60 #include "runtime/commandLineFlagConstraintList.hpp"
  61 #include "runtime/deoptimization.hpp"
  62 #include "runtime/fprofiler.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/init.hpp"
  65 #include "runtime/java.hpp"
  66 #include "runtime/javaCalls.hpp"
  67 #include "runtime/sharedRuntime.hpp"
  68 #include "runtime/synchronizer.hpp"
  69 #include "runtime/thread.inline.hpp"
  70 #include "runtime/timerTrace.hpp"
  71 #include "runtime/vm_operations.hpp"
  72 #include "services/memoryService.hpp"
  73 #include "utilities/copy.hpp"
  74 #include "utilities/events.hpp"
  75 #include "utilities/hashtable.inline.hpp"
  76 #include "utilities/macros.hpp"
  77 #include "utilities/ostream.hpp"
  78 #include "utilities/preserveException.hpp"
  79 #if INCLUDE_CDS
  80 #include "classfile/sharedClassUtil.hpp"
  81 #endif
  82 
  83 // Known objects
  84 Klass* Universe::_boolArrayKlassObj                 = NULL;
  85 Klass* Universe::_byteArrayKlassObj                 = NULL;
  86 Klass* Universe::_charArrayKlassObj                 = NULL;
  87 Klass* Universe::_intArrayKlassObj                  = NULL;
  88 Klass* Universe::_shortArrayKlassObj                = NULL;
  89 Klass* Universe::_longArrayKlassObj                 = NULL;
  90 Klass* Universe::_singleArrayKlassObj               = NULL;
  91 Klass* Universe::_doubleArrayKlassObj               = NULL;
  92 Klass* Universe::_typeArrayKlassObjs[T_VOID+1]      = { NULL /*, NULL...*/ };
  93 Klass* Universe::_objectArrayKlassObj               = NULL;
  94 oop Universe::_int_mirror                             = NULL;
  95 oop Universe::_float_mirror                           = NULL;
  96 oop Universe::_double_mirror                          = NULL;
  97 oop Universe::_byte_mirror                            = NULL;
  98 oop Universe::_bool_mirror                            = NULL;
  99 oop Universe::_char_mirror                            = NULL;
 100 oop Universe::_long_mirror                            = NULL;
 101 oop Universe::_short_mirror                           = NULL;
 102 oop Universe::_void_mirror                            = NULL;
 103 oop Universe::_mirrors[T_VOID+1]                      = { NULL /*, NULL...*/ };
 104 oop Universe::_main_thread_group                      = NULL;
 105 oop Universe::_system_thread_group                    = NULL;
 106 objArrayOop Universe::_the_empty_class_klass_array    = NULL;
 107 Array<Klass*>* Universe::_the_array_interfaces_array = NULL;
 108 oop Universe::_the_null_string                        = NULL;
 109 oop Universe::_the_min_jint_string                   = NULL;
 110 LatestMethodCache* Universe::_finalizer_register_cache = NULL;
 111 LatestMethodCache* Universe::_loader_addClass_cache    = NULL;
 112 LatestMethodCache* Universe::_pd_implies_cache         = NULL;
 113 LatestMethodCache* Universe::_throw_illegal_access_error_cache = NULL;
 114 LatestMethodCache* Universe::_do_stack_walk_cache     = NULL;
 115 oop Universe::_out_of_memory_error_java_heap          = NULL;
 116 oop Universe::_out_of_memory_error_metaspace          = NULL;
 117 oop Universe::_out_of_memory_error_class_metaspace    = NULL;
 118 oop Universe::_out_of_memory_error_array_size         = NULL;
 119 oop Universe::_out_of_memory_error_gc_overhead_limit  = NULL;
 120 oop Universe::_out_of_memory_error_realloc_objects    = NULL;
 121 oop Universe::_delayed_stack_overflow_error_message   = NULL;
 122 objArrayOop Universe::_preallocated_out_of_memory_error_array = NULL;
 123 volatile jint Universe::_preallocated_out_of_memory_error_avail_count = 0;
 124 bool Universe::_verify_in_progress                    = false;
 125 long Universe::verify_flags                           = Universe::Verify_All;
 126 oop Universe::_null_ptr_exception_instance            = NULL;
 127 oop Universe::_arithmetic_exception_instance          = NULL;
 128 oop Universe::_virtual_machine_error_instance         = NULL;
 129 oop Universe::_vm_exception                           = NULL;
 130 oop Universe::_allocation_context_notification_obj    = NULL;
 131 
 132 Array<int>* Universe::_the_empty_int_array            = NULL;
 133 Array<u2>* Universe::_the_empty_short_array           = NULL;
 134 Array<Klass*>* Universe::_the_empty_klass_array     = NULL;
 135 Array<Method*>* Universe::_the_empty_method_array   = NULL;
 136 
 137 // These variables are guarded by FullGCALot_lock.
 138 debug_only(objArrayOop Universe::_fullgc_alot_dummy_array = NULL;)
 139 debug_only(int Universe::_fullgc_alot_dummy_next      = 0;)
 140 
 141 // Heap
 142 int             Universe::_verify_count = 0;
 143 
 144 // Oop verification (see MacroAssembler::verify_oop)
 145 uintptr_t       Universe::_verify_oop_mask = 0;
 146 uintptr_t       Universe::_verify_oop_bits = (uintptr_t) -1;
 147 
 148 int             Universe::_base_vtable_size = 0;
 149 bool            Universe::_bootstrapping = false;
 150 bool            Universe::_module_initialized = false;
 151 bool            Universe::_fully_initialized = false;
 152 
 153 size_t          Universe::_heap_capacity_at_last_gc;
 154 size_t          Universe::_heap_used_at_last_gc = 0;
 155 
 156 NarrowPtrStruct Universe::_narrow_oop = { NULL, 0, true };
 157 NarrowPtrStruct Universe::_narrow_klass = { NULL, 0, true };
 158 address Universe::_narrow_ptrs_base;
 159 
 160 void Universe::basic_type_classes_do(void f(Klass*)) {
 161   f(boolArrayKlassObj());
 162   f(byteArrayKlassObj());
 163   f(charArrayKlassObj());
 164   f(intArrayKlassObj());
 165   f(shortArrayKlassObj());
 166   f(longArrayKlassObj());
 167   f(singleArrayKlassObj());
 168   f(doubleArrayKlassObj());
 169 }
 170 
 171 void Universe::oops_do(OopClosure* f, bool do_all) {
 172 
 173   f->do_oop((oop*) &_int_mirror);
 174   f->do_oop((oop*) &_float_mirror);
 175   f->do_oop((oop*) &_double_mirror);
 176   f->do_oop((oop*) &_byte_mirror);
 177   f->do_oop((oop*) &_bool_mirror);
 178   f->do_oop((oop*) &_char_mirror);
 179   f->do_oop((oop*) &_long_mirror);
 180   f->do_oop((oop*) &_short_mirror);
 181   f->do_oop((oop*) &_void_mirror);
 182 
 183   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 184     f->do_oop((oop*) &_mirrors[i]);
 185   }
 186   assert(_mirrors[0] == NULL && _mirrors[T_BOOLEAN - 1] == NULL, "checking");
 187 
 188   f->do_oop((oop*)&_the_empty_class_klass_array);
 189   f->do_oop((oop*)&_the_null_string);
 190   f->do_oop((oop*)&_the_min_jint_string);
 191   f->do_oop((oop*)&_out_of_memory_error_java_heap);
 192   f->do_oop((oop*)&_out_of_memory_error_metaspace);
 193   f->do_oop((oop*)&_out_of_memory_error_class_metaspace);
 194   f->do_oop((oop*)&_out_of_memory_error_array_size);
 195   f->do_oop((oop*)&_out_of_memory_error_gc_overhead_limit);
 196   f->do_oop((oop*)&_out_of_memory_error_realloc_objects);
 197   f->do_oop((oop*)&_delayed_stack_overflow_error_message);
 198   f->do_oop((oop*)&_preallocated_out_of_memory_error_array);
 199   f->do_oop((oop*)&_null_ptr_exception_instance);
 200   f->do_oop((oop*)&_arithmetic_exception_instance);
 201   f->do_oop((oop*)&_virtual_machine_error_instance);
 202   f->do_oop((oop*)&_main_thread_group);
 203   f->do_oop((oop*)&_system_thread_group);
 204   f->do_oop((oop*)&_vm_exception);
 205   f->do_oop((oop*)&_allocation_context_notification_obj);
 206   debug_only(f->do_oop((oop*)&_fullgc_alot_dummy_array);)
 207 }
 208 
 209 // Serialize metadata in and out of CDS archive, not oops.
 210 void Universe::serialize(SerializeClosure* f, bool do_all) {
 211 
 212   f->do_ptr((void**)&_boolArrayKlassObj);
 213   f->do_ptr((void**)&_byteArrayKlassObj);
 214   f->do_ptr((void**)&_charArrayKlassObj);
 215   f->do_ptr((void**)&_intArrayKlassObj);
 216   f->do_ptr((void**)&_shortArrayKlassObj);
 217   f->do_ptr((void**)&_longArrayKlassObj);
 218   f->do_ptr((void**)&_singleArrayKlassObj);
 219   f->do_ptr((void**)&_doubleArrayKlassObj);
 220   f->do_ptr((void**)&_objectArrayKlassObj);
 221 
 222   {
 223     for (int i = 0; i < T_VOID+1; i++) {
 224       if (_typeArrayKlassObjs[i] != NULL) {
 225         assert(i >= T_BOOLEAN, "checking");
 226         f->do_ptr((void**)&_typeArrayKlassObjs[i]);
 227       } else if (do_all) {
 228         f->do_ptr((void**)&_typeArrayKlassObjs[i]);
 229       }
 230     }
 231   }
 232 
 233   f->do_ptr((void**)&_the_array_interfaces_array);
 234   f->do_ptr((void**)&_the_empty_int_array);
 235   f->do_ptr((void**)&_the_empty_short_array);
 236   f->do_ptr((void**)&_the_empty_method_array);
 237   f->do_ptr((void**)&_the_empty_klass_array);
 238   _finalizer_register_cache->serialize(f);
 239   _loader_addClass_cache->serialize(f);
 240   _pd_implies_cache->serialize(f);
 241   _throw_illegal_access_error_cache->serialize(f);
 242   _do_stack_walk_cache->serialize(f);
 243 }
 244 
 245 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
 246   if (size < alignment || size % alignment != 0) {
 247     vm_exit_during_initialization(
 248       err_msg("Size of %s (" UINTX_FORMAT " bytes) must be aligned to " UINTX_FORMAT " bytes", name, size, alignment));
 249   }
 250 }
 251 
 252 void initialize_basic_type_klass(Klass* k, TRAPS) {
 253   Klass* ok = SystemDictionary::Object_klass();
 254   if (UseSharedSpaces) {
 255     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 256     assert(k->super() == ok, "u3");
 257     k->restore_unshareable_info(loader_data, Handle(), CHECK);
 258   } else {
 259     k->initialize_supers(ok, CHECK);
 260   }
 261   k->append_to_sibling_list();
 262 }
 263 
 264 void Universe::genesis(TRAPS) {
 265   ResourceMark rm;
 266 
 267   { FlagSetting fs(_bootstrapping, true);
 268 
 269     { MutexLocker mc(Compile_lock);
 270 
 271       // determine base vtable size; without that we cannot create the array klasses
 272       compute_base_vtable_size();
 273 
 274       if (!UseSharedSpaces) {
 275         _boolArrayKlassObj      = TypeArrayKlass::create_klass(T_BOOLEAN, sizeof(jboolean), CHECK);
 276         _charArrayKlassObj      = TypeArrayKlass::create_klass(T_CHAR,    sizeof(jchar),    CHECK);
 277         _singleArrayKlassObj    = TypeArrayKlass::create_klass(T_FLOAT,   sizeof(jfloat),   CHECK);
 278         _doubleArrayKlassObj    = TypeArrayKlass::create_klass(T_DOUBLE,  sizeof(jdouble),  CHECK);
 279         _byteArrayKlassObj      = TypeArrayKlass::create_klass(T_BYTE,    sizeof(jbyte),    CHECK);
 280         _shortArrayKlassObj     = TypeArrayKlass::create_klass(T_SHORT,   sizeof(jshort),   CHECK);
 281         _intArrayKlassObj       = TypeArrayKlass::create_klass(T_INT,     sizeof(jint),     CHECK);
 282         _longArrayKlassObj      = TypeArrayKlass::create_klass(T_LONG,    sizeof(jlong),    CHECK);
 283 
 284         _typeArrayKlassObjs[T_BOOLEAN] = _boolArrayKlassObj;
 285         _typeArrayKlassObjs[T_CHAR]    = _charArrayKlassObj;
 286         _typeArrayKlassObjs[T_FLOAT]   = _singleArrayKlassObj;
 287         _typeArrayKlassObjs[T_DOUBLE]  = _doubleArrayKlassObj;
 288         _typeArrayKlassObjs[T_BYTE]    = _byteArrayKlassObj;
 289         _typeArrayKlassObjs[T_SHORT]   = _shortArrayKlassObj;
 290         _typeArrayKlassObjs[T_INT]     = _intArrayKlassObj;
 291         _typeArrayKlassObjs[T_LONG]    = _longArrayKlassObj;
 292 
 293         ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
 294 
 295         _the_array_interfaces_array = MetadataFactory::new_array<Klass*>(null_cld, 2, NULL, CHECK);
 296         _the_empty_int_array        = MetadataFactory::new_array<int>(null_cld, 0, CHECK);
 297         _the_empty_short_array      = MetadataFactory::new_array<u2>(null_cld, 0, CHECK);
 298         _the_empty_method_array     = MetadataFactory::new_array<Method*>(null_cld, 0, CHECK);
 299         _the_empty_klass_array      = MetadataFactory::new_array<Klass*>(null_cld, 0, CHECK);
 300       }
 301     }
 302 
 303     vmSymbols::initialize(CHECK);
 304 
 305     SystemDictionary::initialize(CHECK);
 306 
 307     Klass* ok = SystemDictionary::Object_klass();
 308 
 309     _the_null_string            = StringTable::intern("null", CHECK);
 310     _the_min_jint_string       = StringTable::intern("-2147483648", CHECK);
 311 
 312     if (UseSharedSpaces) {
 313       // Verify shared interfaces array.
 314       assert(_the_array_interfaces_array->at(0) ==
 315              SystemDictionary::Cloneable_klass(), "u3");
 316       assert(_the_array_interfaces_array->at(1) ==
 317              SystemDictionary::Serializable_klass(), "u3");
 318       MetaspaceShared::fixup_shared_string_regions();
 319     } else {
 320       // Set up shared interfaces array.  (Do this before supers are set up.)
 321       _the_array_interfaces_array->at_put(0, SystemDictionary::Cloneable_klass());
 322       _the_array_interfaces_array->at_put(1, SystemDictionary::Serializable_klass());
 323     }
 324 
 325     initialize_basic_type_klass(boolArrayKlassObj(), CHECK);
 326     initialize_basic_type_klass(charArrayKlassObj(), CHECK);
 327     initialize_basic_type_klass(singleArrayKlassObj(), CHECK);
 328     initialize_basic_type_klass(doubleArrayKlassObj(), CHECK);
 329     initialize_basic_type_klass(byteArrayKlassObj(), CHECK);
 330     initialize_basic_type_klass(shortArrayKlassObj(), CHECK);
 331     initialize_basic_type_klass(intArrayKlassObj(), CHECK);
 332     initialize_basic_type_klass(longArrayKlassObj(), CHECK);
 333   } // end of core bootstrapping
 334 
 335   // Maybe this could be lifted up now that object array can be initialized
 336   // during the bootstrapping.
 337 
 338   // OLD
 339   // Initialize _objectArrayKlass after core bootstraping to make
 340   // sure the super class is set up properly for _objectArrayKlass.
 341   // ---
 342   // NEW
 343   // Since some of the old system object arrays have been converted to
 344   // ordinary object arrays, _objectArrayKlass will be loaded when
 345   // SystemDictionary::initialize(CHECK); is run. See the extra check
 346   // for Object_klass_loaded in objArrayKlassKlass::allocate_objArray_klass_impl.
 347   _objectArrayKlassObj = InstanceKlass::
 348     cast(SystemDictionary::Object_klass())->array_klass(1, CHECK);
 349   // OLD
 350   // Add the class to the class hierarchy manually to make sure that
 351   // its vtable is initialized after core bootstrapping is completed.
 352   // ---
 353   // New
 354   // Have already been initialized.
 355   _objectArrayKlassObj->append_to_sibling_list();
 356 
 357   #ifdef ASSERT
 358   if (FullGCALot) {
 359     // Allocate an array of dummy objects.
 360     // We'd like these to be at the bottom of the old generation,
 361     // so that when we free one and then collect,
 362     // (almost) the whole heap moves
 363     // and we find out if we actually update all the oops correctly.
 364     // But we can't allocate directly in the old generation,
 365     // so we allocate wherever, and hope that the first collection
 366     // moves these objects to the bottom of the old generation.
 367     // We can allocate directly in the permanent generation, so we do.
 368     int size;
 369     if (UseConcMarkSweepGC) {
 370       log_warning(gc)("Using +FullGCALot with concurrent mark sweep gc will not force all objects to relocate");
 371       size = FullGCALotDummies;
 372     } else {
 373       size = FullGCALotDummies * 2;
 374     }
 375     objArrayOop    naked_array = oopFactory::new_objArray(SystemDictionary::Object_klass(), size, CHECK);
 376     objArrayHandle dummy_array(THREAD, naked_array);
 377     int i = 0;
 378     while (i < size) {
 379         // Allocate dummy in old generation
 380       oop dummy = SystemDictionary::Object_klass()->allocate_instance(CHECK);
 381       dummy_array->obj_at_put(i++, dummy);
 382     }
 383     {
 384       // Only modify the global variable inside the mutex.
 385       // If we had a race to here, the other dummy_array instances
 386       // and their elements just get dropped on the floor, which is fine.
 387       MutexLocker ml(FullGCALot_lock);
 388       if (_fullgc_alot_dummy_array == NULL) {
 389         _fullgc_alot_dummy_array = dummy_array();
 390       }
 391     }
 392     assert(i == _fullgc_alot_dummy_array->length(), "just checking");
 393   }
 394   #endif
 395 
 396   // Initialize dependency array for null class loader
 397   ClassLoaderData::the_null_class_loader_data()->init_dependencies(CHECK);
 398 
 399 }
 400 
 401 // CDS support for patching vtables in metadata in the shared archive.
 402 // All types inherited from Metadata have vtables, but not types inherited
 403 // from MetaspaceObj, because the latter does not have virtual functions.
 404 // If the metadata type has a vtable, it cannot be shared in the read-only
 405 // section of the CDS archive, because the vtable pointer is patched.
 406 static inline void add_vtable(void** list, int* n, void* o, int count) {
 407   guarantee((*n) < count, "vtable list too small");
 408   void* vtable = dereference_vptr(o);
 409   assert(*(void**)(vtable) != NULL, "invalid vtable");
 410   list[(*n)++] = vtable;
 411 }
 412 
 413 void Universe::init_self_patching_vtbl_list(void** list, int count) {
 414   int n = 0;
 415   { InstanceKlass o;          add_vtable(list, &n, &o, count); }
 416   { InstanceClassLoaderKlass o; add_vtable(list, &n, &o, count); }
 417   { InstanceMirrorKlass o;    add_vtable(list, &n, &o, count); }
 418   { InstanceRefKlass o;       add_vtable(list, &n, &o, count); }
 419   { TypeArrayKlass o;         add_vtable(list, &n, &o, count); }
 420   { ObjArrayKlass o;          add_vtable(list, &n, &o, count); }
 421   { Method o;                 add_vtable(list, &n, &o, count); }
 422   { ConstantPool o;           add_vtable(list, &n, &o, count); }
 423 }
 424 
 425 void Universe::initialize_basic_type_mirrors(TRAPS) {
 426     assert(_int_mirror==NULL, "basic type mirrors already initialized");
 427     _int_mirror     =
 428       java_lang_Class::create_basic_type_mirror("int",    T_INT, CHECK);
 429     _float_mirror   =
 430       java_lang_Class::create_basic_type_mirror("float",  T_FLOAT,   CHECK);
 431     _double_mirror  =
 432       java_lang_Class::create_basic_type_mirror("double", T_DOUBLE,  CHECK);
 433     _byte_mirror    =
 434       java_lang_Class::create_basic_type_mirror("byte",   T_BYTE, CHECK);
 435     _bool_mirror    =
 436       java_lang_Class::create_basic_type_mirror("boolean",T_BOOLEAN, CHECK);
 437     _char_mirror    =
 438       java_lang_Class::create_basic_type_mirror("char",   T_CHAR, CHECK);
 439     _long_mirror    =
 440       java_lang_Class::create_basic_type_mirror("long",   T_LONG, CHECK);
 441     _short_mirror   =
 442       java_lang_Class::create_basic_type_mirror("short",  T_SHORT,   CHECK);
 443     _void_mirror    =
 444       java_lang_Class::create_basic_type_mirror("void",   T_VOID, CHECK);
 445 
 446     _mirrors[T_INT]     = _int_mirror;
 447     _mirrors[T_FLOAT]   = _float_mirror;
 448     _mirrors[T_DOUBLE]  = _double_mirror;
 449     _mirrors[T_BYTE]    = _byte_mirror;
 450     _mirrors[T_BOOLEAN] = _bool_mirror;
 451     _mirrors[T_CHAR]    = _char_mirror;
 452     _mirrors[T_LONG]    = _long_mirror;
 453     _mirrors[T_SHORT]   = _short_mirror;
 454     _mirrors[T_VOID]    = _void_mirror;
 455   //_mirrors[T_OBJECT]  = _object_klass->java_mirror();
 456   //_mirrors[T_ARRAY]   = _object_klass->java_mirror();
 457 }
 458 
 459 void Universe::fixup_mirrors(TRAPS) {
 460   // Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly,
 461   // but we cannot do that for classes created before java.lang.Class is loaded. Here we simply
 462   // walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note
 463   // that the number of objects allocated at this point is very small.
 464   assert(SystemDictionary::Class_klass_loaded(), "java.lang.Class should be loaded");
 465   HandleMark hm(THREAD);
 466   // Cache the start of the static fields
 467   InstanceMirrorKlass::init_offset_of_static_fields();
 468 
 469   GrowableArray <Klass*>* list = java_lang_Class::fixup_mirror_list();
 470   int list_length = list->length();
 471   for (int i = 0; i < list_length; i++) {
 472     Klass* k = list->at(i);
 473     assert(k->is_klass(), "List should only hold classes");
 474     EXCEPTION_MARK;
 475     KlassHandle kh(THREAD, k);
 476     java_lang_Class::fixup_mirror(kh, CATCH);
 477 }
 478   delete java_lang_Class::fixup_mirror_list();
 479   java_lang_Class::set_fixup_mirror_list(NULL);
 480 }
 481 
 482 static bool has_run_finalizers_on_exit = false;
 483 
 484 void Universe::run_finalizers_on_exit() {
 485   if (has_run_finalizers_on_exit) return;
 486   has_run_finalizers_on_exit = true;
 487 
 488   // Called on VM exit. This ought to be run in a separate thread.
 489   log_trace(ref)("Callback to run finalizers on exit");
 490   {
 491     PRESERVE_EXCEPTION_MARK;
 492     KlassHandle finalizer_klass(THREAD, SystemDictionary::Finalizer_klass());
 493     JavaValue result(T_VOID);
 494     JavaCalls::call_static(
 495       &result,
 496       finalizer_klass,
 497       vmSymbols::run_finalizers_on_exit_name(),
 498       vmSymbols::void_method_signature(),
 499       THREAD
 500     );
 501     // Ignore any pending exceptions
 502     CLEAR_PENDING_EXCEPTION;
 503   }
 504 }
 505 
 506 
 507 // initialize_vtable could cause gc if
 508 // 1) we specified true to initialize_vtable and
 509 // 2) this ran after gc was enabled
 510 // In case those ever change we use handles for oops
 511 void Universe::reinitialize_vtable_of(KlassHandle k_h, TRAPS) {
 512   // init vtable of k and all subclasses
 513   Klass* ko = k_h();
 514   klassVtable* vt = ko->vtable();
 515   if (vt) vt->initialize_vtable(false, CHECK);
 516   if (ko->is_instance_klass()) {
 517     for (KlassHandle s_h(THREAD, ko->subklass());
 518          s_h() != NULL;
 519          s_h = KlassHandle(THREAD, s_h()->next_sibling())) {
 520       reinitialize_vtable_of(s_h, CHECK);
 521     }
 522   }
 523 }
 524 
 525 
 526 void initialize_itable_for_klass(Klass* k, TRAPS) {
 527   InstanceKlass::cast(k)->itable()->initialize_itable(false, CHECK);
 528 }
 529 
 530 
 531 void Universe::reinitialize_itables(TRAPS) {
 532   SystemDictionary::classes_do(initialize_itable_for_klass, CHECK);
 533 
 534 }
 535 
 536 
 537 bool Universe::on_page_boundary(void* addr) {
 538   return ((uintptr_t) addr) % os::vm_page_size() == 0;
 539 }
 540 
 541 
 542 bool Universe::should_fill_in_stack_trace(Handle throwable) {
 543   // never attempt to fill in the stack trace of preallocated errors that do not have
 544   // backtrace. These errors are kept alive forever and may be "re-used" when all
 545   // preallocated errors with backtrace have been consumed. Also need to avoid
 546   // a potential loop which could happen if an out of memory occurs when attempting
 547   // to allocate the backtrace.
 548   return ((throwable() != Universe::_out_of_memory_error_java_heap) &&
 549           (throwable() != Universe::_out_of_memory_error_metaspace)  &&
 550           (throwable() != Universe::_out_of_memory_error_class_metaspace)  &&
 551           (throwable() != Universe::_out_of_memory_error_array_size) &&
 552           (throwable() != Universe::_out_of_memory_error_gc_overhead_limit) &&
 553           (throwable() != Universe::_out_of_memory_error_realloc_objects));
 554 }
 555 
 556 
 557 oop Universe::gen_out_of_memory_error(oop default_err) {
 558   // generate an out of memory error:
 559   // - if there is a preallocated error with backtrace available then return it wth
 560   //   a filled in stack trace.
 561   // - if there are no preallocated errors with backtrace available then return
 562   //   an error without backtrace.
 563   int next;
 564   if (_preallocated_out_of_memory_error_avail_count > 0) {
 565     next = (int)Atomic::add(-1, &_preallocated_out_of_memory_error_avail_count);
 566     assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");
 567   } else {
 568     next = -1;
 569   }
 570   if (next < 0) {
 571     // all preallocated errors have been used.
 572     // return default
 573     return default_err;
 574   } else {
 575     // get the error object at the slot and set set it to NULL so that the
 576     // array isn't keeping it alive anymore.
 577     oop exc = preallocated_out_of_memory_errors()->obj_at(next);
 578     assert(exc != NULL, "slot has been used already");
 579     preallocated_out_of_memory_errors()->obj_at_put(next, NULL);
 580 
 581     // use the message from the default error
 582     oop msg = java_lang_Throwable::message(default_err);
 583     assert(msg != NULL, "no message");
 584     java_lang_Throwable::set_message(exc, msg);
 585 
 586     // populate the stack trace and return it.
 587     java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
 588     return exc;
 589   }
 590 }
 591 
 592 intptr_t Universe::_non_oop_bits = 0;
 593 
 594 void* Universe::non_oop_word() {
 595   // Neither the high bits nor the low bits of this value is allowed
 596   // to look like (respectively) the high or low bits of a real oop.
 597   //
 598   // High and low are CPU-specific notions, but low always includes
 599   // the low-order bit.  Since oops are always aligned at least mod 4,
 600   // setting the low-order bit will ensure that the low half of the
 601   // word will never look like that of a real oop.
 602   //
 603   // Using the OS-supplied non-memory-address word (usually 0 or -1)
 604   // will take care of the high bits, however many there are.
 605 
 606   if (_non_oop_bits == 0) {
 607     _non_oop_bits = (intptr_t)os::non_memory_address_word() | 1;
 608   }
 609 
 610   return (void*)_non_oop_bits;
 611 }
 612 
 613 jint universe_init() {
 614   assert(!Universe::_fully_initialized, "called after initialize_vtables");
 615   guarantee(1 << LogHeapWordSize == sizeof(HeapWord),
 616          "LogHeapWordSize is incorrect.");
 617   guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");
 618   guarantee(sizeof(oop) % sizeof(HeapWord) == 0,
 619             "oop size is not not a multiple of HeapWord size");
 620 
 621   TraceTime timer("Genesis", TRACETIME_LOG(Info, startuptime));
 622 
 623   JavaClasses::compute_hard_coded_offsets();
 624 
 625   assert(GC::is_initialized(), "needs to be initialized here");
 626   jint status = GC::gc()->initialize_heap();
 627   if (status != JNI_OK) {
 628     return status;
 629   }
 630 
 631   status = Universe::initialize_heap();
 632   if (status != JNI_OK) {
 633     return status;
 634   }
 635   
 636   Metaspace::global_initialize();
 637 
 638   // Checks 'AfterMemoryInit' constraints.
 639   if (!CommandLineFlagConstraintList::check_constraints(CommandLineFlagConstraint::AfterMemoryInit)) {
 640     return JNI_EINVAL;
 641   }
 642 
 643   // Create memory for metadata.  Must be after initializing heap for
 644   // DumpSharedSpaces.
 645   ClassLoaderData::init_null_class_loader_data();
 646 
 647   // We have a heap so create the Method* caches before
 648   // Metaspace::initialize_shared_spaces() tries to populate them.
 649   Universe::_finalizer_register_cache = new LatestMethodCache();
 650   Universe::_loader_addClass_cache    = new LatestMethodCache();
 651   Universe::_pd_implies_cache         = new LatestMethodCache();
 652   Universe::_throw_illegal_access_error_cache = new LatestMethodCache();
 653   Universe::_do_stack_walk_cache = new LatestMethodCache();
 654 
 655   if (UseSharedSpaces) {
 656     // Read the data structures supporting the shared spaces (shared
 657     // system dictionary, symbol table, etc.).  After that, access to
 658     // the file (other than the mapped regions) is no longer needed, and
 659     // the file is closed. Closing the file does not affect the
 660     // currently mapped regions.
 661     MetaspaceShared::initialize_shared_spaces();
 662     StringTable::create_table();
 663   } else {
 664     SymbolTable::create_table();
 665     StringTable::create_table();
 666 
 667     if (DumpSharedSpaces) {
 668       MetaspaceShared::prepare_for_dumping();
 669     }
 670   }
 671   if (strlen(VerifySubSet) > 0) {
 672     Universe::initialize_verify_flags();
 673   }
 674 
 675   return JNI_OK;
 676 }
 677 
 678 // Choose the heap base address and oop encoding mode
 679 // when compressed oops are used:
 680 // Unscaled  - Use 32-bits oops without encoding when
 681 //     NarrowOopHeapBaseMin + heap_size < 4Gb
 682 // ZeroBased - Use zero based compressed oops with encoding when
 683 //     NarrowOopHeapBaseMin + heap_size < 32Gb
 684 // HeapBased - Use compressed oops with heap base + encoding.
 685 
 686 jint Universe::initialize_heap() {
 687   jint status = JNI_ERR;
 688 
 689   GC* gc = GC::gc();
 690   CollectedHeap* heap = gc->heap();
 691   ThreadLocalAllocBuffer::set_max_size(heap->max_tlab_size());
 692 
 693 #ifdef _LP64
 694   if (UseCompressedOops) {
 695     // Subtract a page because something can get allocated at heap base.
 696     // This also makes implicit null checking work, because the
 697     // memory+1 page below heap_base needs to cause a signal.
 698     // See needs_explicit_null_check.
 699     // Only set the heap base for compressed oops because it indicates
 700     // compressed oops for pstack code.
 701     if ((uint64_t) heap->reserved_region().end() > UnscaledOopHeapMax) {
 702       // Didn't reserve heap below 4Gb.  Must shift.
 703       Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
 704     }
 705     if ((uint64_t) heap->reserved_region().end() <= OopEncodingHeapMax) {
 706       // Did reserve heap below 32Gb. Can use base == 0;
 707       Universe::set_narrow_oop_base(0);
 708     }
 709 
 710     Universe::set_narrow_ptrs_base(Universe::narrow_oop_base());
 711 
 712     if (log_is_enabled(Info, gc, heap, coops)) {
 713       ResourceMark rm;
 714       outputStream* logst = Log(gc, heap, coops)::info_stream();
 715       Universe::print_compressed_oops_mode(logst);
 716     }
 717 
 718     // Tell tests in which mode we run.
 719     Arguments::PropertyList_add(new SystemProperty("java.vm.compressedOopsMode",
 720                                                    narrow_oop_mode_to_string(narrow_oop_mode()),
 721                                                    false));
 722   }
 723   // Universe::narrow_oop_base() is one page below the heap.
 724   assert((intptr_t)Universe::narrow_oop_base() <= (intptr_t)(heap->base() -
 725          os::vm_page_size()) ||
 726          Universe::narrow_oop_base() == NULL, "invalid value");
 727   assert(Universe::narrow_oop_shift() == LogMinObjAlignmentInBytes ||
 728          Universe::narrow_oop_shift() == 0, "invalid value");
 729 #endif
 730 
 731   // We will never reach the CATCH below since Exceptions::_throw will cause
 732   // the VM to exit if an exception is thrown during initialization
 733 
 734   if (UseTLAB) {
 735     assert(heap->supports_tlab_allocation(),
 736            "Should support thread-local allocation buffers");
 737     ThreadLocalAllocBuffer::startup_initialization();
 738   }
 739   return JNI_OK;
 740 }
 741 
 742 void Universe::print_compressed_oops_mode(outputStream* st) {
 743   st->print("Heap address: " PTR_FORMAT ", size: " SIZE_FORMAT " MB",
 744             p2i(GC::gc()->heap()->base()), GC::gc()->heap()->reserved_region().byte_size()/M);
 745 
 746   st->print(", Compressed Oops mode: %s", narrow_oop_mode_to_string(narrow_oop_mode()));
 747 
 748   if (Universe::narrow_oop_base() != 0) {
 749     st->print(": " PTR_FORMAT, p2i(Universe::narrow_oop_base()));
 750   }
 751 
 752   if (Universe::narrow_oop_shift() != 0) {
 753     st->print(", Oop shift amount: %d", Universe::narrow_oop_shift());
 754   }
 755 
 756   if (!Universe::narrow_oop_use_implicit_null_checks()) {
 757     st->print(", no protected page in front of the heap");
 758   }
 759   st->cr();
 760 }
 761 
 762 ReservedSpace Universe::reserve_heap(size_t heap_size, size_t alignment) {
 763 
 764   assert(alignment <= Arguments::conservative_max_heap_alignment(),
 765          "actual alignment " SIZE_FORMAT " must be within maximum heap alignment " SIZE_FORMAT,
 766          alignment, Arguments::conservative_max_heap_alignment());
 767 
 768   size_t total_reserved = align_size_up(heap_size, alignment);
 769   assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),
 770       "heap size is too big for compressed oops");
 771 
 772   bool use_large_pages = UseLargePages && is_size_aligned(alignment, os::large_page_size());
 773   assert(!UseLargePages
 774       || UseParallelGC
 775       || use_large_pages, "Wrong alignment to use large pages");
 776 
 777   // Now create the space.
 778   ReservedHeapSpace total_rs(total_reserved, alignment, use_large_pages);
 779 
 780   if (total_rs.is_reserved()) {
 781     assert((total_reserved == total_rs.size()) && ((uintptr_t)total_rs.base() % alignment == 0),
 782            "must be exactly of required size and alignment");
 783     // We are good.
 784 
 785     if (UseCompressedOops) {
 786       // Universe::initialize_heap() will reset this to NULL if unscaled
 787       // or zero-based narrow oops are actually used.
 788       // Else heap start and base MUST differ, so that NULL can be encoded nonambigous.
 789       Universe::set_narrow_oop_base((address)total_rs.compressed_oop_base());
 790     }
 791 
 792     return total_rs;
 793   }
 794 
 795   vm_exit_during_initialization(
 796     err_msg("Could not reserve enough space for " SIZE_FORMAT "KB object heap",
 797             total_reserved/K));
 798 
 799   // satisfy compiler
 800   ShouldNotReachHere();
 801   return ReservedHeapSpace(0, 0, false);
 802 }
 803 
 804 
 805 // It's the caller's responsibility to ensure glitch-freedom
 806 // (if required).
 807 void Universe::update_heap_info_at_gc() {
 808   _heap_capacity_at_last_gc = GC::gc()->heap()->capacity();
 809   _heap_used_at_last_gc     = GC::gc()->heap()->used();
 810 }
 811 
 812 
 813 const char* Universe::narrow_oop_mode_to_string(Universe::NARROW_OOP_MODE mode) {
 814   switch (mode) {
 815     case UnscaledNarrowOop:
 816       return "32-bit";
 817     case ZeroBasedNarrowOop:
 818       return "Zero based";
 819     case DisjointBaseNarrowOop:
 820       return "Non-zero disjoint base";
 821     case HeapBasedNarrowOop:
 822       return "Non-zero based";
 823   }
 824 
 825   ShouldNotReachHere();
 826   return "";
 827 }
 828 
 829 
 830 Universe::NARROW_OOP_MODE Universe::narrow_oop_mode() {
 831   if (narrow_oop_base_disjoint()) {
 832     return DisjointBaseNarrowOop;
 833   }
 834 
 835   if (narrow_oop_base() != 0) {
 836     return HeapBasedNarrowOop;
 837   }
 838 
 839   if (narrow_oop_shift() != 0) {
 840     return ZeroBasedNarrowOop;
 841   }
 842 
 843   return UnscaledNarrowOop;
 844 }
 845 
 846 void initialize_known_method(LatestMethodCache* method_cache,
 847                              InstanceKlass* ik,
 848                              const char* method,
 849                              Symbol* signature,
 850                              bool is_static, TRAPS)
 851 {
 852   TempNewSymbol name = SymbolTable::new_symbol(method, CHECK);
 853   Method* m = NULL;
 854   // The klass must be linked before looking up the method.
 855   if (!ik->link_class_or_fail(THREAD) ||
 856       ((m = ik->find_method(name, signature)) == NULL) ||
 857       is_static != m->is_static()) {
 858     ResourceMark rm(THREAD);
 859     // NoSuchMethodException doesn't actually work because it tries to run the
 860     // <init> function before java_lang_Class is linked. Print error and exit.
 861     vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",
 862                                  ik->name()->as_C_string(), method));
 863   }
 864   method_cache->init(ik, m);
 865 }
 866 
 867 void Universe::initialize_known_methods(TRAPS) {
 868   // Set up static method for registering finalizers
 869   initialize_known_method(_finalizer_register_cache,
 870                           SystemDictionary::Finalizer_klass(),
 871                           "register",
 872                           vmSymbols::object_void_signature(), true, CHECK);
 873 
 874   initialize_known_method(_throw_illegal_access_error_cache,
 875                           SystemDictionary::internal_Unsafe_klass(),
 876                           "throwIllegalAccessError",
 877                           vmSymbols::void_method_signature(), true, CHECK);
 878 
 879   // Set up method for registering loaded classes in class loader vector
 880   initialize_known_method(_loader_addClass_cache,
 881                           SystemDictionary::ClassLoader_klass(),
 882                           "addClass",
 883                           vmSymbols::class_void_signature(), false, CHECK);
 884 
 885   // Set up method for checking protection domain
 886   initialize_known_method(_pd_implies_cache,
 887                           SystemDictionary::ProtectionDomain_klass(),
 888                           "impliesCreateAccessControlContext",
 889                           vmSymbols::void_boolean_signature(), false, CHECK);
 890 
 891   // Set up method for stack walking
 892   initialize_known_method(_do_stack_walk_cache,
 893                           SystemDictionary::AbstractStackWalker_klass(),
 894                           "doStackWalk",
 895                           vmSymbols::doStackWalk_signature(), false, CHECK);
 896 }
 897 
 898 void universe2_init() {
 899   EXCEPTION_MARK;
 900   Universe::genesis(CATCH);
 901 }
 902 
 903 // Set after initialization of the module runtime, call_initModuleRuntime
 904 void universe_post_module_init() {
 905   Universe::_module_initialized = true;
 906 }
 907 
 908 bool universe_post_init() {
 909   assert(!is_init_completed(), "Error: initialization not yet completed!");
 910   Universe::_fully_initialized = true;
 911   EXCEPTION_MARK;
 912   { ResourceMark rm;
 913     Interpreter::initialize();      // needed for interpreter entry points
 914     if (!UseSharedSpaces) {
 915       HandleMark hm(THREAD);
 916       KlassHandle ok_h(THREAD, SystemDictionary::Object_klass());
 917       Universe::reinitialize_vtable_of(ok_h, CHECK_false);
 918       Universe::reinitialize_itables(CHECK_false);
 919     }
 920   }
 921 
 922   HandleMark hm(THREAD);
 923   Klass* k;
 924   instanceKlassHandle k_h;
 925   // Setup preallocated empty java.lang.Class array
 926   Universe::_the_empty_class_klass_array = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_false);
 927 
 928   // Setup preallocated OutOfMemoryError errors
 929   k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_OutOfMemoryError(), true, CHECK_false);
 930   k_h = instanceKlassHandle(THREAD, k);
 931   Universe::_out_of_memory_error_java_heap = k_h->allocate_instance(CHECK_false);
 932   Universe::_out_of_memory_error_metaspace = k_h->allocate_instance(CHECK_false);
 933   Universe::_out_of_memory_error_class_metaspace = k_h->allocate_instance(CHECK_false);
 934   Universe::_out_of_memory_error_array_size = k_h->allocate_instance(CHECK_false);
 935   Universe::_out_of_memory_error_gc_overhead_limit =
 936     k_h->allocate_instance(CHECK_false);
 937   Universe::_out_of_memory_error_realloc_objects = k_h->allocate_instance(CHECK_false);
 938 
 939   // Setup preallocated cause message for delayed StackOverflowError
 940   if (StackReservedPages > 0) {
 941     Universe::_delayed_stack_overflow_error_message =
 942       java_lang_String::create_oop_from_str("Delayed StackOverflowError due to ReservedStackAccess annotated method", CHECK_false);
 943   }
 944 
 945   // Setup preallocated NullPointerException
 946   // (this is currently used for a cheap & dirty solution in compiler exception handling)
 947   k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_NullPointerException(), true, CHECK_false);
 948   Universe::_null_ptr_exception_instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
 949   // Setup preallocated ArithmeticException
 950   // (this is currently used for a cheap & dirty solution in compiler exception handling)
 951   k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ArithmeticException(), true, CHECK_false);
 952   Universe::_arithmetic_exception_instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
 953   // Virtual Machine Error for when we get into a situation we can't resolve
 954   k = SystemDictionary::resolve_or_fail(
 955     vmSymbols::java_lang_VirtualMachineError(), true, CHECK_false);
 956   bool linked = InstanceKlass::cast(k)->link_class_or_fail(CHECK_false);
 957   if (!linked) {
 958     tty->print_cr("Unable to link/verify VirtualMachineError class");
 959     return false; // initialization failed
 960   }
 961   Universe::_virtual_machine_error_instance =
 962     InstanceKlass::cast(k)->allocate_instance(CHECK_false);
 963 
 964   Universe::_vm_exception = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
 965 
 966   if (!DumpSharedSpaces) {
 967     // These are the only Java fields that are currently set during shared space dumping.
 968     // We prefer to not handle this generally, so we always reinitialize these detail messages.
 969     Handle msg = java_lang_String::create_from_str("Java heap space", CHECK_false);
 970     java_lang_Throwable::set_message(Universe::_out_of_memory_error_java_heap, msg());
 971 
 972     msg = java_lang_String::create_from_str("Metaspace", CHECK_false);
 973     java_lang_Throwable::set_message(Universe::_out_of_memory_error_metaspace, msg());
 974     msg = java_lang_String::create_from_str("Compressed class space", CHECK_false);
 975     java_lang_Throwable::set_message(Universe::_out_of_memory_error_class_metaspace, msg());
 976 
 977     msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK_false);
 978     java_lang_Throwable::set_message(Universe::_out_of_memory_error_array_size, msg());
 979 
 980     msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK_false);
 981     java_lang_Throwable::set_message(Universe::_out_of_memory_error_gc_overhead_limit, msg());
 982 
 983     msg = java_lang_String::create_from_str("Java heap space: failed reallocation of scalar replaced objects", CHECK_false);
 984     java_lang_Throwable::set_message(Universe::_out_of_memory_error_realloc_objects, msg());
 985 
 986     msg = java_lang_String::create_from_str("/ by zero", CHECK_false);
 987     java_lang_Throwable::set_message(Universe::_arithmetic_exception_instance, msg());
 988 
 989     // Setup the array of errors that have preallocated backtrace
 990     k = Universe::_out_of_memory_error_java_heap->klass();
 991     assert(k->name() == vmSymbols::java_lang_OutOfMemoryError(), "should be out of memory error");
 992     k_h = instanceKlassHandle(THREAD, k);
 993 
 994     int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
 995     Universe::_preallocated_out_of_memory_error_array = oopFactory::new_objArray(k_h(), len, CHECK_false);
 996     for (int i=0; i<len; i++) {
 997       oop err = k_h->allocate_instance(CHECK_false);
 998       Handle err_h = Handle(THREAD, err);
 999       java_lang_Throwable::allocate_backtrace(err_h, CHECK_false);
1000       Universe::preallocated_out_of_memory_errors()->obj_at_put(i, err_h());
1001     }
1002     Universe::_preallocated_out_of_memory_error_avail_count = (jint)len;
1003   }
1004 
1005   Universe::initialize_known_methods(CHECK_false);
1006 
1007   // This needs to be done before the first scavenge/gc, since
1008   // it's an input to soft ref clearing policy.
1009   {
1010     MutexLocker x(Heap_lock);
1011     Universe::update_heap_info_at_gc();
1012   }
1013 
1014   // ("weak") refs processing infrastructure initialization
1015   GC::gc()->heap()->post_initialize();
1016 
1017   // Initialize performance counters for metaspaces
1018   MetaspaceCounters::initialize_performance_counters();
1019   CompressedClassSpaceCounters::initialize_performance_counters();
1020 
1021   MemoryService::add_metaspace_memory_pools();
1022 
1023   MemoryService::set_universe_heap(GC::gc()->heap());
1024 #if INCLUDE_CDS
1025   SharedClassUtil::initialize(CHECK_false);
1026 #endif
1027   return true;
1028 }
1029 
1030 
1031 void Universe::compute_base_vtable_size() {
1032   _base_vtable_size = ClassLoader::compute_Object_vtable();
1033 }
1034 
1035 void Universe::print_on(outputStream* st) {
1036   GCMutexLocker hl(Heap_lock); // Heap_lock might be locked by caller thread.
1037   st->print_cr("Heap");
1038   GC::gc()->heap()->print_on(st);
1039 }
1040 
1041 void Universe::print_heap_at_SIGBREAK() {
1042   if (PrintHeapAtSIGBREAK) {
1043     print_on(tty);
1044     tty->cr();
1045     tty->flush();
1046   }
1047 }
1048 
1049 void Universe::print_heap_before_gc() {
1050   Log(gc, heap) log;
1051   if (log.is_debug()) {
1052     log.debug("Heap before GC invocations=%u (full %u):", GC::gc()->heap()->total_collections(), GC::gc()->heap()->total_full_collections());
1053     ResourceMark rm;
1054     GC::gc()->heap()->print_on(log.debug_stream());
1055   }
1056 }
1057 
1058 void Universe::print_heap_after_gc() {
1059   Log(gc, heap) log;
1060   if (log.is_debug()) {
1061     log.debug("Heap after GC invocations=%u (full %u):", GC::gc()->heap()->total_collections(), GC::gc()->heap()->total_full_collections());
1062     ResourceMark rm;
1063     GC::gc()->heap()->print_on(log.debug_stream());
1064   }
1065 }
1066 
1067 void Universe::initialize_verify_flags() {
1068   verify_flags = 0;
1069   const char delimiter[] = " ,";
1070 
1071   size_t length = strlen(VerifySubSet);
1072   char* subset_list = NEW_C_HEAP_ARRAY(char, length + 1, mtInternal);
1073   strncpy(subset_list, VerifySubSet, length + 1);
1074 
1075   char* token = strtok(subset_list, delimiter);
1076   while (token != NULL) {
1077     if (strcmp(token, "threads") == 0) {
1078       verify_flags |= Verify_Threads;
1079     } else if (strcmp(token, "heap") == 0) {
1080       verify_flags |= Verify_Heap;
1081     } else if (strcmp(token, "symbol_table") == 0) {
1082       verify_flags |= Verify_SymbolTable;
1083     } else if (strcmp(token, "string_table") == 0) {
1084       verify_flags |= Verify_StringTable;
1085     } else if (strcmp(token, "codecache") == 0) {
1086       verify_flags |= Verify_CodeCache;
1087     } else if (strcmp(token, "dictionary") == 0) {
1088       verify_flags |= Verify_SystemDictionary;
1089     } else if (strcmp(token, "classloader_data_graph") == 0) {
1090       verify_flags |= Verify_ClassLoaderDataGraph;
1091     } else if (strcmp(token, "metaspace") == 0) {
1092       verify_flags |= Verify_MetaspaceAux;
1093     } else if (strcmp(token, "jni_handles") == 0) {
1094       verify_flags |= Verify_JNIHandles;
1095     } else if (strcmp(token, "c-heap") == 0) {
1096       verify_flags |= Verify_CHeap;
1097     } else if (strcmp(token, "codecache_oops") == 0) {
1098       verify_flags |= Verify_CodeCacheOops;
1099     } else {
1100       vm_exit_during_initialization(err_msg("VerifySubSet: \'%s\' memory sub-system is unknown, please correct it", token));
1101     }
1102     token = strtok(NULL, delimiter);
1103   }
1104   FREE_C_HEAP_ARRAY(char, subset_list);
1105 }
1106 
1107 bool Universe::should_verify_subset(uint subset) {
1108   if (verify_flags & subset) {
1109     return true;
1110   }
1111   return false;
1112 }
1113 
1114 void Universe::verify(VerifyOption option, const char* prefix) {
1115   // The use of _verify_in_progress is a temporary work around for
1116   // 6320749.  Don't bother with a creating a class to set and clear
1117   // it since it is only used in this method and the control flow is
1118   // straight forward.
1119   _verify_in_progress = true;
1120 
1121   COMPILER2_PRESENT(
1122     assert(!DerivedPointerTable::is_active(),
1123          "DPT should not be active during verification "
1124          "(of thread stacks below)");
1125   )
1126 
1127   ResourceMark rm;
1128   HandleMark hm;  // Handles created during verification can be zapped
1129   _verify_count++;
1130 
1131   FormatBuffer<> title("Verifying %s", prefix);
1132   GCTraceTime(Info, gc, verify) tm(title.buffer());
1133   if (should_verify_subset(Verify_Threads)) {
1134     log_debug(gc, verify)("Threads");
1135     Threads::verify();
1136   }
1137   if (should_verify_subset(Verify_Heap)) {
1138     log_debug(gc, verify)("Heap");
1139     GC::gc()->heap()->verify(option);
1140   }
1141   if (should_verify_subset(Verify_SymbolTable)) {
1142     log_debug(gc, verify)("SymbolTable");
1143     SymbolTable::verify();
1144   }
1145   if (should_verify_subset(Verify_StringTable)) {
1146     log_debug(gc, verify)("StringTable");
1147     StringTable::verify();
1148   }
1149   if (should_verify_subset(Verify_CodeCache)) {
1150   {
1151     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1152     log_debug(gc, verify)("CodeCache");
1153     CodeCache::verify();
1154   }
1155   }
1156   if (should_verify_subset(Verify_SystemDictionary)) {
1157     log_debug(gc, verify)("SystemDictionary");
1158     SystemDictionary::verify();
1159   }
1160 #ifndef PRODUCT
1161   if (should_verify_subset(Verify_ClassLoaderDataGraph)) {
1162     log_debug(gc, verify)("ClassLoaderDataGraph");
1163     ClassLoaderDataGraph::verify();
1164   }
1165 #endif
1166   if (should_verify_subset(Verify_MetaspaceAux)) {
1167     log_debug(gc, verify)("MetaspaceAux");
1168     MetaspaceAux::verify_free_chunks();
1169   }
1170   if (should_verify_subset(Verify_JNIHandles)) {
1171     log_debug(gc, verify)("JNIHandles");
1172     JNIHandles::verify();
1173   }
1174   if (should_verify_subset(Verify_CHeap)) {
1175     log_debug(gc, verify)("C-heap");
1176     os::check_heap();
1177   }
1178   if (should_verify_subset(Verify_CodeCacheOops)) {
1179     log_debug(gc, verify)("CodeCache Oops");
1180     CodeCache::verify_oops();
1181   }
1182 
1183   _verify_in_progress = false;
1184 }
1185 
1186 
1187 #ifndef PRODUCT
1188 void Universe::calculate_verify_data(HeapWord* low_boundary, HeapWord* high_boundary) {
1189   assert(low_boundary < high_boundary, "bad interval");
1190 
1191   // decide which low-order bits we require to be clear:
1192   size_t alignSize = MinObjAlignmentInBytes;
1193   size_t min_object_size = CollectedHeap::min_fill_size();
1194 
1195   // make an inclusive limit:
1196   uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;
1197   uintptr_t min = (uintptr_t)low_boundary;
1198   assert(min < max, "bad interval");
1199   uintptr_t diff = max ^ min;
1200 
1201   // throw away enough low-order bits to make the diff vanish
1202   uintptr_t mask = (uintptr_t)(-1);
1203   while ((mask & diff) != 0)
1204     mask <<= 1;
1205   uintptr_t bits = (min & mask);
1206   assert(bits == (max & mask), "correct mask");
1207   // check an intermediate value between min and max, just to make sure:
1208   assert(bits == ((min + (max-min)/2) & mask), "correct mask");
1209 
1210   // require address alignment, too:
1211   mask |= (alignSize - 1);
1212 
1213   if (!(_verify_oop_mask == 0 && _verify_oop_bits == (uintptr_t)-1)) {
1214     assert(_verify_oop_mask == mask && _verify_oop_bits == bits, "mask stability");
1215   }
1216   _verify_oop_mask = mask;
1217   _verify_oop_bits = bits;
1218 }
1219 
1220 // Oop verification (see MacroAssembler::verify_oop)
1221 
1222 uintptr_t Universe::verify_oop_mask() {
1223   MemRegion m = GC::gc()->heap()->reserved_region();
1224   calculate_verify_data(m.start(), m.end());
1225   return _verify_oop_mask;
1226 }
1227 
1228 uintptr_t Universe::verify_oop_bits() {
1229   MemRegion m = GC::gc()->heap()->reserved_region();
1230   calculate_verify_data(m.start(), m.end());
1231   return _verify_oop_bits;
1232 }
1233 
1234 uintptr_t Universe::verify_mark_mask() {
1235   return markOopDesc::lock_mask_in_place;
1236 }
1237 
1238 uintptr_t Universe::verify_mark_bits() {
1239   intptr_t mask = verify_mark_mask();
1240   intptr_t bits = (intptr_t)markOopDesc::prototype();
1241   assert((bits & ~mask) == 0, "no stray header bits");
1242   return bits;
1243 }
1244 #endif // PRODUCT
1245 
1246 
1247 void Universe::compute_verify_oop_data() {
1248   verify_oop_mask();
1249   verify_oop_bits();
1250   verify_mark_mask();
1251   verify_mark_bits();
1252 }
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   if (_fullgc_alot_dummy_array != NULL) {
1285     if (_fullgc_alot_dummy_next >= _fullgc_alot_dummy_array->length()) {
1286       // No more dummies to release, release entire array instead
1287       _fullgc_alot_dummy_array = NULL;
1288       return false;
1289     }
1290     if (!UseConcMarkSweepGC) {
1291       // Release dummy at bottom of old generation
1292       _fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);
1293     }
1294     // Release dummy at bottom of permanent generation
1295     _fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);
1296   }
1297   return true;
1298 }
1299 
1300 #endif // ASSERT