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