< prev index next >

src/hotspot/share/memory/universe.cpp

Print this page

   1 /*
   2  * Copyright (c) 1997, 2025, 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  *

  48 #include "gc/shared/stringdedup/stringDedup.hpp"
  49 #include "gc/shared/tlab_globals.hpp"
  50 #include "logging/log.hpp"
  51 #include "logging/logStream.hpp"
  52 #include "memory/memoryReserver.hpp"
  53 #include "memory/metadataFactory.hpp"
  54 #include "memory/metaspaceClosure.hpp"
  55 #include "memory/metaspaceCounters.hpp"
  56 #include "memory/metaspaceUtils.hpp"
  57 #include "memory/oopFactory.hpp"
  58 #include "memory/resourceArea.hpp"
  59 #include "memory/universe.hpp"
  60 #include "oops/compressedOops.hpp"
  61 #include "oops/instanceKlass.hpp"
  62 #include "oops/instanceMirrorKlass.hpp"
  63 #include "oops/jmethodIDTable.hpp"
  64 #include "oops/klass.inline.hpp"
  65 #include "oops/objArrayOop.inline.hpp"
  66 #include "oops/objLayout.hpp"
  67 #include "oops/oop.inline.hpp"

  68 #include "oops/oopHandle.inline.hpp"

  69 #include "oops/typeArrayKlass.hpp"
  70 #include "prims/resolvedMethodTable.hpp"
  71 #include "runtime/arguments.hpp"
  72 #include "runtime/atomicAccess.hpp"
  73 #include "runtime/cpuTimeCounters.hpp"
  74 #include "runtime/flags/jvmFlagLimit.hpp"
  75 #include "runtime/handles.inline.hpp"
  76 #include "runtime/init.hpp"
  77 #include "runtime/java.hpp"
  78 #include "runtime/javaThread.hpp"
  79 #include "runtime/jniHandles.hpp"
  80 #include "runtime/threads.hpp"
  81 #include "runtime/timerTrace.hpp"
  82 #include "sanitizers/leak.hpp"
  83 #include "services/cpuTimeUsage.hpp"
  84 #include "services/memoryService.hpp"
  85 #include "utilities/align.hpp"
  86 #include "utilities/autoRestore.hpp"
  87 #include "utilities/debug.hpp"
  88 #include "utilities/formatBuffer.hpp"

  96 // interacts with the RedefineClasses API.
  97 class LatestMethodCache {
  98   // We save the InstanceKlass* and the idnum of Method* in order to get
  99   // the current Method*.
 100   InstanceKlass*        _klass;
 101   int                   _method_idnum;
 102 
 103  public:
 104   LatestMethodCache()   { _klass = nullptr; _method_idnum = -1; }
 105 
 106   void init(JavaThread* current, InstanceKlass* ik, const char* method,
 107             Symbol* signature, bool is_static);
 108   Method* get_method();
 109 };
 110 
 111 static LatestMethodCache _finalizer_register_cache;         // Finalizer.register()
 112 static LatestMethodCache _loader_addClass_cache;            // ClassLoader.addClass()
 113 static LatestMethodCache _throw_illegal_access_error_cache; // Unsafe.throwIllegalAccessError()
 114 static LatestMethodCache _throw_no_such_method_error_cache; // Unsafe.throwNoSuchMethodError()
 115 static LatestMethodCache _do_stack_walk_cache;              // AbstractStackWalker.doStackWalk()


 116 
 117 // Known objects
 118 TypeArrayKlass* Universe::_typeArrayKlasses[T_LONG+1] = { nullptr /*, nullptr...*/ };
 119 ObjArrayKlass* Universe::_objectArrayKlass            = nullptr;
 120 Klass* Universe::_fillerArrayKlass                    = nullptr;
 121 OopHandle Universe::_basic_type_mirrors[T_VOID+1];
 122 #if INCLUDE_CDS_JAVA_HEAP
 123 int Universe::_archived_basic_type_mirror_indices[T_VOID+1];
 124 #endif
 125 
 126 OopHandle Universe::_main_thread_group;
 127 OopHandle Universe::_system_thread_group;
 128 OopHandle Universe::_the_empty_class_array;
 129 OopHandle Universe::_the_null_string;
 130 OopHandle Universe::_the_min_jint_string;
 131 
 132 OopHandle Universe::_the_null_sentinel;
 133 
 134 // _out_of_memory_errors is an objArray
 135 enum OutOfMemoryInstance { _oom_java_heap,
 136                            _oom_c_heap,
 137                            _oom_metaspace,
 138                            _oom_class_metaspace,
 139                            _oom_array_size,

 374   f->do_ptr(&_the_empty_instance_klass_array);
 375 }
 376 
 377 
 378 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
 379   if (size < alignment || size % alignment != 0) {
 380     vm_exit_during_initialization(
 381       err_msg("Size of %s (%zu bytes) must be aligned to %zu bytes", name, size, alignment));
 382   }
 383 }
 384 
 385 static void initialize_basic_type_klass(Klass* k, TRAPS) {
 386   Klass* ok = vmClasses::Object_klass();
 387 #if INCLUDE_CDS
 388   if (CDSConfig::is_using_archive()) {
 389     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 390     assert(k->super() == ok, "u3");
 391     if (k->is_instance_klass()) {
 392       InstanceKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), nullptr, CHECK);
 393     } else {
 394       ArrayKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), CHECK);
 395     }
 396   } else
 397 #endif
 398   {
 399     k->initialize_supers(ok, nullptr, CHECK);
 400   }
 401   k->append_to_sibling_list();
 402 }
 403 
 404 void Universe::genesis(TRAPS) {
 405   ResourceMark rm(THREAD);
 406   HandleMark   hm(THREAD);
 407 
 408   // Explicit null checks are needed if these offsets are not smaller than the page size
 409   if (UseCompactObjectHeaders) {
 410     assert(oopDesc::mark_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 411            "Mark offset is expected to be less than the page size");
 412   } else {
 413     assert(oopDesc::klass_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 414            "Klass offset is expected to be less than the page size");

 492     Handle tns = java_lang_String::create_from_str("<null_sentinel>", CHECK);
 493     _the_null_sentinel = OopHandle(vm_global(), tns());
 494   }
 495 
 496   // Create a handle for reference_pending_list
 497   _reference_pending_list = OopHandle(vm_global(), nullptr);
 498 
 499   // Maybe this could be lifted up now that object array can be initialized
 500   // during the bootstrapping.
 501 
 502   // OLD
 503   // Initialize _objectArrayKlass after core bootstraping to make
 504   // sure the super class is set up properly for _objectArrayKlass.
 505   // ---
 506   // NEW
 507   // Since some of the old system object arrays have been converted to
 508   // ordinary object arrays, _objectArrayKlass will be loaded when
 509   // SystemDictionary::initialize(CHECK); is run. See the extra check
 510   // for Object_klass_is_loaded in ObjArrayKlass::allocate_objArray_klass.
 511   {
 512     Klass* oak = vmClasses::Object_klass()->array_klass(CHECK);
 513     _objectArrayKlass = ObjArrayKlass::cast(oak);




 514   }
 515   // OLD
 516   // Add the class to the class hierarchy manually to make sure that
 517   // its vtable is initialized after core bootstrapping is completed.
 518   // ---
 519   // New
 520   // Have already been initialized.
 521   _objectArrayKlass->append_to_sibling_list();
 522 
 523   #ifdef ASSERT
 524   if (FullGCALot) {
 525     // Allocate an array of dummy objects.
 526     // We'd like these to be at the bottom of the old generation,
 527     // so that when we free one and then collect,
 528     // (almost) the whole heap moves
 529     // and we find out if we actually update all the oops correctly.
 530     // But we can't allocate directly in the old generation,
 531     // so we allocate wherever, and hope that the first collection
 532     // moves these objects to the bottom of the old generation.
 533     int size = FullGCALotDummies * 2;
 534 
 535     objArrayOop    naked_array = oopFactory::new_objArray(vmClasses::Object_klass(), size, CHECK);
 536     objArrayHandle dummy_array(THREAD, naked_array);
 537     int i = 0;
 538     while (i < size) {
 539         // Allocate dummy in old generation
 540       oop dummy = vmClasses::Object_klass()->allocate_instance(CHECK);
 541       dummy_array->obj_at_put(i++, dummy);

 636   assert_pll_ownership();
 637   return _reference_pending_list.peek() != nullptr;
 638 }
 639 
 640 oop Universe::swap_reference_pending_list(oop list) {
 641   assert_pll_locked(is_locked);
 642   return _reference_pending_list.xchg(list);
 643 }
 644 
 645 #undef assert_pll_locked
 646 #undef assert_pll_ownership
 647 
 648 static void reinitialize_vtables() {
 649   // The vtables are initialized by starting at java.lang.Object and
 650   // initializing through the subclass links, so that the super
 651   // classes are always initialized first.
 652   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
 653     Klass* sub = iter.klass();
 654     sub->vtable().initialize_vtable();
 655   }



 656 }
 657 
 658 static void reinitialize_itables() {
 659 
 660   class ReinitTableClosure : public KlassClosure {
 661    public:
 662     void do_klass(Klass* k) {
 663       if (k->is_instance_klass()) {
 664          InstanceKlass::cast(k)->itable().initialize_itable();
 665       }
 666     }
 667   };
 668 
 669   MutexLocker mcld(ClassLoaderDataGraph_lock);
 670   ReinitTableClosure cl;
 671   ClassLoaderDataGraph::classes_do(&cl);
 672 }
 673 
 674 bool Universe::on_page_boundary(void* addr) {
 675   return is_aligned(addr, os::vm_page_size());
 676 }
 677 
 678 // the array of preallocated errors with backtraces
 679 objArrayOop Universe::preallocated_out_of_memory_errors() {
 680   return (objArrayOop)_preallocated_out_of_memory_error_array.resolve();
 681 }
 682 
 683 objArrayOop Universe::out_of_memory_errors() { return (objArrayOop)_out_of_memory_errors.resolve(); }
 684 
 685 oop Universe::out_of_memory_error_java_heap() {
 686   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_java_heap));
 687 }
 688 
 689 oop Universe::out_of_memory_error_java_heap_without_backtrace() {
 690   return out_of_memory_errors()->obj_at(_oom_java_heap);
 691 }
 692 
 693 oop Universe::out_of_memory_error_c_heap() {
 694   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_c_heap));
 695 }
 696 
 697 oop Universe::out_of_memory_error_metaspace() {
 698   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_metaspace));
 699 }
 700 
 701 oop Universe::out_of_memory_error_class_metaspace() {
 702   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_class_metaspace));
 703 }

 708 
 709 oop Universe::out_of_memory_error_gc_overhead_limit() {
 710   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_gc_overhead_limit));
 711 }
 712 
 713 oop Universe::out_of_memory_error_realloc_objects() {
 714   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_realloc_objects));
 715 }
 716 
 717 oop Universe::class_init_out_of_memory_error()         { return out_of_memory_errors()->obj_at(_oom_java_heap); }
 718 oop Universe::class_init_stack_overflow_error()        { return _class_init_stack_overflow_error.resolve(); }
 719 oop Universe::delayed_stack_overflow_error_message()   { return _delayed_stack_overflow_error_message.resolve(); }
 720 
 721 
 722 bool Universe::should_fill_in_stack_trace(Handle throwable) {
 723   // never attempt to fill in the stack trace of preallocated errors that do not have
 724   // backtrace. These errors are kept alive forever and may be "re-used" when all
 725   // preallocated errors with backtrace have been consumed. Also need to avoid
 726   // a potential loop which could happen if an out of memory occurs when attempting
 727   // to allocate the backtrace.
 728   objArrayOop preallocated_oom = out_of_memory_errors();
 729   for (int i = 0; i < _oom_count; i++) {
 730     if (throwable() == preallocated_oom->obj_at(i)) {
 731       return false;
 732     }
 733   }
 734   return true;
 735 }
 736 
 737 
 738 oop Universe::gen_out_of_memory_error(oop default_err) {
 739   // generate an out of memory error:
 740   // - if there is a preallocated error and stack traces are available
 741   //   (j.l.Throwable is initialized), then return the preallocated
 742   //   error with a filled in stack trace, and with the message
 743   //   provided by the default error.
 744   // - otherwise, return the default error, without a stack trace.
 745   int next;
 746   if ((_preallocated_out_of_memory_error_avail_count > 0) &&
 747       vmClasses::Throwable_klass()->is_initialized()) {
 748     next = (int)AtomicAccess::add(&_preallocated_out_of_memory_error_avail_count, -1);

 768     assert(msg != nullptr, "no message");
 769     java_lang_Throwable::set_message(exc(), msg);
 770 
 771     // populate the stack trace and return it.
 772     java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
 773     return exc();
 774   }
 775 }
 776 
 777 bool Universe::is_out_of_memory_error_metaspace(oop ex_obj) {
 778   return java_lang_Throwable::message(ex_obj) == _msg_metaspace.resolve();
 779 }
 780 
 781 bool Universe::is_out_of_memory_error_class_metaspace(oop ex_obj) {
 782   return java_lang_Throwable::message(ex_obj) == _msg_class_metaspace.resolve();
 783 }
 784 
 785 // Setup preallocated OutOfMemoryError errors
 786 void Universe::create_preallocated_out_of_memory_errors(TRAPS) {
 787   InstanceKlass* ik = vmClasses::OutOfMemoryError_klass();
 788   objArrayOop oa = oopFactory::new_objArray(ik, _oom_count, CHECK);
 789   objArrayHandle oom_array(THREAD, oa);
 790 
 791   for (int i = 0; i < _oom_count; i++) {
 792     oop oom_obj = ik->allocate_instance(CHECK);
 793     oom_array->obj_at_put(i, oom_obj);
 794   }
 795   _out_of_memory_errors = OopHandle(vm_global(), oom_array());
 796 
 797   Handle msg = java_lang_String::create_from_str("Java heap space", CHECK);
 798   java_lang_Throwable::set_message(oom_array->obj_at(_oom_java_heap), msg());
 799 
 800   msg = java_lang_String::create_from_str("C heap space", CHECK);
 801   java_lang_Throwable::set_message(oom_array->obj_at(_oom_c_heap), msg());
 802 
 803   msg = java_lang_String::create_from_str("Metaspace", CHECK);
 804   _msg_metaspace = OopHandle(vm_global(), msg());
 805   java_lang_Throwable::set_message(oom_array->obj_at(_oom_metaspace), msg());
 806 
 807   msg = java_lang_String::create_from_str("Compressed class space", CHECK);
 808   _msg_class_metaspace = OopHandle(vm_global(), msg());
 809   java_lang_Throwable::set_message(oom_array->obj_at(_oom_class_metaspace), msg());
 810 
 811   msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK);
 812   java_lang_Throwable::set_message(oom_array->obj_at(_oom_array_size), msg());
 813 
 814   msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK);
 815   java_lang_Throwable::set_message(oom_array->obj_at(_oom_gc_overhead_limit), msg());
 816 
 817   msg = java_lang_String::create_from_str("Java heap space: failed reallocation of scalar replaced objects", CHECK);
 818   java_lang_Throwable::set_message(oom_array->obj_at(_oom_realloc_objects), msg());
 819 
 820   // Setup the array of errors that have preallocated backtrace
 821   int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
 822   objArrayOop instance = oopFactory::new_objArray(ik, len, CHECK);
 823   _preallocated_out_of_memory_error_array = OopHandle(vm_global(), instance);
 824   objArrayHandle preallocated_oom_array(THREAD, instance);
 825 
 826   for (int i=0; i<len; i++) {
 827     oop err = ik->allocate_instance(CHECK);
 828     Handle err_h(THREAD, err);
 829     java_lang_Throwable::allocate_backtrace(err_h, CHECK);
 830     preallocated_oom_array->obj_at_put(i, err_h());
 831   }
 832   _preallocated_out_of_memory_error_avail_count = (jint)len;
 833 }
 834 
 835 intptr_t Universe::_non_oop_bits = 0;
 836 
 837 void* Universe::non_oop_word() {
 838   // Neither the high bits nor the low bits of this value is allowed
 839   // to look like (respectively) the high or low bits of a real oop.
 840   //
 841   // High and low are CPU-specific notions, but low always includes
 842   // the low-order bit.  Since oops are always aligned at least mod 4,
 843   // setting the low-order bit will ensure that the low half of the
 844   // word will never look like that of a real oop.

1060     // <init> function before java_lang_Class is linked. Print error and exit.
1061     vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",
1062                                  ik->name()->as_C_string(), method));
1063   }
1064 
1065   _klass = ik;
1066   _method_idnum = m->method_idnum();
1067   assert(_method_idnum >= 0, "sanity check");
1068 }
1069 
1070 Method* LatestMethodCache::get_method() {
1071   if (_klass == nullptr) {
1072     return nullptr;
1073   } else {
1074     Method* m = _klass->method_with_idnum(_method_idnum);
1075     assert(m != nullptr, "sanity check");
1076     return m;
1077   }
1078 }
1079 
1080 Method* Universe::finalizer_register_method()     { return _finalizer_register_cache.get_method(); }
1081 Method* Universe::loader_addClass_method()        { return _loader_addClass_cache.get_method(); }
1082 Method* Universe::throw_illegal_access_error()    { return _throw_illegal_access_error_cache.get_method(); }
1083 Method* Universe::throw_no_such_method_error()    { return _throw_no_such_method_error_cache.get_method(); }
1084 Method* Universe::do_stack_walk_method()          { return _do_stack_walk_cache.get_method(); }


