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