1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)universe.cpp 1.361 07/09/01 18:01:02 JVM"
   3 #endif
   4 /*
   5  * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 # include "incls/_precompiled.incl"
  29 # include "incls/_universe.cpp.incl"
  30 
  31 // Known objects 
  32 klassOop Universe::_boolArrayKlassObj                 = NULL;
  33 klassOop Universe::_byteArrayKlassObj                 = NULL;
  34 klassOop Universe::_charArrayKlassObj                 = NULL;
  35 klassOop Universe::_intArrayKlassObj                  = NULL;
  36 klassOop Universe::_shortArrayKlassObj                = NULL;
  37 klassOop Universe::_longArrayKlassObj                 = NULL;
  38 klassOop Universe::_singleArrayKlassObj               = NULL;
  39 klassOop Universe::_doubleArrayKlassObj               = NULL;
  40 klassOop Universe::_typeArrayKlassObjs[T_VOID+1]      = { NULL /*, NULL...*/ };
  41 klassOop Universe::_objectArrayKlassObj               = NULL;
  42 klassOop Universe::_symbolKlassObj                    = NULL;
  43 klassOop Universe::_methodKlassObj                    = NULL;
  44 klassOop Universe::_constMethodKlassObj               = NULL;
  45 klassOop Universe::_methodDataKlassObj                = NULL;
  46 klassOop Universe::_klassKlassObj                     = NULL;
  47 klassOop Universe::_arrayKlassKlassObj                = NULL;
  48 klassOop Universe::_objArrayKlassKlassObj             = NULL;
  49 klassOop Universe::_typeArrayKlassKlassObj            = NULL;
  50 klassOop Universe::_instanceKlassKlassObj             = NULL;
  51 klassOop Universe::_constantPoolKlassObj              = NULL;
  52 klassOop Universe::_constantPoolCacheKlassObj         = NULL;
  53 klassOop Universe::_compiledICHolderKlassObj          = NULL;
  54 klassOop Universe::_systemObjArrayKlassObj            = NULL;
  55 oop Universe::_int_mirror                             =  NULL;
  56 oop Universe::_float_mirror                           =  NULL;
  57 oop Universe::_double_mirror                          =  NULL;
  58 oop Universe::_byte_mirror                            =  NULL;
  59 oop Universe::_bool_mirror                            =  NULL;
  60 oop Universe::_char_mirror                            =  NULL;
  61 oop Universe::_long_mirror                            =  NULL;
  62 oop Universe::_short_mirror                           =  NULL;
  63 oop Universe::_void_mirror                            =  NULL;
  64 oop Universe::_mirrors[T_VOID+1]                      =  { NULL /*, NULL...*/ };
  65 oop Universe::_main_thread_group                      = NULL;
  66 oop Universe::_system_thread_group                    = NULL;
  67 typeArrayOop Universe::_the_empty_byte_array          = NULL;
  68 typeArrayOop Universe::_the_empty_short_array         = NULL;
  69 typeArrayOop Universe::_the_empty_int_array           = NULL;
  70 objArrayOop Universe::_the_empty_system_obj_array     = NULL;
  71 objArrayOop Universe::_the_empty_class_klass_array    = NULL;
  72 objArrayOop Universe::_the_array_interfaces_array     = NULL;
  73 LatestMethodOopCache* Universe::_finalizer_register_cache = NULL;
  74 LatestMethodOopCache* Universe::_loader_addClass_cache    = NULL;
  75 ActiveMethodOopsCache* Universe::_reflect_invoke_cache    = NULL;
  76 oop Universe::_out_of_memory_error_java_heap          = NULL;
  77 oop Universe::_out_of_memory_error_perm_gen           = NULL;
  78 oop Universe::_out_of_memory_error_array_size         = NULL;
  79 oop Universe::_out_of_memory_error_gc_overhead_limit  = NULL;
  80 objArrayOop Universe::_preallocated_out_of_memory_error_array = NULL;
  81 volatile jint Universe::_preallocated_out_of_memory_error_avail_count = 0;
  82 bool Universe::_verify_in_progress                    = false;
  83 oop Universe::_null_ptr_exception_instance            = NULL;
  84 oop Universe::_arithmetic_exception_instance          = NULL;
  85 oop Universe::_virtual_machine_error_instance         = NULL;
  86 oop Universe::_vm_exception                           = NULL;
  87 oop Universe::_emptySymbol                            = NULL;
  88 
  89 // These variables are guarded by FullGCALot_lock.
  90 debug_only(objArrayOop Universe::_fullgc_alot_dummy_array = NULL;)
  91 debug_only(int Universe::_fullgc_alot_dummy_next      = 0;)
  92 
  93 
  94 // Heap  
  95 int             Universe::_verify_count = 0;
  96 
  97 int             Universe::_base_vtable_size = 0;
  98 bool            Universe::_bootstrapping = false;
  99 bool            Universe::_fully_initialized = false;
 100 
 101 size_t          Universe::_heap_capacity_at_last_gc;
 102 size_t          Universe::_heap_used_at_last_gc;
 103 
 104 CollectedHeap*  Universe::_collectedHeap = NULL;
 105 
 106 
 107 void Universe::basic_type_classes_do(void f(klassOop)) {
 108   f(boolArrayKlassObj());
 109   f(byteArrayKlassObj());
 110   f(charArrayKlassObj());
 111   f(intArrayKlassObj());
 112   f(shortArrayKlassObj());
 113   f(longArrayKlassObj());
 114   f(singleArrayKlassObj());
 115   f(doubleArrayKlassObj());
 116 }
 117 
 118 
 119 void Universe::system_classes_do(void f(klassOop)) {
 120   f(symbolKlassObj());
 121   f(methodKlassObj());
 122   f(constMethodKlassObj());
 123   f(methodDataKlassObj());
 124   f(klassKlassObj());
 125   f(arrayKlassKlassObj());
 126   f(objArrayKlassKlassObj());
 127   f(typeArrayKlassKlassObj());
 128   f(instanceKlassKlassObj());
 129   f(constantPoolKlassObj());
 130   f(systemObjArrayKlassObj());
 131 }
 132 
 133 void Universe::oops_do(OopClosure* f, bool do_all) {
 134 
 135   f->do_oop((oop*) &_int_mirror);
 136   f->do_oop((oop*) &_float_mirror);
 137   f->do_oop((oop*) &_double_mirror);
 138   f->do_oop((oop*) &_byte_mirror);
 139   f->do_oop((oop*) &_bool_mirror);
 140   f->do_oop((oop*) &_char_mirror);
 141   f->do_oop((oop*) &_long_mirror);
 142   f->do_oop((oop*) &_short_mirror);
 143   f->do_oop((oop*) &_void_mirror);
 144 
 145   // It's important to iterate over these guys even if they are null,
 146   // since that's how shared heaps are restored.
 147   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
 148     f->do_oop((oop*) &_mirrors[i]);
 149   }
 150   assert(_mirrors[0] == NULL && _mirrors[T_BOOLEAN - 1] == NULL, "checking");
 151 
 152   // %%% Consider moving those "shared oops" over here with the others.
 153   f->do_oop((oop*)&_boolArrayKlassObj);
 154   f->do_oop((oop*)&_byteArrayKlassObj);
 155   f->do_oop((oop*)&_charArrayKlassObj);
 156   f->do_oop((oop*)&_intArrayKlassObj);
 157   f->do_oop((oop*)&_shortArrayKlassObj);
 158   f->do_oop((oop*)&_longArrayKlassObj);
 159   f->do_oop((oop*)&_singleArrayKlassObj);
 160   f->do_oop((oop*)&_doubleArrayKlassObj);
 161   f->do_oop((oop*)&_objectArrayKlassObj);
 162   {
 163     for (int i = 0; i < T_VOID+1; i++) {
 164       if (_typeArrayKlassObjs[i] != NULL) {
 165         assert(i >= T_BOOLEAN, "checking");
 166         f->do_oop((oop*)&_typeArrayKlassObjs[i]);
 167       } else if (do_all) {
 168         f->do_oop((oop*)&_typeArrayKlassObjs[i]);
 169       }
 170     }
 171   }
 172   f->do_oop((oop*)&_symbolKlassObj);
 173   f->do_oop((oop*)&_methodKlassObj);
 174   f->do_oop((oop*)&_constMethodKlassObj);
 175   f->do_oop((oop*)&_methodDataKlassObj);
 176   f->do_oop((oop*)&_klassKlassObj);
 177   f->do_oop((oop*)&_arrayKlassKlassObj);
 178   f->do_oop((oop*)&_objArrayKlassKlassObj);
 179   f->do_oop((oop*)&_typeArrayKlassKlassObj);
 180   f->do_oop((oop*)&_instanceKlassKlassObj);
 181   f->do_oop((oop*)&_constantPoolKlassObj);
 182   f->do_oop((oop*)&_constantPoolCacheKlassObj);
 183   f->do_oop((oop*)&_compiledICHolderKlassObj);
 184   f->do_oop((oop*)&_systemObjArrayKlassObj);
 185   f->do_oop((oop*)&_the_empty_byte_array);
 186   f->do_oop((oop*)&_the_empty_short_array);
 187   f->do_oop((oop*)&_the_empty_int_array);
 188   f->do_oop((oop*)&_the_empty_system_obj_array);    
 189   f->do_oop((oop*)&_the_empty_class_klass_array);    
 190   f->do_oop((oop*)&_the_array_interfaces_array);    
 191   _finalizer_register_cache->oops_do(f);
 192   _loader_addClass_cache->oops_do(f);
 193   _reflect_invoke_cache->oops_do(f);
 194   f->do_oop((oop*)&_out_of_memory_error_java_heap);
 195   f->do_oop((oop*)&_out_of_memory_error_perm_gen);
 196   f->do_oop((oop*)&_out_of_memory_error_array_size);
 197   f->do_oop((oop*)&_out_of_memory_error_gc_overhead_limit);
 198   if (_preallocated_out_of_memory_error_array != (oop)NULL) {   // NULL when DumpSharedSpaces
 199     f->do_oop((oop*)&_preallocated_out_of_memory_error_array);
 200   } 
 201   f->do_oop((oop*)&_null_ptr_exception_instance);
 202   f->do_oop((oop*)&_arithmetic_exception_instance);
 203   f->do_oop((oop*)&_virtual_machine_error_instance);
 204   f->do_oop((oop*)&_main_thread_group);
 205   f->do_oop((oop*)&_system_thread_group);
 206   f->do_oop((oop*)&_vm_exception);
 207   f->do_oop((oop*)&_emptySymbol);
 208   debug_only(f->do_oop((oop*)&_fullgc_alot_dummy_array);)
 209 }
 210 
 211 
 212 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
 213   if (size < alignment || size % alignment != 0) {
 214     ResourceMark rm;
 215     stringStream st;
 216     st.print("Size of %s (%ld bytes) must be aligned to %ld bytes", name, size, alignment);
 217     char* error = st.as_string();
 218     vm_exit_during_initialization(error);
 219   }
 220 }
 221 
 222 
 223 void Universe::genesis(TRAPS) {
 224   ResourceMark rm;
 225   { FlagSetting fs(_bootstrapping, true);
 226       
 227     { MutexLocker mc(Compile_lock);
 228 
 229       // determine base vtable size; without that we cannot create the array klasses
 230       compute_base_vtable_size();
 231 
 232       if (!UseSharedSpaces) {
 233         _klassKlassObj          = klassKlass::create_klass(CHECK);
 234         _arrayKlassKlassObj     = arrayKlassKlass::create_klass(CHECK);
 235 
 236         _objArrayKlassKlassObj  = objArrayKlassKlass::create_klass(CHECK);
 237         _instanceKlassKlassObj  = instanceKlassKlass::create_klass(CHECK);
 238         _typeArrayKlassKlassObj = typeArrayKlassKlass::create_klass(CHECK);
 239 
 240         _symbolKlassObj         = symbolKlass::create_klass(CHECK);
 241 
 242         _emptySymbol            = oopFactory::new_symbol("", CHECK);
 243 
 244         _boolArrayKlassObj      = typeArrayKlass::create_klass(T_BOOLEAN, sizeof(jboolean), CHECK);
 245         _charArrayKlassObj      = typeArrayKlass::create_klass(T_CHAR,    sizeof(jchar),    CHECK);
 246         _singleArrayKlassObj    = typeArrayKlass::create_klass(T_FLOAT,   sizeof(jfloat),   CHECK);
 247         _doubleArrayKlassObj    = typeArrayKlass::create_klass(T_DOUBLE,  sizeof(jdouble),  CHECK);
 248         _byteArrayKlassObj      = typeArrayKlass::create_klass(T_BYTE,    sizeof(jbyte),    CHECK);
 249         _shortArrayKlassObj     = typeArrayKlass::create_klass(T_SHORT,   sizeof(jshort),   CHECK);
 250         _intArrayKlassObj       = typeArrayKlass::create_klass(T_INT,     sizeof(jint),     CHECK);
 251         _longArrayKlassObj      = typeArrayKlass::create_klass(T_LONG,    sizeof(jlong),    CHECK);
 252 
 253         _typeArrayKlassObjs[T_BOOLEAN] = _boolArrayKlassObj;
 254         _typeArrayKlassObjs[T_CHAR]    = _charArrayKlassObj;
 255         _typeArrayKlassObjs[T_FLOAT]   = _singleArrayKlassObj;
 256         _typeArrayKlassObjs[T_DOUBLE]  = _doubleArrayKlassObj;
 257         _typeArrayKlassObjs[T_BYTE]    = _byteArrayKlassObj;
 258         _typeArrayKlassObjs[T_SHORT]   = _shortArrayKlassObj;
 259         _typeArrayKlassObjs[T_INT]     = _intArrayKlassObj;
 260         _typeArrayKlassObjs[T_LONG]    = _longArrayKlassObj;
 261 
 262         _methodKlassObj         = methodKlass::create_klass(CHECK);
 263         _constMethodKlassObj    = constMethodKlass::create_klass(CHECK);
 264         _methodDataKlassObj     = methodDataKlass::create_klass(CHECK);
 265         _constantPoolKlassObj       = constantPoolKlass::create_klass(CHECK);
 266         _constantPoolCacheKlassObj  = constantPoolCacheKlass::create_klass(CHECK);
 267 
 268         _compiledICHolderKlassObj   = compiledICHolderKlass::create_klass(CHECK);
 269         _systemObjArrayKlassObj     = objArrayKlassKlass::cast(objArrayKlassKlassObj())->allocate_system_objArray_klass(CHECK);
 270 
 271         _the_empty_byte_array      = oopFactory::new_permanent_byteArray(0, CHECK);
 272         _the_empty_short_array      = oopFactory::new_permanent_shortArray(0, CHECK);
 273         _the_empty_int_array        = oopFactory::new_permanent_intArray(0, CHECK);
 274         _the_empty_system_obj_array = oopFactory::new_system_objArray(0, CHECK);
 275 
 276         _the_array_interfaces_array = oopFactory::new_system_objArray(2, CHECK);
 277         _vm_exception               = oopFactory::new_symbol("vm exception holder", CHECK);
 278       } else {
 279 
 280         FileMapInfo *mapinfo = FileMapInfo::current_info();
 281         char* buffer = mapinfo->region_base(CompactingPermGenGen::md);
 282         void** vtbl_list = (void**)buffer;
 283         init_self_patching_vtbl_list(vtbl_list, 
 284                                      CompactingPermGenGen::vtbl_list_size);
 285       }
 286     }
 287 
 288     vmSymbols::initialize(CHECK);
 289 
 290     SystemDictionary::initialize(CHECK);
 291 
 292     klassOop ok = SystemDictionary::object_klass();
 293 
 294     if (UseSharedSpaces) {
 295       // Verify shared interfaces array.
 296       assert(_the_array_interfaces_array->obj_at(0) ==
 297              SystemDictionary::cloneable_klass(), "u3");
 298       assert(_the_array_interfaces_array->obj_at(1) ==
 299              SystemDictionary::serializable_klass(), "u3");
 300 
 301       // Verify element klass for system obj array klass
 302       assert(objArrayKlass::cast(_systemObjArrayKlassObj)->element_klass() == ok, "u1");
 303       assert(objArrayKlass::cast(_systemObjArrayKlassObj)->bottom_klass() == ok, "u2");
 304 
 305       // Verify super class for the classes created above
 306       assert(Klass::cast(boolArrayKlassObj()     )->super() == ok, "u3");
 307       assert(Klass::cast(charArrayKlassObj()     )->super() == ok, "u3");
 308       assert(Klass::cast(singleArrayKlassObj()   )->super() == ok, "u3");
 309       assert(Klass::cast(doubleArrayKlassObj()   )->super() == ok, "u3");
 310       assert(Klass::cast(byteArrayKlassObj()     )->super() == ok, "u3");
 311       assert(Klass::cast(shortArrayKlassObj()    )->super() == ok, "u3");
 312       assert(Klass::cast(intArrayKlassObj()      )->super() == ok, "u3");
 313       assert(Klass::cast(longArrayKlassObj()     )->super() == ok, "u3");
 314       assert(Klass::cast(constantPoolKlassObj()  )->super() == ok, "u3");
 315       assert(Klass::cast(systemObjArrayKlassObj())->super() == ok, "u3");
 316     } else {
 317       // Set up shared interfaces array.  (Do this before supers are set up.)
 318       _the_array_interfaces_array->obj_at_put(0, SystemDictionary::cloneable_klass());
 319       _the_array_interfaces_array->obj_at_put(1, SystemDictionary::serializable_klass());
 320 
 321       // Set element klass for system obj array klass
 322       objArrayKlass::cast(_systemObjArrayKlassObj)->set_element_klass(ok);
 323       objArrayKlass::cast(_systemObjArrayKlassObj)->set_bottom_klass(ok);
 324 
 325       // Set super class for the classes created above
 326       Klass::cast(boolArrayKlassObj()     )->initialize_supers(ok, CHECK);
 327       Klass::cast(charArrayKlassObj()     )->initialize_supers(ok, CHECK);
 328       Klass::cast(singleArrayKlassObj()   )->initialize_supers(ok, CHECK);
 329       Klass::cast(doubleArrayKlassObj()   )->initialize_supers(ok, CHECK);
 330       Klass::cast(byteArrayKlassObj()     )->initialize_supers(ok, CHECK);
 331       Klass::cast(shortArrayKlassObj()    )->initialize_supers(ok, CHECK);
 332       Klass::cast(intArrayKlassObj()      )->initialize_supers(ok, CHECK);
 333       Klass::cast(longArrayKlassObj()     )->initialize_supers(ok, CHECK);
 334       Klass::cast(constantPoolKlassObj()  )->initialize_supers(ok, CHECK);
 335       Klass::cast(systemObjArrayKlassObj())->initialize_supers(ok, CHECK);
 336       Klass::cast(boolArrayKlassObj()     )->set_super(ok);
 337       Klass::cast(charArrayKlassObj()     )->set_super(ok);
 338       Klass::cast(singleArrayKlassObj()   )->set_super(ok);
 339       Klass::cast(doubleArrayKlassObj()   )->set_super(ok);
 340       Klass::cast(byteArrayKlassObj()     )->set_super(ok);
 341       Klass::cast(shortArrayKlassObj()    )->set_super(ok);
 342       Klass::cast(intArrayKlassObj()      )->set_super(ok);
 343       Klass::cast(longArrayKlassObj()     )->set_super(ok);
 344       Klass::cast(constantPoolKlassObj()  )->set_super(ok);
 345       Klass::cast(systemObjArrayKlassObj())->set_super(ok);
 346     }
 347 
 348     Klass::cast(boolArrayKlassObj()     )->append_to_sibling_list();
 349     Klass::cast(charArrayKlassObj()     )->append_to_sibling_list();
 350     Klass::cast(singleArrayKlassObj()   )->append_to_sibling_list();
 351     Klass::cast(doubleArrayKlassObj()   )->append_to_sibling_list();
 352     Klass::cast(byteArrayKlassObj()     )->append_to_sibling_list();
 353     Klass::cast(shortArrayKlassObj()    )->append_to_sibling_list();
 354     Klass::cast(intArrayKlassObj()      )->append_to_sibling_list();
 355     Klass::cast(longArrayKlassObj()     )->append_to_sibling_list();
 356     Klass::cast(constantPoolKlassObj()  )->append_to_sibling_list();
 357     Klass::cast(systemObjArrayKlassObj())->append_to_sibling_list();
 358   } // end of core bootstrapping
 359 
 360   // Initialize _objectArrayKlass after core bootstraping to make
 361   // sure the super class is set up properly for _objectArrayKlass.
 362   _objectArrayKlassObj = instanceKlass::
 363     cast(SystemDictionary::object_klass())->array_klass(1, CHECK);
 364   // Add the class to the class hierarchy manually to make sure that
 365   // its vtable is initialized after core bootstrapping is completed.
 366   Klass::cast(_objectArrayKlassObj)->append_to_sibling_list();
 367 
 368   // Compute is_jdk version flags. 
 369   // Only 1.3 or later has the java.lang.Shutdown class.
 370   // Only 1.4 or later has the java.lang.CharSequence interface.
 371   // Only 1.5 or later has the java.lang.management.MemoryUsage class.
 372   if (JDK_Version::is_pre_jdk16_version()) {
 373     klassOop k = SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_management_MemoryUsage(), THREAD);
 374     CLEAR_PENDING_EXCEPTION; // ignore exceptions
 375     if (k == NULL) {
 376       k = SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_CharSequence(), THREAD);
 377       CLEAR_PENDING_EXCEPTION; // ignore exceptions
 378       if (k == NULL) {
 379         k = SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_Shutdown(), THREAD);
 380         CLEAR_PENDING_EXCEPTION; // ignore exceptions
 381         if (k == NULL) {
 382           JDK_Version::set_jdk12x_version();
 383         } else {
 384           JDK_Version::set_jdk13x_version();
 385         }
 386       } else {
 387           JDK_Version::set_jdk14x_version();
 388       }
 389     } else {
 390           JDK_Version::set_jdk15x_version();
 391     }
 392   }
 393 
 394   #ifdef ASSERT
 395   if (FullGCALot) {
 396     // Allocate an array of dummy objects.
 397     // We'd like these to be at the bottom of the old generation,
 398     // so that when we free one and then collect,
 399     // (almost) the whole heap moves
 400     // and we find out if we actually update all the oops correctly.
 401     // But we can't allocate directly in the old generation,
 402     // so we allocate wherever, and hope that the first collection
 403     // moves these objects to the bottom of the old generation.
 404     // We can allocate directly in the permanent generation, so we do.
 405     int size;
 406     if (UseConcMarkSweepGC) {
 407       warning("Using +FullGCALot with concurrent mark sweep gc "
 408               "will not force all objects to relocate");
 409       size = FullGCALotDummies;
 410     } else {
 411       size = FullGCALotDummies * 2;
 412     }
 413     objArrayOop    naked_array = oopFactory::new_system_objArray(size, CHECK);
 414     objArrayHandle dummy_array(THREAD, naked_array);
 415     int i = 0;
 416     while (i < size) {
 417       if (!UseConcMarkSweepGC) {
 418         // Allocate dummy in old generation
 419         oop dummy = instanceKlass::cast(SystemDictionary::object_klass())->allocate_instance(CHECK);
 420         dummy_array->obj_at_put(i++, dummy);
 421       }
 422       // Allocate dummy in permanent generation
 423       oop dummy = instanceKlass::cast(SystemDictionary::object_klass())->allocate_permanent_instance(CHECK);
 424       dummy_array->obj_at_put(i++, dummy);
 425     }
 426     {
 427       // Only modify the global variable inside the mutex.
 428       // If we had a race to here, the other dummy_array instances
 429       // and their elements just get dropped on the floor, which is fine.
 430       MutexLocker ml(FullGCALot_lock);
 431       if (_fullgc_alot_dummy_array == NULL) {
 432         _fullgc_alot_dummy_array = dummy_array();
 433       }
 434     }
 435     assert(i == _fullgc_alot_dummy_array->length(), "just checking");
 436   }
 437   #endif
 438 }    
 439 
 440 
 441 static inline void add_vtable(void** list, int* n, Klass* o, int count) {
 442   list[(*n)++] = *(void**)&o->vtbl_value();
 443   guarantee((*n) <= count, "vtable list too small.");
 444 }
 445 
 446 
 447 void Universe::init_self_patching_vtbl_list(void** list, int count) {
 448   int n = 0;
 449   { klassKlass o;             add_vtable(list, &n, &o, count); }
 450   { arrayKlassKlass o;        add_vtable(list, &n, &o, count); }
 451   { objArrayKlassKlass o;     add_vtable(list, &n, &o, count); }
 452   { instanceKlassKlass o;     add_vtable(list, &n, &o, count); }
 453   { instanceKlass o;          add_vtable(list, &n, &o, count); }
 454   { instanceRefKlass o;       add_vtable(list, &n, &o, count); }
 455   { typeArrayKlassKlass o;    add_vtable(list, &n, &o, count); }
 456   { symbolKlass o;            add_vtable(list, &n, &o, count); }
 457   { typeArrayKlass o;         add_vtable(list, &n, &o, count); }
 458   { methodKlass o;            add_vtable(list, &n, &o, count); }
 459   { constMethodKlass o;       add_vtable(list, &n, &o, count); }
 460   { constantPoolKlass o;      add_vtable(list, &n, &o, count); }
 461   { constantPoolCacheKlass o; add_vtable(list, &n, &o, count); }
 462   { objArrayKlass o;          add_vtable(list, &n, &o, count); }
 463   { methodDataKlass o;        add_vtable(list, &n, &o, count); }
 464   { compiledICHolderKlass o;  add_vtable(list, &n, &o, count); }
 465 }
 466 
 467 
 468 class FixupMirrorClosure: public ObjectClosure {
 469  public:
 470   void do_object(oop obj) {
 471     if (obj->is_klass()) {
 472       EXCEPTION_MARK;
 473       KlassHandle k(THREAD, klassOop(obj));
 474       // We will never reach the CATCH below since Exceptions::_throw will cause
 475       // the VM to exit if an exception is thrown during initialization
 476       java_lang_Class::create_mirror(k, CATCH);
 477       // This call unconditionally creates a new mirror for k,
 478       // and links in k's component_mirror field if k is an array.
 479       // If k is an objArray, k's element type must already have
 480       // a mirror.  In other words, this closure must process
 481       // the component type of an objArray k before it processes k.
 482       // This works because the permgen iterator presents arrays
 483       // and their component types in order of creation.
 484     }
 485   }
 486 };
 487 
 488 void Universe::initialize_basic_type_mirrors(TRAPS) {
 489   if (UseSharedSpaces) {
 490     assert(_int_mirror != NULL, "already loaded");
 491     assert(_void_mirror == _mirrors[T_VOID], "consistently loaded");
 492   } else {
 493 
 494     assert(_int_mirror==NULL, "basic type mirrors already initialized");
 495     _int_mirror     = 
 496       java_lang_Class::create_basic_type_mirror("int",    T_INT, CHECK);
 497     _float_mirror   = 
 498       java_lang_Class::create_basic_type_mirror("float",  T_FLOAT,   CHECK);
 499     _double_mirror  = 
 500       java_lang_Class::create_basic_type_mirror("double", T_DOUBLE,  CHECK);
 501     _byte_mirror    = 
 502       java_lang_Class::create_basic_type_mirror("byte",   T_BYTE, CHECK);
 503     _bool_mirror    = 
 504       java_lang_Class::create_basic_type_mirror("boolean",T_BOOLEAN, CHECK);
 505     _char_mirror    = 
 506       java_lang_Class::create_basic_type_mirror("char",   T_CHAR, CHECK);
 507     _long_mirror    = 
 508       java_lang_Class::create_basic_type_mirror("long",   T_LONG, CHECK);
 509     _short_mirror   = 
 510       java_lang_Class::create_basic_type_mirror("short",  T_SHORT,   CHECK);
 511     _void_mirror    = 
 512       java_lang_Class::create_basic_type_mirror("void",   T_VOID, CHECK);
 513   
 514     _mirrors[T_INT]     = _int_mirror;
 515     _mirrors[T_FLOAT]   = _float_mirror;
 516     _mirrors[T_DOUBLE]  = _double_mirror;
 517     _mirrors[T_BYTE]    = _byte_mirror;
 518     _mirrors[T_BOOLEAN] = _bool_mirror;
 519     _mirrors[T_CHAR]    = _char_mirror;
 520     _mirrors[T_LONG]    = _long_mirror;
 521     _mirrors[T_SHORT]   = _short_mirror;
 522     _mirrors[T_VOID]    = _void_mirror;
 523     //_mirrors[T_OBJECT]  = instanceKlass::cast(_object_klass)->java_mirror();
 524     //_mirrors[T_ARRAY]   = instanceKlass::cast(_object_klass)->java_mirror();
 525   }
 526 }
 527 
 528 void Universe::fixup_mirrors(TRAPS) {
 529   // Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly,
 530   // but we cannot do that for classes created before java.lang.Class is loaded. Here we simply
 531   // walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note
 532   // that the number of objects allocated at this point is very small.
 533   assert(SystemDictionary::class_klass_loaded(), "java.lang.Class should be loaded");
 534   FixupMirrorClosure blk;
 535   Universe::heap()->permanent_object_iterate(&blk);
 536 }
 537 
 538 
 539 static bool has_run_finalizers_on_exit = false;
 540 
 541 void Universe::run_finalizers_on_exit() {
 542   if (has_run_finalizers_on_exit) return;
 543   has_run_finalizers_on_exit = true;
 544 
 545   // Called on VM exit. This ought to be run in a separate thread.
 546   if (TraceReferenceGC) tty->print_cr("Callback to run finalizers on exit");
 547   { 
 548     PRESERVE_EXCEPTION_MARK;
 549     KlassHandle finalizer_klass(THREAD, SystemDictionary::finalizer_klass());
 550     JavaValue result(T_VOID);
 551     JavaCalls::call_static(
 552       &result, 
 553       finalizer_klass, 
 554       vmSymbolHandles::run_finalizers_on_exit_name(), 
 555       vmSymbolHandles::void_method_signature(),
 556       THREAD
 557     );
 558     // Ignore any pending exceptions
 559     CLEAR_PENDING_EXCEPTION;
 560   }
 561 }
 562 
 563 
 564 // initialize_vtable could cause gc if
 565 // 1) we specified true to initialize_vtable and
 566 // 2) this ran after gc was enabled
 567 // In case those ever change we use handles for oops
 568 void Universe::reinitialize_vtable_of(KlassHandle k_h, TRAPS) {  
 569   // init vtable of k and all subclasses
 570   Klass* ko = k_h()->klass_part();
 571   klassVtable* vt = ko->vtable();
 572   if (vt) vt->initialize_vtable(false, CHECK);
 573   if (ko->oop_is_instance()) {
 574     instanceKlass* ik = (instanceKlass*)ko;
 575     for (KlassHandle s_h(THREAD, ik->subklass()); s_h() != NULL; s_h = (THREAD, s_h()->klass_part()->next_sibling())) {
 576       reinitialize_vtable_of(s_h, CHECK);
 577     }
 578   }
 579 }
 580 
 581 
 582 void initialize_itable_for_klass(klassOop k, TRAPS) {
 583   instanceKlass::cast(k)->itable()->initialize_itable(false, CHECK);        
 584 }
 585 
 586 
 587 void Universe::reinitialize_itables(TRAPS) {
 588   SystemDictionary::classes_do(initialize_itable_for_klass, CHECK);
 589 
 590 }
 591 
 592 
 593 bool Universe::on_page_boundary(void* addr) {
 594   return ((uintptr_t) addr) % os::vm_page_size() == 0;
 595 }
 596 
 597 
 598 bool Universe::should_fill_in_stack_trace(Handle throwable) {
 599   // never attempt to fill in the stack trace of preallocated errors that do not have
 600   // backtrace. These errors are kept alive forever and may be "re-used" when all
 601   // preallocated errors with backtrace have been consumed. Also need to avoid
 602   // a potential loop which could happen if an out of memory occurs when attempting
 603   // to allocate the backtrace.
 604   return ((throwable() != Universe::_out_of_memory_error_java_heap) &&
 605           (throwable() != Universe::_out_of_memory_error_perm_gen)  &&
 606           (throwable() != Universe::_out_of_memory_error_array_size) &&
 607           (throwable() != Universe::_out_of_memory_error_gc_overhead_limit));
 608 }
 609 
 610 
 611 oop Universe::gen_out_of_memory_error(oop default_err) {
 612   // generate an out of memory error:
 613   // - if there is a preallocated error with backtrace available then return it wth
 614   //   a filled in stack trace.
 615   // - if there are no preallocated errors with backtrace available then return
 616   //   an error without backtrace.
 617   int next;
 618   if (_preallocated_out_of_memory_error_avail_count > 0) {
 619     next = (int)Atomic::add(-1, &_preallocated_out_of_memory_error_avail_count);
 620     assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");
 621   } else {
 622     next = -1;
 623   }
 624   if (next < 0) {
 625     // all preallocated errors have been used.
 626     // return default
 627     return default_err;
 628   } else {
 629     // get the error object at the slot and set set it to NULL so that the
 630     // array isn't keeping it alive anymore.
 631     oop exc = preallocated_out_of_memory_errors()->obj_at(next);
 632     assert(exc != NULL, "slot has been used already");
 633     preallocated_out_of_memory_errors()->obj_at_put(next, NULL);
 634 
 635     // use the message from the default error
 636     oop msg = java_lang_Throwable::message(default_err);
 637     assert(msg != NULL, "no message"); 
 638     java_lang_Throwable::set_message(exc, msg);
 639 
 640     // populate the stack trace and return it.
 641     java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
 642     return exc;
 643   }
 644 }
 645 
 646 static intptr_t non_oop_bits = 0;
 647 
 648 void* Universe::non_oop_word() {
 649   // Neither the high bits nor the low bits of this value is allowed
 650   // to look like (respectively) the high or low bits of a real oop.
 651   //
 652   // High and low are CPU-specific notions, but low always includes
 653   // the low-order bit.  Since oops are always aligned at least mod 4,
 654   // setting the low-order bit will ensure that the low half of the
 655   // word will never look like that of a real oop.
 656   //
 657   // Using the OS-supplied non-memory-address word (usually 0 or -1)
 658   // will take care of the high bits, however many there are.
 659 
 660   if (non_oop_bits == 0) {
 661     non_oop_bits = (intptr_t)os::non_memory_address_word() | 1;
 662   }
 663 
 664   return (void*)non_oop_bits;
 665 }
 666 
 667 jint universe_init() {
 668   assert(!Universe::_fully_initialized, "called after initialize_vtables");
 669   guarantee(1 << LogHeapWordSize == sizeof(HeapWord),
 670          "LogHeapWordSize is incorrect.");
 671   guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");
 672   guarantee(sizeof(oop) % sizeof(HeapWord) == 0,
 673          "oop size is not not a multiple of HeapWord size");
 674   TraceTime timer("Genesis", TraceStartupTime);
 675   GC_locker::lock();  // do not allow gc during bootstrapping
 676   JavaClasses::compute_hard_coded_offsets();
 677 
 678   // Get map info from shared archive file.
 679   if (DumpSharedSpaces)
 680     UseSharedSpaces = false;
 681 
 682   FileMapInfo* mapinfo = NULL;
 683   if (UseSharedSpaces) {
 684     mapinfo = NEW_C_HEAP_OBJ(FileMapInfo);
 685     memset(mapinfo, 0, sizeof(FileMapInfo));
 686 
 687     // Open the shared archive file, read and validate the header. If
 688     // initialization files, shared spaces [UseSharedSpaces] are
 689     // disabled and the file is closed.
 690 
 691     if (mapinfo->initialize()) {
 692       FileMapInfo::set_current_info(mapinfo);
 693     } else {
 694       assert(!mapinfo->is_open() && !UseSharedSpaces,
 695              "archive file not closed or shared spaces not disabled.");
 696     }
 697   }
 698 
 699   jint status = Universe::initialize_heap();
 700   if (status != JNI_OK) {
 701     return status;
 702   }
 703 
 704   // We have a heap so create the methodOop caches before
 705   // CompactingPermGenGen::initialize_oops() tries to populate them.
 706   Universe::_finalizer_register_cache = new LatestMethodOopCache();
 707   Universe::_loader_addClass_cache    = new LatestMethodOopCache();
 708   Universe::_reflect_invoke_cache     = new ActiveMethodOopsCache();
 709 
 710   if (UseSharedSpaces) {
 711 
 712     // Read the data structures supporting the shared spaces (shared
 713     // system dictionary, symbol table, etc.).  After that, access to
 714     // the file (other than the mapped regions) is no longer needed, and
 715     // the file is closed. Closing the file does not affect the
 716     // currently mapped regions.
 717 
 718     CompactingPermGenGen::initialize_oops();
 719     mapinfo->close();
 720 
 721   } else {
 722     SymbolTable::create_table();
 723     StringTable::create_table();
 724     ClassLoader::create_package_info_table();
 725   }
 726 
 727   return JNI_OK;
 728 }
 729 
 730 jint Universe::initialize_heap() {
 731 
 732   if (UseParallelGC) {
 733 #ifndef SERIALGC
 734     Universe::_collectedHeap = new ParallelScavengeHeap();
 735 #else  // SERIALGC
 736     fatal("UseParallelGC not supported in java kernel vm.");
 737 #endif // SERIALGC
 738 
 739   } else {
 740     GenCollectorPolicy *gc_policy;
 741 
 742     if (UseSerialGC) {
 743       gc_policy = new MarkSweepPolicy();
 744     } else if (UseConcMarkSweepGC) {
 745 #ifndef SERIALGC
 746       if (UseAdaptiveSizePolicy) {
 747         gc_policy = new ASConcurrentMarkSweepPolicy();
 748       } else {
 749         gc_policy = new ConcurrentMarkSweepPolicy();
 750       }
 751 #else   // SERIALGC
 752     fatal("UseConcMarkSweepGC not supported in java kernel vm.");
 753 #endif // SERIALGC
 754     } else { // default old generation
 755       gc_policy = new MarkSweepPolicy();
 756     }
 757     
 758     Universe::_collectedHeap = new GenCollectedHeap(gc_policy);
 759   }
 760 
 761   jint status = Universe::heap()->initialize();
 762   if (status != JNI_OK) {
 763     return status;
 764   }
 765 
 766   // We will never reach the CATCH below since Exceptions::_throw will cause
 767   // the VM to exit if an exception is thrown during initialization
 768 
 769   if (UseTLAB) {
 770     assert(Universe::heap()->supports_tlab_allocation(),
 771            "Should support thread-local allocation buffers");
 772     ThreadLocalAllocBuffer::startup_initialization();
 773   }
 774   return JNI_OK;
 775 }
 776 
 777 // It's the caller's repsonsibility to ensure glitch-freedom
 778 // (if required).
 779 void Universe::update_heap_info_at_gc() {
 780   _heap_capacity_at_last_gc = heap()->capacity();
 781   _heap_used_at_last_gc     = heap()->used();
 782 }
 783 
 784 
 785 
 786 void universe2_init() {
 787   EXCEPTION_MARK;
 788   Universe::genesis(CATCH);
 789   // Although we'd like to verify here that the state of the heap
 790   // is good, we can't because the main thread has not yet added
 791   // itself to the threads list (so, using current interfaces
 792   // we can't "fill" its TLAB), unless TLABs are disabled.
 793   if (VerifyBeforeGC && !UseTLAB &&
 794       Universe::heap()->total_collections() >= VerifyGCStartAt) { 
 795      Universe::heap()->prepare_for_verify();
 796      Universe::verify();   // make sure we're starting with a clean slate
 797   }
 798 }
 799 
 800 
 801 // This function is defined in JVM.cpp
 802 extern void initialize_converter_functions();
 803 
 804 bool universe_post_init() {
 805   Universe::_fully_initialized = true;
 806   EXCEPTION_MARK;
 807   { ResourceMark rm;
 808     Interpreter::initialize();      // needed for interpreter entry points
 809     if (!UseSharedSpaces) {
 810       KlassHandle ok_h(THREAD, SystemDictionary::object_klass());
 811       Universe::reinitialize_vtable_of(ok_h, CHECK_false);
 812       Universe::reinitialize_itables(CHECK_false);
 813     }
 814   }
 815 
 816   klassOop k;
 817   instanceKlassHandle k_h;
 818   if (!UseSharedSpaces) {
 819     // Setup preallocated empty java.lang.Class array
 820     Universe::_the_empty_class_klass_array = oopFactory::new_objArray(SystemDictionary::class_klass(), 0, CHECK_false);
 821     // Setup preallocated OutOfMemoryError errors
 822     k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_OutOfMemoryError(), true, CHECK_false);
 823     k_h = instanceKlassHandle(THREAD, k);
 824     Universe::_out_of_memory_error_java_heap = k_h->allocate_permanent_instance(CHECK_false);
 825     Universe::_out_of_memory_error_perm_gen = k_h->allocate_permanent_instance(CHECK_false);
 826     Universe::_out_of_memory_error_array_size = k_h->allocate_permanent_instance(CHECK_false);
 827     Universe::_out_of_memory_error_gc_overhead_limit = 
 828       k_h->allocate_permanent_instance(CHECK_false);
 829 
 830     // Setup preallocated NullPointerException
 831     // (this is currently used for a cheap & dirty solution in compiler exception handling)
 832     k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_NullPointerException(), true, CHECK_false);
 833     Universe::_null_ptr_exception_instance = instanceKlass::cast(k)->allocate_permanent_instance(CHECK_false);
 834     // Setup preallocated ArithmeticException
 835     // (this is currently used for a cheap & dirty solution in compiler exception handling)
 836     k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_ArithmeticException(), true, CHECK_false);
 837     Universe::_arithmetic_exception_instance = instanceKlass::cast(k)->allocate_permanent_instance(CHECK_false);
 838     // Virtual Machine Error for when we get into a situation we can't resolve
 839     k = SystemDictionary::resolve_or_fail(
 840       vmSymbolHandles::java_lang_VirtualMachineError(), true, CHECK_false);
 841     bool linked = instanceKlass::cast(k)->link_class_or_fail(CHECK_false);
 842     if (!linked) {
 843       tty->print_cr("Unable to link/verify VirtualMachineError class");
 844       return false; // initialization failed
 845     }
 846     Universe::_virtual_machine_error_instance = 
 847       instanceKlass::cast(k)->allocate_permanent_instance(CHECK_false);
 848   }
 849   if (!DumpSharedSpaces) {
 850     // These are the only Java fields that are currently set during shared space dumping.
 851     // We prefer to not handle this generally, so we always reinitialize these detail messages.
 852     Handle msg = java_lang_String::create_from_str("Java heap space", CHECK_false);
 853     java_lang_Throwable::set_message(Universe::_out_of_memory_error_java_heap, msg());
 854 
 855     msg = java_lang_String::create_from_str("PermGen space", CHECK_false);
 856     java_lang_Throwable::set_message(Universe::_out_of_memory_error_perm_gen, msg());
 857 
 858     msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK_false);
 859     java_lang_Throwable::set_message(Universe::_out_of_memory_error_array_size, msg());
 860 
 861     msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK_false);
 862     java_lang_Throwable::set_message(Universe::_out_of_memory_error_gc_overhead_limit, msg());
 863 
 864     msg = java_lang_String::create_from_str("/ by zero", CHECK_false);
 865     java_lang_Throwable::set_message(Universe::_arithmetic_exception_instance, msg());
 866 
 867     // Setup the array of errors that have preallocated backtrace
 868     k = Universe::_out_of_memory_error_java_heap->klass();
 869     assert(k->klass_part()->name() == vmSymbols::java_lang_OutOfMemoryError(), "should be out of memory error");
 870     k_h = instanceKlassHandle(THREAD, k);
 871 
 872     int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
 873     Universe::_preallocated_out_of_memory_error_array = oopFactory::new_objArray(k_h(), len, CHECK_false);
 874     for (int i=0; i<len; i++) {
 875       oop err = k_h->allocate_permanent_instance(CHECK_false);
 876       Handle err_h = Handle(THREAD, err);
 877       java_lang_Throwable::allocate_backtrace(err_h, CHECK_false);
 878       Universe::preallocated_out_of_memory_errors()->obj_at_put(i, err_h());
 879     }
 880     Universe::_preallocated_out_of_memory_error_avail_count = (jint)len;    
 881   }
 882 
 883   
 884   // Setup static method for registering finalizers
 885   // The finalizer klass must be linked before looking up the method, in
 886   // case it needs to get rewritten.
 887   instanceKlass::cast(SystemDictionary::finalizer_klass())->link_class(CHECK_false);
 888   methodOop m = instanceKlass::cast(SystemDictionary::finalizer_klass())->find_method(
 889                                   vmSymbols::register_method_name(), 
 890                                   vmSymbols::register_method_signature());
 891   if (m == NULL || !m->is_static()) {
 892     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodException(), 
 893       "java.lang.ref.Finalizer.register", false);
 894   }
 895   Universe::_finalizer_register_cache->init(
 896     SystemDictionary::finalizer_klass(), m, CHECK_false);
 897 
 898   // Resolve on first use and initialize class. 
 899   // Note: No race-condition here, since a resolve will always return the same result
 900 
 901   // Setup method for security checks 
 902   k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_reflect_Method(), true, CHECK_false);  
 903   k_h = instanceKlassHandle(THREAD, k);
 904   k_h->link_class(CHECK_false);
 905   m = k_h->find_method(vmSymbols::invoke_name(), vmSymbols::object_array_object_object_signature());
 906   if (m == NULL || m->is_static()) {
 907     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodException(), 
 908       "java.lang.reflect.Method.invoke", false);
 909   }
 910   Universe::_reflect_invoke_cache->init(k_h(), m, CHECK_false);
 911 
 912   // Setup method for registering loaded classes in class loader vector 
 913   instanceKlass::cast(SystemDictionary::classloader_klass())->link_class(CHECK_false);
 914   m = instanceKlass::cast(SystemDictionary::classloader_klass())->find_method(vmSymbols::addClass_name(), vmSymbols::class_void_signature());
 915   if (m == NULL || m->is_static()) {
 916     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodException(), 
 917       "java.lang.ClassLoader.addClass", false);
 918   }
 919   Universe::_loader_addClass_cache->init(
 920     SystemDictionary::classloader_klass(), m, CHECK_false);
 921 
 922   // The folowing is initializing converter functions for serialization in
 923   // JVM.cpp. If we clean up the StrictMath code above we may want to find
 924   // a better solution for this as well.
 925   initialize_converter_functions();
 926 
 927   // This needs to be done before the first scavenge/gc, since
 928   // it's an input to soft ref clearing policy.
 929   Universe::update_heap_info_at_gc();
 930 
 931   // ("weak") refs processing infrastructure initialization
 932   Universe::heap()->post_initialize();
 933 
 934   GC_locker::unlock();  // allow gc after bootstrapping
 935 
 936   MemoryService::set_universe_heap(Universe::_collectedHeap);
 937   return true;
 938 }
 939 
 940 
 941 void Universe::compute_base_vtable_size() {
 942   _base_vtable_size = ClassLoader::compute_Object_vtable();
 943 }
 944 
 945 
 946 // %%% The Universe::flush_foo methods belong in CodeCache.
 947 
 948 // Flushes compiled methods dependent on dependee.
 949 void Universe::flush_dependents_on(instanceKlassHandle dependee) {  
 950   assert_lock_strong(Compile_lock);  
 951 
 952   if (CodeCache::number_of_nmethods_with_dependencies() == 0) return;
 953 
 954   // CodeCache can only be updated by a thread_in_VM and they will all be
 955   // stopped dring the safepoint so CodeCache will be safe to update without
 956   // holding the CodeCache_lock.
 957   
 958   DepChange changes(dependee);
 959 
 960   // Compute the dependent nmethods
 961   if (CodeCache::mark_for_deoptimization(changes) > 0) {
 962     // At least one nmethod has been marked for deoptimization 
 963     VM_Deoptimize op;  
 964     VMThread::execute(&op);    
 965   }
 966 }
 967 
 968 #ifdef HOTSWAP
 969 // Flushes compiled methods dependent on dependee in the evolutionary sense
 970 void Universe::flush_evol_dependents_on(instanceKlassHandle ev_k_h) {
 971   // --- Compile_lock is not held. However we are at a safepoint.
 972   assert_locked_or_safepoint(Compile_lock);
 973   if (CodeCache::number_of_nmethods_with_dependencies() == 0) return;
 974 
 975   // CodeCache can only be updated by a thread_in_VM and they will all be
 976   // stopped dring the safepoint so CodeCache will be safe to update without
 977   // holding the CodeCache_lock.
 978   
 979   // Compute the dependent nmethods
 980   if (CodeCache::mark_for_evol_deoptimization(ev_k_h) > 0) {
 981     // At least one nmethod has been marked for deoptimization 
 982     
 983     // All this already happens inside a VM_Operation, so we'll do all the work here.
 984     // Stuff copied from VM_Deoptimize and modified slightly.
 985 
 986     // We do not want any GCs to happen while we are in the middle of this VM operation
 987     ResourceMark rm;
 988     DeoptimizationMarker dm;
 989 
 990     // Deoptimize all activations depending on marked nmethods  
 991     Deoptimization::deoptimize_dependents();
 992 
 993     // Make the dependent methods not entrant (in VM_Deoptimize they are made zombies)
 994     CodeCache::make_marked_nmethods_not_entrant(); 
 995   }
 996 }
 997 #endif // HOTSWAP
 998 
 999 