1085 
1086 void Universe::initialize_known_methods(JavaThread* current) {
1087   // Set up static method for registering finalizers
1088   _finalizer_register_cache.init(current,
1089                           vmClasses::Finalizer_klass(),
1090                           "register",
1091                           vmSymbols::object_void_signature(), true);
1092 
1093   _throw_illegal_access_error_cache.init(current,
1094                           vmClasses::internal_Unsafe_klass(),
1095                           "throwIllegalAccessError",
1096                           vmSymbols::void_method_signature(), true);
1097 
1098   _throw_no_such_method_error_cache.init(current,
1099                           vmClasses::internal_Unsafe_klass(),
1100                           "throwNoSuchMethodError",
1101                           vmSymbols::void_method_signature(), true);
1102 
1103   // Set up method for registering loaded classes in class loader vector
1104   _loader_addClass_cache.init(current,
1105                           vmClasses::ClassLoader_klass(),
1106                           "addClass",
1107                           vmSymbols::class_void_signature(), false);
1108 
1109   // Set up method for stack walking
1110   _do_stack_walk_cache.init(current,
1111                           vmClasses::AbstractStackWalker_klass(),
1112                           "doStackWalk",
1113                           vmSymbols::doStackWalk_signature(), false);











1114 }
1115 
1116 void universe2_init() {
1117   EXCEPTION_MARK;
1118   Universe::genesis(CATCH);
1119 }
1120 
1121 // Set after initialization of the module runtime, call_initModuleRuntime
1122 void universe_post_module_init() {
1123   Universe::_module_initialized = true;
1124 }
1125 
1126 bool universe_post_init() {
1127   assert(!is_init_completed(), "Error: initialization not yet completed!");
1128   Universe::_fully_initialized = true;
1129   EXCEPTION_MARK;
1130   if (!CDSConfig::is_using_archive()) {
1131     reinitialize_vtables();
1132     reinitialize_itables();
1133   }

   1 /*
   2  * Copyright (c) 1997, 2026, 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  *

  48 #include "gc/shared/stringdedup/stringDedup.hpp"
  49 #include "gc/shared/tlab_globals.hpp"
  50 #include "logging/log.hpp"
  51 #include "logging/logStream.hpp"
  52 #include "memory/memoryReserver.hpp"
  53 #include "memory/metadataFactory.hpp"
  54 #include "memory/metaspaceClosure.hpp"
  55 #include "memory/metaspaceCounters.hpp"
  56 #include "memory/metaspaceUtils.hpp"
  57 #include "memory/oopFactory.hpp"
  58 #include "memory/resourceArea.hpp"
  59 #include "memory/universe.hpp"
  60 #include "oops/compressedOops.hpp"
  61 #include "oops/instanceKlass.hpp"
  62 #include "oops/instanceMirrorKlass.hpp"
  63 #include "oops/jmethodIDTable.hpp"
  64 #include "oops/klass.inline.hpp"
  65 #include "oops/objArrayOop.inline.hpp"
  66 #include "oops/objLayout.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "oops/oopCast.inline.hpp"
  69 #include "oops/oopHandle.inline.hpp"
  70 #include "oops/refArrayKlass.hpp"
  71 #include "oops/typeArrayKlass.hpp"
  72 #include "prims/resolvedMethodTable.hpp"
  73 #include "runtime/arguments.hpp"
  74 #include "runtime/atomicAccess.hpp"
  75 #include "runtime/cpuTimeCounters.hpp"
  76 #include "runtime/flags/jvmFlagLimit.hpp"
  77 #include "runtime/handles.inline.hpp"
  78 #include "runtime/init.hpp"
  79 #include "runtime/java.hpp"
  80 #include "runtime/javaThread.hpp"
  81 #include "runtime/jniHandles.hpp"
  82 #include "runtime/threads.hpp"
  83 #include "runtime/timerTrace.hpp"
  84 #include "sanitizers/leak.hpp"
  85 #include "services/cpuTimeUsage.hpp"
  86 #include "services/memoryService.hpp"
  87 #include "utilities/align.hpp"
  88 #include "utilities/autoRestore.hpp"
  89 #include "utilities/debug.hpp"
  90 #include "utilities/formatBuffer.hpp"

  98 // interacts with the RedefineClasses API.
  99 class LatestMethodCache {
 100   // We save the InstanceKlass* and the idnum of Method* in order to get
 101   // the current Method*.
 102   InstanceKlass*        _klass;
 103   int                   _method_idnum;
 104 
 105  public:
 106   LatestMethodCache()   { _klass = nullptr; _method_idnum = -1; }
 107 
 108   void init(JavaThread* current, InstanceKlass* ik, const char* method,
 109             Symbol* signature, bool is_static);
 110   Method* get_method();
 111 };
 112 
 113 static LatestMethodCache _finalizer_register_cache;         // Finalizer.register()
 114 static LatestMethodCache _loader_addClass_cache;            // ClassLoader.addClass()
 115 static LatestMethodCache _throw_illegal_access_error_cache; // Unsafe.throwIllegalAccessError()
 116 static LatestMethodCache _throw_no_such_method_error_cache; // Unsafe.throwNoSuchMethodError()
 117 static LatestMethodCache _do_stack_walk_cache;              // AbstractStackWalker.doStackWalk()
 118 static LatestMethodCache _is_substitutable_cache;           // ValueObjectMethods.isSubstitutable()
 119 static LatestMethodCache _value_object_hash_code_cache;     // ValueObjectMethods.valueObjectHashCode()
 120 
 121 // Known objects
 122 TypeArrayKlass* Universe::_typeArrayKlasses[T_LONG+1] = { nullptr /*, nullptr...*/ };
 123 RefArrayKlass* Universe::_objectArrayKlass            = nullptr;
 124 Klass* Universe::_fillerArrayKlass                    = nullptr;
 125 OopHandle Universe::_basic_type_mirrors[T_VOID+1];
 126 #if INCLUDE_CDS_JAVA_HEAP
 127 int Universe::_archived_basic_type_mirror_indices[T_VOID+1];
 128 #endif
 129 
 130 OopHandle Universe::_main_thread_group;
 131 OopHandle Universe::_system_thread_group;
 132 OopHandle Universe::_the_empty_class_array;
 133 OopHandle Universe::_the_null_string;
 134 OopHandle Universe::_the_min_jint_string;
 135 
 136 OopHandle Universe::_the_null_sentinel;
 137 
 138 // _out_of_memory_errors is an objArray
 139 enum OutOfMemoryInstance { _oom_java_heap,
 140                            _oom_c_heap,
 141                            _oom_metaspace,
 142                            _oom_class_metaspace,
 143                            _oom_array_size,

 378   f->do_ptr(&_the_empty_instance_klass_array);
 379 }
 380 
 381 
 382 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
 383   if (size < alignment || size % alignment != 0) {
 384     vm_exit_during_initialization(
 385       err_msg("Size of %s (%zu bytes) must be aligned to %zu bytes", name, size, alignment));
 386   }
 387 }
 388 
 389 static void initialize_basic_type_klass(Klass* k, TRAPS) {
 390   Klass* ok = vmClasses::Object_klass();
 391 #if INCLUDE_CDS
 392   if (CDSConfig::is_using_archive()) {
 393     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 394     assert(k->super() == ok, "u3");
 395     if (k->is_instance_klass()) {
 396       InstanceKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), nullptr, CHECK);
 397     } else {
 398       TypeArrayKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), CHECK);
 399     }
 400   } else
 401 #endif
 402   {
 403     k->initialize_supers(ok, nullptr, CHECK);
 404   }
 405   k->append_to_sibling_list();
 406 }
 407 
 408 void Universe::genesis(TRAPS) {
 409   ResourceMark rm(THREAD);
 410   HandleMark   hm(THREAD);
 411 
 412   // Explicit null checks are needed if these offsets are not smaller than the page size
 413   if (UseCompactObjectHeaders) {
 414     assert(oopDesc::mark_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 415            "Mark offset is expected to be less than the page size");
 416   } else {
 417     assert(oopDesc::klass_offset_in_bytes() < static_cast<intptr_t>(os::vm_page_size()),
 418            "Klass offset is expected to be less than the page size");

 496     Handle tns = java_lang_String::create_from_str("<null_sentinel>", CHECK);
 497     _the_null_sentinel = OopHandle(vm_global(), tns());
 498   }
 499 
 500   // Create a handle for reference_pending_list
 501   _reference_pending_list = OopHandle(vm_global(), nullptr);
 502 
 503   // Maybe this could be lifted up now that object array can be initialized
 504   // during the bootstrapping.
 505 
 506   // OLD
 507   // Initialize _objectArrayKlass after core bootstraping to make
 508   // sure the super class is set up properly for _objectArrayKlass.
 509   // ---
 510   // NEW
 511   // Since some of the old system object arrays have been converted to
 512   // ordinary object arrays, _objectArrayKlass will be loaded when
 513   // SystemDictionary::initialize(CHECK); is run. See the extra check
 514   // for Object_klass_is_loaded in ObjArrayKlass::allocate_objArray_klass.
 515   {
 516     ArrayKlass* oak = vmClasses::Object_klass()->array_klass(CHECK);
 517     oak->append_to_sibling_list();
 518 
 519     // Create a RefArrayKlass (which is the default) and initialize.
 520     ObjArrayKlass* rak = ObjArrayKlass::cast(oak)->klass_with_properties(ArrayProperties::Default(), CHECK);
 521     _objectArrayKlass = RefArrayKlass::cast(rak);
 522   }







 523 
 524   #ifdef ASSERT
 525   if (FullGCALot) {
 526     // Allocate an array of dummy objects.
 527     // We'd like these to be at the bottom of the old generation,
 528     // so that when we free one and then collect,
 529     // (almost) the whole heap moves
 530     // and we find out if we actually update all the oops correctly.
 531     // But we can't allocate directly in the old generation,
 532     // so we allocate wherever, and hope that the first collection
 533     // moves these objects to the bottom of the old generation.
 534     int size = FullGCALotDummies * 2;
 535 
 536     objArrayOop    naked_array = oopFactory::new_objArray(vmClasses::Object_klass(), size, CHECK);
 537     objArrayHandle dummy_array(THREAD, naked_array);
 538     int i = 0;
 539     while (i < size) {
 540         // Allocate dummy in old generation
 541       oop dummy = vmClasses::Object_klass()->allocate_instance(CHECK);
 542       dummy_array->obj_at_put(i++, dummy);

 637   assert_pll_ownership();
 638   return _reference_pending_list.peek() != nullptr;
 639 }
 640 
 641 oop Universe::swap_reference_pending_list(oop list) {
 642   assert_pll_locked(is_locked);
 643   return _reference_pending_list.xchg(list);
 644 }
 645 
 646 #undef assert_pll_locked
 647 #undef assert_pll_ownership
 648 
 649 static void reinitialize_vtables() {
 650   // The vtables are initialized by starting at java.lang.Object and
 651   // initializing through the subclass links, so that the super
 652   // classes are always initialized first.
 653   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
 654     Klass* sub = iter.klass();
 655     sub->vtable().initialize_vtable();
 656   }
 657 
 658   // This isn't added to the subclass list, so need to reinitialize vtables directly.
 659   Universe::objectArrayKlass()->vtable().initialize_vtable();
 660 }
 661 
 662 static void reinitialize_itables() {
 663 
 664   class ReinitTableClosure : public KlassClosure {
 665    public:
 666     void do_klass(Klass* k) {
 667       if (k->is_instance_klass()) {
 668          InstanceKlass::cast(k)->itable().initialize_itable();
 669       }
 670     }
 671   };
 672 
 673   MutexLocker mcld(ClassLoaderDataGraph_lock);
 674   ReinitTableClosure cl;
 675   ClassLoaderDataGraph::classes_do(&cl);
 676 }
 677 
 678 bool Universe::on_page_boundary(void* addr) {
 679   return is_aligned(addr, os::vm_page_size());
 680 }
 681 
 682 // the array of preallocated errors with backtraces
 683 refArrayOop Universe::preallocated_out_of_memory_errors() {
 684   return oop_cast<refArrayOop>(_preallocated_out_of_memory_error_array.resolve());
 685 }
 686 
 687 refArrayOop Universe::out_of_memory_errors() { return oop_cast<refArrayOop>(_out_of_memory_errors.resolve()); }
 688 
 689 oop Universe::out_of_memory_error_java_heap() {
 690   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_java_heap));
 691 }
 692 
 693 oop Universe::out_of_memory_error_java_heap_without_backtrace() {
 694   return out_of_memory_errors()->obj_at(_oom_java_heap);
 695 }
 696 
 697 oop Universe::out_of_memory_error_c_heap() {
 698   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_c_heap));
 699 }
 700 
 701 oop Universe::out_of_memory_error_metaspace() {
 702   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_metaspace));
 703 }
 704 
 705 oop Universe::out_of_memory_error_class_metaspace() {
 706   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_class_metaspace));
 707 }

 712 
 713 oop Universe::out_of_memory_error_gc_overhead_limit() {
 714   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_gc_overhead_limit));
 715 }
 716 
 717 oop Universe::out_of_memory_error_realloc_objects() {
 718   return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_realloc_objects));
 719 }
 720 
 721 oop Universe::class_init_out_of_memory_error()         { return out_of_memory_errors()->obj_at(_oom_java_heap); }
 722 oop Universe::class_init_stack_overflow_error()        { return _class_init_stack_overflow_error.resolve(); }
 723 oop Universe::delayed_stack_overflow_error_message()   { return _delayed_stack_overflow_error_message.resolve(); }
 724 
 725 
 726 bool Universe::should_fill_in_stack_trace(Handle throwable) {
 727   // never attempt to fill in the stack trace of preallocated errors that do not have
 728   // backtrace. These errors are kept alive forever and may be "re-used" when all
 729   // preallocated errors with backtrace have been consumed. Also need to avoid
 730   // a potential loop which could happen if an out of memory occurs when attempting
 731   // to allocate the backtrace.
 732   refArrayOop preallocated_oom = out_of_memory_errors();
 733   for (int i = 0; i < _oom_count; i++) {
 734     if (throwable() == preallocated_oom->obj_at(i)) {
 735       return false;
 736     }
 737   }
 738   return true;
 739 }
 740 
 741 
 742 oop Universe::gen_out_of_memory_error(oop default_err) {
 743   // generate an out of memory error:
 744   // - if there is a preallocated error and stack traces are available
 745   //   (j.l.Throwable is initialized), then return the preallocated
 746   //   error with a filled in stack trace, and with the message
 747   //   provided by the default error.
 748   // - otherwise, return the default error, without a stack trace.
 749   int next;
 750   if ((_preallocated_out_of_memory_error_avail_count > 0) &&
 751       vmClasses::Throwable_klass()->is_initialized()) {
 752     next = (int)AtomicAccess::add(&_preallocated_out_of_memory_error_avail_count, -1);

 772     assert(msg != nullptr, "no message");
 773     java_lang_Throwable::set_message(exc(), msg);
 774 
 775     // populate the stack trace and return it.
 776     java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);
 777     return exc();
 778   }
 779 }
 780 
 781 bool Universe::is_out_of_memory_error_metaspace(oop ex_obj) {
 782   return java_lang_Throwable::message(ex_obj) == _msg_metaspace.resolve();
 783 }
 784 
 785 bool Universe::is_out_of_memory_error_class_metaspace(oop ex_obj) {
 786   return java_lang_Throwable::message(ex_obj) == _msg_class_metaspace.resolve();
 787 }
 788 
 789 // Setup preallocated OutOfMemoryError errors
 790 void Universe::create_preallocated_out_of_memory_errors(TRAPS) {
 791   InstanceKlass* ik = vmClasses::OutOfMemoryError_klass();
 792   refArrayOop ra = oopFactory::new_refArray(ik, _oom_count, CHECK);
 793   refArrayHandle oom_array(THREAD, ra);
 794 
 795   for (int i = 0; i < _oom_count; i++) {
 796     oop oom_obj = ik->allocate_instance(CHECK);
 797     oom_array->obj_at_put(i, oom_obj);
 798   }
 799   _out_of_memory_errors = OopHandle(vm_global(), oom_array());
 800 
 801   Handle msg = java_lang_String::create_from_str("Java heap space", CHECK);
 802   java_lang_Throwable::set_message(oom_array->obj_at(_oom_java_heap), msg());
 803 
 804   msg = java_lang_String::create_from_str("C heap space", CHECK);
 805   java_lang_Throwable::set_message(oom_array->obj_at(_oom_c_heap), msg());
 806 
 807   msg = java_lang_String::create_from_str("Metaspace", CHECK);
 808   _msg_metaspace = OopHandle(vm_global(), msg());
 809   java_lang_Throwable::set_message(oom_array->obj_at(_oom_metaspace), msg());
 810 
 811   msg = java_lang_String::create_from_str("Compressed class space", CHECK);
 812   _msg_class_metaspace = OopHandle(vm_global(), msg());
 813   java_lang_Throwable::set_message(oom_array->obj_at(_oom_class_metaspace), msg());
 814 
 815   msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK);
 816   java_lang_Throwable::set_message(oom_array->obj_at(_oom_array_size), msg());
 817 
 818   msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK);
 819   java_lang_Throwable::set_message(oom_array->obj_at(_oom_gc_overhead_limit), msg());
 820 
 821   msg = java_lang_String::create_from_str("Java heap space: failed reallocation of scalar replaced objects", CHECK);
 822   java_lang_Throwable::set_message(oom_array->obj_at(_oom_realloc_objects), msg());
 823 
 824   // Setup the array of errors that have preallocated backtrace
 825   int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;
 826   refArrayOop instance = oopFactory::new_refArray(ik, len, CHECK);
 827   _preallocated_out_of_memory_error_array = OopHandle(vm_global(), instance);
 828   refArrayHandle preallocated_oom_array(THREAD, instance);
 829 
 830   for (int i=0; i<len; i++) {
 831     oop err = ik->allocate_instance(CHECK);
 832     Handle err_h(THREAD, err);
 833     java_lang_Throwable::allocate_backtrace(err_h, CHECK);
 834     preallocated_oom_array->obj_at_put(i, err_h());
 835   }
 836   _preallocated_out_of_memory_error_avail_count = (jint)len;
 837 }
 838 
 839 intptr_t Universe::_non_oop_bits = 0;
 840 
 841 void* Universe::non_oop_word() {
 842   // Neither the high bits nor the low bits of this value is allowed
 843   // to look like (respectively) the high or low bits of a real oop.
 844   //
 845   // High and low are CPU-specific notions, but low always includes
 846   // the low-order bit.  Since oops are always aligned at least mod 4,
 847   // setting the low-order bit will ensure that the low half of the
 848   // word will never look like that of a real oop.

1064     // <init> function before java_lang_Class is linked. Print error and exit.
1065     vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",
1066                                  ik->name()->as_C_string(), method));
1067   }
1068 
1069   _klass = ik;
1070   _method_idnum = m->method_idnum();
1071   assert(_method_idnum >= 0, "sanity check");
1072 }
1073 
1074 Method* LatestMethodCache::get_method() {
1075   if (_klass == nullptr) {
1076     return nullptr;
1077   } else {
1078     Method* m = _klass->method_with_idnum(_method_idnum);
1079     assert(m != nullptr, "sanity check");
1080     return m;
1081   }
1082 }
1083 
1084 Method* Universe::finalizer_register_method()        { return _finalizer_register_cache.get_method(); }
1085 Method* Universe::loader_addClass_method()           { return _loader_addClass_cache.get_method(); }
1086 Method* Universe::throw_illegal_access_error()       { return _throw_illegal_access_error_cache.get_method(); }
1087 Method* Universe::throw_no_such_method_error()       { return _throw_no_such_method_error_cache.get_method(); }
1088 Method* Universe::do_stack_walk_method()             { return _do_stack_walk_cache.get_method(); }
1089 Method* Universe::is_substitutable_method()          { return _is_substitutable_cache.get_method(); }
1090 Method* Universe::value_object_hash_code_method()    { return _value_object_hash_code_cache.get_method(); }
1091 
1092 void Universe::initialize_known_methods(JavaThread* current) {
1093   // Set up static method for registering finalizers
1094   _finalizer_register_cache.init(current,
1095                           vmClasses::Finalizer_klass(),
1096                           "register",
1097                           vmSymbols::object_void_signature(), true);
1098 
1099   _throw_illegal_access_error_cache.init(current,
1100                           vmClasses::internal_Unsafe_klass(),
1101                           "throwIllegalAccessError",
1102                           vmSymbols::void_method_signature(), true);
1103 
1104   _throw_no_such_method_error_cache.init(current,
1105                           vmClasses::internal_Unsafe_klass(),
1106                           "throwNoSuchMethodError",
1107                           vmSymbols::void_method_signature(), true);
1108 
1109   // Set up method for registering loaded classes in class loader vector
1110   _loader_addClass_cache.init(current,
1111                           vmClasses::ClassLoader_klass(),
1112                           "addClass",
1113                           vmSymbols::class_void_signature(), false);
1114 
1115   // Set up method for stack walking
1116   _do_stack_walk_cache.init(current,
1117                           vmClasses::AbstractStackWalker_klass(),
1118                           "doStackWalk",
1119                           vmSymbols::doStackWalk_signature(), false);
1120 
1121   // Set up substitutability testing
1122   ResourceMark rm(current);
1123   _is_substitutable_cache.init(current,
1124                           vmClasses::ValueObjectMethods_klass(),
1125                           vmSymbols::isSubstitutable_name()->as_C_string(),
1126                           vmSymbols::object_object_boolean_signature(), true);
1127   _value_object_hash_code_cache.init(current,
1128                           vmClasses::ValueObjectMethods_klass(),
1129                           vmSymbols::valueObjectHashCode_name()->as_C_string(),
1130                           vmSymbols::object_int_signature(), true);
1131 }
1132 
1133 void universe2_init() {
1134   EXCEPTION_MARK;
1135   Universe::genesis(CATCH);
1136 }
1137 
1138 // Set after initialization of the module runtime, call_initModuleRuntime
1139 void universe_post_module_init() {
1140   Universe::_module_initialized = true;
1141 }
1142 
1143 bool universe_post_init() {
1144   assert(!is_init_completed(), "Error: initialization not yet completed!");
1145   Universe::_fully_initialized = true;
1146   EXCEPTION_MARK;
1147   if (!CDSConfig::is_using_archive()) {
1148     reinitialize_vtables();
1149     reinitialize_itables();
1150   }
< prev index next >