Path: blob/master/src/hotspot/share/memory/universe.cpp
40949 views
/*1* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "cds/heapShared.hpp"26#include "cds/metaspaceShared.hpp"27#include "classfile/classLoader.hpp"28#include "classfile/classLoaderDataGraph.hpp"29#include "classfile/javaClasses.hpp"30#include "classfile/stringTable.hpp"31#include "classfile/symbolTable.hpp"32#include "classfile/systemDictionary.hpp"33#include "classfile/vmClasses.hpp"34#include "classfile/vmSymbols.hpp"35#include "code/codeBehaviours.hpp"36#include "code/codeCache.hpp"37#include "compiler/oopMap.hpp"38#include "gc/shared/collectedHeap.inline.hpp"39#include "gc/shared/gcArguments.hpp"40#include "gc/shared/gcConfig.hpp"41#include "gc/shared/gcLogPrecious.hpp"42#include "gc/shared/gcTraceTime.inline.hpp"43#include "gc/shared/oopStorageSet.hpp"44#include "gc/shared/stringdedup/stringDedup.hpp"45#include "gc/shared/tlab_globals.hpp"46#include "logging/log.hpp"47#include "logging/logStream.hpp"48#include "memory/metadataFactory.hpp"49#include "memory/metaspaceClosure.hpp"50#include "memory/metaspaceCounters.hpp"51#include "memory/metaspaceUtils.hpp"52#include "memory/oopFactory.hpp"53#include "memory/resourceArea.hpp"54#include "memory/universe.hpp"55#include "oops/compressedOops.hpp"56#include "oops/instanceKlass.hpp"57#include "oops/instanceMirrorKlass.hpp"58#include "oops/klass.inline.hpp"59#include "oops/objArrayOop.inline.hpp"60#include "oops/oop.inline.hpp"61#include "oops/oopHandle.inline.hpp"62#include "oops/typeArrayKlass.hpp"63#include "prims/resolvedMethodTable.hpp"64#include "runtime/arguments.hpp"65#include "runtime/atomic.hpp"66#include "runtime/flags/jvmFlagLimit.hpp"67#include "runtime/handles.inline.hpp"68#include "runtime/init.hpp"69#include "runtime/java.hpp"70#include "runtime/jniHandles.hpp"71#include "runtime/thread.inline.hpp"72#include "runtime/timerTrace.hpp"73#include "services/memoryService.hpp"74#include "utilities/align.hpp"75#include "utilities/autoRestore.hpp"76#include "utilities/debug.hpp"77#include "utilities/formatBuffer.hpp"78#include "utilities/macros.hpp"79#include "utilities/ostream.hpp"80#include "utilities/preserveException.hpp"8182// Known objects83Klass* Universe::_typeArrayKlassObjs[T_LONG+1] = { NULL /*, NULL...*/ };84Klass* Universe::_objectArrayKlassObj = NULL;85OopHandle Universe::_mirrors[T_VOID+1];8687OopHandle Universe::_main_thread_group;88OopHandle Universe::_system_thread_group;89OopHandle Universe::_the_empty_class_array;90OopHandle Universe::_the_null_string;91OopHandle Universe::_the_min_jint_string;9293OopHandle Universe::_the_null_sentinel;9495// _out_of_memory_errors is an objArray96enum OutOfMemoryInstance { _oom_java_heap,97_oom_c_heap,98_oom_metaspace,99_oom_class_metaspace,100_oom_array_size,101_oom_gc_overhead_limit,102_oom_realloc_objects,103_oom_retry,104_oom_count };105106OopHandle Universe::_out_of_memory_errors;107OopHandle Universe::_delayed_stack_overflow_error_message;108OopHandle Universe::_preallocated_out_of_memory_error_array;109volatile jint Universe::_preallocated_out_of_memory_error_avail_count = 0;110111OopHandle Universe::_null_ptr_exception_instance;112OopHandle Universe::_arithmetic_exception_instance;113OopHandle Universe::_virtual_machine_error_instance;114115OopHandle Universe::_reference_pending_list;116117Array<Klass*>* Universe::_the_array_interfaces_array = NULL;118LatestMethodCache* Universe::_finalizer_register_cache = NULL;119LatestMethodCache* Universe::_loader_addClass_cache = NULL;120LatestMethodCache* Universe::_throw_illegal_access_error_cache = NULL;121LatestMethodCache* Universe::_throw_no_such_method_error_cache = NULL;122LatestMethodCache* Universe::_do_stack_walk_cache = NULL;123124bool Universe::_verify_in_progress = false;125long Universe::verify_flags = Universe::Verify_All;126127Array<int>* Universe::_the_empty_int_array = NULL;128Array<u2>* Universe::_the_empty_short_array = NULL;129Array<Klass*>* Universe::_the_empty_klass_array = NULL;130Array<InstanceKlass*>* Universe::_the_empty_instance_klass_array = NULL;131Array<Method*>* Universe::_the_empty_method_array = NULL;132133// These variables are guarded by FullGCALot_lock.134debug_only(OopHandle Universe::_fullgc_alot_dummy_array;)135debug_only(int Universe::_fullgc_alot_dummy_next = 0;)136137// Heap138int Universe::_verify_count = 0;139140// Oop verification (see MacroAssembler::verify_oop)141uintptr_t Universe::_verify_oop_mask = 0;142uintptr_t Universe::_verify_oop_bits = (uintptr_t) -1;143144int Universe::_base_vtable_size = 0;145bool Universe::_bootstrapping = false;146bool Universe::_module_initialized = false;147bool Universe::_fully_initialized = false;148149OopStorage* Universe::_vm_weak = NULL;150OopStorage* Universe::_vm_global = NULL;151152CollectedHeap* Universe::_collectedHeap = NULL;153154objArrayOop Universe::the_empty_class_array () {155return (objArrayOop)_the_empty_class_array.resolve();156}157158oop Universe::main_thread_group() { return _main_thread_group.resolve(); }159void Universe::set_main_thread_group(oop group) { _main_thread_group = OopHandle(vm_global(), group); }160161oop Universe::system_thread_group() { return _system_thread_group.resolve(); }162void Universe::set_system_thread_group(oop group) { _system_thread_group = OopHandle(vm_global(), group); }163164oop Universe::the_null_string() { return _the_null_string.resolve(); }165oop Universe::the_min_jint_string() { return _the_min_jint_string.resolve(); }166167oop Universe::null_ptr_exception_instance() { return _null_ptr_exception_instance.resolve(); }168oop Universe::arithmetic_exception_instance() { return _arithmetic_exception_instance.resolve(); }169oop Universe::virtual_machine_error_instance() { return _virtual_machine_error_instance.resolve(); }170171oop Universe::the_null_sentinel() { return _the_null_sentinel.resolve(); }172173oop Universe::int_mirror() { return check_mirror(_mirrors[T_INT].resolve()); }174oop Universe::float_mirror() { return check_mirror(_mirrors[T_FLOAT].resolve()); }175oop Universe::double_mirror() { return check_mirror(_mirrors[T_DOUBLE].resolve()); }176oop Universe::byte_mirror() { return check_mirror(_mirrors[T_BYTE].resolve()); }177oop Universe::bool_mirror() { return check_mirror(_mirrors[T_BOOLEAN].resolve()); }178oop Universe::char_mirror() { return check_mirror(_mirrors[T_CHAR].resolve()); }179oop Universe::long_mirror() { return check_mirror(_mirrors[T_LONG].resolve()); }180oop Universe::short_mirror() { return check_mirror(_mirrors[T_SHORT].resolve()); }181oop Universe::void_mirror() { return check_mirror(_mirrors[T_VOID].resolve()); }182183oop Universe::java_mirror(BasicType t) {184assert((uint)t < T_VOID+1, "range check");185return check_mirror(_mirrors[t].resolve());186}187188// Used by CDS dumping189void Universe::replace_mirror(BasicType t, oop new_mirror) {190Universe::_mirrors[t].replace(new_mirror);191}192193void Universe::basic_type_classes_do(void f(Klass*)) {194for (int i = T_BOOLEAN; i < T_LONG+1; i++) {195f(_typeArrayKlassObjs[i]);196}197}198199void Universe::basic_type_classes_do(KlassClosure *closure) {200for (int i = T_BOOLEAN; i < T_LONG+1; i++) {201closure->do_klass(_typeArrayKlassObjs[i]);202}203}204205void LatestMethodCache::metaspace_pointers_do(MetaspaceClosure* it) {206it->push(&_klass);207}208209void Universe::metaspace_pointers_do(MetaspaceClosure* it) {210for (int i = 0; i < T_LONG+1; i++) {211it->push(&_typeArrayKlassObjs[i]);212}213it->push(&_objectArrayKlassObj);214215it->push(&_the_empty_int_array);216it->push(&_the_empty_short_array);217it->push(&_the_empty_klass_array);218it->push(&_the_empty_instance_klass_array);219it->push(&_the_empty_method_array);220it->push(&_the_array_interfaces_array);221222_finalizer_register_cache->metaspace_pointers_do(it);223_loader_addClass_cache->metaspace_pointers_do(it);224_throw_illegal_access_error_cache->metaspace_pointers_do(it);225_throw_no_such_method_error_cache->metaspace_pointers_do(it);226_do_stack_walk_cache->metaspace_pointers_do(it);227}228229// Serialize metadata and pointers to primitive type mirrors in and out of CDS archive230void Universe::serialize(SerializeClosure* f) {231232#if INCLUDE_CDS_JAVA_HEAP233{234oop mirror_oop;235for (int i = T_BOOLEAN; i < T_VOID+1; i++) {236if (f->reading()) {237f->do_oop(&mirror_oop); // read from archive238assert(oopDesc::is_oop_or_null(mirror_oop), "is oop");239// Only create an OopHandle for non-null mirrors240if (mirror_oop != NULL) {241_mirrors[i] = OopHandle(vm_global(), mirror_oop);242}243} else {244if (HeapShared::is_heap_object_archiving_allowed()) {245mirror_oop = _mirrors[i].resolve();246} else {247mirror_oop = NULL;248}249f->do_oop(&mirror_oop); // write to archive250}251if (mirror_oop != NULL) { // may be null if archived heap is disabled252java_lang_Class::update_archived_primitive_mirror_native_pointers(mirror_oop);253}254}255}256#endif257258for (int i = 0; i < T_LONG+1; i++) {259f->do_ptr((void**)&_typeArrayKlassObjs[i]);260}261262f->do_ptr((void**)&_objectArrayKlassObj);263f->do_ptr((void**)&_the_array_interfaces_array);264f->do_ptr((void**)&_the_empty_int_array);265f->do_ptr((void**)&_the_empty_short_array);266f->do_ptr((void**)&_the_empty_method_array);267f->do_ptr((void**)&_the_empty_klass_array);268f->do_ptr((void**)&_the_empty_instance_klass_array);269_finalizer_register_cache->serialize(f);270_loader_addClass_cache->serialize(f);271_throw_illegal_access_error_cache->serialize(f);272_throw_no_such_method_error_cache->serialize(f);273_do_stack_walk_cache->serialize(f);274}275276277void Universe::check_alignment(uintx size, uintx alignment, const char* name) {278if (size < alignment || size % alignment != 0) {279vm_exit_during_initialization(280err_msg("Size of %s (" UINTX_FORMAT " bytes) must be aligned to " UINTX_FORMAT " bytes", name, size, alignment));281}282}283284void initialize_basic_type_klass(Klass* k, TRAPS) {285Klass* ok = vmClasses::Object_klass();286#if INCLUDE_CDS287if (UseSharedSpaces) {288ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();289assert(k->super() == ok, "u3");290if (k->is_instance_klass()) {291InstanceKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), NULL, CHECK);292} else {293ArrayKlass::cast(k)->restore_unshareable_info(loader_data, Handle(), CHECK);294}295} else296#endif297{298k->initialize_supers(ok, NULL, CHECK);299}300k->append_to_sibling_list();301}302303void Universe::genesis(TRAPS) {304ResourceMark rm(THREAD);305HandleMark hm(THREAD);306307{ AutoModifyRestore<bool> temporarily(_bootstrapping, true);308309{ MutexLocker mc(THREAD, Compile_lock);310311java_lang_Class::allocate_fixup_lists();312313// determine base vtable size; without that we cannot create the array klasses314compute_base_vtable_size();315316if (!UseSharedSpaces) {317for (int i = T_BOOLEAN; i < T_LONG+1; i++) {318_typeArrayKlassObjs[i] = TypeArrayKlass::create_klass((BasicType)i, CHECK);319}320321ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();322323_the_array_interfaces_array = MetadataFactory::new_array<Klass*>(null_cld, 2, NULL, CHECK);324_the_empty_int_array = MetadataFactory::new_array<int>(null_cld, 0, CHECK);325_the_empty_short_array = MetadataFactory::new_array<u2>(null_cld, 0, CHECK);326_the_empty_method_array = MetadataFactory::new_array<Method*>(null_cld, 0, CHECK);327_the_empty_klass_array = MetadataFactory::new_array<Klass*>(null_cld, 0, CHECK);328_the_empty_instance_klass_array = MetadataFactory::new_array<InstanceKlass*>(null_cld, 0, CHECK);329}330}331332vmSymbols::initialize();333334SystemDictionary::initialize(CHECK);335336// Create string constants337oop s = StringTable::intern("null", CHECK);338_the_null_string = OopHandle(vm_global(), s);339s = StringTable::intern("-2147483648", CHECK);340_the_min_jint_string = OopHandle(vm_global(), s);341342343#if INCLUDE_CDS344if (UseSharedSpaces) {345// Verify shared interfaces array.346assert(_the_array_interfaces_array->at(0) ==347vmClasses::Cloneable_klass(), "u3");348assert(_the_array_interfaces_array->at(1) ==349vmClasses::Serializable_klass(), "u3");350} else351#endif352{353// Set up shared interfaces array. (Do this before supers are set up.)354_the_array_interfaces_array->at_put(0, vmClasses::Cloneable_klass());355_the_array_interfaces_array->at_put(1, vmClasses::Serializable_klass());356}357358initialize_basic_type_klass(boolArrayKlassObj(), CHECK);359initialize_basic_type_klass(charArrayKlassObj(), CHECK);360initialize_basic_type_klass(floatArrayKlassObj(), CHECK);361initialize_basic_type_klass(doubleArrayKlassObj(), CHECK);362initialize_basic_type_klass(byteArrayKlassObj(), CHECK);363initialize_basic_type_klass(shortArrayKlassObj(), CHECK);364initialize_basic_type_klass(intArrayKlassObj(), CHECK);365initialize_basic_type_klass(longArrayKlassObj(), CHECK);366} // end of core bootstrapping367368{369Handle tns = java_lang_String::create_from_str("<null_sentinel>", CHECK);370_the_null_sentinel = OopHandle(vm_global(), tns());371}372373// Create a handle for reference_pending_list374_reference_pending_list = OopHandle(vm_global(), NULL);375376// Maybe this could be lifted up now that object array can be initialized377// during the bootstrapping.378379// OLD380// Initialize _objectArrayKlass after core bootstraping to make381// sure the super class is set up properly for _objectArrayKlass.382// ---383// NEW384// Since some of the old system object arrays have been converted to385// ordinary object arrays, _objectArrayKlass will be loaded when386// SystemDictionary::initialize(CHECK); is run. See the extra check387// for Object_klass_loaded in objArrayKlassKlass::allocate_objArray_klass_impl.388_objectArrayKlassObj = InstanceKlass::389cast(vmClasses::Object_klass())->array_klass(1, CHECK);390// OLD391// Add the class to the class hierarchy manually to make sure that392// its vtable is initialized after core bootstrapping is completed.393// ---394// New395// Have already been initialized.396_objectArrayKlassObj->append_to_sibling_list();397398#ifdef ASSERT399if (FullGCALot) {400// Allocate an array of dummy objects.401// We'd like these to be at the bottom of the old generation,402// so that when we free one and then collect,403// (almost) the whole heap moves404// and we find out if we actually update all the oops correctly.405// But we can't allocate directly in the old generation,406// so we allocate wherever, and hope that the first collection407// moves these objects to the bottom of the old generation.408int size = FullGCALotDummies * 2;409410objArrayOop naked_array = oopFactory::new_objArray(vmClasses::Object_klass(), size, CHECK);411objArrayHandle dummy_array(THREAD, naked_array);412int i = 0;413while (i < size) {414// Allocate dummy in old generation415oop dummy = vmClasses::Object_klass()->allocate_instance(CHECK);416dummy_array->obj_at_put(i++, dummy);417}418{419// Only modify the global variable inside the mutex.420// If we had a race to here, the other dummy_array instances421// and their elements just get dropped on the floor, which is fine.422MutexLocker ml(THREAD, FullGCALot_lock);423if (_fullgc_alot_dummy_array.is_empty()) {424_fullgc_alot_dummy_array = OopHandle(vm_global(), dummy_array());425}426}427assert(i == ((objArrayOop)_fullgc_alot_dummy_array.resolve())->length(), "just checking");428}429#endif430}431432void Universe::initialize_basic_type_mirrors(TRAPS) {433#if INCLUDE_CDS_JAVA_HEAP434if (UseSharedSpaces &&435HeapShared::open_archive_heap_region_mapped() &&436_mirrors[T_INT].resolve() != NULL) {437assert(HeapShared::is_heap_object_archiving_allowed(), "Sanity");438439// check that all mirrors are mapped also440for (int i = T_BOOLEAN; i < T_VOID+1; i++) {441if (!is_reference_type((BasicType)i)) {442oop m = _mirrors[i].resolve();443assert(m != NULL, "archived mirrors should not be NULL");444}445}446} else447// _mirror[T_INT} could be NULL if archived heap is not mapped.448#endif449{450for (int i = T_BOOLEAN; i < T_VOID+1; i++) {451BasicType bt = (BasicType)i;452if (!is_reference_type(bt)) {453oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);454_mirrors[i] = OopHandle(vm_global(), m);455}456}457}458}459460void Universe::fixup_mirrors(TRAPS) {461// Bootstrap problem: all classes gets a mirror (java.lang.Class instance) assigned eagerly,462// but we cannot do that for classes created before java.lang.Class is loaded. Here we simply463// walk over permanent objects created so far (mostly classes) and fixup their mirrors. Note464// that the number of objects allocated at this point is very small.465assert(vmClasses::Class_klass_loaded(), "java.lang.Class should be loaded");466HandleMark hm(THREAD);467468if (!UseSharedSpaces) {469// Cache the start of the static fields470InstanceMirrorKlass::init_offset_of_static_fields();471}472473GrowableArray <Klass*>* list = java_lang_Class::fixup_mirror_list();474int list_length = list->length();475for (int i = 0; i < list_length; i++) {476Klass* k = list->at(i);477assert(k->is_klass(), "List should only hold classes");478java_lang_Class::fixup_mirror(k, CATCH);479}480delete java_lang_Class::fixup_mirror_list();481java_lang_Class::set_fixup_mirror_list(NULL);482}483484#define assert_pll_locked(test) \485assert(Heap_lock->test(), "Reference pending list access requires lock")486487#define assert_pll_ownership() assert_pll_locked(owned_by_self)488489oop Universe::reference_pending_list() {490if (Thread::current()->is_VM_thread()) {491assert_pll_locked(is_locked);492} else {493assert_pll_ownership();494}495return _reference_pending_list.resolve();496}497498void Universe::clear_reference_pending_list() {499assert_pll_ownership();500_reference_pending_list.replace(NULL);501}502503bool Universe::has_reference_pending_list() {504assert_pll_ownership();505return _reference_pending_list.peek() != NULL;506}507508oop Universe::swap_reference_pending_list(oop list) {509assert_pll_locked(is_locked);510return _reference_pending_list.xchg(list);511}512513#undef assert_pll_locked514#undef assert_pll_ownership515516static void reinitialize_vtables() {517// The vtables are initialized by starting at java.lang.Object and518// initializing through the subclass links, so that the super519// classes are always initialized first.520for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {521Klass* sub = iter.klass();522sub->vtable().initialize_vtable();523}524}525526527static void initialize_itable_for_klass(InstanceKlass* k) {528k->itable().initialize_itable();529}530531532static void reinitialize_itables() {533MutexLocker mcld(ClassLoaderDataGraph_lock);534ClassLoaderDataGraph::dictionary_classes_do(initialize_itable_for_klass);535}536537538bool Universe::on_page_boundary(void* addr) {539return is_aligned(addr, os::vm_page_size());540}541542// the array of preallocated errors with backtraces543objArrayOop Universe::preallocated_out_of_memory_errors() {544return (objArrayOop)_preallocated_out_of_memory_error_array.resolve();545}546547objArrayOop Universe::out_of_memory_errors() { return (objArrayOop)_out_of_memory_errors.resolve(); }548549oop Universe::out_of_memory_error_java_heap() {550return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_java_heap));551}552553oop Universe::out_of_memory_error_c_heap() {554return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_c_heap));555}556557oop Universe::out_of_memory_error_metaspace() {558return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_metaspace));559}560561oop Universe::out_of_memory_error_class_metaspace() {562return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_class_metaspace));563}564565oop Universe::out_of_memory_error_array_size() {566return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_array_size));567}568569oop Universe::out_of_memory_error_gc_overhead_limit() {570return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_gc_overhead_limit));571}572573oop Universe::out_of_memory_error_realloc_objects() {574return gen_out_of_memory_error(out_of_memory_errors()->obj_at(_oom_realloc_objects));575}576577// Throw default _out_of_memory_error_retry object as it will never propagate out of the VM578oop Universe::out_of_memory_error_retry() { return out_of_memory_errors()->obj_at(_oom_retry); }579oop Universe::delayed_stack_overflow_error_message() { return _delayed_stack_overflow_error_message.resolve(); }580581582bool Universe::should_fill_in_stack_trace(Handle throwable) {583// never attempt to fill in the stack trace of preallocated errors that do not have584// backtrace. These errors are kept alive forever and may be "re-used" when all585// preallocated errors with backtrace have been consumed. Also need to avoid586// a potential loop which could happen if an out of memory occurs when attempting587// to allocate the backtrace.588objArrayOop preallocated_oom = out_of_memory_errors();589for (int i = 0; i < _oom_count; i++) {590if (throwable() == preallocated_oom->obj_at(i)) {591return false;592}593}594return true;595}596597598oop Universe::gen_out_of_memory_error(oop default_err) {599// generate an out of memory error:600// - if there is a preallocated error and stack traces are available601// (j.l.Throwable is initialized), then return the preallocated602// error with a filled in stack trace, and with the message603// provided by the default error.604// - otherwise, return the default error, without a stack trace.605int next;606if ((_preallocated_out_of_memory_error_avail_count > 0) &&607vmClasses::Throwable_klass()->is_initialized()) {608next = (int)Atomic::add(&_preallocated_out_of_memory_error_avail_count, -1);609assert(next < (int)PreallocatedOutOfMemoryErrorCount, "avail count is corrupt");610} else {611next = -1;612}613if (next < 0) {614// all preallocated errors have been used.615// return default616return default_err;617} else {618JavaThread* current = JavaThread::current();619Handle default_err_h(current, default_err);620// get the error object at the slot and set set it to NULL so that the621// array isn't keeping it alive anymore.622Handle exc(current, preallocated_out_of_memory_errors()->obj_at(next));623assert(exc() != NULL, "slot has been used already");624preallocated_out_of_memory_errors()->obj_at_put(next, NULL);625626// use the message from the default error627oop msg = java_lang_Throwable::message(default_err_h());628assert(msg != NULL, "no message");629java_lang_Throwable::set_message(exc(), msg);630631// populate the stack trace and return it.632java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(exc);633return exc();634}635}636637// Setup preallocated OutOfMemoryError errors638void Universe::create_preallocated_out_of_memory_errors(TRAPS) {639InstanceKlass* ik = vmClasses::OutOfMemoryError_klass();640objArrayOop oa = oopFactory::new_objArray(ik, _oom_count, CHECK);641objArrayHandle oom_array(THREAD, oa);642643for (int i = 0; i < _oom_count; i++) {644oop oom_obj = ik->allocate_instance(CHECK);645oom_array->obj_at_put(i, oom_obj);646}647_out_of_memory_errors = OopHandle(vm_global(), oom_array());648649Handle msg = java_lang_String::create_from_str("Java heap space", CHECK);650java_lang_Throwable::set_message(oom_array->obj_at(_oom_java_heap), msg());651652msg = java_lang_String::create_from_str("C heap space", CHECK);653java_lang_Throwable::set_message(oom_array->obj_at(_oom_c_heap), msg());654655msg = java_lang_String::create_from_str("Metaspace", CHECK);656java_lang_Throwable::set_message(oom_array->obj_at(_oom_metaspace), msg());657658msg = java_lang_String::create_from_str("Compressed class space", CHECK);659java_lang_Throwable::set_message(oom_array->obj_at(_oom_class_metaspace), msg());660661msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK);662java_lang_Throwable::set_message(oom_array->obj_at(_oom_array_size), msg());663664msg = java_lang_String::create_from_str("GC overhead limit exceeded", CHECK);665java_lang_Throwable::set_message(oom_array->obj_at(_oom_gc_overhead_limit), msg());666667msg = java_lang_String::create_from_str("Java heap space: failed reallocation of scalar replaced objects", CHECK);668java_lang_Throwable::set_message(oom_array->obj_at(_oom_realloc_objects), msg());669670msg = java_lang_String::create_from_str("Java heap space: failed retryable allocation", CHECK);671java_lang_Throwable::set_message(oom_array->obj_at(_oom_retry), msg());672673// Setup the array of errors that have preallocated backtrace674int len = (StackTraceInThrowable) ? (int)PreallocatedOutOfMemoryErrorCount : 0;675objArrayOop instance = oopFactory::new_objArray(ik, len, CHECK);676_preallocated_out_of_memory_error_array = OopHandle(vm_global(), instance);677objArrayHandle preallocated_oom_array(THREAD, instance);678679for (int i=0; i<len; i++) {680oop err = ik->allocate_instance(CHECK);681Handle err_h(THREAD, err);682java_lang_Throwable::allocate_backtrace(err_h, CHECK);683preallocated_oom_array->obj_at_put(i, err_h());684}685_preallocated_out_of_memory_error_avail_count = (jint)len;686}687688intptr_t Universe::_non_oop_bits = 0;689690void* Universe::non_oop_word() {691// Neither the high bits nor the low bits of this value is allowed692// to look like (respectively) the high or low bits of a real oop.693//694// High and low are CPU-specific notions, but low always includes695// the low-order bit. Since oops are always aligned at least mod 4,696// setting the low-order bit will ensure that the low half of the697// word will never look like that of a real oop.698//699// Using the OS-supplied non-memory-address word (usually 0 or -1)700// will take care of the high bits, however many there are.701702if (_non_oop_bits == 0) {703_non_oop_bits = (intptr_t)os::non_memory_address_word() | 1;704}705706return (void*)_non_oop_bits;707}708709bool Universe::contains_non_oop_word(void* p) {710return *(void**)p == non_oop_word();711}712713static void initialize_global_behaviours() {714CompiledICProtectionBehaviour::set_current(new DefaultICProtectionBehaviour());715}716717jint universe_init() {718assert(!Universe::_fully_initialized, "called after initialize_vtables");719guarantee(1 << LogHeapWordSize == sizeof(HeapWord),720"LogHeapWordSize is incorrect.");721guarantee(sizeof(oop) >= sizeof(HeapWord), "HeapWord larger than oop?");722guarantee(sizeof(oop) % sizeof(HeapWord) == 0,723"oop size is not not a multiple of HeapWord size");724725TraceTime timer("Genesis", TRACETIME_LOG(Info, startuptime));726727initialize_global_behaviours();728729GCLogPrecious::initialize();730731GCConfig::arguments()->initialize_heap_sizes();732733jint status = Universe::initialize_heap();734if (status != JNI_OK) {735return status;736}737738Universe::initialize_tlab();739740Metaspace::global_initialize();741742// Initialize performance counters for metaspaces743MetaspaceCounters::initialize_performance_counters();744745// Checks 'AfterMemoryInit' constraints.746if (!JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterMemoryInit)) {747return JNI_EINVAL;748}749750// Create memory for metadata. Must be after initializing heap for751// DumpSharedSpaces.752ClassLoaderData::init_null_class_loader_data();753754// We have a heap so create the Method* caches before755// Metaspace::initialize_shared_spaces() tries to populate them.756Universe::_finalizer_register_cache = new LatestMethodCache();757Universe::_loader_addClass_cache = new LatestMethodCache();758Universe::_throw_illegal_access_error_cache = new LatestMethodCache();759Universe::_throw_no_such_method_error_cache = new LatestMethodCache();760Universe::_do_stack_walk_cache = new LatestMethodCache();761762#if INCLUDE_CDS763if (UseSharedSpaces) {764// Read the data structures supporting the shared spaces (shared765// system dictionary, symbol table, etc.). After that, access to766// the file (other than the mapped regions) is no longer needed, and767// the file is closed. Closing the file does not affect the768// currently mapped regions.769MetaspaceShared::initialize_shared_spaces();770StringTable::create_table();771} else772#endif773{774SymbolTable::create_table();775StringTable::create_table();776}777778#if INCLUDE_CDS779if (Arguments::is_dumping_archive()) {780MetaspaceShared::prepare_for_dumping();781}782#endif783784if (strlen(VerifySubSet) > 0) {785Universe::initialize_verify_flags();786}787788ResolvedMethodTable::create_table();789790return JNI_OK;791}792793jint Universe::initialize_heap() {794assert(_collectedHeap == NULL, "Heap already created");795_collectedHeap = GCConfig::arguments()->create_heap();796797log_info(gc)("Using %s", _collectedHeap->name());798return _collectedHeap->initialize();799}800801void Universe::initialize_tlab() {802ThreadLocalAllocBuffer::set_max_size(Universe::heap()->max_tlab_size());803if (UseTLAB) {804ThreadLocalAllocBuffer::startup_initialization();805}806}807808ReservedHeapSpace Universe::reserve_heap(size_t heap_size, size_t alignment) {809810assert(alignment <= Arguments::conservative_max_heap_alignment(),811"actual alignment " SIZE_FORMAT " must be within maximum heap alignment " SIZE_FORMAT,812alignment, Arguments::conservative_max_heap_alignment());813814size_t total_reserved = align_up(heap_size, alignment);815assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),816"heap size is too big for compressed oops");817818size_t page_size = os::vm_page_size();819if (UseLargePages && is_aligned(alignment, os::large_page_size())) {820page_size = os::large_page_size();821} else {822// Parallel is the only collector that might opt out of using large pages823// for the heap.824assert(!UseLargePages || UseParallelGC , "Wrong alignment to use large pages");825}826827// Now create the space.828ReservedHeapSpace total_rs(total_reserved, alignment, page_size, AllocateHeapAt);829830if (total_rs.is_reserved()) {831assert((total_reserved == total_rs.size()) && ((uintptr_t)total_rs.base() % alignment == 0),832"must be exactly of required size and alignment");833// We are good.834835if (AllocateHeapAt != NULL) {836log_info(gc,heap)("Successfully allocated Java heap at location %s", AllocateHeapAt);837}838839if (UseCompressedOops) {840CompressedOops::initialize(total_rs);841}842843Universe::calculate_verify_data((HeapWord*)total_rs.base(), (HeapWord*)total_rs.end());844845return total_rs;846}847848vm_exit_during_initialization(849err_msg("Could not reserve enough space for " SIZE_FORMAT "KB object heap",850total_reserved/K));851852// satisfy compiler853ShouldNotReachHere();854return ReservedHeapSpace(0, 0, os::vm_page_size());855}856857OopStorage* Universe::vm_weak() {858return Universe::_vm_weak;859}860861OopStorage* Universe::vm_global() {862return Universe::_vm_global;863}864865void Universe::oopstorage_init() {866Universe::_vm_global = OopStorageSet::create_strong("VM Global", mtInternal);867Universe::_vm_weak = OopStorageSet::create_weak("VM Weak", mtInternal);868}869870void universe_oopstorage_init() {871Universe::oopstorage_init();872}873874void initialize_known_method(LatestMethodCache* method_cache,875InstanceKlass* ik,876const char* method,877Symbol* signature,878bool is_static, TRAPS)879{880TempNewSymbol name = SymbolTable::new_symbol(method);881Method* m = NULL;882// The klass must be linked before looking up the method.883if (!ik->link_class_or_fail(THREAD) ||884((m = ik->find_method(name, signature)) == NULL) ||885is_static != m->is_static()) {886ResourceMark rm(THREAD);887// NoSuchMethodException doesn't actually work because it tries to run the888// <init> function before java_lang_Class is linked. Print error and exit.889vm_exit_during_initialization(err_msg("Unable to link/verify %s.%s method",890ik->name()->as_C_string(), method));891}892method_cache->init(ik, m);893}894895void Universe::initialize_known_methods(TRAPS) {896// Set up static method for registering finalizers897initialize_known_method(_finalizer_register_cache,898vmClasses::Finalizer_klass(),899"register",900vmSymbols::object_void_signature(), true, CHECK);901902initialize_known_method(_throw_illegal_access_error_cache,903vmClasses::internal_Unsafe_klass(),904"throwIllegalAccessError",905vmSymbols::void_method_signature(), true, CHECK);906907initialize_known_method(_throw_no_such_method_error_cache,908vmClasses::internal_Unsafe_klass(),909"throwNoSuchMethodError",910vmSymbols::void_method_signature(), true, CHECK);911912// Set up method for registering loaded classes in class loader vector913initialize_known_method(_loader_addClass_cache,914vmClasses::ClassLoader_klass(),915"addClass",916vmSymbols::class_void_signature(), false, CHECK);917918// Set up method for stack walking919initialize_known_method(_do_stack_walk_cache,920vmClasses::AbstractStackWalker_klass(),921"doStackWalk",922vmSymbols::doStackWalk_signature(), false, CHECK);923}924925void universe2_init() {926EXCEPTION_MARK;927Universe::genesis(CATCH);928}929930// Set after initialization of the module runtime, call_initModuleRuntime931void universe_post_module_init() {932Universe::_module_initialized = true;933}934935bool universe_post_init() {936assert(!is_init_completed(), "Error: initialization not yet completed!");937Universe::_fully_initialized = true;938EXCEPTION_MARK;939if (!UseSharedSpaces) {940reinitialize_vtables();941reinitialize_itables();942}943944HandleMark hm(THREAD);945// Setup preallocated empty java.lang.Class array for Method reflection.946947objArrayOop the_empty_class_array = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_false);948Universe::_the_empty_class_array = OopHandle(Universe::vm_global(), the_empty_class_array);949950// Setup preallocated OutOfMemoryError errors951Universe::create_preallocated_out_of_memory_errors(CHECK_false);952953oop instance;954// Setup preallocated cause message for delayed StackOverflowError955if (StackReservedPages > 0) {956instance = java_lang_String::create_oop_from_str("Delayed StackOverflowError due to ReservedStackAccess annotated method", CHECK_false);957Universe::_delayed_stack_overflow_error_message = OopHandle(Universe::vm_global(), instance);958}959960// Setup preallocated NullPointerException961// (this is currently used for a cheap & dirty solution in compiler exception handling)962Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_NullPointerException(), true, CHECK_false);963instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);964Universe::_null_ptr_exception_instance = OopHandle(Universe::vm_global(), instance);965966// Setup preallocated ArithmeticException967// (this is currently used for a cheap & dirty solution in compiler exception handling)968k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ArithmeticException(), true, CHECK_false);969instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);970Universe::_arithmetic_exception_instance = OopHandle(Universe::vm_global(), instance);971972// Virtual Machine Error for when we get into a situation we can't resolve973k = vmClasses::VirtualMachineError_klass();974bool linked = InstanceKlass::cast(k)->link_class_or_fail(CHECK_false);975if (!linked) {976tty->print_cr("Unable to link/verify VirtualMachineError class");977return false; // initialization failed978}979instance = InstanceKlass::cast(k)->allocate_instance(CHECK_false);980Universe::_virtual_machine_error_instance = OopHandle(Universe::vm_global(), instance);981982Handle msg = java_lang_String::create_from_str("/ by zero", CHECK_false);983java_lang_Throwable::set_message(Universe::arithmetic_exception_instance(), msg());984985Universe::initialize_known_methods(CHECK_false);986987// This needs to be done before the first scavenge/gc, since988// it's an input to soft ref clearing policy.989{990MutexLocker x(THREAD, Heap_lock);991Universe::heap()->update_capacity_and_used_at_gc();992}993994// ("weak") refs processing infrastructure initialization995Universe::heap()->post_initialize();996997MemoryService::add_metaspace_memory_pools();998999MemoryService::set_universe_heap(Universe::heap());1000#if INCLUDE_CDS1001MetaspaceShared::post_initialize(CHECK_false);1002#endif1003return true;1004}100510061007void Universe::compute_base_vtable_size() {1008_base_vtable_size = ClassLoader::compute_Object_vtable();1009}10101011void Universe::print_on(outputStream* st) {1012GCMutexLocker hl(Heap_lock); // Heap_lock might be locked by caller thread.1013st->print_cr("Heap");1014heap()->print_on(st);1015}10161017void Universe::print_heap_at_SIGBREAK() {1018if (PrintHeapAtSIGBREAK) {1019print_on(tty);1020tty->cr();1021tty->flush();1022}1023}10241025void Universe::initialize_verify_flags() {1026verify_flags = 0;1027const char delimiter[] = " ,";10281029size_t length = strlen(VerifySubSet);1030char* subset_list = NEW_C_HEAP_ARRAY(char, length + 1, mtInternal);1031strncpy(subset_list, VerifySubSet, length + 1);1032char* save_ptr;10331034char* token = strtok_r(subset_list, delimiter, &save_ptr);1035while (token != NULL) {1036if (strcmp(token, "threads") == 0) {1037verify_flags |= Verify_Threads;1038} else if (strcmp(token, "heap") == 0) {1039verify_flags |= Verify_Heap;1040} else if (strcmp(token, "symbol_table") == 0) {1041verify_flags |= Verify_SymbolTable;1042} else if (strcmp(token, "string_table") == 0) {1043verify_flags |= Verify_StringTable;1044} else if (strcmp(token, "codecache") == 0) {1045verify_flags |= Verify_CodeCache;1046} else if (strcmp(token, "dictionary") == 0) {1047verify_flags |= Verify_SystemDictionary;1048} else if (strcmp(token, "classloader_data_graph") == 0) {1049verify_flags |= Verify_ClassLoaderDataGraph;1050} else if (strcmp(token, "metaspace") == 0) {1051verify_flags |= Verify_MetaspaceUtils;1052} else if (strcmp(token, "jni_handles") == 0) {1053verify_flags |= Verify_JNIHandles;1054} else if (strcmp(token, "codecache_oops") == 0) {1055verify_flags |= Verify_CodeCacheOops;1056} else if (strcmp(token, "resolved_method_table") == 0) {1057verify_flags |= Verify_ResolvedMethodTable;1058} else if (strcmp(token, "stringdedup") == 0) {1059verify_flags |= Verify_StringDedup;1060} else {1061vm_exit_during_initialization(err_msg("VerifySubSet: \'%s\' memory sub-system is unknown, please correct it", token));1062}1063token = strtok_r(NULL, delimiter, &save_ptr);1064}1065FREE_C_HEAP_ARRAY(char, subset_list);1066}10671068bool Universe::should_verify_subset(uint subset) {1069if (verify_flags & subset) {1070return true;1071}1072return false;1073}10741075void Universe::verify(VerifyOption option, const char* prefix) {1076// The use of _verify_in_progress is a temporary work around for1077// 6320749. Don't bother with a creating a class to set and clear1078// it since it is only used in this method and the control flow is1079// straight forward.1080_verify_in_progress = true;10811082COMPILER2_PRESENT(1083assert(!DerivedPointerTable::is_active(),1084"DPT should not be active during verification "1085"(of thread stacks below)");1086)10871088Thread* thread = Thread::current();1089ResourceMark rm(thread);1090HandleMark hm(thread); // Handles created during verification can be zapped1091_verify_count++;10921093FormatBuffer<> title("Verifying %s", prefix);1094GCTraceTime(Info, gc, verify) tm(title.buffer());1095if (should_verify_subset(Verify_Threads)) {1096log_debug(gc, verify)("Threads");1097Threads::verify();1098}1099if (should_verify_subset(Verify_Heap)) {1100log_debug(gc, verify)("Heap");1101heap()->verify(option);1102}1103if (should_verify_subset(Verify_SymbolTable)) {1104log_debug(gc, verify)("SymbolTable");1105SymbolTable::verify();1106}1107if (should_verify_subset(Verify_StringTable)) {1108log_debug(gc, verify)("StringTable");1109StringTable::verify();1110}1111if (should_verify_subset(Verify_CodeCache)) {1112MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1113log_debug(gc, verify)("CodeCache");1114CodeCache::verify();1115}1116if (should_verify_subset(Verify_SystemDictionary)) {1117log_debug(gc, verify)("SystemDictionary");1118SystemDictionary::verify();1119}1120if (should_verify_subset(Verify_ClassLoaderDataGraph)) {1121log_debug(gc, verify)("ClassLoaderDataGraph");1122ClassLoaderDataGraph::verify();1123}1124if (should_verify_subset(Verify_MetaspaceUtils)) {1125log_debug(gc, verify)("MetaspaceUtils");1126DEBUG_ONLY(MetaspaceUtils::verify();)1127}1128if (should_verify_subset(Verify_JNIHandles)) {1129log_debug(gc, verify)("JNIHandles");1130JNIHandles::verify();1131}1132if (should_verify_subset(Verify_CodeCacheOops)) {1133log_debug(gc, verify)("CodeCache Oops");1134CodeCache::verify_oops();1135}1136if (should_verify_subset(Verify_ResolvedMethodTable)) {1137log_debug(gc, verify)("ResolvedMethodTable Oops");1138ResolvedMethodTable::verify();1139}1140if (should_verify_subset(Verify_StringDedup)) {1141log_debug(gc, verify)("String Deduplication");1142StringDedup::verify();1143}11441145_verify_in_progress = false;1146}114711481149#ifndef PRODUCT1150void Universe::calculate_verify_data(HeapWord* low_boundary, HeapWord* high_boundary) {1151assert(low_boundary < high_boundary, "bad interval");11521153// decide which low-order bits we require to be clear:1154size_t alignSize = MinObjAlignmentInBytes;1155size_t min_object_size = CollectedHeap::min_fill_size();11561157// make an inclusive limit:1158uintptr_t max = (uintptr_t)high_boundary - min_object_size*wordSize;1159uintptr_t min = (uintptr_t)low_boundary;1160assert(min < max, "bad interval");1161uintptr_t diff = max ^ min;11621163// throw away enough low-order bits to make the diff vanish1164uintptr_t mask = (uintptr_t)(-1);1165while ((mask & diff) != 0)1166mask <<= 1;1167uintptr_t bits = (min & mask);1168assert(bits == (max & mask), "correct mask");1169// check an intermediate value between min and max, just to make sure:1170assert(bits == ((min + (max-min)/2) & mask), "correct mask");11711172// require address alignment, too:1173mask |= (alignSize - 1);11741175if (!(_verify_oop_mask == 0 && _verify_oop_bits == (uintptr_t)-1)) {1176assert(_verify_oop_mask == mask && _verify_oop_bits == bits, "mask stability");1177}1178_verify_oop_mask = mask;1179_verify_oop_bits = bits;1180}11811182// Oop verification (see MacroAssembler::verify_oop)11831184uintptr_t Universe::verify_oop_mask() {1185return _verify_oop_mask;1186}11871188uintptr_t Universe::verify_oop_bits() {1189return _verify_oop_bits;1190}11911192uintptr_t Universe::verify_mark_mask() {1193return markWord::lock_mask_in_place;1194}11951196uintptr_t Universe::verify_mark_bits() {1197intptr_t mask = verify_mark_mask();1198intptr_t bits = (intptr_t)markWord::prototype().value();1199assert((bits & ~mask) == 0, "no stray header bits");1200return bits;1201}1202#endif // PRODUCT120312041205void LatestMethodCache::init(Klass* k, Method* m) {1206if (!UseSharedSpaces) {1207_klass = k;1208}1209#ifndef PRODUCT1210else {1211// sharing initilization should have already set up _klass1212assert(_klass != NULL, "just checking");1213}1214#endif12151216_method_idnum = m->method_idnum();1217assert(_method_idnum >= 0, "sanity check");1218}121912201221Method* LatestMethodCache::get_method() {1222if (klass() == NULL) return NULL;1223InstanceKlass* ik = InstanceKlass::cast(klass());1224Method* m = ik->method_with_idnum(method_idnum());1225assert(m != NULL, "sanity check");1226return m;1227}12281229#ifdef ASSERT1230// Release dummy object(s) at bottom of heap1231bool Universe::release_fullgc_alot_dummy() {1232MutexLocker ml(FullGCALot_lock);1233objArrayOop fullgc_alot_dummy_array = (objArrayOop)_fullgc_alot_dummy_array.resolve();1234if (fullgc_alot_dummy_array != NULL) {1235if (_fullgc_alot_dummy_next >= fullgc_alot_dummy_array->length()) {1236// No more dummies to release, release entire array instead1237_fullgc_alot_dummy_array.release(Universe::vm_global());1238return false;1239}12401241// Release dummy at bottom of old generation1242fullgc_alot_dummy_array->obj_at_put(_fullgc_alot_dummy_next++, NULL);1243}1244return true;1245}12461247bool Universe::is_gc_active() {1248return heap()->is_gc_active();1249}12501251bool Universe::is_in_heap(const void* p) {1252return heap()->is_in(p);1253}12541255#endif // ASSERT125612571258