Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/oops/instanceKlass.cpp
48693 views
/*1* Copyright (c) 1997, 2019, 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 "classfile/javaClasses.hpp"26#include "classfile/systemDictionary.hpp"27#include "classfile/systemDictionaryShared.hpp"28#include "classfile/verifier.hpp"29#include "classfile/vmSymbols.hpp"30#include "compiler/compileBroker.hpp"31#include "gc_implementation/shared/markSweep.inline.hpp"32#include "gc_interface/collectedHeap.inline.hpp"33#include "interpreter/oopMapCache.hpp"34#include "interpreter/rewriter.hpp"35#include "jvmtifiles/jvmti.h"36#include "memory/genOopClosures.inline.hpp"37#include "memory/heapInspection.hpp"38#include "memory/iterator.inline.hpp"39#include "memory/metadataFactory.hpp"40#include "memory/oopFactory.hpp"41#include "oops/fieldStreams.hpp"42#include "oops/instanceClassLoaderKlass.hpp"43#include "oops/instanceKlass.hpp"44#include "oops/instanceMirrorKlass.hpp"45#include "oops/instanceOop.hpp"46#include "oops/klass.inline.hpp"47#include "oops/method.hpp"48#include "oops/oop.inline.hpp"49#include "oops/symbol.hpp"50#include "prims/jvmtiExport.hpp"51#include "prims/jvmtiRedefineClassesTrace.hpp"52#include "prims/jvmtiRedefineClasses.hpp"53#include "prims/jvmtiThreadState.hpp"54#include "prims/methodComparator.hpp"55#include "runtime/fieldDescriptor.hpp"56#include "runtime/handles.inline.hpp"57#include "runtime/javaCalls.hpp"58#include "runtime/mutexLocker.hpp"59#include "runtime/orderAccess.inline.hpp"60#include "runtime/thread.inline.hpp"61#include "services/classLoadingService.hpp"62#include "services/threadService.hpp"63#include "utilities/dtrace.hpp"64#include "utilities/macros.hpp"65#if INCLUDE_ALL_GCS66#include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"67#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"68#include "gc_implementation/g1/g1OopClosures.inline.hpp"69#include "gc_implementation/g1/g1RemSet.inline.hpp"70#include "gc_implementation/g1/heapRegionManager.inline.hpp"71#include "gc_implementation/parNew/parOopClosures.inline.hpp"72#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"73#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"74#include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"75#include "oops/oop.pcgc.inline.hpp"76#endif // INCLUDE_ALL_GCS77#ifdef COMPILER178#include "c1/c1_Compiler.hpp"79#endif80#if INCLUDE_JFR81#include "jfr/jfrEvents.hpp"82#endif838485PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC8687#ifdef DTRACE_ENABLED8889#ifndef USDT29091HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,92char*, intptr_t, oop, intptr_t);93HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,94char*, intptr_t, oop, intptr_t, int);95HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,96char*, intptr_t, oop, intptr_t, int);97HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,98char*, intptr_t, oop, intptr_t, int);99HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,100char*, intptr_t, oop, intptr_t, int);101HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,102char*, intptr_t, oop, intptr_t, int);103HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,104char*, intptr_t, oop, intptr_t, int);105HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,106char*, intptr_t, oop, intptr_t, int);107108#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \109{ \110char* data = NULL; \111int len = 0; \112Symbol* name = (clss)->name(); \113if (name != NULL) { \114data = (char*)name->bytes(); \115len = name->utf8_length(); \116} \117HS_DTRACE_PROBE4(hotspot, class__initialization__##type, \118data, len, (void *)(clss)->class_loader(), thread_type); \119}120121#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \122{ \123char* data = NULL; \124int len = 0; \125Symbol* name = (clss)->name(); \126if (name != NULL) { \127data = (char*)name->bytes(); \128len = name->utf8_length(); \129} \130HS_DTRACE_PROBE5(hotspot, class__initialization__##type, \131data, len, (void *)(clss)->class_loader(), thread_type, wait); \132}133#else /* USDT2 */134135#define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED136#define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE137#define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT138#define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS139#define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED140#define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT141#define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR142#define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END143#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \144{ \145char* data = NULL; \146int len = 0; \147Symbol* name = (clss)->name(); \148if (name != NULL) { \149data = (char*)name->bytes(); \150len = name->utf8_length(); \151} \152HOTSPOT_CLASS_INITIALIZATION_##type( \153data, len, (void *)(clss)->class_loader(), thread_type); \154}155156#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \157{ \158char* data = NULL; \159int len = 0; \160Symbol* name = (clss)->name(); \161if (name != NULL) { \162data = (char*)name->bytes(); \163len = name->utf8_length(); \164} \165HOTSPOT_CLASS_INITIALIZATION_##type( \166data, len, (void *)(clss)->class_loader(), thread_type, wait); \167}168#endif /* USDT2 */169170#else // ndef DTRACE_ENABLED171172#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)173#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)174175#endif // ndef DTRACE_ENABLED176177volatile int InstanceKlass::_total_instanceKlass_count = 0;178179InstanceKlass* InstanceKlass::allocate_instance_klass(180ClassLoaderData* loader_data,181int vtable_len,182int itable_len,183int static_field_size,184int nonstatic_oop_map_size,185ReferenceType rt,186AccessFlags access_flags,187Symbol* name,188Klass* super_klass,189bool is_anonymous,190TRAPS) {191192int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,193access_flags.is_interface(), is_anonymous);194195// Allocation196InstanceKlass* ik;197if (rt == REF_NONE) {198if (name == vmSymbols::java_lang_Class()) {199ik = new (loader_data, size, THREAD) InstanceMirrorKlass(200vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,201access_flags, is_anonymous);202} else if (name == vmSymbols::java_lang_ClassLoader() ||203(SystemDictionary::ClassLoader_klass_loaded() &&204super_klass != NULL &&205super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {206ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(207vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,208access_flags, is_anonymous);209} else {210// normal class211ik = new (loader_data, size, THREAD) InstanceKlass(212vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,213access_flags, is_anonymous);214}215} else {216// reference klass217ik = new (loader_data, size, THREAD) InstanceRefKlass(218vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,219access_flags, is_anonymous);220}221222// Check for pending exception before adding to the loader data and incrementing223// class count. Can get OOM here.224if (HAS_PENDING_EXCEPTION) {225return NULL;226}227228// Add all classes to our internal class loader list here,229// including classes in the bootstrap (NULL) class loader.230loader_data->add_class(ik);231232Atomic::inc(&_total_instanceKlass_count);233return ik;234}235236237// copy method ordering from resource area to Metaspace238void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {239if (m != NULL) {240// allocate a new array and copy contents (memcpy?)241_method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);242for (int i = 0; i < m->length(); i++) {243_method_ordering->at_put(i, m->at(i));244}245} else {246_method_ordering = Universe::the_empty_int_array();247}248}249250// create a new array of vtable_indices for default methods251Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {252Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);253assert(default_vtable_indices() == NULL, "only create once");254set_default_vtable_indices(vtable_indices);255return vtable_indices;256}257258InstanceKlass::InstanceKlass(int vtable_len,259int itable_len,260int static_field_size,261int nonstatic_oop_map_size,262ReferenceType rt,263AccessFlags access_flags,264bool is_anonymous) {265No_Safepoint_Verifier no_safepoint; // until k becomes parsable266267int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,268access_flags.is_interface(), is_anonymous);269270set_vtable_length(vtable_len);271set_itable_length(itable_len);272set_static_field_size(static_field_size);273set_nonstatic_oop_map_size(nonstatic_oop_map_size);274set_access_flags(access_flags);275_misc_flags = 0; // initialize to zero276set_is_anonymous(is_anonymous);277assert(size() == iksize, "wrong size for object");278279set_array_klasses(NULL);280set_methods(NULL);281set_method_ordering(NULL);282set_default_methods(NULL);283set_default_vtable_indices(NULL);284set_local_interfaces(NULL);285set_transitive_interfaces(NULL);286init_implementor();287set_fields(NULL, 0);288set_constants(NULL);289set_class_loader_data(NULL);290set_source_file_name_index(0);291set_source_debug_extension(NULL, 0);292set_array_name(NULL);293set_inner_classes(NULL);294set_static_oop_field_count(0);295set_nonstatic_field_size(0);296set_is_marked_dependent(false);297set_has_unloaded_dependent(false);298set_init_state(InstanceKlass::allocated);299set_init_thread(NULL);300set_init_state(allocated);301set_reference_type(rt);302set_oop_map_cache(NULL);303set_jni_ids(NULL);304set_osr_nmethods_head(NULL);305set_breakpoints(NULL);306init_previous_versions();307set_generic_signature_index(0);308release_set_methods_jmethod_ids(NULL);309set_annotations(NULL);310set_jvmti_cached_class_field_map(NULL);311set_initial_method_idnum(0);312_dependencies = NULL;313set_jvmti_cached_class_field_map(NULL);314set_cached_class_file(NULL);315set_initial_method_idnum(0);316set_minor_version(0);317set_major_version(0);318NOT_PRODUCT(_verify_count = 0;)319320// initialize the non-header words to zero321intptr_t* p = (intptr_t*)this;322for (int index = InstanceKlass::header_size(); index < iksize; index++) {323p[index] = NULL_WORD;324}325326// Set temporary value until parseClassFile updates it with the real instance327// size.328set_layout_helper(Klass::instance_layout_helper(0, true));329}330331332void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,333Array<Method*>* methods) {334if (methods != NULL && methods != Universe::the_empty_method_array() &&335!methods->is_shared()) {336for (int i = 0; i < methods->length(); i++) {337Method* method = methods->at(i);338if (method == NULL) continue; // maybe null if error processing339// Only want to delete methods that are not executing for RedefineClasses.340// The previous version will point to them so they're not totally dangling341assert (!method->on_stack(), "shouldn't be called with methods on stack");342MetadataFactory::free_metadata(loader_data, method);343}344MetadataFactory::free_array<Method*>(loader_data, methods);345}346}347348void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,349Klass* super_klass,350Array<Klass*>* local_interfaces,351Array<Klass*>* transitive_interfaces) {352// Only deallocate transitive interfaces if not empty, same as super class353// or same as local interfaces. See code in parseClassFile.354Array<Klass*>* ti = transitive_interfaces;355if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {356// check that the interfaces don't come from super class357Array<Klass*>* sti = (super_klass == NULL) ? NULL :358InstanceKlass::cast(super_klass)->transitive_interfaces();359if (ti != sti && ti != NULL && !ti->is_shared()) {360MetadataFactory::free_array<Klass*>(loader_data, ti);361}362}363364// local interfaces can be empty365if (local_interfaces != Universe::the_empty_klass_array() &&366local_interfaces != NULL && !local_interfaces->is_shared()) {367MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);368}369}370371// This function deallocates the metadata and C heap pointers that the372// InstanceKlass points to.373void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {374375// Orphan the mirror first, CMS thinks it's still live.376if (java_mirror() != NULL) {377java_lang_Class::set_klass(java_mirror(), NULL);378}379380// Need to take this class off the class loader data list.381loader_data->remove_class(this);382383// The array_klass for this class is created later, after error handling.384// For class redefinition, we keep the original class so this scratch class385// doesn't have an array class. Either way, assert that there is nothing386// to deallocate.387assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");388389// Release C heap allocated data that this might point to, which includes390// reference counting symbol names.391release_C_heap_structures();392393deallocate_methods(loader_data, methods());394set_methods(NULL);395396if (method_ordering() != NULL &&397method_ordering() != Universe::the_empty_int_array() &&398!method_ordering()->is_shared()) {399MetadataFactory::free_array<int>(loader_data, method_ordering());400}401set_method_ordering(NULL);402403// default methods can be empty404if (default_methods() != NULL &&405default_methods() != Universe::the_empty_method_array() &&406!default_methods()->is_shared()) {407MetadataFactory::free_array<Method*>(loader_data, default_methods());408}409// Do NOT deallocate the default methods, they are owned by superinterfaces.410set_default_methods(NULL);411412// default methods vtable indices can be empty413if (default_vtable_indices() != NULL &&414!default_vtable_indices()->is_shared()) {415MetadataFactory::free_array<int>(loader_data, default_vtable_indices());416}417set_default_vtable_indices(NULL);418419420// This array is in Klass, but remove it with the InstanceKlass since421// this place would be the only caller and it can share memory with transitive422// interfaces.423if (secondary_supers() != NULL &&424secondary_supers() != Universe::the_empty_klass_array() &&425secondary_supers() != transitive_interfaces() &&426!secondary_supers()->is_shared()) {427MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());428}429set_secondary_supers(NULL);430431deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());432set_transitive_interfaces(NULL);433set_local_interfaces(NULL);434435if (fields() != NULL && !fields()->is_shared()) {436MetadataFactory::free_array<jushort>(loader_data, fields());437}438set_fields(NULL, 0);439440// If a method from a redefined class is using this constant pool, don't441// delete it, yet. The new class's previous version will point to this.442if (constants() != NULL) {443assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");444if (!constants()->is_shared()) {445MetadataFactory::free_metadata(loader_data, constants());446}447// Delete any cached resolution errors for the constant pool448SystemDictionary::delete_resolution_error(constants());449450set_constants(NULL);451}452453if (inner_classes() != NULL &&454inner_classes() != Universe::the_empty_short_array() &&455!inner_classes()->is_shared()) {456MetadataFactory::free_array<jushort>(loader_data, inner_classes());457}458set_inner_classes(NULL);459460// We should deallocate the Annotations instance if it's not in shared spaces.461if (annotations() != NULL && !annotations()->is_shared()) {462MetadataFactory::free_metadata(loader_data, annotations());463}464set_annotations(NULL);465}466467bool InstanceKlass::should_be_initialized() const {468return !is_initialized();469}470471klassVtable* InstanceKlass::vtable() const {472return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());473}474475klassItable* InstanceKlass::itable() const {476return new klassItable(instanceKlassHandle(this));477}478479void InstanceKlass::eager_initialize(Thread *thread) {480if (!EagerInitialization) return;481482if (this->is_not_initialized()) {483// abort if the the class has a class initializer484if (this->class_initializer() != NULL) return;485486// abort if it is java.lang.Object (initialization is handled in genesis)487Klass* super = this->super();488if (super == NULL) return;489490// abort if the super class should be initialized491if (!InstanceKlass::cast(super)->is_initialized()) return;492493// call body to expose the this pointer494instanceKlassHandle this_oop(thread, this);495eager_initialize_impl(this_oop);496}497}498499// JVMTI spec thinks there are signers and protection domain in the500// instanceKlass. These accessors pretend these fields are there.501// The hprof specification also thinks these fields are in InstanceKlass.502oop InstanceKlass::protection_domain() const {503// return the protection_domain from the mirror504return java_lang_Class::protection_domain(java_mirror());505}506507// To remove these from requires an incompatible change and CCC request.508objArrayOop InstanceKlass::signers() const {509// return the signers from the mirror510return java_lang_Class::signers(java_mirror());511}512513oop InstanceKlass::init_lock() const {514// return the init lock from the mirror515oop lock = java_lang_Class::init_lock(java_mirror());516// Prevent reordering with any access of initialization state517OrderAccess::loadload();518assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state519"only fully initialized state can have a null lock");520return lock;521}522523// Set the initialization lock to null so the object can be GC'ed. Any racing524// threads to get this lock will see a null lock and will not lock.525// That's okay because they all check for initialized state after getting526// the lock and return.527void InstanceKlass::fence_and_clear_init_lock() {528// make sure previous stores are all done, notably the init_state.529OrderAccess::storestore();530java_lang_Class::set_init_lock(java_mirror(), NULL);531assert(!is_not_initialized(), "class must be initialized now");532}533534void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {535EXCEPTION_MARK;536oop init_lock = this_oop->init_lock();537ObjectLocker ol(init_lock, THREAD, init_lock != NULL);538539// abort if someone beat us to the initialization540if (!this_oop->is_not_initialized()) return; // note: not equivalent to is_initialized()541542ClassState old_state = this_oop->init_state();543link_class_impl(this_oop, true, THREAD);544if (HAS_PENDING_EXCEPTION) {545CLEAR_PENDING_EXCEPTION;546// Abort if linking the class throws an exception.547548// Use a test to avoid redundantly resetting the state if there's549// no change. Set_init_state() asserts that state changes make550// progress, whereas here we might just be spinning in place.551if( old_state != this_oop->_init_state )552this_oop->set_init_state (old_state);553} else {554// linking successfull, mark class as initialized555this_oop->set_init_state (fully_initialized);556this_oop->fence_and_clear_init_lock();557// trace558if (TraceClassInitialization) {559ResourceMark rm(THREAD);560tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());561}562}563}564565566// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization567// process. The step comments refers to the procedure described in that section.568// Note: implementation moved to static method to expose the this pointer.569void InstanceKlass::initialize(TRAPS) {570if (this->should_be_initialized()) {571HandleMark hm(THREAD);572instanceKlassHandle this_oop(THREAD, this);573initialize_impl(this_oop, CHECK);574// Note: at this point the class may be initialized575// OR it may be in the state of being initialized576// in case of recursive initialization!577} else {578assert(is_initialized(), "sanity check");579}580}581582583bool InstanceKlass::verify_code(584instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {585// 1) Verify the bytecodes586Verifier::Mode mode =587throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;588return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), THREAD);589}590591592// Used exclusively by the shared spaces dump mechanism to prevent593// classes mapped into the shared regions in new VMs from appearing linked.594595void InstanceKlass::unlink_class() {596assert(is_linked(), "must be linked");597_init_state = loaded;598}599600void InstanceKlass::link_class(TRAPS) {601assert(is_loaded(), "must be loaded");602if (!is_linked()) {603HandleMark hm(THREAD);604instanceKlassHandle this_oop(THREAD, this);605link_class_impl(this_oop, true, CHECK);606}607}608609// Called to verify that a class can link during initialization, without610// throwing a VerifyError.611bool InstanceKlass::link_class_or_fail(TRAPS) {612assert(is_loaded(), "must be loaded");613if (!is_linked()) {614HandleMark hm(THREAD);615instanceKlassHandle this_oop(THREAD, this);616link_class_impl(this_oop, false, CHECK_false);617}618return is_linked();619}620621bool InstanceKlass::link_class_impl(622instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {623// check for error state.624// This is checking for the wrong state. If the state is initialization_error,625// then this class *was* linked. The CDS code does a try_link_class and uses626// initialization_error to mark classes to not include in the archive during627// DumpSharedSpaces. This should be removed when the CDS bug is fixed.628if (this_oop->is_in_error_state()) {629ResourceMark rm(THREAD);630THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),631this_oop->external_name(), false);632}633// return if already verified634if (this_oop->is_linked()) {635return true;636}637638// Timing639// timer handles recursion640assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");641JavaThread* jt = (JavaThread*)THREAD;642643// link super class before linking this class644instanceKlassHandle super(THREAD, this_oop->super());645if (super.not_null()) {646if (super->is_interface()) { // check if super class is an interface647ResourceMark rm(THREAD);648Exceptions::fthrow(649THREAD_AND_LOCATION,650vmSymbols::java_lang_IncompatibleClassChangeError(),651"class %s has interface %s as super class",652this_oop->external_name(),653super->external_name()654);655return false;656}657658link_class_impl(super, throw_verifyerror, CHECK_false);659}660661// link all interfaces implemented by this class before linking this class662Array<Klass*>* interfaces = this_oop->local_interfaces();663int num_interfaces = interfaces->length();664for (int index = 0; index < num_interfaces; index++) {665HandleMark hm(THREAD);666instanceKlassHandle ih(THREAD, interfaces->at(index));667link_class_impl(ih, throw_verifyerror, CHECK_false);668}669670// in case the class is linked in the process of linking its superclasses671if (this_oop->is_linked()) {672return true;673}674675// trace only the link time for this klass that includes676// the verification time677PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),678ClassLoader::perf_class_link_selftime(),679ClassLoader::perf_classes_linked(),680jt->get_thread_stat()->perf_recursion_counts_addr(),681jt->get_thread_stat()->perf_timers_addr(),682PerfClassTraceTime::CLASS_LINK);683684// verification & rewriting685{686oop init_lock = this_oop->init_lock();687ObjectLocker ol(init_lock, THREAD, init_lock != NULL);688// rewritten will have been set if loader constraint error found689// on an earlier link attempt690// don't verify or rewrite if already rewritten691692if (!this_oop->is_linked()) {693if (!this_oop->is_rewritten()) {694{695// Timer includes any side effects of class verification (resolution,696// etc), but not recursive entry into verify_code().697PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),698ClassLoader::perf_class_verify_selftime(),699ClassLoader::perf_classes_verified(),700jt->get_thread_stat()->perf_recursion_counts_addr(),701jt->get_thread_stat()->perf_timers_addr(),702PerfClassTraceTime::CLASS_VERIFY);703bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);704if (!verify_ok) {705return false;706}707}708709// Just in case a side-effect of verify linked this class already710// (which can sometimes happen since the verifier loads classes711// using custom class loaders, which are free to initialize things)712if (this_oop->is_linked()) {713return true;714}715716// also sets rewritten717this_oop->rewrite_class(CHECK_false);718} else if (this_oop()->is_shared()) {719ResourceMark rm(THREAD);720char* message_buffer; // res-allocated by check_verification_dependencies721Handle loader = this_oop()->class_loader();722Handle pd = this_oop()->protection_domain();723bool verified = SystemDictionaryShared::check_verification_dependencies(this_oop(),724loader, pd, &message_buffer, THREAD);725if (!verified) {726THROW_MSG_(vmSymbols::java_lang_VerifyError(), message_buffer, false);727}728}729730// relocate jsrs and link methods after they are all rewritten731this_oop->link_methods(CHECK_false);732733// Initialize the vtable and interface table after734// methods have been rewritten since rewrite may735// fabricate new Method*s.736// also does loader constraint checking737//738// Initialize_vtable and initialize_itable need to be rerun for739// a shared class if the class is not loaded by the NULL classloader.740ClassLoaderData * loader_data = this_oop->class_loader_data();741if (!(this_oop()->is_shared() &&742loader_data->is_the_null_class_loader_data())) {743ResourceMark rm(THREAD);744this_oop->vtable()->initialize_vtable(true, CHECK_false);745this_oop->itable()->initialize_itable(true, CHECK_false);746}747#ifdef ASSERT748else {749ResourceMark rm(THREAD);750this_oop->vtable()->verify(tty, true);751// In case itable verification is ever added.752// this_oop->itable()->verify(tty, true);753}754#endif755this_oop->set_init_state(linked);756if (JvmtiExport::should_post_class_prepare()) {757Thread *thread = THREAD;758assert(thread->is_Java_thread(), "thread->is_Java_thread()");759JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());760}761}762}763return true;764}765766767// Rewrite the byte codes of all of the methods of a class.768// The rewriter must be called exactly once. Rewriting must happen after769// verification but before the first method of the class is executed.770void InstanceKlass::rewrite_class(TRAPS) {771assert(is_loaded(), "must be loaded");772instanceKlassHandle this_oop(THREAD, this);773if (this_oop->is_rewritten()) {774assert(this_oop()->is_shared(), "rewriting an unshared class?");775return;776}777Rewriter::rewrite(this_oop, CHECK);778this_oop->set_rewritten();779}780781// Now relocate and link method entry points after class is rewritten.782// This is outside is_rewritten flag. In case of an exception, it can be783// executed more than once.784void InstanceKlass::link_methods(TRAPS) {785int len = methods()->length();786for (int i = len-1; i >= 0; i--) {787methodHandle m(THREAD, methods()->at(i));788789// Set up method entry points for compiler and interpreter .790m->link_method(m, CHECK);791792// This is for JVMTI and unrelated to relocator but the last thing we do793#ifdef ASSERT794if (StressMethodComparator) {795ResourceMark rm(THREAD);796static int nmc = 0;797for (int j = i; j >= 0 && j >= i-4; j--) {798if ((++nmc % 1000) == 0) tty->print_cr("Have run MethodComparator %d times...", nmc);799bool z = MethodComparator::methods_EMCP(m(),800methods()->at(j));801if (j == i && !z) {802tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();803assert(z, "method must compare equal to itself");804}805}806}807#endif //ASSERT808}809}810811// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)812void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {813assert (this_k->has_default_methods(), "caller should have checked this");814for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {815Klass* iface = this_k->local_interfaces()->at(i);816InstanceKlass* ik = InstanceKlass::cast(iface);817818// Initialization is depth first search ie. we start with top of the inheritance tree819// has_default_methods drives searching superinterfaces since it820// means has_default_methods in its superinterface hierarchy821if (ik->has_default_methods()) {822ik->initialize_super_interfaces(ik, CHECK);823}824825// Only initialize() interfaces that "declare" concrete methods.826if (ik->should_be_initialized() && ik->declares_default_methods()) {827ik->initialize(CHECK);828}829}830}831832void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {833// Make sure klass is linked (verified) before initialization834// A class could already be verified, since it has been reflected upon.835this_oop->link_class(CHECK);836837DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);838839bool wait = false;840841// refer to the JVM book page 47 for description of steps842// Step 1843{844oop init_lock = this_oop->init_lock();845ObjectLocker ol(init_lock, THREAD, init_lock != NULL);846847Thread *self = THREAD; // it's passed the current thread848849// Step 2850// If we were to use wait() instead of waitInterruptibly() then851// we might end up throwing IE from link/symbol resolution sites852// that aren't expected to throw. This would wreak havoc. See 6320309.853while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {854wait = true;855ol.waitUninterruptibly(CHECK);856}857858// Step 3859if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {860DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);861return;862}863864// Step 4865if (this_oop->is_initialized()) {866DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);867return;868}869870// Step 5871if (this_oop->is_in_error_state()) {872DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);873ResourceMark rm(THREAD);874const char* desc = "Could not initialize class ";875const char* className = this_oop->external_name();876size_t msglen = strlen(desc) + strlen(className) + 1;877char* message = NEW_RESOURCE_ARRAY(char, msglen);878if (NULL == message) {879// Out of memory: can't create detailed error message880THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);881} else {882jio_snprintf(message, msglen, "%s%s", desc, className);883THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);884}885}886887// Step 6888this_oop->set_init_state(being_initialized);889this_oop->set_init_thread(self);890}891892// Step 7893// Next, if C is a class rather than an interface, initialize its super class and super894// interfaces.895if (!this_oop->is_interface()) {896Klass* super_klass = this_oop->super();897if (super_klass != NULL && super_klass->should_be_initialized()) {898super_klass->initialize(THREAD);899}900// If C implements any interfaces that declares a non-abstract, non-static method,901// the initialization of C triggers initialization of its super interfaces.902// Only need to recurse if has_default_methods which includes declaring and903// inheriting default methods904if (!HAS_PENDING_EXCEPTION && this_oop->has_default_methods()) {905this_oop->initialize_super_interfaces(this_oop, THREAD);906}907908// If any exceptions, complete abruptly, throwing the same exception as above.909if (HAS_PENDING_EXCEPTION) {910Handle e(THREAD, PENDING_EXCEPTION);911CLEAR_PENDING_EXCEPTION;912{913EXCEPTION_MARK;914// Locks object, set state, and notify all waiting threads915this_oop->set_initialization_state_and_notify(initialization_error, THREAD);916CLEAR_PENDING_EXCEPTION;917}918DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);919THROW_OOP(e());920}921}922923// Step 8924{925assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");926JavaThread* jt = (JavaThread*)THREAD;927DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);928// Timer includes any side effects of class initialization (resolution,929// etc), but not recursive entry into call_class_initializer().930PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),931ClassLoader::perf_class_init_selftime(),932ClassLoader::perf_classes_inited(),933jt->get_thread_stat()->perf_recursion_counts_addr(),934jt->get_thread_stat()->perf_timers_addr(),935PerfClassTraceTime::CLASS_CLINIT);936this_oop->call_class_initializer(THREAD);937}938939// Step 9940if (!HAS_PENDING_EXCEPTION) {941this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);942{ ResourceMark rm(THREAD);943debug_only(this_oop->vtable()->verify(tty, true);)944}945}946else {947// Step 10 and 11948Handle e(THREAD, PENDING_EXCEPTION);949CLEAR_PENDING_EXCEPTION;950// JVMTI has already reported the pending exception951// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError952JvmtiExport::clear_detected_exception((JavaThread*)THREAD);953{954EXCEPTION_MARK;955this_oop->set_initialization_state_and_notify(initialization_error, THREAD);956CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below957// JVMTI has already reported the pending exception958// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError959JvmtiExport::clear_detected_exception((JavaThread*)THREAD);960}961DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);962if (e->is_a(SystemDictionary::Error_klass())) {963THROW_OOP(e());964} else {965JavaCallArguments args(e);966THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),967vmSymbols::throwable_void_signature(),968&args);969}970}971DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);972}973974975// Note: implementation moved to static method to expose the this pointer.976void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {977instanceKlassHandle kh(THREAD, this);978set_initialization_state_and_notify_impl(kh, state, CHECK);979}980981void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {982oop init_lock = this_oop->init_lock();983if (init_lock != NULL) {984ObjectLocker ol(init_lock, THREAD);985this_oop->set_init_thread(NULL); // reset _init_thread before changing _init_state986this_oop->set_init_state(state);987this_oop->fence_and_clear_init_lock();988ol.notify_all(CHECK);989} else {990assert(init_lock != NULL, "The initialization state should never be set twice");991this_oop->set_init_thread(NULL); // reset _init_thread before changing _init_state992this_oop->set_init_state(state);993}994}995996// The embedded _implementor field can only record one implementor.997// When there are more than one implementors, the _implementor field998// is set to the interface Klass* itself. Following are the possible999// values for the _implementor field:1000// NULL - no implementor1001// implementor Klass* - one implementor1002// self - more than one implementor1003//1004// The _implementor field only exists for interfaces.1005void InstanceKlass::add_implementor(Klass* k) {1006assert(Compile_lock->owned_by_self(), "");1007assert(is_interface(), "not interface");1008// Filter out my subinterfaces.1009// (Note: Interfaces are never on the subklass list.)1010if (InstanceKlass::cast(k)->is_interface()) return;10111012// Filter out subclasses whose supers already implement me.1013// (Note: CHA must walk subclasses of direct implementors1014// in order to locate indirect implementors.)1015Klass* sk = InstanceKlass::cast(k)->super();1016if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))1017// We only need to check one immediate superclass, since the1018// implements_interface query looks at transitive_interfaces.1019// Any supers of the super have the same (or fewer) transitive_interfaces.1020return;10211022Klass* ik = implementor();1023if (ik == NULL) {1024set_implementor(k);1025} else if (ik != this) {1026// There is already an implementor. Use itself as an indicator of1027// more than one implementors.1028set_implementor(this);1029}10301031// The implementor also implements the transitive_interfaces1032for (int index = 0; index < local_interfaces()->length(); index++) {1033InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);1034}1035}10361037void InstanceKlass::init_implementor() {1038if (is_interface()) {1039set_implementor(NULL);1040}1041}104210431044void InstanceKlass::process_interfaces(Thread *thread) {1045// link this class into the implementors list of every interface it implements1046Klass* this_as_klass_oop = this;1047for (int i = local_interfaces()->length() - 1; i >= 0; i--) {1048assert(local_interfaces()->at(i)->is_klass(), "must be a klass");1049InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));1050assert(interf->is_interface(), "expected interface");1051interf->add_implementor(this_as_klass_oop);1052}1053}10541055bool InstanceKlass::can_be_primary_super_slow() const {1056if (is_interface())1057return false;1058else1059return Klass::can_be_primary_super_slow();1060}10611062GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {1063// The secondaries are the implemented interfaces.1064InstanceKlass* ik = InstanceKlass::cast(this);1065Array<Klass*>* interfaces = ik->transitive_interfaces();1066int num_secondaries = num_extra_slots + interfaces->length();1067if (num_secondaries == 0) {1068// Must share this for correct bootstrapping!1069set_secondary_supers(Universe::the_empty_klass_array());1070return NULL;1071} else if (num_extra_slots == 0) {1072// The secondary super list is exactly the same as the transitive interfaces.1073// Redefine classes has to be careful not to delete this!1074set_secondary_supers(interfaces);1075return NULL;1076} else {1077// Copy transitive interfaces to a temporary growable array to be constructed1078// into the secondary super list with extra slots.1079GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());1080for (int i = 0; i < interfaces->length(); i++) {1081secondaries->push(interfaces->at(i));1082}1083return secondaries;1084}1085}10861087bool InstanceKlass::compute_is_subtype_of(Klass* k) {1088if (k->is_interface()) {1089return implements_interface(k);1090} else {1091return Klass::compute_is_subtype_of(k);1092}1093}10941095bool InstanceKlass::implements_interface(Klass* k) const {1096if (this == k) return true;1097assert(k->is_interface(), "should be an interface class");1098for (int i = 0; i < transitive_interfaces()->length(); i++) {1099if (transitive_interfaces()->at(i) == k) {1100return true;1101}1102}1103return false;1104}11051106bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {1107// Verify direct super interface1108if (this == k) return true;1109assert(k->is_interface(), "should be an interface class");1110for (int i = 0; i < local_interfaces()->length(); i++) {1111if (local_interfaces()->at(i) == k) {1112return true;1113}1114}1115return false;1116}11171118objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {1119if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());1120if (length > arrayOopDesc::max_array_length(T_OBJECT)) {1121report_java_out_of_memory("Requested array size exceeds VM limit");1122JvmtiExport::post_array_size_exhausted();1123THROW_OOP_0(Universe::out_of_memory_error_array_size());1124}1125int size = objArrayOopDesc::object_size(length);1126Klass* ak = array_klass(n, CHECK_NULL);1127KlassHandle h_ak (THREAD, ak);1128objArrayOop o =1129(objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);1130return o;1131}11321133instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {1134if (TraceFinalizerRegistration) {1135tty->print("Registered ");1136i->print_value_on(tty);1137tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);1138}1139instanceHandle h_i(THREAD, i);1140// Pass the handle as argument, JavaCalls::call expects oop as jobjects1141JavaValue result(T_VOID);1142JavaCallArguments args(h_i);1143methodHandle mh (THREAD, Universe::finalizer_register_method());1144JavaCalls::call(&result, mh, &args, CHECK_NULL);1145return h_i();1146}11471148instanceOop InstanceKlass::allocate_instance(TRAPS) {1149bool has_finalizer_flag = has_finalizer(); // Query before possible GC1150int size = size_helper(); // Query before forming handle.11511152KlassHandle h_k(THREAD, this);11531154instanceOop i;11551156i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);1157if (has_finalizer_flag && !RegisterFinalizersAtInit) {1158i = register_finalizer(i, CHECK_NULL);1159}1160return i;1161}11621163void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {1164if (is_interface() || is_abstract()) {1165ResourceMark rm(THREAD);1166THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()1167: vmSymbols::java_lang_InstantiationException(), external_name());1168}1169if (this == SystemDictionary::Class_klass()) {1170ResourceMark rm(THREAD);1171THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()1172: vmSymbols::java_lang_IllegalAccessException(), external_name());1173}1174}11751176Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {1177instanceKlassHandle this_oop(THREAD, this);1178return array_klass_impl(this_oop, or_null, n, THREAD);1179}11801181Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {1182if (this_oop->array_klasses() == NULL) {1183if (or_null) return NULL;11841185ResourceMark rm;1186JavaThread *jt = (JavaThread *)THREAD;1187{1188// Atomic creation of array_klasses1189MutexLocker mc(Compile_lock, THREAD); // for vtables1190MutexLocker ma(MultiArray_lock, THREAD);11911192// Check if update has already taken place1193if (this_oop->array_klasses() == NULL) {1194Klass* k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);1195this_oop->set_array_klasses(k);1196}1197}1198}1199// _this will always be set at this point1200ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();1201if (or_null) {1202return oak->array_klass_or_null(n);1203}1204return oak->array_klass(n, THREAD);1205}12061207Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {1208return array_klass_impl(or_null, 1, THREAD);1209}12101211void InstanceKlass::call_class_initializer(TRAPS) {1212instanceKlassHandle ik (THREAD, this);1213call_class_initializer_impl(ik, THREAD);1214}12151216static int call_class_initializer_impl_counter = 0; // for debugging12171218Method* InstanceKlass::class_initializer() {1219Method* clinit = find_method(1220vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());1221if (clinit != NULL && clinit->has_valid_initializer_flags()) {1222return clinit;1223}1224return NULL;1225}12261227void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {1228if (ReplayCompiles &&1229(ReplaySuppressInitializers == 1 ||1230ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {1231// Hide the existence of the initializer for the purpose of replaying the compile1232return;1233}12341235methodHandle h_method(THREAD, this_oop->class_initializer());1236assert(!this_oop->is_initialized(), "we cannot initialize twice");1237if (TraceClassInitialization) {1238tty->print("%d Initializing ", call_class_initializer_impl_counter++);1239this_oop->name()->print_value();1240tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());1241}1242if (h_method() != NULL) {1243JavaCallArguments args; // No arguments1244JavaValue result(T_VOID);1245JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)1246}1247}124812491250void InstanceKlass::mask_for(methodHandle method, int bci,1251InterpreterOopMap* entry_for) {1252// Dirty read, then double-check under a lock.1253if (_oop_map_cache == NULL) {1254// Otherwise, allocate a new one.1255MutexLocker x(OopMapCacheAlloc_lock);1256// First time use. Allocate a cache in C heap1257if (_oop_map_cache == NULL) {1258// Release stores from OopMapCache constructor before assignment1259// to _oop_map_cache. C++ compilers on ppc do not emit the1260// required memory barrier only because of the volatile1261// qualifier of _oop_map_cache.1262OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());1263}1264}1265// _oop_map_cache is constant after init; lookup below does is own locking.1266_oop_map_cache->lookup(method, bci, entry_for);1267}126812691270bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1271for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1272Symbol* f_name = fs.name();1273Symbol* f_sig = fs.signature();1274if (f_name == name && f_sig == sig) {1275fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1276return true;1277}1278}1279return false;1280}128112821283Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1284const int n = local_interfaces()->length();1285for (int i = 0; i < n; i++) {1286Klass* intf1 = local_interfaces()->at(i);1287assert(intf1->is_interface(), "just checking type");1288// search for field in current interface1289if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {1290assert(fd->is_static(), "interface field must be static");1291return intf1;1292}1293// search for field in direct superinterfaces1294Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);1295if (intf2 != NULL) return intf2;1296}1297// otherwise field lookup fails1298return NULL;1299}130013011302Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1303// search order according to newest JVM spec (5.4.3.2, p.167).1304// 1) search for field in current klass1305if (find_local_field(name, sig, fd)) {1306return const_cast<InstanceKlass*>(this);1307}1308// 2) search for field recursively in direct superinterfaces1309{ Klass* intf = find_interface_field(name, sig, fd);1310if (intf != NULL) return intf;1311}1312// 3) apply field lookup recursively if superclass exists1313{ Klass* supr = super();1314if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);1315}1316// 4) otherwise field lookup fails1317return NULL;1318}131913201321Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {1322// search order according to newest JVM spec (5.4.3.2, p.167).1323// 1) search for field in current klass1324if (find_local_field(name, sig, fd)) {1325if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);1326}1327// 2) search for field recursively in direct superinterfaces1328if (is_static) {1329Klass* intf = find_interface_field(name, sig, fd);1330if (intf != NULL) return intf;1331}1332// 3) apply field lookup recursively if superclass exists1333{ Klass* supr = super();1334if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);1335}1336// 4) otherwise field lookup fails1337return NULL;1338}133913401341bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1342for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1343if (fs.offset() == offset) {1344fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1345if (fd->is_static() == is_static) return true;1346}1347}1348return false;1349}135013511352bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1353Klass* klass = const_cast<InstanceKlass*>(this);1354while (klass != NULL) {1355if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {1356return true;1357}1358klass = klass->super();1359}1360return false;1361}136213631364void InstanceKlass::methods_do(void f(Method* method)) {1365int len = methods()->length();1366for (int index = 0; index < len; index++) {1367Method* m = methods()->at(index);1368assert(m->is_method(), "must be method");1369f(m);1370}1371}137213731374void InstanceKlass::do_local_static_fields(FieldClosure* cl) {1375for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1376if (fs.access_flags().is_static()) {1377fieldDescriptor& fd = fs.field_descriptor();1378cl->do_field(&fd);1379}1380}1381}138213831384void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {1385instanceKlassHandle h_this(THREAD, this);1386do_local_static_fields_impl(h_this, f, mirror, CHECK);1387}138813891390void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,1391void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {1392for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {1393if (fs.access_flags().is_static()) {1394fieldDescriptor& fd = fs.field_descriptor();1395f(&fd, mirror, CHECK);1396}1397}1398}139914001401static int compare_fields_by_offset(int* a, int* b) {1402return a[0] - b[0];1403}14041405void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {1406InstanceKlass* super = superklass();1407if (super != NULL) {1408super->do_nonstatic_fields(cl);1409}1410fieldDescriptor fd;1411int length = java_fields_count();1412// In DebugInfo nonstatic fields are sorted by offset.1413int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);1414int j = 0;1415for (int i = 0; i < length; i += 1) {1416fd.reinitialize(this, i);1417if (!fd.is_static()) {1418fields_sorted[j + 0] = fd.offset();1419fields_sorted[j + 1] = i;1420j += 2;1421}1422}1423if (j > 0) {1424length = j;1425// _sort_Fn is defined in growableArray.hpp.1426qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);1427for (int i = 0; i < length; i += 2) {1428fd.reinitialize(this, fields_sorted[i + 1]);1429assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");1430cl->do_field(&fd);1431}1432}1433FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);1434}143514361437void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {1438if (array_klasses() != NULL)1439ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);1440}14411442void InstanceKlass::array_klasses_do(void f(Klass* k)) {1443if (array_klasses() != NULL)1444ArrayKlass::cast(array_klasses())->array_klasses_do(f);1445}14461447#ifdef ASSERT1448static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {1449int len = methods->length();1450for (int index = 0; index < len; index++) {1451Method* m = methods->at(index);1452assert(m->is_method(), "must be method");1453if (m->signature() == signature && m->name() == name) {1454return index;1455}1456}1457return -1;1458}1459#endif14601461static int binary_search(Array<Method*>* methods, Symbol* name) {1462int len = methods->length();1463// methods are sorted, so do binary search1464int l = 0;1465int h = len - 1;1466while (l <= h) {1467int mid = (l + h) >> 1;1468Method* m = methods->at(mid);1469assert(m->is_method(), "must be method");1470int res = m->name()->fast_compare(name);1471if (res == 0) {1472return mid;1473} else if (res < 0) {1474l = mid + 1;1475} else {1476h = mid - 1;1477}1478}1479return -1;1480}14811482// find_method looks up the name/signature in the local methods array1483Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {1484return find_method_impl(name, signature, find_overpass, find_static, find_private);1485}14861487Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature,1488OverpassLookupMode overpass_mode,1489StaticLookupMode static_mode,1490PrivateLookupMode private_mode) const {1491return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);1492}14931494// find_instance_method looks up the name/signature in the local methods array1495// and skips over static methods1496Method* InstanceKlass::find_instance_method(Array<Method*>* methods,1497Symbol* name,1498Symbol* signature,1499PrivateLookupMode private_mode) {1500Method* meth = InstanceKlass::find_method_impl(methods, name, signature,1501find_overpass, skip_static, private_mode);1502assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");1503return meth;1504}15051506// find_instance_method looks up the name/signature in the local methods array1507// and skips over static methods1508Method* InstanceKlass::find_instance_method(Symbol* name,1509Symbol* signature,1510PrivateLookupMode private_mode) {1511return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);1512}15131514// Find looks up the name/signature in the local methods array1515// and filters on the overpass, static and private flags1516// This returns the first one found1517// note that the local methods array can have up to one overpass, one static1518// and one instance (private or not) with the same name/signature1519Method* InstanceKlass::find_local_method(Symbol* name, Symbol* signature,1520OverpassLookupMode overpass_mode,1521StaticLookupMode static_mode,1522PrivateLookupMode private_mode) const {1523return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);1524}15251526// Find looks up the name/signature in the local methods array1527// and filters on the overpass, static and private flags1528// This returns the first one found1529// note that the local methods array can have up to one overpass, one static1530// and one instance (private or not) with the same name/signature1531Method* InstanceKlass::find_local_method(Array<Method*>* methods,1532Symbol* name, Symbol* signature,1533OverpassLookupMode overpass_mode,1534StaticLookupMode static_mode,1535PrivateLookupMode private_mode) {1536return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode);1537}153815391540// find_method looks up the name/signature in the local methods array1541Method* InstanceKlass::find_method(1542Array<Method*>* methods, Symbol* name, Symbol* signature) {1543return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private);1544}15451546Method* InstanceKlass::find_method_impl(1547Array<Method*>* methods, Symbol* name, Symbol* signature,1548OverpassLookupMode overpass_mode, StaticLookupMode static_mode,1549PrivateLookupMode private_mode) {1550int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);1551return hit >= 0 ? methods->at(hit): NULL;1552}15531554bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) {1555return ((m->signature() == signature) &&1556(!skipping_overpass || !m->is_overpass()) &&1557(!skipping_static || !m->is_static()) &&1558(!skipping_private || !m->is_private()));1559}15601561// Used directly for default_methods to find the index into the1562// default_vtable_indices, and indirectly by find_method1563// find_method_index looks in the local methods array to return the index1564// of the matching name/signature. If, overpass methods are being ignored,1565// the search continues to find a potential non-overpass match. This capability1566// is important during method resolution to prefer a static method, for example,1567// over an overpass method.1568// There is the possibility in any _method's array to have the same name/signature1569// for a static method, an overpass method and a local instance method1570// To correctly catch a given method, the search criteria may need1571// to explicitly skip the other two. For local instance methods, it1572// is often necessary to skip private methods1573int InstanceKlass::find_method_index(1574Array<Method*>* methods, Symbol* name, Symbol* signature,1575OverpassLookupMode overpass_mode, StaticLookupMode static_mode,1576PrivateLookupMode private_mode) {1577bool skipping_overpass = (overpass_mode == skip_overpass);1578bool skipping_static = (static_mode == skip_static);1579bool skipping_private = (private_mode == skip_private);1580int hit = binary_search(methods, name);1581if (hit != -1) {1582Method* m = methods->at(hit);15831584// Do linear search to find matching signature. First, quick check1585// for common case, ignoring overpasses if requested.1586if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit;15871588// search downwards through overloaded methods1589int i;1590for (i = hit - 1; i >= 0; --i) {1591Method* m = methods->at(i);1592assert(m->is_method(), "must be method");1593if (m->name() != name) break;1594if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;1595}1596// search upwards1597for (i = hit + 1; i < methods->length(); ++i) {1598Method* m = methods->at(i);1599assert(m->is_method(), "must be method");1600if (m->name() != name) break;1601if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;1602}1603// not found1604#ifdef ASSERT1605int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature);1606assert(index == -1, err_msg("binary search should have found entry %d", index));1607#endif1608}1609return -1;1610}1611int InstanceKlass::find_method_by_name(Symbol* name, int* end) {1612return find_method_by_name(methods(), name, end);1613}16141615int InstanceKlass::find_method_by_name(1616Array<Method*>* methods, Symbol* name, int* end_ptr) {1617assert(end_ptr != NULL, "just checking");1618int start = binary_search(methods, name);1619int end = start + 1;1620if (start != -1) {1621while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;1622while (end < methods->length() && (methods->at(end))->name() == name) ++end;1623*end_ptr = end;1624return start;1625}1626return -1;1627}16281629// uncached_lookup_method searches both the local class methods array and all1630// superclasses methods arrays, skipping any overpass methods in superclasses.1631Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {1632OverpassLookupMode overpass_local_mode = overpass_mode;1633Klass* klass = const_cast<InstanceKlass*>(this);1634while (klass != NULL) {1635Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private);1636if (method != NULL) {1637return method;1638}1639klass = InstanceKlass::cast(klass)->super();1640overpass_local_mode = skip_overpass; // Always ignore overpass methods in superclasses1641}1642return NULL;1643}16441645#ifdef ASSERT1646// search through class hierarchy and return true if this class or1647// one of the superclasses was redefined1648bool InstanceKlass::has_redefined_this_or_super() const {1649const InstanceKlass* klass = this;1650while (klass != NULL) {1651if (klass->has_been_redefined()) {1652return true;1653}1654klass = InstanceKlass::cast(klass->super());1655}1656return false;1657}1658#endif16591660// lookup a method in the default methods list then in all transitive interfaces1661// Do NOT return private or static methods1662Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,1663Symbol* signature) const {1664Method* m = NULL;1665if (default_methods() != NULL) {1666m = find_method(default_methods(), name, signature);1667}1668// Look up interfaces1669if (m == NULL) {1670m = lookup_method_in_all_interfaces(name, signature, find_defaults);1671}1672return m;1673}16741675// lookup a method in all the interfaces that this class implements1676// Do NOT return private or static methods, new in JDK8 which are not externally visible1677// They should only be found in the initial InterfaceMethodRef1678Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,1679Symbol* signature,1680DefaultsLookupMode defaults_mode) const {1681Array<Klass*>* all_ifs = transitive_interfaces();1682int num_ifs = all_ifs->length();1683InstanceKlass *ik = NULL;1684for (int i = 0; i < num_ifs; i++) {1685ik = InstanceKlass::cast(all_ifs->at(i));1686Method* m = ik->lookup_method(name, signature);1687if (m != NULL && m->is_public() && !m->is_static() &&1688((defaults_mode != skip_defaults) || !m->is_default_method())) {1689return m;1690}1691}1692return NULL;1693}16941695/* jni_id_for_impl for jfieldIds only */1696JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {1697MutexLocker ml(JfieldIdCreation_lock);1698// Retry lookup after we got the lock1699JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);1700if (probe == NULL) {1701// Slow case, allocate new static field identifier1702probe = new JNIid(this_oop(), offset, this_oop->jni_ids());1703this_oop->set_jni_ids(probe);1704}1705return probe;1706}170717081709/* jni_id_for for jfieldIds only */1710JNIid* InstanceKlass::jni_id_for(int offset) {1711JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);1712if (probe == NULL) {1713probe = jni_id_for_impl(this, offset);1714}1715return probe;1716}17171718u2 InstanceKlass::enclosing_method_data(int offset) {1719Array<jushort>* inner_class_list = inner_classes();1720if (inner_class_list == NULL) {1721return 0;1722}1723int length = inner_class_list->length();1724if (length % inner_class_next_offset == 0) {1725return 0;1726} else {1727int index = length - enclosing_method_attribute_size;1728assert(offset < enclosing_method_attribute_size, "invalid offset");1729return inner_class_list->at(index + offset);1730}1731}17321733void InstanceKlass::set_enclosing_method_indices(u2 class_index,1734u2 method_index) {1735Array<jushort>* inner_class_list = inner_classes();1736assert (inner_class_list != NULL, "_inner_classes list is not set up");1737int length = inner_class_list->length();1738if (length % inner_class_next_offset == enclosing_method_attribute_size) {1739int index = length - enclosing_method_attribute_size;1740inner_class_list->at_put(1741index + enclosing_method_class_index_offset, class_index);1742inner_class_list->at_put(1743index + enclosing_method_method_index_offset, method_index);1744}1745}17461747// Lookup or create a jmethodID.1748// This code is called by the VMThread and JavaThreads so the1749// locking has to be done very carefully to avoid deadlocks1750// and/or other cache consistency problems.1751//1752jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {1753size_t idnum = (size_t)method_h->method_idnum();1754jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();1755size_t length = 0;1756jmethodID id = NULL;17571758// We use a double-check locking idiom here because this cache is1759// performance sensitive. In the normal system, this cache only1760// transitions from NULL to non-NULL which is safe because we use1761// release_set_methods_jmethod_ids() to advertise the new cache.1762// A partially constructed cache should never be seen by a racing1763// thread. We also use release_store_ptr() to save a new jmethodID1764// in the cache so a partially constructed jmethodID should never be1765// seen either. Cache reads of existing jmethodIDs proceed without a1766// lock, but cache writes of a new jmethodID requires uniqueness and1767// creation of the cache itself requires no leaks so a lock is1768// generally acquired in those two cases.1769//1770// If the RedefineClasses() API has been used, then this cache can1771// grow and we'll have transitions from non-NULL to bigger non-NULL.1772// Cache creation requires no leaks and we require safety between all1773// cache accesses and freeing of the old cache so a lock is generally1774// acquired when the RedefineClasses() API has been used.17751776if (jmeths != NULL) {1777// the cache already exists1778if (!ik_h->idnum_can_increment()) {1779// the cache can't grow so we can just get the current values1780get_jmethod_id_length_value(jmeths, idnum, &length, &id);1781} else {1782// cache can grow so we have to be more careful1783if (Threads::number_of_threads() == 0 ||1784SafepointSynchronize::is_at_safepoint()) {1785// we're single threaded or at a safepoint - no locking needed1786get_jmethod_id_length_value(jmeths, idnum, &length, &id);1787} else {1788MutexLocker ml(JmethodIdCreation_lock);1789get_jmethod_id_length_value(jmeths, idnum, &length, &id);1790}1791}1792}1793// implied else:1794// we need to allocate a cache so default length and id values are good17951796if (jmeths == NULL || // no cache yet1797length <= idnum || // cache is too short1798id == NULL) { // cache doesn't contain entry17991800// This function can be called by the VMThread so we have to do all1801// things that might block on a safepoint before grabbing the lock.1802// Otherwise, we can deadlock with the VMThread or have a cache1803// consistency issue. These vars keep track of what we might have1804// to free after the lock is dropped.1805jmethodID to_dealloc_id = NULL;1806jmethodID* to_dealloc_jmeths = NULL;18071808// may not allocate new_jmeths or use it if we allocate it1809jmethodID* new_jmeths = NULL;1810if (length <= idnum) {1811// allocate a new cache that might be used1812size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());1813new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);1814memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));1815// cache size is stored in element[0], other elements offset by one1816new_jmeths[0] = (jmethodID)size;1817}18181819// allocate a new jmethodID that might be used1820jmethodID new_id = NULL;1821if (method_h->is_old() && !method_h->is_obsolete()) {1822// The method passed in is old (but not obsolete), we need to use the current version1823Method* current_method = ik_h->method_with_idnum((int)idnum);1824assert(current_method != NULL, "old and but not obsolete, so should exist");1825new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);1826} else {1827// It is the current version of the method or an obsolete method,1828// use the version passed in1829new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());1830}18311832if (Threads::number_of_threads() == 0 ||1833SafepointSynchronize::is_at_safepoint()) {1834// we're single threaded or at a safepoint - no locking needed1835id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,1836&to_dealloc_id, &to_dealloc_jmeths);1837} else {1838MutexLocker ml(JmethodIdCreation_lock);1839id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,1840&to_dealloc_id, &to_dealloc_jmeths);1841}18421843// The lock has been dropped so we can free resources.1844// Free up either the old cache or the new cache if we allocated one.1845if (to_dealloc_jmeths != NULL) {1846FreeHeap(to_dealloc_jmeths);1847}1848// free up the new ID since it wasn't needed1849if (to_dealloc_id != NULL) {1850Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);1851}1852}1853return id;1854}185518561857// Common code to fetch the jmethodID from the cache or update the1858// cache with the new jmethodID. This function should never do anything1859// that causes the caller to go to a safepoint or we can deadlock with1860// the VMThread or have cache consistency issues.1861//1862jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(1863instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,1864jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,1865jmethodID** to_dealloc_jmeths_p) {1866assert(new_id != NULL, "sanity check");1867assert(to_dealloc_id_p != NULL, "sanity check");1868assert(to_dealloc_jmeths_p != NULL, "sanity check");1869assert(Threads::number_of_threads() == 0 ||1870SafepointSynchronize::is_at_safepoint() ||1871JmethodIdCreation_lock->owned_by_self(), "sanity check");18721873// reacquire the cache - we are locked, single threaded or at a safepoint1874jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();1875jmethodID id = NULL;1876size_t length = 0;18771878if (jmeths == NULL || // no cache yet1879(length = (size_t)jmeths[0]) <= idnum) { // cache is too short1880if (jmeths != NULL) {1881// copy any existing entries from the old cache1882for (size_t index = 0; index < length; index++) {1883new_jmeths[index+1] = jmeths[index+1];1884}1885*to_dealloc_jmeths_p = jmeths; // save old cache for later delete1886}1887ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);1888} else {1889// fetch jmethodID (if any) from the existing cache1890id = jmeths[idnum+1];1891*to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete1892}1893if (id == NULL) {1894// No matching jmethodID in the existing cache or we have a new1895// cache or we just grew the cache. This cache write is done here1896// by the first thread to win the foot race because a jmethodID1897// needs to be unique once it is generally available.1898id = new_id;18991900// The jmethodID cache can be read while unlocked so we have to1901// make sure the new jmethodID is complete before installing it1902// in the cache.1903OrderAccess::release_store_ptr(&jmeths[idnum+1], id);1904} else {1905*to_dealloc_id_p = new_id; // save new id for later delete1906}1907return id;1908}190919101911// Common code to get the jmethodID cache length and the jmethodID1912// value at index idnum if there is one.1913//1914void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,1915size_t idnum, size_t *length_p, jmethodID* id_p) {1916assert(cache != NULL, "sanity check");1917assert(length_p != NULL, "sanity check");1918assert(id_p != NULL, "sanity check");19191920// cache size is stored in element[0], other elements offset by one1921*length_p = (size_t)cache[0];1922if (*length_p <= idnum) { // cache is too short1923*id_p = NULL;1924} else {1925*id_p = cache[idnum+1]; // fetch jmethodID (if any)1926}1927}192819291930// Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles1931jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {1932size_t idnum = (size_t)method->method_idnum();1933jmethodID* jmeths = methods_jmethod_ids_acquire();1934size_t length; // length assigned as debugging crumb1935jmethodID id = NULL;1936if (jmeths != NULL && // If there is a cache1937(length = (size_t)jmeths[0]) > idnum) { // and if it is long enough,1938id = jmeths[idnum+1]; // Look up the id (may be NULL)1939}1940return id;1941}19421943int nmethodBucket::decrement() {1944return Atomic::add(-1, (volatile int *)&_count);1945}19461947//1948// Walk the list of dependent nmethods searching for nmethods which1949// are dependent on the changes that were passed in and mark them for1950// deoptimization. Returns the number of nmethods found.1951//1952int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {1953assert_locked_or_safepoint(CodeCache_lock);1954int found = 0;1955nmethodBucket* b = _dependencies;1956while (b != NULL) {1957nmethod* nm = b->get_nmethod();1958// since dependencies aren't removed until an nmethod becomes a zombie,1959// the dependency list may contain nmethods which aren't alive.1960if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {1961if (TraceDependencies) {1962ResourceMark rm;1963tty->print_cr("Marked for deoptimization");1964tty->print_cr(" context = %s", this->external_name());1965changes.print();1966nm->print();1967nm->print_dependencies();1968}1969nm->mark_for_deoptimization();1970found++;1971}1972b = b->next();1973}1974return found;1975}19761977void InstanceKlass::clean_dependent_nmethods() {1978assert_locked_or_safepoint(CodeCache_lock);19791980if (has_unloaded_dependent()) {1981nmethodBucket* b = _dependencies;1982nmethodBucket* last = NULL;1983while (b != NULL) {1984assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));19851986nmethodBucket* next = b->next();19871988if (b->count() == 0) {1989if (last == NULL) {1990_dependencies = next;1991} else {1992last->set_next(next);1993}1994delete b;1995// last stays the same.1996} else {1997last = b;1998}19992000b = next;2001}2002set_has_unloaded_dependent(false);2003}2004#ifdef ASSERT2005else {2006// Verification2007for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {2008assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));2009assert(b->count() != 0, "empty buckets need to be cleaned");2010}2011}2012#endif2013}20142015//2016// Add an nmethodBucket to the list of dependencies for this nmethod.2017// It's possible that an nmethod has multiple dependencies on this klass2018// so a count is kept for each bucket to guarantee that creation and2019// deletion of dependencies is consistent.2020//2021void InstanceKlass::add_dependent_nmethod(nmethod* nm) {2022assert_locked_or_safepoint(CodeCache_lock);2023nmethodBucket* b = _dependencies;2024nmethodBucket* last = NULL;2025while (b != NULL) {2026if (nm == b->get_nmethod()) {2027b->increment();2028return;2029}2030b = b->next();2031}2032_dependencies = new nmethodBucket(nm, _dependencies);2033}203420352036//2037// Decrement count of the nmethod in the dependency list and remove2038// the bucket competely when the count goes to 0. This method must2039// find a corresponding bucket otherwise there's a bug in the2040// recording of dependecies.2041//2042void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {2043assert_locked_or_safepoint(CodeCache_lock);2044nmethodBucket* b = _dependencies;2045nmethodBucket* last = NULL;2046while (b != NULL) {2047if (nm == b->get_nmethod()) {2048int val = b->decrement();2049guarantee(val >= 0, err_msg("Underflow: %d", val));2050if (val == 0) {2051if (delete_immediately) {2052if (last == NULL) {2053_dependencies = b->next();2054} else {2055last->set_next(b->next());2056}2057delete b;2058} else {2059// The deletion of this entry is deferred until a later, potentially parallel GC phase.2060set_has_unloaded_dependent(true);2061}2062}2063return;2064}2065last = b;2066b = b->next();2067}2068#ifdef ASSERT2069tty->print_cr("### %s can't find dependent nmethod:", this->external_name());2070nm->print();2071#endif // ASSERT2072ShouldNotReachHere();2073}207420752076#ifndef PRODUCT2077void InstanceKlass::print_dependent_nmethods(bool verbose) {2078nmethodBucket* b = _dependencies;2079int idx = 0;2080while (b != NULL) {2081nmethod* nm = b->get_nmethod();2082tty->print("[%d] count=%d { ", idx++, b->count());2083if (!verbose) {2084nm->print_on(tty, "nmethod");2085tty->print_cr(" } ");2086} else {2087nm->print();2088nm->print_dependencies();2089tty->print_cr("--- } ");2090}2091b = b->next();2092}2093}209420952096bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {2097nmethodBucket* b = _dependencies;2098while (b != NULL) {2099if (nm == b->get_nmethod()) {2100#ifdef ASSERT2101int count = b->count();2102assert(count >= 0, err_msg("count shouldn't be negative: %d", count));2103#endif2104return true;2105}2106b = b->next();2107}2108return false;2109}2110#endif //PRODUCT211121122113// Garbage collection21142115#ifdef ASSERT2116template <class T> void assert_is_in(T *p) {2117T heap_oop = oopDesc::load_heap_oop(p);2118if (!oopDesc::is_null(heap_oop)) {2119oop o = oopDesc::decode_heap_oop_not_null(heap_oop);2120assert(Universe::heap()->is_in(o), "should be in heap");2121}2122}2123template <class T> void assert_is_in_closed_subset(T *p) {2124T heap_oop = oopDesc::load_heap_oop(p);2125if (!oopDesc::is_null(heap_oop)) {2126oop o = oopDesc::decode_heap_oop_not_null(heap_oop);2127assert(Universe::heap()->is_in_closed_subset(o),2128err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));2129}2130}2131template <class T> void assert_is_in_reserved(T *p) {2132T heap_oop = oopDesc::load_heap_oop(p);2133if (!oopDesc::is_null(heap_oop)) {2134oop o = oopDesc::decode_heap_oop_not_null(heap_oop);2135assert(Universe::heap()->is_in_reserved(o), "should be in reserved");2136}2137}2138template <class T> void assert_nothing(T *p) {}21392140#else2141template <class T> void assert_is_in(T *p) {}2142template <class T> void assert_is_in_closed_subset(T *p) {}2143template <class T> void assert_is_in_reserved(T *p) {}2144template <class T> void assert_nothing(T *p) {}2145#endif // ASSERT21462147//2148// Macros that iterate over areas of oops which are specialized on type of2149// oop pointer either narrow or wide, depending on UseCompressedOops2150//2151// Parameters are:2152// T - type of oop to point to (either oop or narrowOop)2153// start_p - starting pointer for region to iterate over2154// count - number of oops or narrowOops to iterate over2155// do_oop - action to perform on each oop (it's arbitrary C code which2156// makes it more efficient to put in a macro rather than making2157// it a template function)2158// assert_fn - assert function which is template function because performance2159// doesn't matter when enabled.2160#define InstanceKlass_SPECIALIZED_OOP_ITERATE( \2161T, start_p, count, do_oop, \2162assert_fn) \2163{ \2164T* p = (T*)(start_p); \2165T* const end = p + (count); \2166while (p < end) { \2167(assert_fn)(p); \2168do_oop; \2169++p; \2170} \2171}21722173#define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \2174T, start_p, count, do_oop, \2175assert_fn) \2176{ \2177T* const start = (T*)(start_p); \2178T* p = start + (count); \2179while (start < p) { \2180--p; \2181(assert_fn)(p); \2182do_oop; \2183} \2184}21852186#define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \2187T, start_p, count, low, high, \2188do_oop, assert_fn) \2189{ \2190T* const l = (T*)(low); \2191T* const h = (T*)(high); \2192assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \2193mask_bits((intptr_t)h, sizeof(T)-1) == 0, \2194"bounded region must be properly aligned"); \2195T* p = (T*)(start_p); \2196T* end = p + (count); \2197if (p < l) p = l; \2198if (end > h) end = h; \2199while (p < end) { \2200(assert_fn)(p); \2201do_oop; \2202++p; \2203} \2204}220522062207// The following macros call specialized macros, passing either oop or2208// narrowOop as the specialization type. These test the UseCompressedOops2209// flag.2210#define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn) \2211{ \2212/* Compute oopmap block range. The common case \2213is nonstatic_oop_map_size == 1. */ \2214OopMapBlock* map = start_of_nonstatic_oop_maps(); \2215OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \2216if (UseCompressedOops) { \2217while (map < end_map) { \2218InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop, \2219obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \2220do_oop, assert_fn) \2221++map; \2222} \2223} else { \2224while (map < end_map) { \2225InstanceKlass_SPECIALIZED_OOP_ITERATE(oop, \2226obj->obj_field_addr<oop>(map->offset()), map->count(), \2227do_oop, assert_fn) \2228++map; \2229} \2230} \2231}22322233#define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn) \2234{ \2235OopMapBlock* const start_map = start_of_nonstatic_oop_maps(); \2236OopMapBlock* map = start_map + nonstatic_oop_map_count(); \2237if (UseCompressedOops) { \2238while (start_map < map) { \2239--map; \2240InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop, \2241obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \2242do_oop, assert_fn) \2243} \2244} else { \2245while (start_map < map) { \2246--map; \2247InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop, \2248obj->obj_field_addr<oop>(map->offset()), map->count(), \2249do_oop, assert_fn) \2250} \2251} \2252}22532254#define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop, \2255assert_fn) \2256{ \2257/* Compute oopmap block range. The common case is \2258nonstatic_oop_map_size == 1, so we accept the \2259usually non-existent extra overhead of examining \2260all the maps. */ \2261OopMapBlock* map = start_of_nonstatic_oop_maps(); \2262OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \2263if (UseCompressedOops) { \2264while (map < end_map) { \2265InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop, \2266obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \2267low, high, \2268do_oop, assert_fn) \2269++map; \2270} \2271} else { \2272while (map < end_map) { \2273InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop, \2274obj->obj_field_addr<oop>(map->offset()), map->count(), \2275low, high, \2276do_oop, assert_fn) \2277++map; \2278} \2279} \2280}22812282void InstanceKlass::oop_follow_contents(oop obj) {2283assert(obj != NULL, "can't follow the content of NULL object");2284MarkSweep::follow_klass(obj->klass());2285InstanceKlass_OOP_MAP_ITERATE( \2286obj, \2287MarkSweep::mark_and_push(p), \2288assert_is_in_closed_subset)2289}22902291#if INCLUDE_ALL_GCS2292void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,2293oop obj) {2294assert(obj != NULL, "can't follow the content of NULL object");2295PSParallelCompact::follow_klass(cm, obj->klass());2296// Only mark the header and let the scan of the meta-data mark2297// everything else.2298InstanceKlass_OOP_MAP_ITERATE( \2299obj, \2300PSParallelCompact::mark_and_push(cm, p), \2301assert_is_in)2302}2303#endif // INCLUDE_ALL_GCS23042305// closure's do_metadata() method dictates whether the given closure should be2306// applied to the klass ptr in the object header.23072308#define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix) \2309\2310int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \2311SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\2312/* header */ \2313if_do_metadata_checked(closure, nv_suffix) { \2314closure->do_klass##nv_suffix(obj->klass()); \2315} \2316InstanceKlass_OOP_MAP_ITERATE( \2317obj, \2318SpecializationStats:: \2319record_do_oop_call##nv_suffix(SpecializationStats::ik); \2320(closure)->do_oop##nv_suffix(p), \2321assert_is_in_closed_subset) \2322return size_helper(); \2323}23242325#if INCLUDE_ALL_GCS2326#define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \2327\2328int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj, \2329OopClosureType* closure) { \2330SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \2331\2332assert_should_ignore_metadata(closure, nv_suffix); \2333\2334/* instance variables */ \2335InstanceKlass_OOP_MAP_REVERSE_ITERATE( \2336obj, \2337SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\2338(closure)->do_oop##nv_suffix(p), \2339assert_is_in_closed_subset) \2340return size_helper(); \2341}2342#endif // INCLUDE_ALL_GCS23432344#define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \2345\2346int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj, \2347OopClosureType* closure, \2348MemRegion mr) { \2349SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\2350if_do_metadata_checked(closure, nv_suffix) { \2351if (mr.contains(obj)) { \2352closure->do_klass##nv_suffix(obj->klass()); \2353} \2354} \2355InstanceKlass_BOUNDED_OOP_MAP_ITERATE( \2356obj, mr.start(), mr.end(), \2357(closure)->do_oop##nv_suffix(p), \2358assert_is_in_closed_subset) \2359return size_helper(); \2360}23612362ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)2363ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)2364ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)2365ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)2366#if INCLUDE_ALL_GCS2367ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)2368ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)2369#endif // INCLUDE_ALL_GCS23702371int InstanceKlass::oop_adjust_pointers(oop obj) {2372int size = size_helper();2373InstanceKlass_OOP_MAP_ITERATE( \2374obj, \2375MarkSweep::adjust_pointer(p), \2376assert_is_in)2377return size;2378}23792380#if INCLUDE_ALL_GCS2381void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {2382InstanceKlass_OOP_MAP_REVERSE_ITERATE( \2383obj, \2384if (PSScavenge::should_scavenge(p)) { \2385pm->claim_or_forward_depth(p); \2386}, \2387assert_nothing )2388}23892390int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {2391int size = size_helper();2392InstanceKlass_OOP_MAP_ITERATE( \2393obj, \2394PSParallelCompact::adjust_pointer(p), \2395assert_is_in)2396return size;2397}23982399#endif // INCLUDE_ALL_GCS24002401void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {2402clean_implementors_list(is_alive);2403clean_method_data(is_alive);24042405clean_dependent_nmethods();2406}24072408void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {2409assert(class_loader_data()->is_alive(is_alive), "this klass should be live");2410if (is_interface()) {2411if (ClassUnloading) {2412Klass* impl = implementor();2413if (impl != NULL) {2414if (!impl->is_loader_alive(is_alive)) {2415// remove this guy2416Klass** klass = adr_implementor();2417assert(klass != NULL, "null klass");2418if (klass != NULL) {2419*klass = NULL;2420}2421}2422}2423}2424}2425}24262427void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {2428for (int m = 0; m < methods()->length(); m++) {2429MethodData* mdo = methods()->at(m)->method_data();2430if (mdo != NULL) {2431mdo->clean_method_data(is_alive);2432}2433}2434}243524362437static void remove_unshareable_in_class(Klass* k) {2438// remove klass's unshareable info2439k->remove_unshareable_info();2440}24412442void InstanceKlass::remove_unshareable_info() {2443Klass::remove_unshareable_info();2444// Unlink the class2445if (is_linked()) {2446unlink_class();2447}2448init_implementor();24492450constants()->remove_unshareable_info();24512452for (int i = 0; i < methods()->length(); i++) {2453Method* m = methods()->at(i);2454m->remove_unshareable_info();2455}24562457// do array classes also.2458array_klasses_do(remove_unshareable_in_class);2459}24602461static void restore_unshareable_in_class(Klass* k, TRAPS) {2462// Array classes have null protection domain.2463// --> see ArrayKlass::complete_create_array_klass()2464k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);2465}24662467void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {2468Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);2469instanceKlassHandle ik(THREAD, this);24702471Array<Method*>* methods = ik->methods();2472int num_methods = methods->length();2473for (int index2 = 0; index2 < num_methods; ++index2) {2474methodHandle m(THREAD, methods->at(index2));2475m->restore_unshareable_info(CHECK);2476}2477if (JvmtiExport::has_redefined_a_class()) {2478// Reinitialize vtable because RedefineClasses may have changed some2479// entries in this vtable for super classes so the CDS vtable might2480// point to old or obsolete entries. RedefineClasses doesn't fix up2481// vtables in the shared system dictionary, only the main one.2482// It also redefines the itable too so fix that too.2483ResourceMark rm(THREAD);2484ik->vtable()->initialize_vtable(false, CHECK);2485ik->itable()->initialize_itable(false, CHECK);2486}24872488// restore constant pool resolved references2489ik->constants()->restore_unshareable_info(CHECK);24902491ik->array_klasses_do(restore_unshareable_in_class, CHECK);2492}24932494// returns true IFF is_in_error_state() has been changed as a result of this call.2495bool InstanceKlass::check_sharing_error_state() {2496assert(DumpSharedSpaces, "should only be called during dumping");2497bool old_state = is_in_error_state();24982499if (!is_in_error_state()) {2500bool bad = false;2501for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {2502if (sup->is_in_error_state()) {2503bad = true;2504break;2505}2506}2507if (!bad) {2508Array<Klass*>* interfaces = transitive_interfaces();2509for (int i = 0; i < interfaces->length(); i++) {2510Klass* iface = interfaces->at(i);2511if (InstanceKlass::cast(iface)->is_in_error_state()) {2512bad = true;2513break;2514}2515}2516}25172518if (bad) {2519set_in_error_state();2520}2521}25222523return (old_state != is_in_error_state());2524}25252526static void clear_all_breakpoints(Method* m) {2527m->clear_all_breakpoints();2528}252925302531void InstanceKlass::notify_unload_class(InstanceKlass* ik) {2532// notify the debugger2533if (JvmtiExport::should_post_class_unload()) {2534JvmtiExport::post_class_unload(ik);2535}25362537// notify ClassLoadingService of class unload2538ClassLoadingService::notify_class_unloaded(ik);25392540#if INCLUDE_JFR2541assert(ik != NULL, "invariant");2542EventClassUnload event;2543event.set_unloadedClass(ik);2544event.set_definingClassLoader(ik->class_loader_data());2545event.commit();2546#endif2547}25482549void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {2550// Clean up C heap2551ik->release_C_heap_structures();2552ik->constants()->release_C_heap_structures();2553}25542555void InstanceKlass::release_C_heap_structures() {25562557// Can't release the constant pool here because the constant pool can be2558// deallocated separately from the InstanceKlass for default methods and2559// redefine classes.25602561// Deallocate oop map cache2562if (_oop_map_cache != NULL) {2563delete _oop_map_cache;2564_oop_map_cache = NULL;2565}25662567// Deallocate JNI identifiers for jfieldIDs2568JNIid::deallocate(jni_ids());2569set_jni_ids(NULL);25702571jmethodID* jmeths = methods_jmethod_ids_acquire();2572if (jmeths != (jmethodID*)NULL) {2573release_set_methods_jmethod_ids(NULL);2574FreeHeap(jmeths);2575}25762577// Deallocate MemberNameTable2578{2579Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;2580MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);2581MemberNameTable* mnt = member_names();2582if (mnt != NULL) {2583delete mnt;2584set_member_names(NULL);2585}2586}25872588// release dependencies2589nmethodBucket* b = _dependencies;2590_dependencies = NULL;2591while (b != NULL) {2592nmethodBucket* next = b->next();2593delete b;2594b = next;2595}25962597// Deallocate breakpoint records2598if (breakpoints() != 0x0) {2599methods_do(clear_all_breakpoints);2600assert(breakpoints() == 0x0, "should have cleared breakpoints");2601}26022603// deallocate the cached class file2604if (_cached_class_file != NULL) {2605os::free(_cached_class_file, mtClass);2606_cached_class_file = NULL;2607}26082609// Decrement symbol reference counts associated with the unloaded class.2610if (_name != NULL) _name->decrement_refcount();2611// unreference array name derived from this class name (arrays of an unloaded2612// class can't be referenced anymore).2613if (_array_name != NULL) _array_name->decrement_refcount();2614if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);26152616assert(_total_instanceKlass_count >= 1, "Sanity check");2617Atomic::dec(&_total_instanceKlass_count);2618}26192620void InstanceKlass::set_source_debug_extension(char* array, int length) {2621if (array == NULL) {2622_source_debug_extension = NULL;2623} else {2624// Adding one to the attribute length in order to store a null terminator2625// character could cause an overflow because the attribute length is2626// already coded with an u4 in the classfile, but in practice, it's2627// unlikely to happen.2628assert((length+1) > length, "Overflow checking");2629char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);2630for (int i = 0; i < length; i++) {2631sde[i] = array[i];2632}2633sde[length] = '\0';2634_source_debug_extension = sde;2635}2636}26372638address InstanceKlass::static_field_addr(int offset) {2639return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));2640}264126422643const char* InstanceKlass::signature_name() const {2644int hash_len = 0;2645char hash_buf[40];26462647// If this is an anonymous class, append a hash to make the name unique2648if (is_anonymous()) {2649assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");2650intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;2651sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);2652hash_len = (int)strlen(hash_buf);2653}26542655// Get the internal name as a c string2656const char* src = (const char*) (name()->as_C_string());2657const int src_length = (int)strlen(src);26582659char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);26602661// Add L as type indicator2662int dest_index = 0;2663dest[dest_index++] = 'L';26642665// Add the actual class name2666for (int src_index = 0; src_index < src_length; ) {2667dest[dest_index++] = src[src_index++];2668}26692670// If we have a hash, append it2671for (int hash_index = 0; hash_index < hash_len; ) {2672dest[dest_index++] = hash_buf[hash_index++];2673}26742675// Add the semicolon and the NULL2676dest[dest_index++] = ';';2677dest[dest_index] = '\0';2678return dest;2679}26802681// different verisons of is_same_class_package2682bool InstanceKlass::is_same_class_package(Klass* class2) {2683Klass* class1 = this;2684oop classloader1 = InstanceKlass::cast(class1)->class_loader();2685Symbol* classname1 = class1->name();26862687if (class2->oop_is_objArray()) {2688class2 = ObjArrayKlass::cast(class2)->bottom_klass();2689}2690oop classloader2;2691if (class2->oop_is_instance()) {2692classloader2 = InstanceKlass::cast(class2)->class_loader();2693} else {2694assert(class2->oop_is_typeArray(), "should be type array");2695classloader2 = NULL;2696}2697Symbol* classname2 = class2->name();26982699return InstanceKlass::is_same_class_package(classloader1, classname1,2700classloader2, classname2);2701}27022703bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {2704Klass* class1 = this;2705oop classloader1 = InstanceKlass::cast(class1)->class_loader();2706Symbol* classname1 = class1->name();27072708return InstanceKlass::is_same_class_package(classloader1, classname1,2709classloader2, classname2);2710}27112712// return true if two classes are in the same package, classloader2713// and classname information is enough to determine a class's package2714bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,2715oop class_loader2, Symbol* class_name2) {2716if (class_loader1 != class_loader2) {2717return false;2718} else if (class_name1 == class_name2) {2719return true; // skip painful bytewise comparison2720} else {2721ResourceMark rm;27222723// The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly2724// for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.2725// Otherwise, we just compare jbyte values between the strings.2726const jbyte *name1 = class_name1->base();2727const jbyte *name2 = class_name2->base();27282729const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');2730const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');27312732if ((last_slash1 == NULL) || (last_slash2 == NULL)) {2733// One of the two doesn't have a package. Only return true2734// if the other one also doesn't have a package.2735return last_slash1 == last_slash2;2736} else {2737// Skip over '['s2738if (*name1 == '[') {2739do {2740name1++;2741} while (*name1 == '[');2742if (*name1 != 'L') {2743// Something is terribly wrong. Shouldn't be here.2744return false;2745}2746}2747if (*name2 == '[') {2748do {2749name2++;2750} while (*name2 == '[');2751if (*name2 != 'L') {2752// Something is terribly wrong. Shouldn't be here.2753return false;2754}2755}27562757// Check that package part is identical2758int length1 = last_slash1 - name1;2759int length2 = last_slash2 - name2;27602761return UTF8::equal(name1, length1, name2, length2);2762}2763}2764}27652766// Returns true iff super_method can be overridden by a method in targetclassname2767// See JSL 3rd edition 8.4.6.12768// Assumes name-signature match2769// "this" is InstanceKlass of super_method which must exist2770// note that the InstanceKlass of the method in the targetclassname has not always been created yet2771bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {2772// Private methods can not be overridden2773if (super_method->is_private()) {2774return false;2775}2776// If super method is accessible, then override2777if ((super_method->is_protected()) ||2778(super_method->is_public())) {2779return true;2780}2781// Package-private methods are not inherited outside of package2782assert(super_method->is_package_private(), "must be package private");2783return(is_same_class_package(targetclassloader(), targetclassname));2784}27852786/* defined for now in jvm.cpp, for historical reasons *--2787Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,2788Symbol*& simple_name_result, TRAPS) {2789...2790}2791*/27922793// tell if two classes have the same enclosing class (at package level)2794bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,2795Klass* class2_oop, TRAPS) {2796if (class2_oop == class1()) return true;2797if (!class2_oop->oop_is_instance()) return false;2798instanceKlassHandle class2(THREAD, class2_oop);27992800// must be in same package before we try anything else2801if (!class1->is_same_class_package(class2->class_loader(), class2->name()))2802return false;28032804// As long as there is an outer1.getEnclosingClass,2805// shift the search outward.2806instanceKlassHandle outer1 = class1;2807for (;;) {2808// As we walk along, look for equalities between outer1 and class2.2809// Eventually, the walks will terminate as outer1 stops2810// at the top-level class around the original class.2811bool ignore_inner_is_member;2812Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,2813CHECK_false);2814if (next == NULL) break;2815if (next == class2()) return true;2816outer1 = instanceKlassHandle(THREAD, next);2817}28182819// Now do the same for class2.2820instanceKlassHandle outer2 = class2;2821for (;;) {2822bool ignore_inner_is_member;2823Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,2824CHECK_false);2825if (next == NULL) break;2826// Might as well check the new outer against all available values.2827if (next == class1()) return true;2828if (next == outer1()) return true;2829outer2 = instanceKlassHandle(THREAD, next);2830}28312832// If by this point we have not found an equality between the2833// two classes, we know they are in separate package members.2834return false;2835}283628372838jint InstanceKlass::compute_modifier_flags(TRAPS) const {2839jint access = access_flags().as_int();28402841// But check if it happens to be member class.2842instanceKlassHandle ik(THREAD, this);2843InnerClassesIterator iter(ik);2844for (; !iter.done(); iter.next()) {2845int ioff = iter.inner_class_info_index();2846// Inner class attribute can be zero, skip it.2847// Strange but true: JVM spec. allows null inner class refs.2848if (ioff == 0) continue;28492850// only look at classes that are already loaded2851// since we are looking for the flags for our self.2852Symbol* inner_name = ik->constants()->klass_name_at(ioff);2853if ((ik->name() == inner_name)) {2854// This is really a member class.2855access = iter.inner_access_flags();2856break;2857}2858}2859// Remember to strip ACC_SUPER bit2860return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;2861}28622863jint InstanceKlass::jvmti_class_status() const {2864jint result = 0;28652866if (is_linked()) {2867result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;2868}28692870if (is_initialized()) {2871assert(is_linked(), "Class status is not consistent");2872result |= JVMTI_CLASS_STATUS_INITIALIZED;2873}2874if (is_in_error_state()) {2875result |= JVMTI_CLASS_STATUS_ERROR;2876}2877return result;2878}28792880Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {2881itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();2882int method_table_offset_in_words = ioe->offset()/wordSize;2883int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())2884/ itableOffsetEntry::size();28852886for (int cnt = 0 ; ; cnt ++, ioe ++) {2887// If the interface isn't implemented by the receiver class,2888// the VM should throw IncompatibleClassChangeError.2889if (cnt >= nof_interfaces) {2890THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());2891}28922893Klass* ik = ioe->interface_klass();2894if (ik == holder) break;2895}28962897itableMethodEntry* ime = ioe->first_method_entry(this);2898Method* m = ime[index].method();2899if (m == NULL) {2900THROW_NULL(vmSymbols::java_lang_AbstractMethodError());2901}2902return m;2903}290429052906#if INCLUDE_JVMTI2907// update default_methods for redefineclasses for methods that are2908// not yet in the vtable due to concurrent subclass define and superinterface2909// redefinition2910// Note: those in the vtable, should have been updated via adjust_method_entries2911void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {2912// search the default_methods for uses of either obsolete or EMCP methods2913if (default_methods() != NULL) {2914for (int index = 0; index < default_methods()->length(); index ++) {2915Method* old_method = default_methods()->at(index);2916if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {2917continue; // skip uninteresting entries2918}2919assert(!old_method->is_deleted(), "default methods may not be deleted");29202921Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());29222923assert(new_method != NULL, "method_with_idnum() should not be NULL");2924assert(old_method != new_method, "sanity check");29252926default_methods()->at_put(index, new_method);2927if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {2928if (!(*trace_name_printed)) {2929// RC_TRACE_MESG macro has an embedded ResourceMark2930RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",2931external_name(),2932old_method->method_holder()->external_name()));2933*trace_name_printed = true;2934}2935RC_TRACE(0x00100000, ("default method update: %s(%s) ",2936new_method->name()->as_C_string(),2937new_method->signature()->as_C_string()));2938}2939}2940}2941}2942#endif // INCLUDE_JVMTI29432944// On-stack replacement stuff2945void InstanceKlass::add_osr_nmethod(nmethod* n) {2946#ifndef PRODUCT2947if (TieredCompilation) {2948nmethod * prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);2949assert(prev == NULL || !prev->is_in_use(),2950"redundunt OSR recompilation detected. memory leak in CodeCache!");2951}2952#endif2953// only one compilation can be active2954NEEDS_CLEANUP2955// This is a short non-blocking critical region, so the no safepoint check is ok.2956OsrList_lock->lock_without_safepoint_check();2957assert(n->is_osr_method(), "wrong kind of nmethod");2958n->set_osr_link(osr_nmethods_head());2959set_osr_nmethods_head(n);2960// Raise the highest osr level if necessary2961if (TieredCompilation) {2962Method* m = n->method();2963m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));2964}2965// Remember to unlock again2966OsrList_lock->unlock();29672968// Get rid of the osr methods for the same bci that have lower levels.2969if (TieredCompilation) {2970for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {2971nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);2972if (inv != NULL && inv->is_in_use()) {2973inv->make_not_entrant();2974}2975}2976}2977}297829792980void InstanceKlass::remove_osr_nmethod(nmethod* n) {2981// This is a short non-blocking critical region, so the no safepoint check is ok.2982OsrList_lock->lock_without_safepoint_check();2983assert(n->is_osr_method(), "wrong kind of nmethod");2984nmethod* last = NULL;2985nmethod* cur = osr_nmethods_head();2986int max_level = CompLevel_none; // Find the max comp level excluding n2987Method* m = n->method();2988// Search for match2989while(cur != NULL && cur != n) {2990if (TieredCompilation && m == cur->method()) {2991// Find max level before n2992max_level = MAX2(max_level, cur->comp_level());2993}2994last = cur;2995cur = cur->osr_link();2996}2997nmethod* next = NULL;2998if (cur == n) {2999next = cur->osr_link();3000if (last == NULL) {3001// Remove first element3002set_osr_nmethods_head(next);3003} else {3004last->set_osr_link(next);3005}3006}3007n->set_osr_link(NULL);3008if (TieredCompilation) {3009cur = next;3010while (cur != NULL) {3011// Find max level after n3012if (m == cur->method()) {3013max_level = MAX2(max_level, cur->comp_level());3014}3015cur = cur->osr_link();3016}3017m->set_highest_osr_comp_level(max_level);3018}3019// Remember to unlock again3020OsrList_lock->unlock();3021}30223023int InstanceKlass::mark_osr_nmethods(const Method* m) {3024// This is a short non-blocking critical region, so the no safepoint check is ok.3025MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);3026nmethod* osr = osr_nmethods_head();3027int found = 0;3028while (osr != NULL) {3029assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3030if (osr->method() == m) {3031osr->mark_for_deoptimization();3032found++;3033}3034osr = osr->osr_link();3035}3036return found;3037}30383039nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {3040// This is a short non-blocking critical region, so the no safepoint check is ok.3041OsrList_lock->lock_without_safepoint_check();3042nmethod* osr = osr_nmethods_head();3043nmethod* best = NULL;3044while (osr != NULL) {3045assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3046// There can be a time when a c1 osr method exists but we are waiting3047// for a c2 version. When c2 completes its osr nmethod we will trash3048// the c1 version and only be able to find the c2 version. However3049// while we overflow in the c1 code at back branches we don't want to3050// try and switch to the same code as we are already running30513052if (osr->method() == m &&3053(bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {3054if (match_level) {3055if (osr->comp_level() == comp_level) {3056// Found a match - return it.3057OsrList_lock->unlock();3058return osr;3059}3060} else {3061if (best == NULL || (osr->comp_level() > best->comp_level())) {3062if (osr->comp_level() == CompLevel_highest_tier) {3063// Found the best possible - return it.3064OsrList_lock->unlock();3065return osr;3066}3067best = osr;3068}3069}3070}3071osr = osr->osr_link();3072}3073OsrList_lock->unlock();30743075assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");3076if (best != NULL && best->comp_level() >= comp_level) {3077return best;3078}3079return NULL;3080}30813082oop InstanceKlass::add_member_name(Handle mem_name, bool intern) {3083jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);3084MutexLocker ml(MemberNameTable_lock);3085DEBUG_ONLY(No_Safepoint_Verifier nsv);30863087// Check if method has been redefined while taking out MemberNameTable_lock, if so3088// return false. We cannot cache obsolete methods. They will crash when the function3089// is called!3090Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());3091if (method->is_obsolete()) {3092return NULL;3093} else if (method->is_old()) {3094// Replace method with redefined version3095java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));3096}30973098if (_member_names == NULL) {3099_member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());3100}3101if (intern) {3102return _member_names->find_or_add_member_name(mem_name_wref);3103} else {3104return _member_names->add_member_name(mem_name_wref);3105}3106}31073108// -----------------------------------------------------------------------------------------------------3109// Printing31103111#ifndef PRODUCT31123113#define BULLET " - "31143115static const char* state_names[] = {3116"allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"3117};31183119static void print_vtable(intptr_t* start, int len, outputStream* st) {3120for (int i = 0; i < len; i++) {3121intptr_t e = start[i];3122st->print("%d : " INTPTR_FORMAT, i, e);3123if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {3124st->print(" ");3125((Metadata*)e)->print_value_on(st);3126}3127st->cr();3128}3129}31303131void InstanceKlass::print_on(outputStream* st) const {3132assert(is_klass(), "must be klass");3133Klass::print_on(st);31343135st->print(BULLET"instance size: %d", size_helper()); st->cr();3136st->print(BULLET"klass size: %d", size()); st->cr();3137st->print(BULLET"access: "); access_flags().print_on(st); st->cr();3138st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]);3139st->print(BULLET"name: "); name()->print_value_on(st); st->cr();3140st->print(BULLET"super: "); super()->print_value_on_maybe_null(st); st->cr();3141st->print(BULLET"sub: ");3142Klass* sub = subklass();3143int n;3144for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {3145if (n < MaxSubklassPrintSize) {3146sub->print_value_on(st);3147st->print(" ");3148}3149}3150if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);3151st->cr();31523153if (is_interface()) {3154st->print_cr(BULLET"nof implementors: %d", nof_implementors());3155if (nof_implementors() == 1) {3156st->print_cr(BULLET"implementor: ");3157st->print(" ");3158implementor()->print_value_on(st);3159st->cr();3160}3161}31623163st->print(BULLET"arrays: "); array_klasses()->print_value_on_maybe_null(st); st->cr();3164st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();3165if (Verbose || WizardMode) {3166Array<Method*>* method_array = methods();3167for (int i = 0; i < method_array->length(); i++) {3168st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3169}3170}3171st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();3172st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();3173if (Verbose && default_methods() != NULL) {3174Array<Method*>* method_array = default_methods();3175for (int i = 0; i < method_array->length(); i++) {3176st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3177}3178}3179if (default_vtable_indices() != NULL) {3180st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr();3181}3182st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();3183st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();3184st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();3185if (class_loader_data() != NULL) {3186st->print(BULLET"class loader data: ");3187class_loader_data()->print_value_on(st);3188st->cr();3189}3190st->print(BULLET"host class: "); host_klass()->print_value_on_maybe_null(st); st->cr();3191if (source_file_name() != NULL) {3192st->print(BULLET"source file: ");3193source_file_name()->print_value_on(st);3194st->cr();3195}3196if (source_debug_extension() != NULL) {3197st->print(BULLET"source debug extension: ");3198st->print("%s", source_debug_extension());3199st->cr();3200}3201st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr();3202st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr();3203st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr();3204st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr();3205{3206bool have_pv = false;3207// previous versions are linked together through the InstanceKlass3208for (InstanceKlass* pv_node = _previous_versions;3209pv_node != NULL;3210pv_node = pv_node->previous_versions()) {3211if (!have_pv)3212st->print(BULLET"previous version: ");3213have_pv = true;3214pv_node->constants()->print_value_on(st);3215}3216if (have_pv) st->cr();3217}32183219if (generic_signature() != NULL) {3220st->print(BULLET"generic signature: ");3221generic_signature()->print_value_on(st);3222st->cr();3223}3224st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();3225st->print(BULLET"java mirror: "); java_mirror()->print_value_on(st); st->cr();3226st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable()); st->cr();3227if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);3228st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();3229if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);3230st->print_cr(BULLET"---- static fields (%d words):", static_field_size());3231FieldPrinter print_static_field(st);3232((InstanceKlass*)this)->do_local_static_fields(&print_static_field);3233st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());3234FieldPrinter print_nonstatic_field(st);3235((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);32363237st->print(BULLET"non-static oop maps: ");3238OopMapBlock* map = start_of_nonstatic_oop_maps();3239OopMapBlock* end_map = map + nonstatic_oop_map_count();3240while (map < end_map) {3241st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));3242map++;3243}3244st->cr();3245}32463247#endif //PRODUCT32483249void InstanceKlass::print_value_on(outputStream* st) const {3250assert(is_klass(), "must be klass");3251if (Verbose || WizardMode) access_flags().print_on(st);3252name()->print_value_on(st);3253}32543255#ifndef PRODUCT32563257void FieldPrinter::do_field(fieldDescriptor* fd) {3258_st->print(BULLET);3259if (_obj == NULL) {3260fd->print_on(_st);3261_st->cr();3262} else {3263fd->print_on_for(_st, _obj);3264_st->cr();3265}3266}326732683269void InstanceKlass::oop_print_on(oop obj, outputStream* st) {3270Klass::oop_print_on(obj, st);32713272if (this == SystemDictionary::String_klass()) {3273typeArrayOop value = java_lang_String::value(obj);3274juint offset = java_lang_String::offset(obj);3275juint length = java_lang_String::length(obj);3276if (value != NULL &&3277value->is_typeArray() &&3278offset <= (juint) value->length() &&3279offset + length <= (juint) value->length()) {3280st->print(BULLET"string: ");3281java_lang_String::print(obj, st);3282st->cr();3283if (!WizardMode) return; // that is enough3284}3285}32863287st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));3288FieldPrinter print_field(st, obj);3289do_nonstatic_fields(&print_field);32903291if (this == SystemDictionary::Class_klass()) {3292st->print(BULLET"signature: ");3293java_lang_Class::print_signature(obj, st);3294st->cr();3295Klass* mirrored_klass = java_lang_Class::as_Klass(obj);3296st->print(BULLET"fake entry for mirror: ");3297mirrored_klass->print_value_on_maybe_null(st);3298st->cr();3299Klass* array_klass = java_lang_Class::array_klass(obj);3300st->print(BULLET"fake entry for array: ");3301array_klass->print_value_on_maybe_null(st);3302st->cr();3303st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));3304st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));3305Klass* real_klass = java_lang_Class::as_Klass(obj);3306if (real_klass != NULL && real_klass->oop_is_instance()) {3307InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);3308}3309} else if (this == SystemDictionary::MethodType_klass()) {3310st->print(BULLET"signature: ");3311java_lang_invoke_MethodType::print_signature(obj, st);3312st->cr();3313}3314}33153316#endif //PRODUCT33173318void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {3319st->print("a ");3320name()->print_value_on(st);3321obj->print_address_on(st);3322if (this == SystemDictionary::String_klass()3323&& java_lang_String::value(obj) != NULL) {3324ResourceMark rm;3325int len = java_lang_String::length(obj);3326int plen = (len < 24 ? len : 12);3327char* str = java_lang_String::as_utf8_string(obj, 0, plen);3328st->print(" = \"%s\"", str);3329if (len > plen)3330st->print("...[%d]", len);3331} else if (this == SystemDictionary::Class_klass()) {3332Klass* k = java_lang_Class::as_Klass(obj);3333st->print(" = ");3334if (k != NULL) {3335k->print_value_on(st);3336} else {3337const char* tname = type2name(java_lang_Class::primitive_type(obj));3338st->print("%s", tname ? tname : "type?");3339}3340} else if (this == SystemDictionary::MethodType_klass()) {3341st->print(" = ");3342java_lang_invoke_MethodType::print_signature(obj, st);3343} else if (java_lang_boxing_object::is_instance(obj)) {3344st->print(" = ");3345java_lang_boxing_object::print(obj, st);3346} else if (this == SystemDictionary::LambdaForm_klass()) {3347oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);3348if (vmentry != NULL) {3349st->print(" => ");3350vmentry->print_value_on(st);3351}3352} else if (this == SystemDictionary::MemberName_klass()) {3353Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);3354if (vmtarget != NULL) {3355st->print(" = ");3356vmtarget->print_value_on(st);3357} else {3358java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);3359st->print(".");3360java_lang_invoke_MemberName::name(obj)->print_value_on(st);3361}3362}3363}33643365const char* InstanceKlass::internal_name() const {3366return external_name();3367}33683369#if INCLUDE_SERVICES3370// Size Statistics3371void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {3372Klass::collect_statistics(sz);33733374sz->_inst_size = HeapWordSize * size_helper();3375sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());3376sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());3377sz->_nonstatic_oopmap_bytes = HeapWordSize *3378((is_interface() || is_anonymous()) ?3379align_object_offset(nonstatic_oop_map_size()) :3380nonstatic_oop_map_size());33813382int n = 0;3383n += (sz->_methods_array_bytes = sz->count_array(methods()));3384n += (sz->_method_ordering_bytes = sz->count_array(method_ordering()));3385n += (sz->_local_interfaces_bytes = sz->count_array(local_interfaces()));3386n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));3387n += (sz->_fields_bytes = sz->count_array(fields()));3388n += (sz->_inner_classes_bytes = sz->count_array(inner_classes()));3389sz->_ro_bytes += n;33903391const ConstantPool* cp = constants();3392if (cp) {3393cp->collect_statistics(sz);3394}33953396const Annotations* anno = annotations();3397if (anno) {3398anno->collect_statistics(sz);3399}34003401const Array<Method*>* methods_array = methods();3402if (methods()) {3403for (int i = 0; i < methods_array->length(); i++) {3404Method* method = methods_array->at(i);3405if (method) {3406sz->_method_count ++;3407method->collect_statistics(sz);3408}3409}3410}3411}3412#endif // INCLUDE_SERVICES34133414// Verification34153416class VerifyFieldClosure: public OopClosure {3417protected:3418template <class T> void do_oop_work(T* p) {3419oop obj = oopDesc::load_decode_heap_oop(p);3420if (!obj->is_oop_or_null()) {3421tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);3422Universe::print();3423guarantee(false, "boom");3424}3425}3426public:3427virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }3428virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }3429};34303431void InstanceKlass::verify_on(outputStream* st) {3432#ifndef PRODUCT3433// Avoid redundant verifies, this really should be in product.3434if (_verify_count == Universe::verify_count()) return;3435_verify_count = Universe::verify_count();3436#endif34373438// Verify Klass3439Klass::verify_on(st);34403441// Verify that klass is present in ClassLoaderData3442guarantee(class_loader_data()->contains_klass(this),3443"this class isn't found in class loader data");34443445// Verify vtables3446if (is_linked()) {3447ResourceMark rm;3448// $$$ This used to be done only for m/s collections. Doing it3449// always seemed a valid generalization. (DLD -- 6/00)3450vtable()->verify(st);3451}34523453// Verify first subklass3454if (subklass_oop() != NULL) {3455guarantee(subklass_oop()->is_klass(), "should be klass");3456}34573458// Verify siblings3459Klass* super = this->super();3460Klass* sib = next_sibling();3461if (sib != NULL) {3462if (sib == this) {3463fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));3464}34653466guarantee(sib->is_klass(), "should be klass");3467guarantee(sib->super() == super, "siblings should have same superklass");3468}34693470// Verify implementor fields3471Klass* im = implementor();3472if (im != NULL) {3473guarantee(is_interface(), "only interfaces should have implementor set");3474guarantee(im->is_klass(), "should be klass");3475guarantee(!im->is_interface() || im == this,3476"implementors cannot be interfaces");3477}34783479// Verify local interfaces3480if (local_interfaces()) {3481Array<Klass*>* local_interfaces = this->local_interfaces();3482for (int j = 0; j < local_interfaces->length(); j++) {3483Klass* e = local_interfaces->at(j);3484guarantee(e->is_klass() && e->is_interface(), "invalid local interface");3485}3486}34873488// Verify transitive interfaces3489if (transitive_interfaces() != NULL) {3490Array<Klass*>* transitive_interfaces = this->transitive_interfaces();3491for (int j = 0; j < transitive_interfaces->length(); j++) {3492Klass* e = transitive_interfaces->at(j);3493guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");3494}3495}34963497// Verify methods3498if (methods() != NULL) {3499Array<Method*>* methods = this->methods();3500for (int j = 0; j < methods->length(); j++) {3501guarantee(methods->at(j)->is_method(), "non-method in methods array");3502}3503for (int j = 0; j < methods->length() - 1; j++) {3504Method* m1 = methods->at(j);3505Method* m2 = methods->at(j + 1);3506guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3507}3508}35093510// Verify method ordering3511if (method_ordering() != NULL) {3512Array<int>* method_ordering = this->method_ordering();3513int length = method_ordering->length();3514if (JvmtiExport::can_maintain_original_method_order() ||3515((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {3516guarantee(length == methods()->length(), "invalid method ordering length");3517jlong sum = 0;3518for (int j = 0; j < length; j++) {3519int original_index = method_ordering->at(j);3520guarantee(original_index >= 0, "invalid method ordering index");3521guarantee(original_index < length, "invalid method ordering index");3522sum += original_index;3523}3524// Verify sum of indices 0,1,...,length-13525guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");3526} else {3527guarantee(length == 0, "invalid method ordering length");3528}3529}35303531// Verify default methods3532if (default_methods() != NULL) {3533Array<Method*>* methods = this->default_methods();3534for (int j = 0; j < methods->length(); j++) {3535guarantee(methods->at(j)->is_method(), "non-method in methods array");3536}3537for (int j = 0; j < methods->length() - 1; j++) {3538Method* m1 = methods->at(j);3539Method* m2 = methods->at(j + 1);3540guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3541}3542}35433544// Verify JNI static field identifiers3545if (jni_ids() != NULL) {3546jni_ids()->verify(this);3547}35483549// Verify other fields3550if (array_klasses() != NULL) {3551guarantee(array_klasses()->is_klass(), "should be klass");3552}3553if (constants() != NULL) {3554guarantee(constants()->is_constantPool(), "should be constant pool");3555}3556const Klass* host = host_klass();3557if (host != NULL) {3558guarantee(host->is_klass(), "should be klass");3559}3560}35613562void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {3563Klass::oop_verify_on(obj, st);3564VerifyFieldClosure blk;3565obj->oop_iterate_no_header(&blk);3566}356735683569// JNIid class for jfieldIDs only3570// Note to reviewers:3571// These JNI functions are just moved over to column 1 and not changed3572// in the compressed oops workspace.3573JNIid::JNIid(Klass* holder, int offset, JNIid* next) {3574_holder = holder;3575_offset = offset;3576_next = next;3577debug_only(_is_static_field_id = false;)3578}357935803581JNIid* JNIid::find(int offset) {3582JNIid* current = this;3583while (current != NULL) {3584if (current->offset() == offset) return current;3585current = current->next();3586}3587return NULL;3588}35893590void JNIid::deallocate(JNIid* current) {3591while (current != NULL) {3592JNIid* next = current->next();3593delete current;3594current = next;3595}3596}359735983599void JNIid::verify(Klass* holder) {3600int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();3601int end_field_offset;3602end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);36033604JNIid* current = this;3605while (current != NULL) {3606guarantee(current->holder() == holder, "Invalid klass in JNIid");3607#ifdef ASSERT3608int o = current->offset();3609if (current->is_static_field_id()) {3610guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");3611}3612#endif3613current = current->next();3614}3615}361636173618#ifdef ASSERT3619void InstanceKlass::set_init_state(ClassState state) {3620bool good_state = is_shared() ? (_init_state <= state)3621: (_init_state < state);3622assert(good_state || state == allocated, "illegal state transition");3623assert(_init_thread == NULL, "should be cleared before state change");3624_init_state = (u1)state;3625}3626#endif362736283629// RedefineClasses() support for previous versions:36303631// Purge previous versions3632void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {3633if (ik->previous_versions() != NULL) {3634// This klass has previous versions so see what we can cleanup3635// while it is safe to do so.36363637int deleted_count = 0; // leave debugging breadcrumbs3638int live_count = 0;3639ClassLoaderData* loader_data = ik->class_loader_data();3640assert(loader_data != NULL, "should never be null");36413642// RC_TRACE macro has an embedded ResourceMark3643RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));36443645// previous versions are linked together through the InstanceKlass3646InstanceKlass* pv_node = ik->previous_versions();3647InstanceKlass* last = ik;3648int version = 0;36493650// check the previous versions list3651for (; pv_node != NULL; ) {36523653ConstantPool* pvcp = pv_node->constants();3654assert(pvcp != NULL, "cp ref was unexpectedly cleared");365536563657if (!pvcp->on_stack()) {3658// If the constant pool isn't on stack, none of the methods3659// are executing. Unlink this previous_version.3660// The previous version InstanceKlass is on the ClassLoaderData deallocate list3661// so will be deallocated during the next phase of class unloading.3662pv_node = pv_node->previous_versions();3663last->link_previous_versions(pv_node);3664deleted_count++;3665version++;3666continue;3667} else {3668RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",3669pv_node));3670assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");3671guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");3672live_count++;3673}36743675// At least one method is live in this previous version so clean its MethodData.3676// Reset dead EMCP methods not to get breakpoints.3677// All methods are deallocated when all of the methods for this class are no3678// longer running.3679Array<Method*>* method_refs = pv_node->methods();3680if (method_refs != NULL) {3681RC_TRACE(0x00000200, ("purge: previous methods length=%d",3682method_refs->length()));3683for (int j = 0; j < method_refs->length(); j++) {3684Method* method = method_refs->at(j);36853686if (!method->on_stack()) {3687// no breakpoints for non-running methods3688if (method->is_running_emcp()) {3689method->set_running_emcp(false);3690}3691} else {3692assert (method->is_obsolete() || method->is_running_emcp(),3693"emcp method cannot run after emcp bit is cleared");3694// RC_TRACE macro has an embedded ResourceMark3695RC_TRACE(0x00000200,3696("purge: %s(%s): prev method @%d in version @%d is alive",3697method->name()->as_C_string(),3698method->signature()->as_C_string(), j, version));3699if (method->method_data() != NULL) {3700// Clean out any weak method links for running methods3701// (also should include not EMCP methods)3702method->method_data()->clean_weak_method_links();3703}3704}3705}3706}3707// next previous version3708last = pv_node;3709pv_node = pv_node->previous_versions();3710version++;3711}3712RC_TRACE(0x00000200,3713("purge: previous version stats: live=%d, deleted=%d", live_count,3714deleted_count));3715}37163717// Clean MethodData of this class's methods so they don't refer to3718// old methods that are no longer running.3719Array<Method*>* methods = ik->methods();3720int num_methods = methods->length();3721for (int index2 = 0; index2 < num_methods; ++index2) {3722if (methods->at(index2)->method_data() != NULL) {3723methods->at(index2)->method_data()->clean_weak_method_links();3724}3725}3726}37273728void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,3729int emcp_method_count) {3730int obsolete_method_count = old_methods->length() - emcp_method_count;37313732if (emcp_method_count != 0 && obsolete_method_count != 0 &&3733_previous_versions != NULL) {3734// We have a mix of obsolete and EMCP methods so we have to3735// clear out any matching EMCP method entries the hard way.3736int local_count = 0;3737for (int i = 0; i < old_methods->length(); i++) {3738Method* old_method = old_methods->at(i);3739if (old_method->is_obsolete()) {3740// only obsolete methods are interesting3741Symbol* m_name = old_method->name();3742Symbol* m_signature = old_method->signature();37433744// previous versions are linked together through the InstanceKlass3745int j = 0;3746for (InstanceKlass* prev_version = _previous_versions;3747prev_version != NULL;3748prev_version = prev_version->previous_versions(), j++) {37493750Array<Method*>* method_refs = prev_version->methods();3751for (int k = 0; k < method_refs->length(); k++) {3752Method* method = method_refs->at(k);37533754if (!method->is_obsolete() &&3755method->name() == m_name &&3756method->signature() == m_signature) {3757// The current RedefineClasses() call has made all EMCP3758// versions of this method obsolete so mark it as obsolete3759RC_TRACE(0x00000400,3760("add: %s(%s): flush obsolete method @%d in version @%d",3761m_name->as_C_string(), m_signature->as_C_string(), k, j));37623763method->set_is_obsolete();3764break;3765}3766}37673768// The previous loop may not find a matching EMCP method, but3769// that doesn't mean that we can optimize and not go any3770// further back in the PreviousVersion generations. The EMCP3771// method for this generation could have already been made obsolete,3772// but there still may be an older EMCP method that has not3773// been made obsolete.3774}37753776if (++local_count >= obsolete_method_count) {3777// no more obsolete methods so bail out now3778break;3779}3780}3781}3782}3783}37843785// Save the scratch_class as the previous version if any of the methods are running.3786// The previous_versions are used to set breakpoints in EMCP methods and they are3787// also used to clean MethodData links to redefined methods that are no longer running.3788void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,3789int emcp_method_count) {3790assert(Thread::current()->is_VM_thread(),3791"only VMThread can add previous versions");37923793// RC_TRACE macro has an embedded ResourceMark3794RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",3795scratch_class->external_name(), emcp_method_count));37963797// Clean out old previous versions3798purge_previous_versions(this);37993800// Mark newly obsolete methods in remaining previous versions. An EMCP method from3801// a previous redefinition may be made obsolete by this redefinition.3802Array<Method*>* old_methods = scratch_class->methods();3803mark_newly_obsolete_methods(old_methods, emcp_method_count);38043805// If the constant pool for this previous version of the class3806// is not marked as being on the stack, then none of the methods3807// in this previous version of the class are on the stack so3808// we don't need to add this as a previous version.3809ConstantPool* cp_ref = scratch_class->constants();3810if (!cp_ref->on_stack()) {3811RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));3812return;3813}38143815if (emcp_method_count != 0) {3816// At least one method is still running, check for EMCP methods3817for (int i = 0; i < old_methods->length(); i++) {3818Method* old_method = old_methods->at(i);3819if (!old_method->is_obsolete() && old_method->on_stack()) {3820// if EMCP method (not obsolete) is on the stack, mark as EMCP so that3821// we can add breakpoints for it.38223823// We set the method->on_stack bit during safepoints for class redefinition and3824// class unloading and use this bit to set the is_running_emcp bit.3825// After the safepoint, the on_stack bit is cleared and the running emcp3826// method may exit. If so, we would set a breakpoint in a method that3827// is never reached, but this won't be noticeable to the programmer.3828old_method->set_running_emcp(true);3829RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,3830old_method->name_and_sig_as_C_string(), old_method));3831} else if (!old_method->is_obsolete()) {3832RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,3833old_method->name_and_sig_as_C_string(), old_method));3834}3835}3836}38373838// Add previous version if any methods are still running.3839RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));3840assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");3841scratch_class->link_previous_versions(previous_versions());3842link_previous_versions(scratch_class());3843} // end add_previous_version()38443845Method* InstanceKlass::method_with_idnum(int idnum) {3846Method* m = NULL;3847if (idnum < methods()->length()) {3848m = methods()->at(idnum);3849}3850if (m == NULL || m->method_idnum() != idnum) {3851for (int index = 0; index < methods()->length(); ++index) {3852m = methods()->at(index);3853if (m->method_idnum() == idnum) {3854return m;3855}3856}3857// None found, return null for the caller to handle.3858return NULL;3859}3860return m;3861}386238633864Method* InstanceKlass::method_with_orig_idnum(int idnum) {3865if (idnum >= methods()->length()) {3866return NULL;3867}3868Method* m = methods()->at(idnum);3869if (m != NULL && m->orig_method_idnum() == idnum) {3870return m;3871}3872// Obsolete method idnum does not match the original idnum3873for (int index = 0; index < methods()->length(); ++index) {3874m = methods()->at(index);3875if (m->orig_method_idnum() == idnum) {3876return m;3877}3878}3879// None found, return null for the caller to handle.3880return NULL;3881}388238833884Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {3885InstanceKlass* holder = get_klass_version(version);3886if (holder == NULL) {3887return NULL; // The version of klass is gone, no method is found3888}3889Method* method = holder->method_with_orig_idnum(idnum);3890return method;3891}389238933894jint InstanceKlass::get_cached_class_file_len() {3895return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);3896}38973898unsigned char * InstanceKlass::get_cached_class_file_bytes() {3899return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);3900}390139023903