1000 // Flushes compiled methods dependent on dependee
1001 void Universe::flush_dependents_on_method(methodHandle m_h) {
1002   // --- Compile_lock is not held. However we are at a safepoint.
1003   assert_locked_or_safepoint(Compile_lock);
1004 
1005   // CodeCache can only be updated by a thread_in_VM and they will all be
1006   // stopped dring the safepoint so CodeCache will be safe to update without
1007   // holding the CodeCache_lock.
1008   
1009   // Compute the dependent nmethods
1010   if (CodeCache::mark_for_deoptimization(m_h()) > 0) {
1011     // At least one nmethod has been marked for deoptimization 
1012     
1013     // All this already happens inside a VM_Operation, so we'll do all the work here.
1014     // Stuff copied from VM_Deoptimize and modified slightly.
1015 
1016     // We do not want any GCs to happen while we are in the middle of this VM operation
1017     ResourceMark rm;
1018     DeoptimizationMarker dm;
1019 
1020     // Deoptimize all activations depending on marked nmethods  
1021     Deoptimization::deoptimize_dependents();
1022 
1023     // Make the dependent methods not entrant (in VM_Deoptimize they are made zombies)
1024     CodeCache::make_marked_nmethods_not_entrant(); 
1025   }
1026 }
1027 
1028 void Universe::print() { print_on(gclog_or_tty); }
1029 
1030 void Universe::print_on(outputStream* st) {
1031   st->print_cr("Heap");
1032   heap()->print_on(st);
1033 }
1034 
1035 void Universe::print_heap_at_SIGBREAK() {
1036   if (PrintHeapAtSIGBREAK) {
1037     MutexLocker hl(Heap_lock);
1038     print_on(tty);
1039     tty->cr();
1040     tty->flush();
1041   }
1042 }
1043 
1044 void Universe::print_heap_before_gc(outputStream* st) {  
1045   st->print_cr("{Heap before GC invocations=%u (full %u):",
1046                heap()->total_collections(),
1047                heap()->total_full_collections());
1048   heap()->print_on(st);
1049 }
1050 
1051 void Universe::print_heap_after_gc(outputStream* st) {
1052   st->print_cr("Heap after GC invocations=%u (full %u):",
1053                heap()->total_collections(),
1054                heap()->total_full_collections());
1055   heap()->print_on(st);
1056   st->print_cr("}");
1057 }
1058 
1059 void Universe::verify(bool allow_dirty, bool silent) {
1060   if (SharedSkipVerify) {
1061     return;
1062   }
1063 
1064   // The use of _verify_in_progress is a temporary work around for
1065   // 6320749.  Don't bother with a creating a class to set and clear
1066   // it since it is only used in this method and the control flow is
1067   // straight forward.
1068   _verify_in_progress = true;
1069 
1070   COMPILER2_PRESENT(
1071     assert(!DerivedPointerTable::is_active(),
1072          "DPT should not be active during verification "
1073          "(of thread stacks below)");
1074   )
1075 
1076   ResourceMark rm;
1077   HandleMark hm;  // Handles created during verification can be zapped
1078   _verify_count++;
1079 
1080   if (!silent) gclog_or_tty->print("[Verifying ");
1081   if (!silent) gclog_or_tty->print("threads ");     
1082   Threads::verify();
1083   heap()->verify(allow_dirty, silent);
1084 
1085   if (!silent) gclog_or_tty->print("syms ");        
1086   SymbolTable::verify();
1087   if (!silent) gclog_or_tty->print("strs ");        
1088   StringTable::verify();
1089   {
1090     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1091     if (!silent) gclog_or_tty->print("zone ");      
1092     CodeCache::verify();
1093   }
1094   if (!silent) gclog_or_tty->print("dict ");        
1095   SystemDictionary::verify();
1096   if (!silent) gclog_or_tty->print("hand ");        
1097   JNIHandles::verify();
1098   if (!silent) gclog_or_tty->print("C-heap ");      
1099   os::check_heap();
1100   if (!silent) gclog_or_tty->print_cr("]");
1101 
1102   _verify_in_progress = false;
1103 }
1104 
1105 // Oop verification (see MacroAssembler::verify_oop)
1106 
1107 static uintptr_t _verify_oop_data[2]   = {0, (uintptr_t)-1};
1108 static uintptr_t _verify_klass_data[2] = {0, (uintptr_t)-1};
1109 
1110 
1111 static void calculate_verify_data(uintptr_t verify_data[2],
1112                                   HeapWord* low_boundary,
1113                                   HeapWord* high_boundary) {
1114   assert(low_boundary < high_boundary, "bad interval");
1115 
1116   // decide which low-order bits we require to be clear:
1117   size_t alignSize = MinObjAlignmentInBytes;
1118   size_t min_object_size = oopDesc::header_size();
1119 
1120   // make an inclusive limit:
1121   uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;
1122   uintptr_t min = (uintptr_t)low_boundary;
1123   assert(min < max, "bad interval");
1124   uintptr_t diff = max ^ min;
1125 
1126   // throw away enough low-order bits to make the diff vanish
1127   uintptr_t mask = (uintptr_t)(-1);
1128   while ((mask & diff) != 0)
1129     mask <<= 1;
1130   uintptr_t bits = (min & mask);
1131   assert(bits == (max & mask), "correct mask");
1132   // check an intermediate value between min and max, just to make sure:
1133   assert(bits == ((min + (max-min)/2) & mask), "correct mask");
1134 
1135   // require address alignment, too:
1136   mask |= (alignSize - 1);
1137 
1138   if (!(verify_data[0] == 0 && verify_data[1] == (uintptr_t)-1)) {
1139     assert(verify_data[0] == mask && verify_data[1] == bits, "mask stability");
1140   }
1141   verify_data[0] = mask;
1142   verify_data[1] = bits;
1143 }
1144 
1145 
1146 // Oop verification (see MacroAssembler::verify_oop)
1147 #ifndef PRODUCT
1148 
1149 uintptr_t Universe::verify_oop_mask() {
1150   MemRegion m = heap()->reserved_region();
1151   calculate_verify_data(_verify_oop_data,
1152                         m.start(),
1153                         m.end());
1154   return _verify_oop_data[0];
1155 }
1156 
1157 
1158 
1159 uintptr_t Universe::verify_oop_bits() {
1160   verify_oop_mask();
1161   return _verify_oop_data[1];
1162 }
1163 
1164 
1165 uintptr_t Universe::verify_klass_mask() {
1166   /* $$$
1167   // A klass can never live in the new space.  Since the new and old
1168   // spaces can change size, we must settle for bounds-checking against
1169   // the bottom of the world, plus the smallest possible new and old
1170   // space sizes that may arise during execution.
1171   size_t min_new_size = Universe::new_size();   // in bytes
1172   size_t min_old_size = Universe::old_size();   // in bytes
1173   calculate_verify_data(_verify_klass_data,
1174           (HeapWord*)((uintptr_t)_new_gen->low_boundary + min_new_size + min_old_size),
1175           _perm_gen->high_boundary);
1176                         */
1177   // Why doesn't the above just say that klass's always live in the perm
1178   // gen?  I'll see if that seems to work...
1179   MemRegion permanent_reserved;
1180   switch (Universe::heap()->kind()) {
1181   default:
1182     // ???: What if a CollectedHeap doesn't have a permanent generation?
1183     ShouldNotReachHere();
1184     break;
1185   case CollectedHeap::GenCollectedHeap: {
1186     GenCollectedHeap* gch = (GenCollectedHeap*) Universe::heap();
1187     permanent_reserved = gch->perm_gen()->reserved();
1188     break;
1189   }
1190 #ifndef SERIALGC
1191   case CollectedHeap::ParallelScavengeHeap: {
1192     ParallelScavengeHeap* psh = (ParallelScavengeHeap*) Universe::heap();
1193     permanent_reserved = psh->perm_gen()->reserved();
1194     break;
1195   }
1196 #endif // SERIALGC
1197   }
1198   calculate_verify_data(_verify_klass_data,
1199                         permanent_reserved.start(), 
1200                         permanent_reserved.end());
1201   
1202   return _verify_klass_data[0];
1203 }
1204 
1205 
1206 
1207 uintptr_t Universe::verify_klass_bits() {
1208   verify_klass_mask();
1209   return _verify_klass_data[1];
1210 }
1211 
1212 
1213 uintptr_t Universe::verify_mark_mask() {
1214   return markOopDesc::lock_mask_in_place;
1215 }
1216 
1217 
1218 
1219 uintptr_t Universe::verify_mark_bits() {
1220   intptr_t mask = verify_mark_mask();
1221   intptr_t bits = (intptr_t)markOopDesc::prototype();
1222   assert((bits & ~mask) == 0, "no stray header bits");
1223   return bits;
1224 }
1225 #endif // PRODUCT
1226 
1227 
1228 void Universe::compute_verify_oop_data() {
1229   verify_oop_mask();
1230   verify_oop_bits();
1231   verify_mark_mask();
1232   verify_mark_bits();
1233   verify_klass_mask();
1234   verify_klass_bits();
1235 }
1236 
1237 
1238 void CommonMethodOopCache::init(klassOop k, methodOop m, TRAPS) {
1239   if (!UseSharedSpaces) {
1240     _klass = k;
1241   }
1242 #ifndef PRODUCT
1243   else {
1244     // sharing initilization should have already set up _klass
1245     assert(_klass != NULL, "just checking");
1246   }
1247 #endif
1248 
1249   _method_idnum = m->method_idnum();
1250   assert(_method_idnum >= 0, "sanity check");
1251 }
1252 
1253 
1254 ActiveMethodOopsCache::~ActiveMethodOopsCache() {
1255   if (_prev_methods != NULL) {
1256     for (int i = _prev_methods->length() - 1; i >= 0; i--) {
1257       jweak method_ref = _prev_methods->at(i);
1258       if (method_ref != NULL) {
1259         JNIHandles::destroy_weak_global(method_ref);
1260       }
1261     }
1262     delete _prev_methods;
1263     _prev_methods = NULL;
1264   }
1265 }
1266 
1267 
1268 void ActiveMethodOopsCache::add_previous_version(const methodOop method) {
1269   assert(Thread::current()->is_VM_thread(),
1270     "only VMThread can add previous versions");
1271 
1272   if (_prev_methods == NULL) {
1273     // This is the first previous version so make some space.
1274     // Start with 2 elements under the assumption that the class
1275     // won't be redefined much.
1276     _prev_methods = new (ResourceObj::C_HEAP) GrowableArray<jweak>(2, true);
1277   }
1278 
1279   // RC_TRACE macro has an embedded ResourceMark
1280   RC_TRACE(0x00000100,
1281     ("add: %s(%s): adding prev version ref for cached method @%d",
1282     method->name()->as_C_string(), method->signature()->as_C_string(),
1283     _prev_methods->length()));
1284 
1285   methodHandle method_h(method);
1286   jweak method_ref = JNIHandles::make_weak_global(method_h);
1287   _prev_methods->append(method_ref);
1288 
1289   // Using weak references allows previous versions of the cached
1290   // method to be GC'ed when they are no longer needed. Since the
1291   // caller is the VMThread and we are at a safepoint, this is a good
1292   // time to clear out unused weak references.
1293 
1294   for (int i = _prev_methods->length() - 1; i >= 0; i--) {
1295     jweak method_ref = _prev_methods->at(i);
1296     assert(method_ref != NULL, "weak method ref was unexpectedly cleared");
1297     if (method_ref == NULL) {
1298       _prev_methods->remove_at(i);
1299       // Since we are traversing the array backwards, we don't have to
1300       // do anything special with the index.
1301       continue;  // robustness
1302     }
1303       
1304     methodOop m = (methodOop)JNIHandles::resolve(method_ref);
1305     if (m == NULL) {
1306       // this method entry has been GC'ed so remove it
1307       JNIHandles::destroy_weak_global(method_ref);
1308       _prev_methods->remove_at(i);
1309     } else {
1310       // RC_TRACE macro has an embedded ResourceMark
1311       RC_TRACE(0x00000400, ("add: %s(%s): previous cached method @%d is alive",
1312         m->name()->as_C_string(), m->signature()->as_C_string(), i));
1313     }
1314   }
1315 } // end add_previous_version()
1316 
1317 
1318 bool ActiveMethodOopsCache::is_same_method(const methodOop method) const {
1319   instanceKlass* ik = instanceKlass::cast(klass());
1320   methodOop check_method = ik->method_with_idnum(method_idnum());
1321   assert(check_method != NULL, "sanity check");
1322   if (check_method == method) {
1323     // done with the easy case
1324     return true;
1325   }
1326 
1327   if (_prev_methods != NULL) {
1328     // The cached method has been redefined at least once so search
1329     // the previous versions for a match.
1330     for (int i = 0; i < _prev_methods->length(); i++) {
1331       jweak method_ref = _prev_methods->at(i);
1332       assert(method_ref != NULL, "weak method ref was unexpectedly cleared");
1333       if (method_ref == NULL) {
1334         continue;  // robustness
1335       }
1336 
1337       check_method = (methodOop)JNIHandles::resolve(method_ref);
1338       if (check_method == method) {
1339         // a previous version matches
1340         return true;
1341       }
1342     }
1343   }
1344 
1345   // either no previous versions or no previous version matched
1346   return false;
1347 }
1348 
1349 
1350 methodOop LatestMethodOopCache::get_methodOop() {
1351   instanceKlass* ik = instanceKlass::cast(klass());
1352   methodOop m = ik->method_with_idnum(method_idnum());
1353   assert(m != NULL, "sanity check");
1354   return m;
1355 }
1356 
1357 
1358 #ifdef ASSERT
1359 // Release dummy object(s) at bottom of heap
1360 bool Universe::release_fullgc_alot_dummy() {
1361   MutexLocker ml(FullGCALot_lock);
1362   if (_fullgc_alot_dummy_array != NULL) {
1363     if (_fullgc_alot_dummy_next >= _fullgc_alot_dummy_array->length()) {
1364       // No more dummies to release, release entire array instead
1365       _fullgc_alot_dummy_array = NULL;
1366       return false;
1367     }
1368     if (!UseConcMarkSweepGC) {
1369       // Release dummy at bottom of old generation
1370       _fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);
1371     }
1372     // Release dummy at bottom of permanent generation
1373     _fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);
1374   }
1375   return true;
1376 }
1377 
1378 #endif // ASSERT