1 /*
   2  * Copyright (c) 1997, 2013, 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/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/dependencies.hpp"
  34 #include "gc_interface/collectedHeap.inline.hpp"
  35 #include "interpreter/interpreter.hpp"
  36 #include "memory/cardTableModRefBS.hpp"
  37 #include "memory/gcLocker.inline.hpp"
  38 #include "memory/genCollectedHeap.hpp"
  39 #include "memory/genRemSet.hpp"
  40 #include "memory/generation.hpp"
  41 #include "memory/metadataFactory.hpp"
  42 #include "memory/metaspaceShared.hpp"
  43 #include "memory/oopFactory.hpp"
  44 #include "memory/space.hpp"
  45 #include "memory/universe.hpp"
  46 #include "memory/universe.inline.hpp"
  47 #include "oops/constantPool.hpp"
  48 #include "oops/instanceClassLoaderKlass.hpp"
  49 #include "oops/instanceKlass.hpp"
  50 #include "oops/instanceMirrorKlass.hpp"
  51 #include "oops/instanceRefKlass.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "oops/typeArrayKlass.hpp"
  54 #include "prims/jvmtiRedefineClassesTrace.hpp"
  55 #include "runtime/arguments.hpp"
  56 #include "runtime/deoptimization.hpp"
  57 #include "runtime/fprofiler.hpp"
  58 #include "runtime/handles.inline.hpp"
  59 #include "runtime/init.hpp"
  60 #include "runtime/java.hpp"
  61 #include "runtime/javaCalls.hpp"
  62 #include "runtime/sharedRuntime.hpp"
  63 #include "runtime/synchronizer.hpp"
  64 #include "runtime/thread.inline.hpp"
  65 #include "runtime/timer.hpp"
  66 #include "runtime/vm_operations.hpp"
  67 #include "services/memoryService.hpp"
  68 #include "utilities/copy.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/hashtable.inline.hpp"
  71 #include "utilities/preserveException.hpp"
  72 #include "utilities/macros.hpp"
  73 #if INCLUDE_ALL_GCS
  74 #include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
  75 #include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp"
  76 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  77 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
  78 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
  79 #endif // INCLUDE_ALL_GCS
  80 
  81 // Known objects
  82 Klass* Universe::_boolArrayKlassObj                 = NULL;
  83 Klass* Universe::_byteArrayKlassObj                 = NULL;
  84 Klass* Universe::_charArrayKlassObj                 = NULL;
  85 Klass* Universe::_intArrayKlassObj                  = NULL;
  86 Klass* Universe::_shortArrayKlassObj                = NULL;
  87 Klass* Universe::_longArrayKlassObj                 = NULL;
  88 Klass* Universe::_singleArrayKlassObj               = NULL;
  89 Klass* Universe::_doubleArrayKlassObj               = NULL;
  90 Klass* Universe::_typeArrayKlassObjs[T_VOID+1]      = { NULL /*, NULL...*/ };
  91 Klass* Universe::_objectArrayKlassObj               = NULL;
  92 oop Universe::_int_mirror                             = NULL;
  93 oop Universe::_float_mirror                           = NULL;
  94 oop Universe::_double_mirror                          = NULL;
  95 oop Universe::_byte_mirror                            = NULL;
  96 oop Universe::_bool_mirror                            = NULL;
  97 oop Universe::_char_mirror                            = NULL;
  98 oop Universe::_long_mirror                            = NULL;
  99 oop Universe::_short_mirror                           = NULL;
 100 oop Universe::_void_mirror                            = NULL;
 101 oop Universe::_mirrors[T_VOID+1]                      = { NULL /*, NULL...*/ };
 102 oop Universe::_main_thread_group                      = NULL;
 103 oop Universe::_system_thread_group                    = NULL;
 104 objArrayOop Universe::_the_empty_class_klass_array    = NULL;
 105 Array<Klass*>* Universe::_the_array_interfaces_array = NULL;
 106 oop Universe::_the_null_string                        = NULL;
 107 oop Universe::_the_min_jint_string                   = NULL;
 108 LatestMethodOopCache* Universe::_finalizer_register_cache = NULL;
 109 LatestMethodOopCache* Universe::_loader_addClass_cache    = NULL;
 110 ActiveMethodOopsCache* Universe::_reflect_invoke_cache    = NULL;
 111 oop Universe::_out_of_memory_error_java_heap          = NULL;
 112 oop Universe::_out_of_memory_error_perm_gen           = NULL;
 113 oop Universe::_out_of_memory_error_array_size         = NULL;
 114 oop Universe::_out_of_memory_error_gc_overhead_limit  = NULL;
 115 objArrayOop Universe::_preallocated_out_of_memory_error_array = NULL;
 116 volatile jint Universe::_preallocated_out_of_memory_error_avail_count = 0;
 117 bool Universe::_verify_in_progress                    = false;
 118 oop Universe::_null_ptr_exception_instance            = NULL;
 119 oop Universe::_arithmetic_exception_instance          = NULL;
 120 oop Universe::_virtual_machine_error_instance         = NULL;
 121 oop Universe::_vm_exception                           = NULL;
 122 Array<int>* Universe::_the_empty_int_array            = NULL;
 123 Array<u2>* Universe::_the_empty_short_array           = NULL;
 124 Array<Klass*>* Universe::_the_empty_klass_array     = NULL;
 125 Array<Method*>* Universe::_the_empty_method_array   = NULL;
 126 
 127 // These variables are guarded by FullGCALot_lock.
 128 debug_only(objArrayOop Universe::_fullgc_alot_dummy_array = NULL;)
 129 debug_only(int Universe::_fullgc_alot_dummy_next      = 0;)
 130 
 131 // Heap
 132 int             Universe::_verify_count = 0;
 133 
 134 int             Universe::_base_vtable_size = 0;
 135 bool            Universe::_bootstrapping = false;
 136 bool            Universe::_fully_initialized = false;
 137 
 138 size_t          Universe::_heap_capacity_at_last_gc;
 139 size_t          Universe::_heap_used_at_last_gc = 0;
 140 
 141 CollectedHeap*  Universe::_collectedHeap = NULL;
 142 
 143 NarrowPtrStruct Universe::_narrow_oop = { NULL, 0, true };
 144 NarrowPtrStruct Universe::_narrow_klass = { NULL, 0, true };
 145 address Universe::_narrow_ptrs_base;
 146 
 147 size_t          Universe::_class_metaspace_size;
 148 
 149 void Universe::basic_type_classes_do(void f(Klass*)) {
 150   f(boolArrayKlassObj());
 151   f(byteArrayKlassObj());
 152   f(charArrayKlassObj());
 153   f(intArrayKlassObj());
 154   f(shortArrayKlassObj());
 155   f(longArrayKlassObj());
 156   f(singleArrayKlassObj());
 157   f(doubleArrayKlassObj());
 158 }
 159 
 160 void Universe::oops_do(OopClosure* f, bool do_all) {
 161 
 162   f->do_oop((oop*) &_int_mirror);
 163   f->do_oop((oop*) &_float_mirror);
 164   f->do_oop((oop*) &_double_mirror);
 165   f->do_oop((oop*) &_byte_mirror);
 166   f->do_oop((oop*) &_bool_mirror);
 167   f->do_oop((oop*) &_char_mirror);
 168   f->do_oop((oop*) &_long_mirror);
 169   f->do_oop((oop*) &_short_mirror);
 170   f->do_oop((oop*) &_void_mirror);
 171 
 172   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 173     f->do_oop((oop*) &_mirrors[i]);
 174   }
 175   assert(_mirrors[0] == NULL && _mirrors[T_BOOLEAN - 1] == NULL, "checking");
 176 
 177   f->do_oop((oop*)&_the_empty_class_klass_array);
 178   f->do_oop((oop*)&_the_null_string);
 179   f->do_oop((oop*)&_the_min_jint_string);
 180   f->do_oop((oop*)&_out_of_memory_error_java_heap);
 181   f->do_oop((oop*)&_out_of_memory_error_perm_gen);
 182   f->do_oop((oop*)&_out_of_memory_error_array_size);
 183   f->do_oop((oop*)&_out_of_memory_error_gc_overhead_limit);
 184     f->do_oop((oop*)&_preallocated_out_of_memory_error_array);
 185   f->do_oop((oop*)&_null_ptr_exception_instance);
 186   f->do_oop((oop*)&_arithmetic_exception_instance);
 187   f->do_oop((oop*)&_virtual_machine_error_instance);
 188   f->do_oop((oop*)&_main_thread_group);
 189   f->do_oop((oop*)&_system_thread_group);
 190   f->do_oop((oop*)&_vm_exception);
 191   debug_only(f->do_oop((oop*)&_fullgc_alot_dummy_array);)
 192 }
 193 
 194 // Serialize metadata in and out of CDS archive, not oops.
 195 void Universe::serialize(SerializeClosure* f, bool do_all) {
 196 
 197   f->do_ptr((void**)&_boolArrayKlassObj);
 198   f->do_ptr((void**)&_byteArrayKlassObj);
 199   f->do_ptr((void**)&_charArrayKlassObj);
 200   f->do_ptr((void**)&_intArrayKlassObj);
 201   f->do_ptr((void**)&_shortArrayKlassObj);
 202   f->do_ptr((void**)&_longArrayKlassObj);
 203   f->do_ptr((void**)&_singleArrayKlassObj);
 204   f->do_ptr((void**)&_doubleArrayKlassObj);
 205   f->do_ptr((void**)&_objectArrayKlassObj);
 206 
 207   {
 208     for (int i = 0; i < T_VOID+1; i++) {
 209       if (_typeArrayKlassObjs[i] != NULL) {
 210         assert(i >= T_BOOLEAN, "checking");
 211         f->do_ptr((void**)&_typeArrayKlassObjs[i]);
 212       } else if (do_all) {
 213         f->do_ptr((void**)&_typeArrayKlassObjs[i]);
 214       }
 215     }
 216   }
 217 
 218   f->do_ptr((void**)&_the_array_interfaces_array);
 219   f->do_ptr((void**)&_the_empty_int_array);
 220   f->do_ptr((void**)&_the_empty_short_array);
 221   f->do_ptr((void**)&_the_empty_method_array);
 222   f->do_ptr((void**)&_the_empty_klass_array);
 223   _finalizer_register_cache->serialize(f);
 224   _loader_addClass_cache->serialize(f);
 225   _reflect_invoke_cache->serialize(f);
 226 }
 227 
 228 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
 229   if (size < alignment || size % alignment != 0) {
 230     vm_exit_during_initialization(
 231       err_msg("Size of %s (" UINTX_FORMAT " bytes) must be aligned to " UINTX_FORMAT " bytes", name, size, alignment));
 232   }
 233 }
 234 
 235 void initialize_basic_type_klass(Klass* k, TRAPS) {
 236   Klass* ok = SystemDictionary::Object_klass();
 237   if (UseSharedSpaces) {
 238     assert(k->super() == ok, "u3");
 239     k->restore_unshareable_info(CHECK);
 240   } else {
 241     k->initialize_supers(ok, CHECK);
 242   }
 243   k->append_to_sibling_list();
 244 }
 245 
 246 void Universe::genesis(TRAPS) {
 247   ResourceMark rm;
 248 
 249   { FlagSetting fs(_bootstrapping, true);
 250 
 251     { MutexLocker mc(Compile_lock);
 252 
 253       // determine base vtable size; without that we cannot create the array klasses
 254       compute_base_vtable_size();
 255 
 256       if (!UseSharedSpaces) {
 257         _boolArrayKlassObj      = TypeArrayKlass::create_klass(T_BOOLEAN, sizeof(jboolean), CHECK);
 258         _charArrayKlassObj      = TypeArrayKlass::create_klass(T_CHAR,    sizeof(jchar),    CHECK);
 259         _singleArrayKlassObj    = TypeArrayKlass::create_klass(T_FLOAT,   sizeof(jfloat),   CHECK);
 260         _doubleArrayKlassObj    = TypeArrayKlass::create_klass(T_DOUBLE,  sizeof(jdouble),  CHECK);
 261         _byteArrayKlassObj      = TypeArrayKlass::create_klass(T_BYTE,    sizeof(jbyte),    CHECK);
 262         _shortArrayKlassObj     = TypeArrayKlass::create_klass(T_SHORT,   sizeof(jshort),   CHECK);
 263         _intArrayKlassObj       = TypeArrayKlass::create_klass(T_INT,     sizeof(jint),     CHECK);
 264         _longArrayKlassObj      = TypeArrayKlass::create_klass(T_LONG,    sizeof(jlong),    CHECK);
 265 
 266         _typeArrayKlassObjs[T_BOOLEAN] = _boolArrayKlassObj;
 267         _typeArrayKlassObjs[T_CHAR]    = _charArrayKlassObj;
 268         _typeArrayKlassObjs[T_FLOAT]   = _singleArrayKlassObj;
 269         _typeArrayKlassObjs[T_DOUBLE]  = _doubleArrayKlassObj;
 270         _typeArrayKlassObjs[T_BYTE]    = _byteArrayKlassObj;
 271         _typeArrayKlassObjs[T_SHORT]   = _shortArrayKlassObj;
 272         _typeArrayKlassObjs[T_INT]     = _intArrayKlassObj;
 273         _typeArrayKlassObjs[T_LONG]    = _longArrayKlassObj;
 274 
 275         ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
 276 
 277         _the_array_interfaces_array = MetadataFactory::new_array<Klass*>(null_cld, 2, NULL, CHECK);
 278         _the_empty_int_array        = MetadataFactory::new_array<int>(null_cld, 0, CHECK);
 279         _the_empty_short_array      = MetadataFactory::new_array<u2>(null_cld, 0, CHECK);
 280         _the_empty_method_array     = MetadataFactory::new_array<Method*>(null_cld, 0, CHECK);
 281         _the_empty_klass_array      = MetadataFactory::new_array<Klass*>(null_cld, 0, CHECK);
 282       }
 283     }
 284 
 285     vmSymbols::initialize(CHECK);
 286 
 287     SystemDictionary::initialize(CHECK);
 288 
 289     Klass* ok = SystemDictionary::Object_klass();
 290 
 291     _the_null_string            = StringTable::intern("null", CHECK);
 292     _the_min_jint_string       = StringTable::intern("-2147483648", CHECK);
 293 
 294     if (UseSharedSpaces) {
 295       // Verify shared interfaces array.
 296       assert(_the_array_interfaces_array->at(0) ==
 297              SystemDictionary::Cloneable_klass(), "u3");
 298       assert(_the_array_interfaces_array->at(1) ==
 299              SystemDictionary::Serializable_klass(), "u3");
 300     } else {
 301       // Set up shared interfaces array.  (Do this before supers are set up.)
 302       _the_array_interfaces_array->at_put(0, SystemDictionary::Cloneable_klass());
 303       _the_array_interfaces_array->at_put(1, SystemDictionary::Serializable_klass());
 304     }
 305 
 306     initialize_basic_type_klass(boolArrayKlassObj(), CHECK);
 307     initialize_basic_type_klass(charArrayKlassObj(), CHECK);
 308     initialize_basic_type_klass(singleArrayKlassObj(), CHECK);
 309     initialize_basic_type_klass(doubleArrayKlassObj(), CHECK);
 310     initialize_basic_type_klass(byteArrayKlassObj(), CHECK);
 311     initialize_basic_type_klass(shortArrayKlassObj(), CHECK);
 312     initialize_basic_type_klass(intArrayKlassObj(), CHECK);
 313     initialize_basic_type_klass(longArrayKlassObj(), CHECK);
 314   } // end of core bootstrapping
 315 
 316   // Maybe this could be lifted up now that object array can be initialized
 317   // during the bootstrapping.
 318 
 319   // OLD
 320   // Initialize _objectArrayKlass after core bootstraping to make
 321   // sure the super class is set up properly for _objectArrayKlass.
 322   // ---
 323   // NEW
 324   // Since some of the old system object arrays have been converted to
 325   // ordinary object arrays, _objectArrayKlass will be loaded when
 326   // SystemDictionary::initialize(CHECK); is run. See the extra check
 327   // for Object_klass_loaded in objArrayKlassKlass::allocate_objArray_klass_impl.
 328   _objectArrayKlassObj = InstanceKlass::
 329     cast(SystemDictionary::Object_klass())->array_klass(1, CHECK);
 330   // OLD
 331   // Add the class to the class hierarchy manually to make sure that
 332   // its vtable is initialized after core bootstrapping is completed.
 333   // ---
 334   // New
 335   // Have already been initialized.
 336   _objectArrayKlassObj->append_to_sibling_list();
 337 
 338   // Compute is_jdk version flags.
 339   // Only 1.3 or later has the java.lang.Shutdown class.
 340   // Only 1.4 or later has the java.lang.CharSequence interface.
 341   // Only 1.5 or later has the java.lang.management.MemoryUsage class.
 342   if (JDK_Version::is_partially_initialized()) {
 343     uint8_t jdk_version;
 344     Klass* k = SystemDictionary::resolve_or_null(
 345         vmSymbols::java_lang_management_MemoryUsage(), THREAD);
 346     CLEAR_PENDING_EXCEPTION; // ignore exceptions
 347     if (k == NULL) {
 348       k = SystemDictionary::resolve_or_null(
 349           vmSymbols::java_lang_CharSequence(), THREAD);
 350       CLEAR_PENDING_EXCEPTION; // ignore exceptions
 351       if (k == NULL) {
 352         k = SystemDictionary::resolve_or_null(
 353             vmSymbols::java_lang_Shutdown(), THREAD);
 354         CLEAR_PENDING_EXCEPTION; // ignore exceptions
 355         if (k == NULL) {
 356           jdk_version = 2;
 357         } else {
 358           jdk_version = 3;
 359         }
 360       } else {
 361         jdk_version = 4;
 362       }
 363     } else {
 364       jdk_version = 5;
 365     }
 366     JDK_Version::fully_initialize(jdk_version);
 367   }
 368 
 369   #ifdef ASSERT
 370   if (FullGCALot) {
 371     // Allocate an array of dummy objects.
 372     // We'd like these to be at the bottom of the old generation,
 373     // so that when we free one and then collect,
 374     // (almost) the whole heap moves
 375     // and we find out if we actually update all the oops correctly.
 376     // But we can't allocate directly in the old generation,
 377     // so we allocate wherever, and hope that the first collection
 378     // moves these objects to the bottom of the old generation.
 379     // We can allocate directly in the permanent generation, so we do.
 380     int size;
 381     if (UseConcMarkSweepGC) {
 382       warning("Using +FullGCALot with concurrent mark sweep gc "
 383               "will not force all objects to relocate");
 384       size = FullGCALotDummies;
 385     } else {
 386       size = FullGCALotDummies * 2;
 387     }
 388     objArrayOop    naked_array = oopFactory::new_objArray(SystemDictionary::Object_klass(), size, CHECK);
 389     objArrayHandle dummy_array(THREAD, naked_array);
 390     int i = 0;
 391     while (i < size) {
 392         // Allocate dummy in old generation
 393       oop dummy = InstanceKlass::cast(SystemDictionary::Object_klass())->allocate_instance(CHECK);
 394       dummy_array->obj_at_put(i++, dummy);
 395     }
 396     {
 397       // Only modify the global variable inside the mutex.
 398       // If we had a race to here, the other dummy_array instances
 399       // and their elements just get dropped on the floor, which is fine.
 400       MutexLocker ml(FullGCALot_lock);
 401       if (_fullgc_alot_dummy_array == NULL) {
 402         _fullgc_alot_dummy_array = dummy_array();
 403       }
 404     }
 405     assert(i == _fullgc_alot_dummy_array->length(), "just checking");
 406   }
 407   #endif
 408 
 409   // Initialize dependency array for null class loader
 410   ClassLoaderData::the_null_class_loader_data()->init_dependencies(CHECK);
 411 
 412 }
 413 
 414 // CDS support for patching vtables in metadata in the shared archive.
 415 // All types inherited from Metadata have vtables, but not types inherited
 416 // from MetaspaceObj, because the latter does not have virtual functions.
 417 // If the metadata type has a vtable, it cannot be shared in the read-only
 418 // section of the CDS archive, because the vtable pointer is patched.
 419 static inline void add_vtable(void** list, int* n, void* o, int count) {
 420   guarantee((*n) < count, "vtable list too small");
 421   void* vtable = dereference_vptr(o);
 422   assert(*(void**)(vtable) != NULL, "invalid vtable");
 423   list[(*n)++] = vtable;
 424 }
 425 
 426 void Universe::init_self_patching_vtbl_list(void** list, int count) {
 427   int n = 0;
 428   { InstanceKlass o;          add_vtable(list, &n, &o, count); }
 429   { InstanceClassLoaderKlass o; add_vtable(list, &n, &o, count); }
 430   { InstanceMirrorKlass o;    add_vtable(list, &n, &o, count); }
 431   { InstanceRefKlass o;       add_vtable(list, &n, &o, count); }
 432   { TypeArrayKlass o;         add_vtable(list, &n, &o, count); }
 433   { ObjArrayKlass o;          add_vtable(list, &n, &o, count); }
 434   { Method o;                 add_vtable(list, &n, &o, count); }
 435   { ConstantPool o;           add_vtable(list, &n, &o, count); }
 436 }
 437 
 438 void Universe::initialize_basic_type_mirrors(TRAPS) {
 439     assert(_int_mirror==NULL, "basic type mirrors already initialized");
 440     _int_mirror     =
 441       java_lang_Class::create_basic_type_mirror("int",    T_INT, CHECK);
 442     _float_mirror   =
 443       java_lang_Class::create_basic_type_mirror("float",  T_FLOAT,   CHECK);
 444     _double_mirror  =
 445       java_lang_Class::create_basic_type_mirror("double", T_DOUBLE,  CHECK);
 446     _byte_mirror    =
 447       java_lang_Class::create_basic_type_mirror("byte",   T_BYTE, CHECK);
 448     _bool_mirror    =
 449       java_lang_Class::create_basic_type_mirror("boolean",T_BOOLEAN, CHECK);
 450     _char_mirror    =
 451       java_lang_Class::create_basic_type_mirror("char",   T_CHAR, CHECK);
 452     _long_mirror    =
 453       java_lang_Class::create_basic_type_mirror("long",   T_LONG, CHECK);
 454     _short_mirror   =
 455       java_lang_Class::create_basic_type_mirror("short",  T_SHORT,   CHECK);
 456     _void_mirror    =
 457       java_lang_Class::create_basic_type_mirror("void",   T_VOID, CHECK);
 458 
 459     _mirrors[T_INT]     = _int_mirror;
 460     _mirrors[T_FLOAT]   = _float_mirror;
 461     _mirrors[T_DOUBLE]  = _double_mirror;
 462     _mirrors[T_BYTE]    = _byte_mirror;
 463     _mirrors[T_BOOLEAN] = _bool_mirror;
 464     _mirrors[T_CHAR]    = _char_mirror;
 465     _mirrors[T_LONG]    = _long_mirror;
 466     _mirrors[T_SHORT]   = _short_mirror;
 467     _mirrors[T_VOID]    = _void_mirror;
 468   //_mirrors[T_OBJECT]  = InstanceKlass::cast(_object_klass)->java_mirror();
 469   //_mirrors[T_ARRAY]   = InstanceKlass::cast(_object_klass)->java_mirror();
 470 }
 471 
 472 void Universe::fixup_mirrors(TRAPS) {
 473   // Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly,
 474   // but we cannot do that for classes created before java.lang.Class is loaded. Here we simply
 475   // walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note
 476   // that the number of objects allocated at this point is very small.
 477   assert(SystemDictionary::Class_klass_loaded(), "java.lang.Class should be loaded");
 478   HandleMark hm(THREAD);
 479   // Cache the start of the static fields
 480   InstanceMirrorKlass::init_offset_of_static_fields();
 481 
 482   GrowableArray <Klass*>* list = java_lang_Class::fixup_mirror_list();
 483   int list_length = list->length();
 484   for (int i = 0; i < list_length; i++) {
 485     Klass* k = list->at(i);
 486     assert(k->is_klass(), "List should only hold classes");
 487     EXCEPTION_MARK;
 488     KlassHandle kh(THREAD, k);
 489     java_lang_Class::fixup_mirror(kh, CATCH);
 490 }
 491   delete java_lang_Class::fixup_mirror_list();
 492   java_lang_Class::set_fixup_mirror_list(NULL);
 493 }
 494 
 495 static bool has_run_finalizers_on_exit = false;
 496 
 497 void Universe::run_finalizers_on_exit() {
 498   if (has_run_finalizers_on_exit) return;
 499   has_run_finalizers_on_exit = true;
 500 
 501   // Called on VM exit. This ought to be run in a separate thread.
 502   if (TraceReferenceGC) tty->print_cr("Callback to run finalizers on exit");
 503   {
 504     PRESERVE_EXCEPTION_MARK;
 505     KlassHandle finalizer_klass(THREAD, SystemDictionary::Finalizer_klass());
 506     JavaValue result(T_VOID);
 507     JavaCalls::call_static(
 508       &result,
 509       finalizer_klass,
 510       vmSymbols::run_finalizers_on_exit_name(),
 511       vmSymbols::void_method_signature(),
 512       THREAD
 513     );
 514     // Ignore any pending exceptions
 515     CLEAR_PENDING_EXCEPTION;
 516   }
 517 }
 518 
 519 
 520 // initialize_vtable could cause gc if
 521 // 1) we specified true to initialize_vtable and
 522 // 2) this ran after gc was enabled
 523 // In case those ever change we use handles for oops
 524 void Universe::reinitialize_vtable_of(KlassHandle k_h, TRAPS) {
 525   // init vtable of k and all subclasses
 526   Klass* ko = k_h();
 527   klassVtable* vt = ko->vtable();
 528   if (vt) vt->initialize_vtable(false, CHECK);
 529   if (ko->oop_is_instance()) {
 530     InstanceKlass* ik = (InstanceKlass*)ko;
 531     for (KlassHandle s_h(THREAD, ik->subklass()); s_h() != NULL; s_h = (THREAD, s_h()->next_sibling())) {
 532       reinitialize_vtable_of(s_h, CHECK);
 533     }
 534   }
 535 }
 536 
 537 
 538 void initialize_itable_for_klass(Klass* k, TRAPS) {
 539   InstanceKlass::cast(k)->itable()->initialize_itable(false, CHECK);
 540 }
 541 
 542 
 543 void Universe::reinitialize_itables(TRAPS) {
 544   SystemDictionary::classes_do(initialize_itable_for_klass, CHECK);
 545 
 546 }
 547 
 548 
 549 bool Universe::on_page_boundary(void* addr) {
 550   return ((uintptr_t) addr) % os::vm_page_size() == 0;
 551 }
 552 
 553 
 554 bool Universe::should_fill_in_stack_trace(Handle throwable) {
 555   // never attempt to fill in the stack trace of preallocated errors that do not have
 556   // backtrace. These errors are kept alive forever and may be "re-used" when all
 557   // preallocated errors with backtrace have been consumed. Also need to avoid
 558   // a potential loop which could happen if an out of memory occurs when attempting
 559   // to allocate the backtrace.
 560   return ((throwable() != Universe::_out_of_memory_error_java_heap) &&
 561           (throwable() != Universe::_out_of_memory_error_perm_gen)  &&
 562           (throwable() != Universe::_out_of_memory_error_array_size) &&
 563           (throwable() != Universe::_out_of_memory_error_gc_overhead_limit));
 564 }
 565 
 566 
 567 oop Universe::gen_out_of_memory_error(oop default_err) {
 568   // generate an out of memory error:
 569   // - if there is a preallocated error with backtrace available then return it wth
 570   //   a filled in stack trace.
 571   // - if there are no preallocated errors with backtrace available then return
 572   //   an error without backtrace.
 573   int next;
 574   if (_preallocated_out_of_memory_error_avail_count > 0) {
 575     next = (int)Atomic::add(-1, &_preallocated_out_of_memory_error_avail_count);
 576     assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");
 577   } else {
 578     next = -1;
 579   }
 580   if (next < 0) {
 581     // all preallocated errors have been used.
 582     // return default
 583     return default_err;
 584   } else {
 585     // get the error object at the slot and set set it to NULL so that the
 586     // array isn't keeping it alive anymore.
 587     oop exc = preallocated_out_of_memory_errors()->obj_at(next);
 588     assert(exc != NULL, "slot has been used already");
 589     preallocated_out_of_memory_errors()->obj_at_put(next, NULL);
 590 
 591     // use the message from the default error
 592     oop msg = java_lang_Throwable::message(default_err);
 593     assert(msg != NULL, "no message");
 594     java_lang_Throwable::set_message(exc, msg);
 595 
 596     // populate the stack trace and return it.
 597     java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
 598     return exc;
 599   }
 600 }
 601 
 602 static intptr_t non_oop_bits = 0;
 603 
 604 void* Universe::non_oop_word() {
 605   // Neither the high bits nor the low bits of this value is allowed
 606   // to look like (respectively) the high or low bits of a real oop.
 607   //
 608   // High and low are CPU-specific notions, but low always includes
 609   // the low-order bit.  Since oops are always aligned at least mod 4,
 610   // setting the low-order bit will ensure that the low half of the
 611   // word will never look like that of a real oop.
 612   //
 613   // Using the OS-supplied non-memory-address word (usually 0 or -1)
 614   // will take care of the high bits, however many there are.
 615 
 616   if (non_oop_bits == 0) {
 617     non_oop_bits = (intptr_t)os::non_memory_address_word() | 1;
 618   }
 619 
 620   return (void*)non_oop_bits;
 621 }
 622 
 623 jint universe_init() {
 624   assert(!Universe::_fully_initialized, "called after initialize_vtables");
 625   guarantee(1 << LogHeapWordSize == sizeof(HeapWord),
 626          "LogHeapWordSize is incorrect.");
 627   guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");
 628   guarantee(sizeof(oop) % sizeof(HeapWord) == 0,
 629             "oop size is not not a multiple of HeapWord size");
 630   TraceTime timer("Genesis", TraceStartupTime);
 631   GC_locker::lock();  // do not allow gc during bootstrapping
 632   JavaClasses::compute_hard_coded_offsets();
 633 
 634   jint status = Universe::initialize_heap();
 635   if (status != JNI_OK) {
 636     return status;
 637   }
 638 
 639   // Create memory for metadata.  Must be after initializing heap for
 640   // DumpSharedSpaces.
 641   ClassLoaderData::init_null_class_loader_data();
 642 
 643   // We have a heap so create the Method* caches before
 644   // Metaspace::initialize_shared_spaces() tries to populate them.
 645   Universe::_finalizer_register_cache = new LatestMethodOopCache();
 646   Universe::_loader_addClass_cache    = new LatestMethodOopCache();
 647   Universe::_reflect_invoke_cache     = new ActiveMethodOopsCache();
 648 
 649   if (UseSharedSpaces) {
 650     // Read the data structures supporting the shared spaces (shared
 651     // system dictionary, symbol table, etc.).  After that, access to
 652     // the file (other than the mapped regions) is no longer needed, and
 653     // the file is closed. Closing the file does not affect the
 654     // currently mapped regions.
 655     MetaspaceShared::initialize_shared_spaces();
 656     StringTable::create_table();
 657   } else {
 658     SymbolTable::create_table();
 659     StringTable::create_table();
 660     ClassLoader::create_package_info_table();
 661   }
 662 
 663   return JNI_OK;
 664 }
 665 
 666 // Choose the heap base address and oop encoding mode
 667 // when compressed oops are used:
 668 // Unscaled  - Use 32-bits oops without encoding when
 669 //     NarrowOopHeapBaseMin + heap_size < 4Gb
 670 // ZeroBased - Use zero based compressed oops with encoding when
 671 //     NarrowOopHeapBaseMin + heap_size < 32Gb
 672 // HeapBased - Use compressed oops with heap base + encoding.
 673 
 674 // 4Gb
 675 static const uint64_t NarrowOopHeapMax = (uint64_t(max_juint) + 1);
 676 // 32Gb
 677 // OopEncodingHeapMax == NarrowOopHeapMax << LogMinObjAlignmentInBytes;
 678 
 679 char* Universe::preferred_heap_base(size_t heap_size, NARROW_OOP_MODE mode) {
 680   size_t base = 0;
 681 #ifdef _LP64
 682   if (UseCompressedOops) {
 683     assert(mode == UnscaledNarrowOop  ||
 684            mode == ZeroBasedNarrowOop ||
 685            mode == HeapBasedNarrowOop, "mode is invalid");
 686     const size_t total_size = heap_size + HeapBaseMinAddress;
 687     // Return specified base for the first request.
 688     if (!FLAG_IS_DEFAULT(HeapBaseMinAddress) && (mode == UnscaledNarrowOop)) {
 689       base = HeapBaseMinAddress;
 690 
 691     // If the total size and the metaspace size are small enough to allow
 692     // UnscaledNarrowOop then just use UnscaledNarrowOop.
 693     } else if ((total_size <= OopEncodingHeapMax) && (mode != HeapBasedNarrowOop) &&
 694         (!UseCompressedKlassPointers ||
 695           (((OopEncodingHeapMax - heap_size) + Universe::class_metaspace_size()) <= KlassEncodingMetaspaceMax))) {
 696       // We don't need to check the metaspace size here because it is always smaller
 697       // than total_size.
 698       if ((total_size <= NarrowOopHeapMax) && (mode == UnscaledNarrowOop) &&
 699           (Universe::narrow_oop_shift() == 0)) {
 700         // Use 32-bits oops without encoding and
 701         // place heap's top on the 4Gb boundary
 702         base = (NarrowOopHeapMax - heap_size);
 703       } else {
 704         // Can't reserve with NarrowOopShift == 0
 705         Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
 706         if (mode == UnscaledNarrowOop ||
 707             mode == ZeroBasedNarrowOop && total_size <= NarrowOopHeapMax) {
 708           // Use zero based compressed oops with encoding and
 709           // place heap's top on the 32Gb boundary in case
 710           // total_size > 4Gb or failed to reserve below 4Gb.
 711           base = (OopEncodingHeapMax - heap_size);
 712         }
 713       }
 714 
 715     // See if ZeroBaseNarrowOop encoding will work for a heap based at
 716     // (KlassEncodingMetaspaceMax - class_metaspace_size()).
 717     } else if (UseCompressedKlassPointers && (mode != HeapBasedNarrowOop) &&
 718         (Universe::class_metaspace_size() + HeapBaseMinAddress <= KlassEncodingMetaspaceMax) &&
 719         (KlassEncodingMetaspaceMax + heap_size - Universe::class_metaspace_size() <= OopEncodingHeapMax)) {
 720       base = (KlassEncodingMetaspaceMax - Universe::class_metaspace_size());
 721     } else {
 722       // UnscaledNarrowOop encoding didn't work, and no base was found for ZeroBasedOops or
 723       // HeapBasedNarrowOop encoding was requested.  So, can't reserve below 32Gb.
 724       Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
 725     }
 726 
 727     // Set narrow_oop_base and narrow_oop_use_implicit_null_checks
 728     // used in ReservedHeapSpace() constructors.
 729     // The final values will be set in initialize_heap() below.
 730     if ((base != 0) && ((base + heap_size) <= OopEncodingHeapMax) &&
 731         (!UseCompressedKlassPointers || (base + Universe::class_metaspace_size()) <= KlassEncodingMetaspaceMax)) {
 732       // Use zero based compressed oops
 733       Universe::set_narrow_oop_base(NULL);
 734       // Don't need guard page for implicit checks in indexed
 735       // addressing mode with zero based Compressed Oops.
 736       Universe::set_narrow_oop_use_implicit_null_checks(true);
 737     } else {
 738       // Set to a non-NULL value so the ReservedSpace ctor computes
 739       // the correct no-access prefix.
 740       // The final value will be set in initialize_heap() below.
 741       Universe::set_narrow_oop_base((address)NarrowOopHeapMax);
 742 #ifdef _WIN64
 743       if (UseLargePages) {
 744         // Cannot allocate guard pages for implicit checks in indexed
 745         // addressing mode when large pages are specified on windows.
 746         Universe::set_narrow_oop_use_implicit_null_checks(false);
 747       }
 748 #endif //  _WIN64
 749     }
 750   }
 751 #endif
 752   return (char*)base; // also return NULL (don't care) for 32-bit VM
 753 }
 754 
 755 jint Universe::initialize_heap() {
 756 
 757   if (UseParallelGC) {
 758 #if INCLUDE_ALL_GCS
 759     Universe::_collectedHeap = new ParallelScavengeHeap();
 760 #else  // INCLUDE_ALL_GCS
 761     fatal("UseParallelGC not supported in this VM.");
 762 #endif // INCLUDE_ALL_GCS
 763 
 764   } else if (UseG1GC) {
 765 #if INCLUDE_ALL_GCS
 766     G1CollectorPolicy* g1p = new G1CollectorPolicy();
 767     G1CollectedHeap* g1h = new G1CollectedHeap(g1p);
 768     Universe::_collectedHeap = g1h;
 769 #else  // INCLUDE_ALL_GCS
 770     fatal("UseG1GC not supported in java kernel vm.");
 771 #endif // INCLUDE_ALL_GCS
 772 
 773   } else {
 774     GenCollectorPolicy *gc_policy;
 775 
 776     if (UseSerialGC) {
 777       gc_policy = new MarkSweepPolicy();
 778     } else if (UseConcMarkSweepGC) {
 779 #if INCLUDE_ALL_GCS
 780       if (UseAdaptiveSizePolicy) {
 781         gc_policy = new ASConcurrentMarkSweepPolicy();
 782       } else {
 783         gc_policy = new ConcurrentMarkSweepPolicy();
 784       }
 785 #else  // INCLUDE_ALL_GCS
 786     fatal("UseConcMarkSweepGC not supported in this VM.");
 787 #endif // INCLUDE_ALL_GCS
 788     } else { // default old generation
 789       gc_policy = new MarkSweepPolicy();
 790     }
 791 
 792     Universe::_collectedHeap = new GenCollectedHeap(gc_policy);
 793   }
 794 
 795   jint status = Universe::heap()->initialize();
 796   if (status != JNI_OK) {
 797     return status;
 798   }
 799 
 800 #ifdef _LP64
 801   if (UseCompressedOops) {
 802     // Subtract a page because something can get allocated at heap base.
 803     // This also makes implicit null checking work, because the
 804     // memory+1 page below heap_base needs to cause a signal.
 805     // See needs_explicit_null_check.
 806     // Only set the heap base for compressed oops because it indicates
 807     // compressed oops for pstack code.
 808     bool verbose = PrintCompressedOopsMode || (PrintMiscellaneous && Verbose);
 809     if (verbose) {
 810       tty->cr();
 811       tty->print("heap address: " PTR_FORMAT ", size: " SIZE_FORMAT " MB",
 812                  Universe::heap()->base(), Universe::heap()->reserved_region().byte_size()/M);
 813     }
 814     if (((uint64_t)Universe::heap()->reserved_region().end() > OopEncodingHeapMax) ||
 815         (UseCompressedKlassPointers &&
 816         ((uint64_t)Universe::heap()->base() + Universe::class_metaspace_size() > KlassEncodingMetaspaceMax))) {
 817       // Can't reserve heap below 32Gb.
 818       // keep the Universe::narrow_oop_base() set in Universe::reserve_heap()
 819       Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
 820       if (verbose) {
 821         tty->print(", Compressed Oops with base: "PTR_FORMAT, Universe::narrow_oop_base());
 822       }
 823     } else {
 824       Universe::set_narrow_oop_base(0);
 825       if (verbose) {
 826         tty->print(", zero based Compressed Oops");
 827       }
 828 #ifdef _WIN64
 829       if (!Universe::narrow_oop_use_implicit_null_checks()) {
 830         // Don't need guard page for implicit checks in indexed addressing
 831         // mode with zero based Compressed Oops.
 832         Universe::set_narrow_oop_use_implicit_null_checks(true);
 833       }
 834 #endif //  _WIN64
 835       if((uint64_t)Universe::heap()->reserved_region().end() > NarrowOopHeapMax) {
 836         // Can't reserve heap below 4Gb.
 837         Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
 838       } else {
 839         Universe::set_narrow_oop_shift(0);
 840         if (verbose) {
 841           tty->print(", 32-bits Oops");
 842         }
 843       }
 844     }
 845     if (verbose) {
 846       tty->cr();
 847       tty->cr();
 848     }
 849     if (UseCompressedKlassPointers) {
 850       Universe::set_narrow_klass_base(Universe::narrow_oop_base());
 851       Universe::set_narrow_klass_shift(MIN2(Universe::narrow_oop_shift(), LogKlassAlignmentInBytes));
 852     }
 853     Universe::set_narrow_ptrs_base(Universe::narrow_oop_base());
 854   }
 855   // Universe::narrow_oop_base() is one page below the metaspace
 856   // base. The actual metaspace base depends on alignment constraints
 857   // so we don't know its exact location here.
 858   assert((intptr_t)Universe::narrow_oop_base() <= (intptr_t)(Universe::heap()->base() - os::vm_page_size() - ClassMetaspaceSize) ||
 859          Universe::narrow_oop_base() == NULL, "invalid value");
 860   assert(Universe::narrow_oop_shift() == LogMinObjAlignmentInBytes ||
 861          Universe::narrow_oop_shift() == 0, "invalid value");
 862 #endif
 863 
 864   // We will never reach the CATCH below since Exceptions::_throw will cause
 865   // the VM to exit if an exception is thrown during initialization
 866 
 867   if (UseTLAB) {
 868     assert(Universe::heap()->supports_tlab_allocation(),
 869            "Should support thread-local allocation buffers");
 870     ThreadLocalAllocBuffer::startup_initialization();
 871   }
 872   return JNI_OK;
 873 }
 874 
 875 
 876 // Reserve the Java heap, which is now the same for all GCs.
 877 ReservedSpace Universe::reserve_heap(size_t heap_size, size_t alignment) {
 878   // Add in the class metaspace area so the classes in the headers can
 879   // be compressed the same as instances.
 880   // Need to round class space size up because it's below the heap and
 881   // the actual alignment depends on its size.
 882   Universe::set_class_metaspace_size(align_size_up(ClassMetaspaceSize, alignment));
 883   size_t total_reserved = align_size_up(heap_size + Universe::class_metaspace_size(), alignment);
 884   assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),
 885       "heap size is too big for compressed oops");
 886   char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
 887 
 888   ReservedHeapSpace total_rs(total_reserved, alignment, UseLargePages, addr);
 889 
 890   if (UseCompressedOops) {
 891     if (addr != NULL && !total_rs.is_reserved()) {
 892       // Failed to reserve at specified address - the requested memory
 893       // region is taken already, for example, by 'java' launcher.
 894       // Try again to reserver heap higher.
 895       addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
 896 
 897       ReservedHeapSpace total_rs0(total_reserved, alignment,
 898                                   UseLargePages, addr);
 899 
 900       if (addr != NULL && !total_rs0.is_reserved()) {
 901         // Failed to reserve at specified address again - give up.
 902         addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
 903         assert(addr == NULL, "");
 904 
 905         ReservedHeapSpace total_rs1(total_reserved, alignment,
 906                                     UseLargePages, addr);
 907         total_rs = total_rs1;
 908       } else {
 909         total_rs = total_rs0;
 910       }
 911     }
 912   }
 913 
 914   if (!total_rs.is_reserved()) {
 915     vm_exit_during_initialization(err_msg("Could not reserve enough space for " SIZE_FORMAT "KB object heap", total_reserved/K));
 916     return total_rs;
 917   }
 918 
 919   // Split the reserved space into main Java heap and a space for
 920   // classes so that they can be compressed using the same algorithm
 921   // as compressed oops. If compress oops and compress klass ptrs are
 922   // used we need the meta space first: if the alignment used for
 923   // compressed oops is greater than the one used for compressed klass
 924   // ptrs, a metadata space on top of the heap could become
 925   // unreachable.
 926   ReservedSpace class_rs = total_rs.first_part(Universe::class_metaspace_size());
 927   ReservedSpace heap_rs = total_rs.last_part(Universe::class_metaspace_size(), alignment);
 928   Metaspace::initialize_class_space(class_rs);
 929 
 930   if (UseCompressedOops) {
 931     // Universe::initialize_heap() will reset this to NULL if unscaled
 932     // or zero-based narrow oops are actually used.
 933     address base = (address)(total_rs.base() - os::vm_page_size());
 934     Universe::set_narrow_oop_base(base);
 935   }
 936   return heap_rs;
 937 }
 938 
 939 
 940 // It's the caller's repsonsibility to ensure glitch-freedom
 941 // (if required).
 942 void Universe::update_heap_info_at_gc() {
 943   _heap_capacity_at_last_gc = heap()->capacity();
 944   _heap_used_at_last_gc     = heap()->used();
 945 }
 946 
 947 
 948 
 949 void universe2_init() {
 950   EXCEPTION_MARK;
 951   Universe::genesis(CATCH);
 952 }
 953 
 954 
 955 // This function is defined in JVM.cpp
 956 extern void initialize_converter_functions();
 957 
 958 bool universe_post_init() {
 959   assert(!is_init_completed(), "Error: initialization not yet completed!");
 960   Universe::_fully_initialized = true;
 961   EXCEPTION_MARK;
 962   { ResourceMark rm;
 963     Interpreter::initialize();      // needed for interpreter entry points
 964     if (!UseSharedSpaces) {
 965       HandleMark hm(THREAD);
 966       KlassHandle ok_h(THREAD, SystemDictionary::Object_klass());
 967       Universe::reinitialize_vtable_of(ok_h, CHECK_false);
 968       Universe::reinitialize_itables(CHECK_false);
 969     }
 970   }
 971 
 972   HandleMark hm(THREAD);
 973   Klass* k;
 974   instanceKlassHandle k_h;
 975     // Setup preallocated empty java.lang.Class array
 976     Universe::_the_empty_class_klass_array = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_false);
 977 
 978     // Setup preallocated OutOfMemoryError errors
 979     k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_OutOfMemoryError(), true, CHECK_false);
 980     k_h = instanceKlassHandle(THREAD, k);
 981     Universe::_out_of_memory_error_java_heap = k_h->allocate_instance(CHECK_false);
 982     Universe::_out_of_memory_error_perm_gen = k_h->allocate_instance(CHECK_false);
 983     Universe::_out_of_memory_error_array_size = k_h->allocate_instance(CHECK_false);
 984     Universe::_out_of_memory_error_gc_overhead_limit =
 985       k_h->allocate_instance(CHECK_false);
 986 
 987     // Setup preallocated NullPointerException
 988     // (this is currently used for a cheap & dirty solution in compiler exception handling)
 989     k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_NullPointerException(), true, CHECK_false);
 990     Universe::_null_ptr_exception_instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
 991     // Setup preallocated ArithmeticException
 992     // (this is currently used for a cheap & dirty solution in compiler exception handling)
 993     k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ArithmeticException(), true, CHECK_false);
 994     Universe::_arithmetic_exception_instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
 995     // Virtual Machine Error for when we get into a situation we can't resolve
 996     k = SystemDictionary::resolve_or_fail(
 997       vmSymbols::java_lang_VirtualMachineError(), true, CHECK_false);
 998     bool linked = InstanceKlass::cast(k)->link_class_or_fail(CHECK_false);
 999     if (!linked) {
1000       tty->print_cr("Unable to link/verify VirtualMachineError class");
1001       return false; // initialization failed
1002     }
1003     Universe::_virtual_machine_error_instance =
1004       InstanceKlass::cast(k)->allocate_instance(CHECK_false);
1005 
1006     Universe::_vm_exception               = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
1007 
1008   if (!DumpSharedSpaces) {
1009     // These are the only Java fields that are currently set during shared space dumping.
1010     // We prefer to not handle this generally, so we always reinitialize these detail messages.
1011     Handle msg = java_lang_String::create_from_str("Java heap space", CHECK_false);
1012     java_lang_Throwable::set_message(Universe::_out_of_memory_error_java_heap, msg());
1013 
1014     msg = java_lang_String::create_from_str("Metadata space", CHECK_false);
1015     java_lang_Throwable::set_message(Universe::_out_of_memory_error_perm_gen, msg());
1016 
1017     msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK_false);
1018     java_lang_Throwable::set_message(Universe::_out_of_memory_error_array_size, msg());
1019 
1020     msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK_false);
1021     java_lang_Throwable::set_message(Universe::_out_of_memory_error_gc_overhead_limit, msg());
1022 
1023     msg = java_lang_String::create_from_str("/ by zero", CHECK_false);
1024     java_lang_Throwable::set_message(Universe::_arithmetic_exception_instance, msg());
1025 
1026     // Setup the array of errors that have preallocated backtrace
1027     k = Universe::_out_of_memory_error_java_heap->klass();
1028     assert(k->name() == vmSymbols::java_lang_OutOfMemoryError(), "should be out of memory error");
1029     k_h = instanceKlassHandle(THREAD, k);
1030 
1031     int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
1032     Universe::_preallocated_out_of_memory_error_array = oopFactory::new_objArray(k_h(), len, CHECK_false);
1033     for (int i=0; i<len; i++) {
1034       oop err = k_h->allocate_instance(CHECK_false);
1035       Handle err_h = Handle(THREAD, err);
1036       java_lang_Throwable::allocate_backtrace(err_h, CHECK_false);
1037       Universe::preallocated_out_of_memory_errors()->obj_at_put(i, err_h());
1038     }
1039     Universe::_preallocated_out_of_memory_error_avail_count = (jint)len;
1040   }
1041 
1042 
1043   // Setup static method for registering finalizers
1044   // The finalizer klass must be linked before looking up the method, in
1045   // case it needs to get rewritten.
1046   InstanceKlass::cast(SystemDictionary::Finalizer_klass())->link_class(CHECK_false);
1047   Method* m = InstanceKlass::cast(SystemDictionary::Finalizer_klass())->find_method(
1048                                   vmSymbols::register_method_name(),
1049                                   vmSymbols::register_method_signature());
1050   if (m == NULL || !m->is_static()) {
1051     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodException(),
1052       "java.lang.ref.Finalizer.register", false);
1053   }
1054   Universe::_finalizer_register_cache->init(
1055     SystemDictionary::Finalizer_klass(), m, CHECK_false);
1056 
1057   // Resolve on first use and initialize class.
1058   // Note: No race-condition here, since a resolve will always return the same result
1059 
1060   // Setup method for security checks
1061   k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_reflect_Method(), true, CHECK_false);
1062   k_h = instanceKlassHandle(THREAD, k);
1063   k_h->link_class(CHECK_false);
1064   m = k_h->find_method(vmSymbols::invoke_name(), vmSymbols::object_object_array_object_signature());
1065   if (m == NULL || m->is_static()) {
1066     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodException(),
1067       "java.lang.reflect.Method.invoke", false);
1068   }
1069   Universe::_reflect_invoke_cache->init(k_h(), m, CHECK_false);
1070 
1071   // Setup method for registering loaded classes in class loader vector
1072   InstanceKlass::cast(SystemDictionary::ClassLoader_klass())->link_class(CHECK_false);
1073   m = InstanceKlass::cast(SystemDictionary::ClassLoader_klass())->find_method(vmSymbols::addClass_name(), vmSymbols::class_void_signature());
1074   if (m == NULL || m->is_static()) {
1075     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodException(),
1076       "java.lang.ClassLoader.addClass", false);
1077   }
1078   Universe::_loader_addClass_cache->init(
1079     SystemDictionary::ClassLoader_klass(), m, CHECK_false);
1080 
1081   // The folowing is initializing converter functions for serialization in
1082   // JVM.cpp. If we clean up the StrictMath code above we may want to find
1083   // a better solution for this as well.
1084   initialize_converter_functions();
1085 
1086   // This needs to be done before the first scavenge/gc, since
1087   // it's an input to soft ref clearing policy.
1088   {
1089     MutexLocker x(Heap_lock);
1090     Universe::update_heap_info_at_gc();
1091   }
1092 
1093   // ("weak") refs processing infrastructure initialization
1094   Universe::heap()->post_initialize();
1095 
1096   // Initialize performance counters for metaspaces
1097   MetaspaceCounters::initialize_performance_counters();
1098 
1099   GC_locker::unlock();  // allow gc after bootstrapping
1100 
1101   MemoryService::set_universe_heap(Universe::_collectedHeap);
1102   return true;
1103 }
1104 
1105 
1106 void Universe::compute_base_vtable_size() {
1107   _base_vtable_size = ClassLoader::compute_Object_vtable();
1108 }
1109 
1110 
1111 // %%% The Universe::flush_foo methods belong in CodeCache.
1112 
1113 // Flushes compiled methods dependent on dependee.
1114 void Universe::flush_dependents_on(instanceKlassHandle dependee) {
1115   assert_lock_strong(Compile_lock);
1116 
1117   if (CodeCache::number_of_nmethods_with_dependencies() == 0) return;
1118 
1119   // CodeCache can only be updated by a thread_in_VM and they will all be
1120   // stopped dring the safepoint so CodeCache will be safe to update without
1121   // holding the CodeCache_lock.
1122 
1123   KlassDepChange changes(dependee);
1124 
1125   // Compute the dependent nmethods
1126   if (CodeCache::mark_for_deoptimization(changes) > 0) {
1127     // At least one nmethod has been marked for deoptimization
1128     VM_Deoptimize op;
1129     VMThread::execute(&op);
1130   }
1131 }
1132 
1133 // Flushes compiled methods dependent on a particular CallSite
1134 // instance when its target is different than the given MethodHandle.
1135 void Universe::flush_dependents_on(Handle call_site, Handle method_handle) {
1136   assert_lock_strong(Compile_lock);
1137 
1138   if (CodeCache::number_of_nmethods_with_dependencies() == 0) return;
1139 
1140   // CodeCache can only be updated by a thread_in_VM and they will all be
1141   // stopped dring the safepoint so CodeCache will be safe to update without
1142   // holding the CodeCache_lock.
1143 
1144   CallSiteDepChange changes(call_site(), method_handle());
1145 
1146   // Compute the dependent nmethods that have a reference to a
1147   // CallSite object.  We use InstanceKlass::mark_dependent_nmethod
1148   // directly instead of CodeCache::mark_for_deoptimization because we
1149   // want dependents on the call site class only not all classes in
1150   // the ContextStream.
1151   int marked = 0;
1152   {
1153     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1154     InstanceKlass* call_site_klass = InstanceKlass::cast(call_site->klass());
1155     marked = call_site_klass->mark_dependent_nmethods(changes);
1156   }
1157   if (marked > 0) {
1158     // At least one nmethod has been marked for deoptimization
1159     VM_Deoptimize op;
1160     VMThread::execute(&op);
1161   }
1162 }
1163 
1164 #ifdef HOTSWAP
1165 // Flushes compiled methods dependent on dependee in the evolutionary sense
1166 void Universe::flush_evol_dependents_on(instanceKlassHandle ev_k_h) {
1167   // --- Compile_lock is not held. However we are at a safepoint.
1168   assert_locked_or_safepoint(Compile_lock);
1169   if (CodeCache::number_of_nmethods_with_dependencies() == 0) return;
1170 
1171   // CodeCache can only be updated by a thread_in_VM and they will all be
1172   // stopped dring the safepoint so CodeCache will be safe to update without
1173   // holding the CodeCache_lock.
1174 
1175   // Compute the dependent nmethods
1176   if (CodeCache::mark_for_evol_deoptimization(ev_k_h) > 0) {
1177     // At least one nmethod has been marked for deoptimization
1178 
1179     // All this already happens inside a VM_Operation, so we'll do all the work here.
1180     // Stuff copied from VM_Deoptimize and modified slightly.
1181 
1182     // We do not want any GCs to happen while we are in the middle of this VM operation
1183     ResourceMark rm;
1184     DeoptimizationMarker dm;
1185 
1186     // Deoptimize all activations depending on marked nmethods
1187     Deoptimization::deoptimize_dependents();
1188 
1189     // Make the dependent methods not entrant (in VM_Deoptimize they are made zombies)
1190     CodeCache::make_marked_nmethods_not_entrant();
1191   }
1192 }
1193 #endif // HOTSWAP
1194 
1195 
1196 // Flushes compiled methods dependent on dependee
1197 void Universe::flush_dependents_on_method(methodHandle m_h) {
1198   // --- Compile_lock is not held. However we are at a safepoint.
1199   assert_locked_or_safepoint(Compile_lock);
1200 
1201   // CodeCache can only be updated by a thread_in_VM and they will all be
1202   // stopped dring the safepoint so CodeCache will be safe to update without
1203   // holding the CodeCache_lock.
1204 
1205   // Compute the dependent nmethods
1206   if (CodeCache::mark_for_deoptimization(m_h()) > 0) {
1207     // At least one nmethod has been marked for deoptimization
1208 
1209     // All this already happens inside a VM_Operation, so we'll do all the work here.
1210     // Stuff copied from VM_Deoptimize and modified slightly.
1211 
1212     // We do not want any GCs to happen while we are in the middle of this VM operation
1213     ResourceMark rm;
1214     DeoptimizationMarker dm;
1215 
1216     // Deoptimize all activations depending on marked nmethods
1217     Deoptimization::deoptimize_dependents();
1218 
1219     // Make the dependent methods not entrant (in VM_Deoptimize they are made zombies)
1220     CodeCache::make_marked_nmethods_not_entrant();
1221   }
1222 }
1223 
1224 void Universe::print() {
1225   print_on(gclog_or_tty);
1226 }
1227 
1228 void Universe::print_on(outputStream* st, bool extended) {
1229   st->print_cr("Heap");
1230   if (!extended) {
1231     heap()->print_on(st);
1232   } else {
1233     heap()->print_extended_on(st);
1234   }
1235 }
1236 
1237 void Universe::print_heap_at_SIGBREAK() {
1238   if (PrintHeapAtSIGBREAK) {
1239     MutexLocker hl(Heap_lock);
1240     print_on(tty);
1241     tty->cr();
1242     tty->flush();
1243   }
1244 }
1245 
1246 void Universe::print_heap_before_gc(outputStream* st, bool ignore_extended) {
1247   st->print_cr("{Heap before GC invocations=%u (full %u):",
1248                heap()->total_collections(),
1249                heap()->total_full_collections());
1250   if (!PrintHeapAtGCExtended || ignore_extended) {
1251     heap()->print_on(st);
1252   } else {
1253     heap()->print_extended_on(st);
1254   }
1255 }
1256 
1257 void Universe::print_heap_after_gc(outputStream* st, bool ignore_extended) {
1258   st->print_cr("Heap after GC invocations=%u (full %u):",
1259                heap()->total_collections(),
1260                heap()->total_full_collections());
1261   if (!PrintHeapAtGCExtended || ignore_extended) {
1262     heap()->print_on(st);
1263   } else {
1264     heap()->print_extended_on(st);
1265   }
1266   st->print_cr("}");
1267 }
1268 
1269 void Universe::verify(VerifyOption option, const char* prefix, bool silent) {
1270   // The use of _verify_in_progress is a temporary work around for
1271   // 6320749.  Don't bother with a creating a class to set and clear
1272   // it since it is only used in this method and the control flow is
1273   // straight forward.
1274   _verify_in_progress = true;
1275 
1276   COMPILER2_PRESENT(
1277     assert(!DerivedPointerTable::is_active(),
1278          "DPT should not be active during verification "
1279          "(of thread stacks below)");
1280   )
1281 
1282   ResourceMark rm;
1283   HandleMark hm;  // Handles created during verification can be zapped
1284   _verify_count++;
1285 
1286   if (!silent) gclog_or_tty->print(prefix);
1287   if (!silent) gclog_or_tty->print("[Verifying ");
1288   if (!silent) gclog_or_tty->print("threads ");
1289   Threads::verify();
1290   if (!silent) gclog_or_tty->print("heap ");
1291   heap()->verify(silent, option);
1292   if (!silent) gclog_or_tty->print("syms ");
1293   SymbolTable::verify();
1294   if (!silent) gclog_or_tty->print("strs ");
1295   StringTable::verify();
1296   {
1297     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1298     if (!silent) gclog_or_tty->print("zone ");
1299     CodeCache::verify();
1300   }
1301   if (!silent) gclog_or_tty->print("dict ");
1302   SystemDictionary::verify();
1303 #ifndef PRODUCT
1304   if (!silent) gclog_or_tty->print("cldg ");
1305   ClassLoaderDataGraph::verify();
1306 #endif
1307   if (!silent) gclog_or_tty->print("metaspace chunks ");
1308   MetaspaceAux::verify_free_chunks();
1309   if (!silent) gclog_or_tty->print("hand ");
1310   JNIHandles::verify();
1311   if (!silent) gclog_or_tty->print("C-heap ");
1312   os::check_heap();
1313   if (!silent) gclog_or_tty->print("code cache ");
1314   CodeCache::verify_oops();
1315   if (!silent) gclog_or_tty->print_cr("]");
1316 
1317   _verify_in_progress = false;
1318 }
1319 
1320 // Oop verification (see MacroAssembler::verify_oop)
1321 
1322 static uintptr_t _verify_oop_data[2]   = {0, (uintptr_t)-1};
1323 static uintptr_t _verify_klass_data[2] = {0, (uintptr_t)-1};
1324 
1325 
1326 #ifndef PRODUCT
1327 
1328 static void calculate_verify_data(uintptr_t verify_data[2],
1329                                   HeapWord* low_boundary,
1330                                   HeapWord* high_boundary) {
1331   assert(low_boundary < high_boundary, "bad interval");
1332 
1333   // decide which low-order bits we require to be clear:
1334   size_t alignSize = MinObjAlignmentInBytes;
1335   size_t min_object_size = CollectedHeap::min_fill_size();
1336 
1337   // make an inclusive limit:
1338   uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;
1339   uintptr_t min = (uintptr_t)low_boundary;
1340   assert(min < max, "bad interval");
1341   uintptr_t diff = max ^ min;
1342 
1343   // throw away enough low-order bits to make the diff vanish
1344   uintptr_t mask = (uintptr_t)(-1);
1345   while ((mask & diff) != 0)
1346     mask <<= 1;
1347   uintptr_t bits = (min & mask);
1348   assert(bits == (max & mask), "correct mask");
1349   // check an intermediate value between min and max, just to make sure:
1350   assert(bits == ((min + (max-min)/2) & mask), "correct mask");
1351 
1352   // require address alignment, too:
1353   mask |= (alignSize - 1);
1354 
1355   if (!(verify_data[0] == 0 && verify_data[1] == (uintptr_t)-1)) {
1356     assert(verify_data[0] == mask && verify_data[1] == bits, "mask stability");
1357   }
1358   verify_data[0] = mask;
1359   verify_data[1] = bits;
1360 }
1361 
1362 // Oop verification (see MacroAssembler::verify_oop)
1363 
1364 uintptr_t Universe::verify_oop_mask() {
1365   MemRegion m = heap()->reserved_region();
1366   calculate_verify_data(_verify_oop_data,
1367                         m.start(),
1368                         m.end());
1369   return _verify_oop_data[0];
1370 }
1371 
1372 
1373 
1374 uintptr_t Universe::verify_oop_bits() {
1375   verify_oop_mask();
1376   return _verify_oop_data[1];
1377 }
1378 
1379 uintptr_t Universe::verify_mark_mask() {
1380   return markOopDesc::lock_mask_in_place;
1381 }
1382 
1383 uintptr_t Universe::verify_mark_bits() {
1384   intptr_t mask = verify_mark_mask();
1385   intptr_t bits = (intptr_t)markOopDesc::prototype();
1386   assert((bits & ~mask) == 0, "no stray header bits");
1387   return bits;
1388 }
1389 #endif // PRODUCT
1390 
1391 
1392 void Universe::compute_verify_oop_data() {
1393   verify_oop_mask();
1394   verify_oop_bits();
1395   verify_mark_mask();
1396   verify_mark_bits();
1397 }
1398 
1399 
1400 void CommonMethodOopCache::init(Klass* k, Method* m, TRAPS) {
1401   if (!UseSharedSpaces) {
1402     _klass = k;
1403   }
1404 #ifndef PRODUCT
1405   else {
1406     // sharing initilization should have already set up _klass
1407     assert(_klass != NULL, "just checking");
1408   }
1409 #endif
1410 
1411   _method_idnum = m->method_idnum();
1412   assert(_method_idnum >= 0, "sanity check");
1413 }
1414 
1415 
1416 ActiveMethodOopsCache::~ActiveMethodOopsCache() {
1417   if (_prev_methods != NULL) {
1418     delete _prev_methods;
1419     _prev_methods = NULL;
1420   }
1421 }
1422 
1423 
1424 void ActiveMethodOopsCache::add_previous_version(Method* method) {
1425   assert(Thread::current()->is_VM_thread(),
1426     "only VMThread can add previous versions");
1427 
1428   // Only append the previous method if it is executing on the stack.
1429   if (method->on_stack()) {
1430 
1431     if (_prev_methods == NULL) {
1432       // This is the first previous version so make some space.
1433       // Start with 2 elements under the assumption that the class
1434       // won't be redefined much.
1435       _prev_methods = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Method*>(2, true);
1436     }
1437 
1438     // RC_TRACE macro has an embedded ResourceMark
1439     RC_TRACE(0x00000100,
1440       ("add: %s(%s): adding prev version ref for cached method @%d",
1441         method->name()->as_C_string(), method->signature()->as_C_string(),
1442         _prev_methods->length()));
1443 
1444     _prev_methods->append(method);
1445   }
1446 
1447 
1448   // Since the caller is the VMThread and we are at a safepoint, this is a good
1449   // time to clear out unused method references.
1450 
1451   if (_prev_methods == NULL) return;
1452 
1453   for (int i = _prev_methods->length() - 1; i >= 0; i--) {
1454     Method* method = _prev_methods->at(i);
1455     assert(method != NULL, "weak method ref was unexpectedly cleared");
1456 
1457     if (!method->on_stack()) {
1458       // This method isn't running anymore so remove it
1459       _prev_methods->remove_at(i);
1460       MetadataFactory::free_metadata(method->method_holder()->class_loader_data(), method);
1461     } else {
1462       // RC_TRACE macro has an embedded ResourceMark
1463       RC_TRACE(0x00000400,
1464         ("add: %s(%s): previous cached method @%d is alive",
1465          method->name()->as_C_string(), method->signature()->as_C_string(), i));
1466     }
1467   }
1468 } // end add_previous_version()
1469 
1470 
1471 bool ActiveMethodOopsCache::is_same_method(const Method* method) const {
1472   InstanceKlass* ik = InstanceKlass::cast(klass());
1473   const Method* check_method = ik->method_with_idnum(method_idnum());
1474   assert(check_method != NULL, "sanity check");
1475   if (check_method == method) {
1476     // done with the easy case
1477     return true;
1478   }
1479 
1480   if (_prev_methods != NULL) {
1481     // The cached method has been redefined at least once so search
1482     // the previous versions for a match.
1483     for (int i = 0; i < _prev_methods->length(); i++) {
1484       check_method = _prev_methods->at(i);
1485       if (check_method == method) {
1486         // a previous version matches
1487         return true;
1488       }
1489     }
1490   }
1491 
1492   // either no previous versions or no previous version matched
1493   return false;
1494 }
1495 
1496 
1497 Method* LatestMethodOopCache::get_Method() {
1498   InstanceKlass* ik = InstanceKlass::cast(klass());
1499   Method* m = ik->method_with_idnum(method_idnum());
1500   assert(m != NULL, "sanity check");
1501   return m;
1502 }
1503 
1504 
1505 #ifdef ASSERT
1506 // Release dummy object(s) at bottom of heap
1507 bool Universe::release_fullgc_alot_dummy() {
1508   MutexLocker ml(FullGCALot_lock);
1509   if (_fullgc_alot_dummy_array != NULL) {
1510     if (_fullgc_alot_dummy_next >= _fullgc_alot_dummy_array->length()) {
1511       // No more dummies to release, release entire array instead
1512       _fullgc_alot_dummy_array = NULL;
1513       return false;
1514     }
1515     if (!UseConcMarkSweepGC) {
1516       // Release dummy at bottom of old generation
1517       _fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);
1518     }
1519     // Release dummy at bottom of permanent generation
1520     _fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);
1521   }
1522   return true;
1523 }
1524 
1525 #endif // ASSERT