/* * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. *
*/
// Message details for OOME objects, preallocate these objects since they could be // used when throwing OOME, we should try to avoid further allocation in such case
OopHandle Universe::_msg_metaspace;
OopHandle Universe::_msg_class_metaspace;
// These variables are guarded by FullGCALot_lock.
debug_only(OopHandle Universe::_fullgc_alot_dummy_array;)
debug_only(int Universe::_fullgc_alot_dummy_next = 0;)
void Universe::basic_type_classes_do(KlassClosure *closure) { for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
closure->do_klass(_typeArrayKlassObjs[i]);
} // We don't do the following because it will confuse JVMTI. // _fillerArrayKlassObj is used only by GC, which doesn't need to see // this klass from basic_type_classes_do(). // // closure->do_klass(_fillerArrayKlassObj);
}
void Universe::update_archived_basic_type_mirrors() { if (ArchiveHeapLoader::are_archived_mirrors_available()) { for (int i = T_BOOLEAN; i < T_VOID+1; i++) { int index = _archived_basic_type_mirror_indices[i]; if (!is_reference_type((BasicType)i) && index >= 0) {
oop mirror_oop = HeapShared::get_root(index);
assert(mirror_oop != NULL, "must be");
_basic_type_mirrors[i] = OopHandle(vm_global(), mirror_oop);
}
}
}
} #endif
void Universe::serialize(SerializeClosure* f) {
#if INCLUDE_CDS_JAVA_HEAP for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
f->do_u4((u4*)&_archived_basic_type_mirror_indices[i]); // if f->reading(): We can't call HeapShared::get_root() yet, as the heap // contents may need to be relocated. _basic_type_mirrors[i] will be // updated later in Universe::update_archived_basic_type_mirrors().
} #endif
f->do_ptr((void**)&_fillerArrayKlassObj); for (int i = 0; i < T_LONG+1; i++) {
f->do_ptr((void**)&_typeArrayKlassObjs[i]);
}
// determine base vtable size; without that we cannot create the array klasses
compute_base_vtable_size();
if (!UseSharedSpaces) { // Initialization of the fillerArrayKlass must come before regular // int-TypeArrayKlass so that the int-Array mirror points to the // int-TypeArrayKlass.
_fillerArrayKlassObj = TypeArrayKlass::create_klass(T_INT, "Ljdk/internal/vm/FillerArray;", CHECK); for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
_typeArrayKlassObjs[i] = TypeArrayKlass::create_klass((BasicType)i, CHECK);
}
#if INCLUDE_CDS if (UseSharedSpaces) { // Verify shared interfaces array.
assert(_the_array_interfaces_array->at(0) ==
vmClasses::Cloneable_klass(), "u3");
assert(_the_array_interfaces_array->at(1) ==
vmClasses::Serializable_klass(), "u3");
} else #endif
{ // Set up shared interfaces array. (Do this before supers are set up.)
_the_array_interfaces_array->at_put(0, vmClasses::Cloneable_klass());
_the_array_interfaces_array->at_put(1, vmClasses::Serializable_klass());
}
assert(_fillerArrayKlassObj != intArrayKlassObj(), "Internal filler array klass should be different to int array Klass");
} // end of core bootstrapping
// Create a handle for reference_pending_list
_reference_pending_list = OopHandle(vm_global(), NULL);
// Maybe this could be lifted up now that object array can be initialized // during the bootstrapping.
// OLD // Initialize _objectArrayKlass after core bootstraping to make // sure the super class is set up properly for _objectArrayKlass. // --- // NEW // Since some of the old system object arrays have been converted to // ordinary object arrays, _objectArrayKlass will be loaded when // SystemDictionary::initialize(CHECK); is run. See the extra check // for Object_klass_loaded in objArrayKlassKlass::allocate_objArray_klass_impl.
_objectArrayKlassObj = InstanceKlass::
cast(vmClasses::Object_klass())->array_klass(1, CHECK); // OLD // Add the class to the class hierarchy manually to make sure that // its vtable is initialized after core bootstrapping is completed. // --- // New // Have already been initialized.
_objectArrayKlassObj->append_to_sibling_list();
#ifdef ASSERT if (FullGCALot) { // Allocate an array of dummy objects. // We'd like these to be at the bottom of the old generation, // so that when we free one and then collect, // (almost) the whole heap moves // and we find out if we actually update all the oops correctly. // But we can't allocate directly in the old generation, // so we allocate wherever, and hope that the first collection // moves these objects to the bottom of the old generation. int size = FullGCALotDummies * 2;
objArrayOop naked_array = oopFactory::new_objArray(vmClasses::Object_klass(), size, CHECK);
objArrayHandle dummy_array(THREAD, naked_array); int i = 0; while (i < size) { // Allocate dummy in old generation
oop dummy = vmClasses::Object_klass()->allocate_instance(CHECK);
dummy_array->obj_at_put(i++, dummy);
}
{ // Only modify the global variable inside the mutex. // If we had a race to here, the other dummy_array instances // and their elements just get dropped on the floor, which is fine.
MutexLocker ml(THREAD, FullGCALot_lock); if (_fullgc_alot_dummy_array.is_empty()) {
_fullgc_alot_dummy_array = OopHandle(vm_global(), dummy_array());
}
}
assert(i == ((objArrayOop)_fullgc_alot_dummy_array.resolve())->length(), "just checking");
} #endif
}
// check that all basic type mirrors are mapped also for (int i = T_BOOLEAN; i < T_VOID+1; i++) { if (!is_reference_type((BasicType)i)) {
oop m = _basic_type_mirrors[i].resolve();
assert(m != NULL, "archived mirrors should not be NULL");
}
}
} else // _basic_type_mirrors[T_INT], etc, are NULL if archived heap is not mapped. #endif
{ for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
BasicType bt = (BasicType)i; if (!is_reference_type(bt)) {
oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
_basic_type_mirrors[i] = OopHandle(vm_global(), m);
}
CDS_JAVA_HEAP_ONLY(_archived_basic_type_mirror_indices[i] = -1);
}
}
}
void Universe::fixup_mirrors(TRAPS) { // Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly, // but we cannot do that for classes created before java.lang.Class is loaded. Here we simply // walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note // that the number of objects allocated at this point is very small.
assert(vmClasses::Class_klass_loaded(), "java.lang.Class should be loaded");
HandleMark hm(THREAD);
if (!UseSharedSpaces) { // Cache the start of the static fields
InstanceMirrorKlass::init_offset_of_static_fields();
}
GrowableArray <Klass*>* list = java_lang_Class::fixup_mirror_list(); int list_length = list->length(); for (int i = 0; i < list_length; i++) {
Klass* k = list->at(i);
assert(k->is_klass(), "List should only hold classes");
java_lang_Class::fixup_mirror(k, CATCH);
} delete java_lang_Class::fixup_mirror_list();
java_lang_Class::set_fixup_mirror_list(NULL);
}
#define assert_pll_locked(test) \
assert(Heap_lock->test(), "Reference pending list access requires lock")
staticvoid reinitialize_vtables() { // The vtables are initialized by starting at java.lang.Object and // initializing through the subclass links, so that the super // classes are always initialized first. for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
Klass* sub = iter.klass();
sub->vtable().initialize_vtable();
}
}
staticvoid reinitialize_itables() {
class ReinitTableClosure : public KlassClosure { public: void do_klass(Klass* k) { if (k->is_instance_klass()) {
InstanceKlass::cast(k)->itable().initialize_itable();
}
}
};
// the array of preallocated errors with backtraces
objArrayOop Universe::preallocated_out_of_memory_errors() { return (objArrayOop)_preallocated_out_of_memory_error_array.resolve();
}
// Throw default _out_of_memory_error_retry object as it will never propagate out of the VM
oop Universe::out_of_memory_error_retry() { return out_of_memory_errors()->obj_at(_oom_retry); }
oop Universe::delayed_stack_overflow_error_message() { return _delayed_stack_overflow_error_message.resolve(); }
bool Universe::should_fill_in_stack_trace(Handle throwable) { // never attempt to fill in the stack trace of preallocated errors that do not have // backtrace. These errors are kept alive forever and may be "re-used" when all // preallocated errors with backtrace have been consumed. Also need to avoid // a potential loop which could happen if an out of memory occurs when attempting // to allocate the backtrace.
objArrayOop preallocated_oom = out_of_memory_errors(); for (int i = 0; i < _oom_count; i++) { if (throwable() == preallocated_oom->obj_at(i)) { returnfalse;
}
} returntrue;
}
oop Universe::gen_out_of_memory_error(oop default_err) { // generate an out of memory error: // - if there is a preallocated error and stack traces are available // (j.l.Throwable is initialized), then return the preallocated // error with a filled in stack trace, and with the message // provided by the default error. // - otherwise, return the default error, without a stack trace. int next; if ((_preallocated_out_of_memory_error_avail_count > 0) &&
vmClasses::Throwable_klass()->is_initialized()) {
next = (int)Atomic::add(&_preallocated_out_of_memory_error_avail_count, -1);
assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");
} else {
next = -1;
} if (next < 0) { // all preallocated errors have been used. // return default return default_err;
} else {
JavaThread* current = JavaThread::current();
Handle default_err_h(current, default_err); // get the error object at the slot and set set it to NULL so that the // array isn't keeping it alive anymore.
Handle exc(current, preallocated_out_of_memory_errors()->obj_at(next));
assert(exc() != NULL, "slot has been used already");
preallocated_out_of_memory_errors()->obj_at_put(next, NULL);
// use the message from the default error
oop msg = java_lang_Throwable::message(default_err_h());
assert(msg != NULL, "no message");
java_lang_Throwable::set_message(exc(), msg);
// populate the stack trace and return it.
java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc); return exc();
}
}
void* Universe::non_oop_word() { // Neither the high bits nor the low bits of this value is allowed // to look like (respectively) the high or low bits of a real oop. // // High and low are CPU-specific notions, but low always includes // the low-order bit. Since oops are always aligned at least mod 4, // setting the low-order bit will ensure that the low half of the // word will never look like that of a real oop. // // Using the OS-supplied non-memory-address word (usually 0 or -1) // will take care of the high bits, however many there are.
jint universe_init() {
assert(!Universe::_fully_initialized, "called after initialize_vtables");
guarantee(1 << LogHeapWordSize == sizeof(HeapWord), "LogHeapWordSize is incorrect.");
guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");
guarantee(sizeof(oop) % sizeof(HeapWord) == 0, "oop size is not not a multiple of HeapWord size");
jint status = Universe::initialize_heap(); if (status != JNI_OK) { return status;
}
Universe::initialize_tlab();
Metaspace::global_initialize();
// Initialize performance counters for metaspaces
MetaspaceCounters::initialize_performance_counters();
// Checks 'AfterMemoryInit' constraints. if (!JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterMemoryInit)) { return JNI_EINVAL;
}
// Create memory for metadata. Must be after initializing heap for // DumpSharedSpaces.
ClassLoaderData::init_null_class_loader_data();
// We have a heap so create the Method* caches before // Metaspace::initialize_shared_spaces() tries to populate them.
Universe::_finalizer_register_cache = new LatestMethodCache();
Universe::_loader_addClass_cache = new LatestMethodCache();
Universe::_throw_illegal_access_error_cache = new LatestMethodCache();
Universe::_throw_no_such_method_error_cache = new LatestMethodCache();
Universe::_do_stack_walk_cache = new LatestMethodCache();
#if INCLUDE_CDS
DynamicArchive::check_for_dynamic_dump(); if (UseSharedSpaces) { // Read the data structures supporting the shared spaces (shared // system dictionary, symbol table, etc.). After that, access to // the file (other than the mapped regions) is no longer needed, and // the file is closed. Closing the file does not affect the // currently mapped regions.
MetaspaceShared::initialize_shared_spaces();
StringTable::create_table(); if (ArchiveHeapLoader::is_loaded()) {
StringTable::transfer_shared_strings_to_local_table();
}
} else #endif
{
SymbolTable::create_table();
StringTable::create_table();
}
#if INCLUDE_CDS if (Arguments::is_dumping_archive()) {
MetaspaceShared::prepare_for_dumping();
} #endif
if (strlen(VerifySubSet) > 0) {
Universe::initialize_verify_flags();
}
assert(alignment <= Arguments::conservative_max_heap_alignment(), "actual alignment " SIZE_FORMAT " must be within maximum heap alignment " SIZE_FORMAT,
alignment, Arguments::conservative_max_heap_alignment());
size_t total_reserved = align_up(heap_size, alignment);
assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())), "heap size is too big for compressed oops");
size_t page_size = os::vm_page_size(); if (UseLargePages && is_aligned(alignment, os::large_page_size())) {
page_size = os::large_page_size();
} else { // Parallel is the only collector that might opt out of using large pages // for the heap.
assert(!UseLargePages || UseParallelGC , "Wrong alignment to use large pages");
}
// Now create the space.
ReservedHeapSpace total_rs(total_reserved, alignment, page_size, AllocateHeapAt);
if (total_rs.is_reserved()) {
assert((total_reserved == total_rs.size()) && ((uintptr_t)total_rs.base() % alignment == 0), "must be exactly of required size and alignment"); // We are good.
if (AllocateHeapAt != NULL) {
log_info(gc,heap)("Successfully allocated Java heap at location %s", AllocateHeapAt);
}
if (UseCompressedOops) {
CompressedOops::initialize(total_rs);
}
void initialize_known_method(LatestMethodCache* method_cache,
InstanceKlass* ik, constchar* method,
Symbol* signature, bool is_static, TRAPS)
{
TempNewSymbol name = SymbolTable::new_symbol(method);
Method* m = NULL; // The klass must be linked before looking up the method. if (!ik->link_class_or_fail(THREAD) ||
((m = ik->find_method(name, signature)) == NULL) ||
is_static != m->is_static()) {
ResourceMark rm(THREAD); // NoSuchMethodException doesn't actually work because it tries to run the // <init> function before java_lang_Class is linked. Print error and exit.
vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",
ik->name()->as_C_string(), method));
}
method_cache->init(ik, m);
}
void Universe::initialize_known_methods(TRAPS) { // Set up static method for registering finalizers
initialize_known_method(_finalizer_register_cache,
vmClasses::Finalizer_klass(), "register",
vmSymbols::object_void_signature(), true, CHECK);
// Set up method for registering loaded classes in class loader vector
initialize_known_method(_loader_addClass_cache,
vmClasses::ClassLoader_klass(), "addClass",
vmSymbols::class_void_signature(), false, CHECK);
// Set up method for stack walking
initialize_known_method(_do_stack_walk_cache,
vmClasses::AbstractStackWalker_klass(), "doStackWalk",
vmSymbols::doStackWalk_signature(), false, CHECK);
}
oop instance; // Setup preallocated cause message for delayed StackOverflowError if (StackReservedPages > 0) {
instance = java_lang_String::create_oop_from_str("Delayed StackOverflowError due to ReservedStackAccess annotated method", CHECK_false);
Universe::_delayed_stack_overflow_error_message = OopHandle(Universe::vm_global(), instance);
}
// Setup preallocated NullPointerException // (this is currently used for a cheap & dirty solution in compiler exception handling)
Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_NullPointerException(), true, CHECK_false);
instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
Universe::_null_ptr_exception_instance = OopHandle(Universe::vm_global(), instance);
// Setup preallocated ArithmeticException // (this is currently used for a cheap & dirty solution in compiler exception handling)
k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ArithmeticException(), true, CHECK_false);
instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
Universe::_arithmetic_exception_instance = OopHandle(Universe::vm_global(), instance);
// Virtual Machine Error for when we get into a situation we can't resolve
k = vmClasses::VirtualMachineError_klass(); bool linked = InstanceKlass::cast(k)->link_class_or_fail(CHECK_false); if (!linked) {
tty->print_cr("Unable to link/verify VirtualMachineError class"); returnfalse; // initialization failed
}
instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);
Universe::_virtual_machine_error_instance = OopHandle(Universe::vm_global(), instance);
Handle msg = java_lang_String::create_from_str("/ by zero", CHECK_false);
java_lang_Throwable::set_message(Universe::arithmetic_exception_instance(), msg());
Universe::initialize_known_methods(CHECK_false);
// This needs to be done before the first scavenge/gc, since // it's an input to soft ref clearing policy.
{
MutexLocker x(THREAD, Heap_lock);
Universe::heap()->update_capacity_and_used_at_gc();
}
void Universe::verify(VerifyOption option, constchar* prefix) {
COMPILER2_PRESENT(
assert(!DerivedPointerTable::is_active(), "DPT should not be active during verification " "(of thread stacks below)");
)
Thread* thread = Thread::current();
ResourceMark rm(thread);
HandleMark hm(thread); // Handles created during verification can be zapped
_verify_count++;
FormatBuffer<> title("Verifying %s", prefix);
GCTraceTime(Info, gc, verify) tm(title.buffer()); if (should_verify_subset(Verify_Threads)) {
log_debug(gc, verify)("Threads");
Threads::verify();
} if (should_verify_subset(Verify_Heap)) {
log_debug(gc, verify)("Heap");
heap()->verify(option);
} if (should_verify_subset(Verify_SymbolTable)) {
log_debug(gc, verify)("SymbolTable");
SymbolTable::verify();
} if (should_verify_subset(Verify_StringTable)) {
log_debug(gc, verify)("StringTable");
StringTable::verify();
} if (should_verify_subset(Verify_CodeCache)) {
log_debug(gc, verify)("CodeCache");
CodeCache::verify();
} if (should_verify_subset(Verify_SystemDictionary)) {
log_debug(gc, verify)("SystemDictionary");
SystemDictionary::verify();
} if (should_verify_subset(Verify_ClassLoaderDataGraph)) {
log_debug(gc, verify)("ClassLoaderDataGraph");
ClassLoaderDataGraph::verify();
} if (should_verify_subset(Verify_MetaspaceUtils)) {
log_debug(gc, verify)("MetaspaceUtils");
DEBUG_ONLY(MetaspaceUtils::verify();)
} if (should_verify_subset(Verify_JNIHandles)) {
log_debug(gc, verify)("JNIHandles");
JNIHandles::verify();
} if (should_verify_subset(Verify_CodeCacheOops)) {
log_debug(gc, verify)("CodeCache Oops");
CodeCache::verify_oops();
} if (should_verify_subset(Verify_ResolvedMethodTable)) {
log_debug(gc, verify)("ResolvedMethodTable Oops");
ResolvedMethodTable::verify();
} if (should_verify_subset(Verify_StringDedup)) {
log_debug(gc, verify)("String Deduplication");
StringDedup::verify();
}
}
// decide which low-order bits we require to be clear:
size_t alignSize = MinObjAlignmentInBytes;
size_t min_object_size = CollectedHeap::min_fill_size();
// make an inclusive limit:
uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;
uintptr_t min = (uintptr_t)low_boundary;
assert(min < max, "bad interval");
uintptr_t diff = max ^ min;
// throw away enough low-order bits to make the diff vanish
uintptr_t mask = (uintptr_t)(-1); while ((mask & diff) != 0)
mask <<= 1;
uintptr_t bits = (min & mask);
assert(bits == (max & mask), "correct mask"); // check an intermediate value between min and max, just to make sure:
assert(bits == ((min + (max-min)/2) & mask), "correct mask");
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.