Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/oops/instanceKlass.cpp
32285 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 "gc_implementation/shenandoah/shenandoahOopClosures.inline.hpp"76#include "oops/oop.pcgc.inline.hpp"77#endif // INCLUDE_ALL_GCS78#ifdef COMPILER179#include "c1/c1_Compiler.hpp"80#endif81#if INCLUDE_JFR82#include "jfr/jfrEvents.hpp"83#endif848586PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC8788#ifdef DTRACE_ENABLED8990#ifndef USDT29192HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,93char*, intptr_t, oop, intptr_t);94HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,95char*, intptr_t, oop, intptr_t, int);96HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,97char*, intptr_t, oop, intptr_t, int);98HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,99char*, intptr_t, oop, intptr_t, int);100HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,101char*, intptr_t, oop, intptr_t, int);102HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,103char*, intptr_t, oop, intptr_t, int);104HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,105char*, intptr_t, oop, intptr_t, int);106HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,107char*, intptr_t, oop, intptr_t, int);108109#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \110{ \111char* data = NULL; \112int len = 0; \113Symbol* name = (clss)->name(); \114if (name != NULL) { \115data = (char*)name->bytes(); \116len = name->utf8_length(); \117} \118HS_DTRACE_PROBE4(hotspot, class__initialization__##type, \119data, len, (void *)(clss)->class_loader(), thread_type); \120}121122#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \123{ \124char* data = NULL; \125int len = 0; \126Symbol* name = (clss)->name(); \127if (name != NULL) { \128data = (char*)name->bytes(); \129len = name->utf8_length(); \130} \131HS_DTRACE_PROBE5(hotspot, class__initialization__##type, \132data, len, (void *)(clss)->class_loader(), thread_type, wait); \133}134#else /* USDT2 */135136#define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED137#define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE138#define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT139#define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS140#define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED141#define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT142#define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR143#define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END144#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \145{ \146char* data = NULL; \147int len = 0; \148Symbol* name = (clss)->name(); \149if (name != NULL) { \150data = (char*)name->bytes(); \151len = name->utf8_length(); \152} \153HOTSPOT_CLASS_INITIALIZATION_##type( \154data, len, (void *)(clss)->class_loader(), thread_type); \155}156157#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \158{ \159char* data = NULL; \160int len = 0; \161Symbol* name = (clss)->name(); \162if (name != NULL) { \163data = (char*)name->bytes(); \164len = name->utf8_length(); \165} \166HOTSPOT_CLASS_INITIALIZATION_##type( \167data, len, (void *)(clss)->class_loader(), thread_type, wait); \168}169#endif /* USDT2 */170171#else // ndef DTRACE_ENABLED172173#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)174#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)175176#endif // ndef DTRACE_ENABLED177178volatile int InstanceKlass::_total_instanceKlass_count = 0;179180InstanceKlass* InstanceKlass::allocate_instance_klass(181ClassLoaderData* loader_data,182int vtable_len,183int itable_len,184int static_field_size,185int nonstatic_oop_map_size,186ReferenceType rt,187AccessFlags access_flags,188Symbol* name,189Klass* super_klass,190bool is_anonymous,191TRAPS) {192193int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,194access_flags.is_interface(), is_anonymous);195196// Allocation197InstanceKlass* ik;198if (rt == REF_NONE) {199if (name == vmSymbols::java_lang_Class()) {200ik = new (loader_data, size, THREAD) InstanceMirrorKlass(201vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,202access_flags, is_anonymous);203} else if (name == vmSymbols::java_lang_ClassLoader() ||204(SystemDictionary::ClassLoader_klass_loaded() &&205super_klass != NULL &&206super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {207ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(208vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,209access_flags, is_anonymous);210} else {211// normal class212ik = new (loader_data, size, THREAD) InstanceKlass(213vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,214access_flags, is_anonymous);215}216} else {217// reference klass218ik = new (loader_data, size, THREAD) InstanceRefKlass(219vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,220access_flags, is_anonymous);221}222223// Check for pending exception before adding to the loader data and incrementing224// class count. Can get OOM here.225if (HAS_PENDING_EXCEPTION) {226return NULL;227}228229// Add all classes to our internal class loader list here,230// including classes in the bootstrap (NULL) class loader.231loader_data->add_class(ik);232233Atomic::inc(&_total_instanceKlass_count);234return ik;235}236237238// copy method ordering from resource area to Metaspace239void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {240if (m != NULL) {241// allocate a new array and copy contents (memcpy?)242_method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);243for (int i = 0; i < m->length(); i++) {244_method_ordering->at_put(i, m->at(i));245}246} else {247_method_ordering = Universe::the_empty_int_array();248}249}250251// create a new array of vtable_indices for default methods252Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {253Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);254assert(default_vtable_indices() == NULL, "only create once");255set_default_vtable_indices(vtable_indices);256return vtable_indices;257}258259InstanceKlass::InstanceKlass(int vtable_len,260int itable_len,261int static_field_size,262int nonstatic_oop_map_size,263ReferenceType rt,264AccessFlags access_flags,265bool is_anonymous) {266No_Safepoint_Verifier no_safepoint; // until k becomes parsable267268int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,269access_flags.is_interface(), is_anonymous);270271set_vtable_length(vtable_len);272set_itable_length(itable_len);273set_static_field_size(static_field_size);274set_nonstatic_oop_map_size(nonstatic_oop_map_size);275set_access_flags(access_flags);276_misc_flags = 0; // initialize to zero277set_is_anonymous(is_anonymous);278assert(size() == iksize, "wrong size for object");279280set_array_klasses(NULL);281set_methods(NULL);282set_method_ordering(NULL);283set_default_methods(NULL);284set_default_vtable_indices(NULL);285set_local_interfaces(NULL);286set_transitive_interfaces(NULL);287init_implementor();288set_fields(NULL, 0);289set_constants(NULL);290set_class_loader_data(NULL);291set_source_file_name_index(0);292set_source_debug_extension(NULL, 0);293set_array_name(NULL);294set_inner_classes(NULL);295set_static_oop_field_count(0);296set_nonstatic_field_size(0);297set_is_marked_dependent(false);298set_has_unloaded_dependent(false);299set_init_state(InstanceKlass::allocated);300set_init_thread(NULL);301set_init_state(allocated);302set_reference_type(rt);303set_oop_map_cache(NULL);304set_jni_ids(NULL);305set_osr_nmethods_head(NULL);306set_breakpoints(NULL);307init_previous_versions();308set_generic_signature_index(0);309release_set_methods_jmethod_ids(NULL);310set_annotations(NULL);311set_jvmti_cached_class_field_map(NULL);312set_initial_method_idnum(0);313_dependencies = NULL;314set_jvmti_cached_class_field_map(NULL);315set_cached_class_file(NULL);316set_initial_method_idnum(0);317set_minor_version(0);318set_major_version(0);319NOT_PRODUCT(_verify_count = 0;)320321// initialize the non-header words to zero322intptr_t* p = (intptr_t*)this;323for (int index = InstanceKlass::header_size(); index < iksize; index++) {324p[index] = NULL_WORD;325}326327// Set temporary value until parseClassFile updates it with the real instance328// size.329set_layout_helper(Klass::instance_layout_helper(0, true));330}331332333void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,334Array<Method*>* methods) {335if (methods != NULL && methods != Universe::the_empty_method_array() &&336!methods->is_shared()) {337for (int i = 0; i < methods->length(); i++) {338Method* method = methods->at(i);339if (method == NULL) continue; // maybe null if error processing340// Only want to delete methods that are not executing for RedefineClasses.341// The previous version will point to them so they're not totally dangling342assert (!method->on_stack(), "shouldn't be called with methods on stack");343MetadataFactory::free_metadata(loader_data, method);344}345MetadataFactory::free_array<Method*>(loader_data, methods);346}347}348349void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,350Klass* super_klass,351Array<Klass*>* local_interfaces,352Array<Klass*>* transitive_interfaces) {353// Only deallocate transitive interfaces if not empty, same as super class354// or same as local interfaces. See code in parseClassFile.355Array<Klass*>* ti = transitive_interfaces;356if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {357// check that the interfaces don't come from super class358Array<Klass*>* sti = (super_klass == NULL) ? NULL :359InstanceKlass::cast(super_klass)->transitive_interfaces();360if (ti != sti && ti != NULL && !ti->is_shared()) {361MetadataFactory::free_array<Klass*>(loader_data, ti);362}363}364365// local interfaces can be empty366if (local_interfaces != Universe::the_empty_klass_array() &&367local_interfaces != NULL && !local_interfaces->is_shared()) {368MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);369}370}371372// This function deallocates the metadata and C heap pointers that the373// InstanceKlass points to.374void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {375376// Orphan the mirror first, CMS thinks it's still live.377if (java_mirror() != NULL) {378java_lang_Class::set_klass(java_mirror(), NULL);379}380381// Need to take this class off the class loader data list.382loader_data->remove_class(this);383384// The array_klass for this class is created later, after error handling.385// For class redefinition, we keep the original class so this scratch class386// doesn't have an array class. Either way, assert that there is nothing387// to deallocate.388assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");389390// Release C heap allocated data that this might point to, which includes391// reference counting symbol names.392release_C_heap_structures();393394deallocate_methods(loader_data, methods());395set_methods(NULL);396397if (method_ordering() != NULL &&398method_ordering() != Universe::the_empty_int_array() &&399!method_ordering()->is_shared()) {400MetadataFactory::free_array<int>(loader_data, method_ordering());401}402set_method_ordering(NULL);403404// default methods can be empty405if (default_methods() != NULL &&406default_methods() != Universe::the_empty_method_array() &&407!default_methods()->is_shared()) {408MetadataFactory::free_array<Method*>(loader_data, default_methods());409}410// Do NOT deallocate the default methods, they are owned by superinterfaces.411set_default_methods(NULL);412413// default methods vtable indices can be empty414if (default_vtable_indices() != NULL &&415!default_vtable_indices()->is_shared()) {416MetadataFactory::free_array<int>(loader_data, default_vtable_indices());417}418set_default_vtable_indices(NULL);419420421// This array is in Klass, but remove it with the InstanceKlass since422// this place would be the only caller and it can share memory with transitive423// interfaces.424if (secondary_supers() != NULL &&425secondary_supers() != Universe::the_empty_klass_array() &&426secondary_supers() != transitive_interfaces() &&427!secondary_supers()->is_shared()) {428MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());429}430set_secondary_supers(NULL);431432deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());433set_transitive_interfaces(NULL);434set_local_interfaces(NULL);435436if (fields() != NULL && !fields()->is_shared()) {437MetadataFactory::free_array<jushort>(loader_data, fields());438}439set_fields(NULL, 0);440441// If a method from a redefined class is using this constant pool, don't442// delete it, yet. The new class's previous version will point to this.443if (constants() != NULL) {444assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");445if (!constants()->is_shared()) {446MetadataFactory::free_metadata(loader_data, constants());447}448// Delete any cached resolution errors for the constant pool449SystemDictionary::delete_resolution_error(constants());450451set_constants(NULL);452}453454if (inner_classes() != NULL &&455inner_classes() != Universe::the_empty_short_array() &&456!inner_classes()->is_shared()) {457MetadataFactory::free_array<jushort>(loader_data, inner_classes());458}459set_inner_classes(NULL);460461// We should deallocate the Annotations instance if it's not in shared spaces.462if (annotations() != NULL && !annotations()->is_shared()) {463MetadataFactory::free_metadata(loader_data, annotations());464}465set_annotations(NULL);466}467468bool InstanceKlass::should_be_initialized() const {469return !is_initialized();470}471472klassVtable* InstanceKlass::vtable() const {473return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());474}475476klassItable* InstanceKlass::itable() const {477return new klassItable(instanceKlassHandle(this));478}479480void InstanceKlass::eager_initialize(Thread *thread) {481if (!EagerInitialization) return;482483if (this->is_not_initialized()) {484// abort if the the class has a class initializer485if (this->class_initializer() != NULL) return;486487// abort if it is java.lang.Object (initialization is handled in genesis)488Klass* super = this->super();489if (super == NULL) return;490491// abort if the super class should be initialized492if (!InstanceKlass::cast(super)->is_initialized()) return;493494// call body to expose the this pointer495instanceKlassHandle this_oop(thread, this);496eager_initialize_impl(this_oop);497}498}499500// JVMTI spec thinks there are signers and protection domain in the501// instanceKlass. These accessors pretend these fields are there.502// The hprof specification also thinks these fields are in InstanceKlass.503oop InstanceKlass::protection_domain() const {504// return the protection_domain from the mirror505return java_lang_Class::protection_domain(java_mirror());506}507508// To remove these from requires an incompatible change and CCC request.509objArrayOop InstanceKlass::signers() const {510// return the signers from the mirror511return java_lang_Class::signers(java_mirror());512}513514oop InstanceKlass::init_lock() const {515// return the init lock from the mirror516oop lock = java_lang_Class::init_lock(java_mirror());517// Prevent reordering with any access of initialization state518OrderAccess::loadload();519assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state520"only fully initialized state can have a null lock");521return lock;522}523524// Set the initialization lock to null so the object can be GC'ed. Any racing525// threads to get this lock will see a null lock and will not lock.526// That's okay because they all check for initialized state after getting527// the lock and return.528void InstanceKlass::fence_and_clear_init_lock() {529// make sure previous stores are all done, notably the init_state.530OrderAccess::storestore();531java_lang_Class::set_init_lock(java_mirror(), NULL);532assert(!is_not_initialized(), "class must be initialized now");533}534535void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {536EXCEPTION_MARK;537oop init_lock = this_oop->init_lock();538ObjectLocker ol(init_lock, THREAD, init_lock != NULL);539540// abort if someone beat us to the initialization541if (!this_oop->is_not_initialized()) return; // note: not equivalent to is_initialized()542543ClassState old_state = this_oop->init_state();544link_class_impl(this_oop, true, THREAD);545if (HAS_PENDING_EXCEPTION) {546CLEAR_PENDING_EXCEPTION;547// Abort if linking the class throws an exception.548549// Use a test to avoid redundantly resetting the state if there's550// no change. Set_init_state() asserts that state changes make551// progress, whereas here we might just be spinning in place.552if( old_state != this_oop->_init_state )553this_oop->set_init_state (old_state);554} else {555// linking successfull, mark class as initialized556this_oop->set_init_state (fully_initialized);557this_oop->fence_and_clear_init_lock();558// trace559if (TraceClassInitialization) {560ResourceMark rm(THREAD);561tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());562}563}564}565566567// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization568// process. The step comments refers to the procedure described in that section.569// Note: implementation moved to static method to expose the this pointer.570void InstanceKlass::initialize(TRAPS) {571if (this->should_be_initialized()) {572HandleMark hm(THREAD);573instanceKlassHandle this_oop(THREAD, this);574initialize_impl(this_oop, CHECK);575// Note: at this point the class may be initialized576// OR it may be in the state of being initialized577// in case of recursive initialization!578} else {579assert(is_initialized(), "sanity check");580}581}582583584bool InstanceKlass::verify_code(585instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {586// 1) Verify the bytecodes587Verifier::Mode mode =588throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;589return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), THREAD);590}591592593// Used exclusively by the shared spaces dump mechanism to prevent594// classes mapped into the shared regions in new VMs from appearing linked.595596void InstanceKlass::unlink_class() {597assert(is_linked(), "must be linked");598_init_state = loaded;599}600601void InstanceKlass::link_class(TRAPS) {602assert(is_loaded(), "must be loaded");603if (!is_linked()) {604HandleMark hm(THREAD);605instanceKlassHandle this_oop(THREAD, this);606link_class_impl(this_oop, true, CHECK);607}608}609610// Called to verify that a class can link during initialization, without611// throwing a VerifyError.612bool InstanceKlass::link_class_or_fail(TRAPS) {613assert(is_loaded(), "must be loaded");614if (!is_linked()) {615HandleMark hm(THREAD);616instanceKlassHandle this_oop(THREAD, this);617link_class_impl(this_oop, false, CHECK_false);618}619return is_linked();620}621622bool InstanceKlass::link_class_impl(623instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {624// check for error state.625// This is checking for the wrong state. If the state is initialization_error,626// then this class *was* linked. The CDS code does a try_link_class and uses627// initialization_error to mark classes to not include in the archive during628// DumpSharedSpaces. This should be removed when the CDS bug is fixed.629if (this_oop->is_in_error_state()) {630ResourceMark rm(THREAD);631THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),632this_oop->external_name(), false);633}634// return if already verified635if (this_oop->is_linked()) {636return true;637}638639// Timing640// timer handles recursion641assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");642JavaThread* jt = (JavaThread*)THREAD;643644// link super class before linking this class645instanceKlassHandle super(THREAD, this_oop->super());646if (super.not_null()) {647if (super->is_interface()) { // check if super class is an interface648ResourceMark rm(THREAD);649Exceptions::fthrow(650THREAD_AND_LOCATION,651vmSymbols::java_lang_IncompatibleClassChangeError(),652"class %s has interface %s as super class",653this_oop->external_name(),654super->external_name()655);656return false;657}658659link_class_impl(super, throw_verifyerror, CHECK_false);660}661662// link all interfaces implemented by this class before linking this class663Array<Klass*>* interfaces = this_oop->local_interfaces();664int num_interfaces = interfaces->length();665for (int index = 0; index < num_interfaces; index++) {666HandleMark hm(THREAD);667instanceKlassHandle ih(THREAD, interfaces->at(index));668link_class_impl(ih, throw_verifyerror, CHECK_false);669}670671// in case the class is linked in the process of linking its superclasses672if (this_oop->is_linked()) {673return true;674}675676// trace only the link time for this klass that includes677// the verification time678PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),679ClassLoader::perf_class_link_selftime(),680ClassLoader::perf_classes_linked(),681jt->get_thread_stat()->perf_recursion_counts_addr(),682jt->get_thread_stat()->perf_timers_addr(),683PerfClassTraceTime::CLASS_LINK);684685// verification & rewriting686{687oop init_lock = this_oop->init_lock();688ObjectLocker ol(init_lock, THREAD, init_lock != NULL);689// rewritten will have been set if loader constraint error found690// on an earlier link attempt691// don't verify or rewrite if already rewritten692693if (!this_oop->is_linked()) {694if (!this_oop->is_rewritten()) {695{696// Timer includes any side effects of class verification (resolution,697// etc), but not recursive entry into verify_code().698PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),699ClassLoader::perf_class_verify_selftime(),700ClassLoader::perf_classes_verified(),701jt->get_thread_stat()->perf_recursion_counts_addr(),702jt->get_thread_stat()->perf_timers_addr(),703PerfClassTraceTime::CLASS_VERIFY);704bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);705if (!verify_ok) {706return false;707}708}709710// Just in case a side-effect of verify linked this class already711// (which can sometimes happen since the verifier loads classes712// using custom class loaders, which are free to initialize things)713if (this_oop->is_linked()) {714return true;715}716717// also sets rewritten718this_oop->rewrite_class(CHECK_false);719} else if (this_oop()->is_shared()) {720ResourceMark rm(THREAD);721char* message_buffer; // res-allocated by check_verification_dependencies722Handle loader = this_oop()->class_loader();723Handle pd = this_oop()->protection_domain();724bool verified = SystemDictionaryShared::check_verification_dependencies(this_oop(),725loader, pd, &message_buffer, THREAD);726if (!verified) {727THROW_MSG_(vmSymbols::java_lang_VerifyError(), message_buffer, false);728}729}730731// relocate jsrs and link methods after they are all rewritten732this_oop->link_methods(CHECK_false);733734// Initialize the vtable and interface table after735// methods have been rewritten since rewrite may736// fabricate new Method*s.737// also does loader constraint checking738//739// Initialize_vtable and initialize_itable need to be rerun for740// a shared class if the class is not loaded by the NULL classloader.741ClassLoaderData * loader_data = this_oop->class_loader_data();742if (!(this_oop()->is_shared() &&743loader_data->is_the_null_class_loader_data())) {744ResourceMark rm(THREAD);745this_oop->vtable()->initialize_vtable(true, CHECK_false);746this_oop->itable()->initialize_itable(true, CHECK_false);747}748#ifdef ASSERT749else {750ResourceMark rm(THREAD);751this_oop->vtable()->verify(tty, true);752// In case itable verification is ever added.753// this_oop->itable()->verify(tty, true);754}755#endif756this_oop->set_init_state(linked);757if (JvmtiExport::should_post_class_prepare()) {758Thread *thread = THREAD;759assert(thread->is_Java_thread(), "thread->is_Java_thread()");760JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());761}762}763}764return true;765}766767768// Rewrite the byte codes of all of the methods of a class.769// The rewriter must be called exactly once. Rewriting must happen after770// verification but before the first method of the class is executed.771void InstanceKlass::rewrite_class(TRAPS) {772assert(is_loaded(), "must be loaded");773instanceKlassHandle this_oop(THREAD, this);774if (this_oop->is_rewritten()) {775assert(this_oop()->is_shared(), "rewriting an unshared class?");776return;777}778Rewriter::rewrite(this_oop, CHECK);779this_oop->set_rewritten();780}781782// Now relocate and link method entry points after class is rewritten.783// This is outside is_rewritten flag. In case of an exception, it can be784// executed more than once.785void InstanceKlass::link_methods(TRAPS) {786int len = methods()->length();787for (int i = len-1; i >= 0; i--) {788methodHandle m(THREAD, methods()->at(i));789790// Set up method entry points for compiler and interpreter .791m->link_method(m, CHECK);792793// This is for JVMTI and unrelated to relocator but the last thing we do794#ifdef ASSERT795if (StressMethodComparator) {796ResourceMark rm(THREAD);797static int nmc = 0;798for (int j = i; j >= 0 && j >= i-4; j--) {799if ((++nmc % 1000) == 0) tty->print_cr("Have run MethodComparator %d times...", nmc);800bool z = MethodComparator::methods_EMCP(m(),801methods()->at(j));802if (j == i && !z) {803tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();804assert(z, "method must compare equal to itself");805}806}807}808#endif //ASSERT809}810}811812// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)813void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {814assert (this_k->has_default_methods(), "caller should have checked this");815for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {816Klass* iface = this_k->local_interfaces()->at(i);817InstanceKlass* ik = InstanceKlass::cast(iface);818819// Initialization is depth first search ie. we start with top of the inheritance tree820// has_default_methods drives searching superinterfaces since it821// means has_default_methods in its superinterface hierarchy822if (ik->has_default_methods()) {823ik->initialize_super_interfaces(ik, CHECK);824}825826// Only initialize() interfaces that "declare" concrete methods.827if (ik->should_be_initialized() && ik->declares_default_methods()) {828ik->initialize(CHECK);829}830}831}832833void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {834// Make sure klass is linked (verified) before initialization835// A class could already be verified, since it has been reflected upon.836this_oop->link_class(CHECK);837838DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);839840bool wait = false;841842// refer to the JVM book page 47 for description of steps843// Step 1844{845oop init_lock = this_oop->init_lock();846ObjectLocker ol(init_lock, THREAD, init_lock != NULL);847848Thread *self = THREAD; // it's passed the current thread849850// Step 2851// If we were to use wait() instead of waitInterruptibly() then852// we might end up throwing IE from link/symbol resolution sites853// that aren't expected to throw. This would wreak havoc. See 6320309.854while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {855wait = true;856ol.waitUninterruptibly(CHECK);857}858859// Step 3860if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {861DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);862return;863}864865// Step 4866if (this_oop->is_initialized()) {867DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);868return;869}870871// Step 5872if (this_oop->is_in_error_state()) {873DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);874ResourceMark rm(THREAD);875const char* desc = "Could not initialize class ";876const char* className = this_oop->external_name();877size_t msglen = strlen(desc) + strlen(className) + 1;878char* message = NEW_RESOURCE_ARRAY(char, msglen);879if (NULL == message) {880// Out of memory: can't create detailed error message881THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);882} else {883jio_snprintf(message, msglen, "%s%s", desc, className);884THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);885}886}887888// Step 6889this_oop->set_init_state(being_initialized);890this_oop->set_init_thread(self);891}892893// Step 7894// Next, if C is a class rather than an interface, initialize its super class and super895// interfaces.896if (!this_oop->is_interface()) {897Klass* super_klass = this_oop->super();898if (super_klass != NULL && super_klass->should_be_initialized()) {899super_klass->initialize(THREAD);900}901// If C implements any interfaces that declares a non-abstract, non-static method,902// the initialization of C triggers initialization of its super interfaces.903// Only need to recurse if has_default_methods which includes declaring and904// inheriting default methods905if (!HAS_PENDING_EXCEPTION && this_oop->has_default_methods()) {906this_oop->initialize_super_interfaces(this_oop, THREAD);907}908909// If any exceptions, complete abruptly, throwing the same exception as above.910if (HAS_PENDING_EXCEPTION) {911Handle e(THREAD, PENDING_EXCEPTION);912CLEAR_PENDING_EXCEPTION;913{914EXCEPTION_MARK;915// Locks object, set state, and notify all waiting threads916this_oop->set_initialization_state_and_notify(initialization_error, THREAD);917CLEAR_PENDING_EXCEPTION;918}919DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);920THROW_OOP(e());921}922}923924// Step 8925{926assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");927JavaThread* jt = (JavaThread*)THREAD;928DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);929// Timer includes any side effects of class initialization (resolution,930// etc), but not recursive entry into call_class_initializer().931PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),932ClassLoader::perf_class_init_selftime(),933ClassLoader::perf_classes_inited(),934jt->get_thread_stat()->perf_recursion_counts_addr(),935jt->get_thread_stat()->perf_timers_addr(),936PerfClassTraceTime::CLASS_CLINIT);937this_oop->call_class_initializer(THREAD);938}939940// Step 9941if (!HAS_PENDING_EXCEPTION) {942this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);943{ ResourceMark rm(THREAD);944debug_only(this_oop->vtable()->verify(tty, true);)945}946}947else {948// Step 10 and 11949Handle e(THREAD, PENDING_EXCEPTION);950CLEAR_PENDING_EXCEPTION;951// JVMTI has already reported the pending exception952// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError953JvmtiExport::clear_detected_exception((JavaThread*)THREAD);954{955EXCEPTION_MARK;956this_oop->set_initialization_state_and_notify(initialization_error, THREAD);957CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below958// JVMTI has already reported the pending exception959// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError960JvmtiExport::clear_detected_exception((JavaThread*)THREAD);961}962DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);963if (e->is_a(SystemDictionary::Error_klass())) {964THROW_OOP(e());965} else {966JavaCallArguments args(e);967THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),968vmSymbols::throwable_void_signature(),969&args);970}971}972DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);973}974975976// Note: implementation moved to static method to expose the this pointer.977void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {978instanceKlassHandle kh(THREAD, this);979set_initialization_state_and_notify_impl(kh, state, CHECK);980}981982void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {983oop init_lock = this_oop->init_lock();984if (init_lock != NULL) {985ObjectLocker ol(init_lock, THREAD);986this_oop->set_init_thread(NULL); // reset _init_thread before changing _init_state987this_oop->set_init_state(state);988this_oop->fence_and_clear_init_lock();989ol.notify_all(CHECK);990} else {991assert(init_lock != NULL, "The initialization state should never be set twice");992this_oop->set_init_thread(NULL); // reset _init_thread before changing _init_state993this_oop->set_init_state(state);994}995}996997// The embedded _implementor field can only record one implementor.998// When there are more than one implementors, the _implementor field999// is set to the interface Klass* itself. Following are the possible1000// values for the _implementor field:1001// NULL - no implementor1002// implementor Klass* - one implementor1003// self - more than one implementor1004//1005// The _implementor field only exists for interfaces.1006void InstanceKlass::add_implementor(Klass* k) {1007assert(Compile_lock->owned_by_self(), "");1008assert(is_interface(), "not interface");1009// Filter out my subinterfaces.1010// (Note: Interfaces are never on the subklass list.)1011if (InstanceKlass::cast(k)->is_interface()) return;10121013// Filter out subclasses whose supers already implement me.1014// (Note: CHA must walk subclasses of direct implementors1015// in order to locate indirect implementors.)1016Klass* sk = InstanceKlass::cast(k)->super();1017if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))1018// We only need to check one immediate superclass, since the1019// implements_interface query looks at transitive_interfaces.1020// Any supers of the super have the same (or fewer) transitive_interfaces.1021return;10221023Klass* ik = implementor();1024if (ik == NULL) {1025set_implementor(k);1026} else if (ik != this) {1027// There is already an implementor. Use itself as an indicator of1028// more than one implementors.1029set_implementor(this);1030}10311032// The implementor also implements the transitive_interfaces1033for (int index = 0; index < local_interfaces()->length(); index++) {1034InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);1035}1036}10371038void InstanceKlass::init_implementor() {1039if (is_interface()) {1040set_implementor(NULL);1041}1042}104310441045void InstanceKlass::process_interfaces(Thread *thread) {1046// link this class into the implementors list of every interface it implements1047Klass* this_as_klass_oop = this;1048for (int i = local_interfaces()->length() - 1; i >= 0; i--) {1049assert(local_interfaces()->at(i)->is_klass(), "must be a klass");1050InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));1051assert(interf->is_interface(), "expected interface");1052interf->add_implementor(this_as_klass_oop);1053}1054}10551056bool InstanceKlass::can_be_primary_super_slow() const {1057if (is_interface())1058return false;1059else1060return Klass::can_be_primary_super_slow();1061}10621063GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {1064// The secondaries are the implemented interfaces.1065InstanceKlass* ik = InstanceKlass::cast(this);1066Array<Klass*>* interfaces = ik->transitive_interfaces();1067int num_secondaries = num_extra_slots + interfaces->length();1068if (num_secondaries == 0) {1069// Must share this for correct bootstrapping!1070set_secondary_supers(Universe::the_empty_klass_array());1071return NULL;1072} else if (num_extra_slots == 0) {1073// The secondary super list is exactly the same as the transitive interfaces.1074// Redefine classes has to be careful not to delete this!1075set_secondary_supers(interfaces);1076return NULL;1077} else {1078// Copy transitive interfaces to a temporary growable array to be constructed1079// into the secondary super list with extra slots.1080GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());1081for (int i = 0; i < interfaces->length(); i++) {1082secondaries->push(interfaces->at(i));1083}1084return secondaries;1085}1086}10871088bool InstanceKlass::compute_is_subtype_of(Klass* k) {1089if (k->is_interface()) {1090return implements_interface(k);1091} else {1092return Klass::compute_is_subtype_of(k);1093}1094}10951096bool InstanceKlass::implements_interface(Klass* k) const {1097if (this == k) return true;1098assert(k->is_interface(), "should be an interface class");1099for (int i = 0; i < transitive_interfaces()->length(); i++) {1100if (transitive_interfaces()->at(i) == k) {1101return true;1102}1103}1104return false;1105}11061107bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {1108// Verify direct super interface1109if (this == k) return true;1110assert(k->is_interface(), "should be an interface class");1111for (int i = 0; i < local_interfaces()->length(); i++) {1112if (local_interfaces()->at(i) == k) {1113return true;1114}1115}1116return false;1117}11181119objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {1120if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());1121if (length > arrayOopDesc::max_array_length(T_OBJECT)) {1122report_java_out_of_memory("Requested array size exceeds VM limit");1123JvmtiExport::post_array_size_exhausted();1124THROW_OOP_0(Universe::out_of_memory_error_array_size());1125}1126int size = objArrayOopDesc::object_size(length);1127Klass* ak = array_klass(n, CHECK_NULL);1128KlassHandle h_ak (THREAD, ak);1129objArrayOop o =1130(objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);1131return o;1132}11331134instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {1135if (TraceFinalizerRegistration) {1136tty->print("Registered ");1137i->print_value_on(tty);1138tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);1139}1140instanceHandle h_i(THREAD, i);1141// Pass the handle as argument, JavaCalls::call expects oop as jobjects1142JavaValue result(T_VOID);1143JavaCallArguments args(h_i);1144methodHandle mh (THREAD, Universe::finalizer_register_method());1145JavaCalls::call(&result, mh, &args, CHECK_NULL);1146return h_i();1147}11481149instanceOop InstanceKlass::allocate_instance(TRAPS) {1150bool has_finalizer_flag = has_finalizer(); // Query before possible GC1151int size = size_helper(); // Query before forming handle.11521153KlassHandle h_k(THREAD, this);11541155instanceOop i;11561157i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);1158if (has_finalizer_flag && !RegisterFinalizersAtInit) {1159i = register_finalizer(i, CHECK_NULL);1160}1161return i;1162}11631164void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {1165if (is_interface() || is_abstract()) {1166ResourceMark rm(THREAD);1167THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()1168: vmSymbols::java_lang_InstantiationException(), external_name());1169}1170if (this == SystemDictionary::Class_klass()) {1171ResourceMark rm(THREAD);1172THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()1173: vmSymbols::java_lang_IllegalAccessException(), external_name());1174}1175}11761177Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {1178instanceKlassHandle this_oop(THREAD, this);1179return array_klass_impl(this_oop, or_null, n, THREAD);1180}11811182Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {1183if (this_oop->array_klasses() == NULL) {1184if (or_null) return NULL;11851186ResourceMark rm;1187JavaThread *jt = (JavaThread *)THREAD;1188{1189// Atomic creation of array_klasses1190MutexLocker mc(Compile_lock, THREAD); // for vtables1191MutexLocker ma(MultiArray_lock, THREAD);11921193// Check if update has already taken place1194if (this_oop->array_klasses() == NULL) {1195Klass* k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);1196this_oop->set_array_klasses(k);1197}1198}1199}1200// _this will always be set at this point1201ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();1202if (or_null) {1203return oak->array_klass_or_null(n);1204}1205return oak->array_klass(n, THREAD);1206}12071208Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {1209return array_klass_impl(or_null, 1, THREAD);1210}12111212void InstanceKlass::call_class_initializer(TRAPS) {1213instanceKlassHandle ik (THREAD, this);1214call_class_initializer_impl(ik, THREAD);1215}12161217static int call_class_initializer_impl_counter = 0; // for debugging12181219Method* InstanceKlass::class_initializer() {1220Method* clinit = find_method(1221vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());1222if (clinit != NULL && clinit->has_valid_initializer_flags()) {1223return clinit;1224}1225return NULL;1226}12271228void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {1229if (ReplayCompiles &&1230(ReplaySuppressInitializers == 1 ||1231ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {1232// Hide the existence of the initializer for the purpose of replaying the compile1233return;1234}12351236methodHandle h_method(THREAD, this_oop->class_initializer());1237assert(!this_oop->is_initialized(), "we cannot initialize twice");1238if (TraceClassInitialization) {1239tty->print("%d Initializing ", call_class_initializer_impl_counter++);1240this_oop->name()->print_value();1241tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());1242}1243if (h_method() != NULL) {1244JavaCallArguments args; // No arguments1245JavaValue result(T_VOID);1246JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)1247}1248}124912501251void InstanceKlass::mask_for(methodHandle method, int bci,1252InterpreterOopMap* entry_for) {1253// Dirty read, then double-check under a lock.1254if (_oop_map_cache == NULL) {1255// Otherwise, allocate a new one.1256MutexLocker x(OopMapCacheAlloc_lock);1257// First time use. Allocate a cache in C heap1258if (_oop_map_cache == NULL) {1259// Release stores from OopMapCache constructor before assignment1260// to _oop_map_cache. C++ compilers on ppc do not emit the1261// required memory barrier only because of the volatile1262// qualifier of _oop_map_cache.1263OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());1264}1265}1266// _oop_map_cache is constant after init; lookup below does is own locking.1267_oop_map_cache->lookup(method, bci, entry_for);1268}126912701271bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1272for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1273Symbol* f_name = fs.name();1274Symbol* f_sig = fs.signature();1275if (f_name == name && f_sig == sig) {1276fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1277return true;1278}1279}1280return false;1281}128212831284Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1285const int n = local_interfaces()->length();1286for (int i = 0; i < n; i++) {1287Klass* intf1 = local_interfaces()->at(i);1288assert(intf1->is_interface(), "just checking type");1289// search for field in current interface1290if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {1291assert(fd->is_static(), "interface field must be static");1292return intf1;1293}1294// search for field in direct superinterfaces1295Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);1296if (intf2 != NULL) return intf2;1297}1298// otherwise field lookup fails1299return NULL;1300}130113021303Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1304// search order according to newest JVM spec (5.4.3.2, p.167).1305// 1) search for field in current klass1306if (find_local_field(name, sig, fd)) {1307return const_cast<InstanceKlass*>(this);1308}1309// 2) search for field recursively in direct superinterfaces1310{ Klass* intf = find_interface_field(name, sig, fd);1311if (intf != NULL) return intf;1312}1313// 3) apply field lookup recursively if superclass exists1314{ Klass* supr = super();1315if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);1316}1317// 4) otherwise field lookup fails1318return NULL;1319}132013211322Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {1323// search order according to newest JVM spec (5.4.3.2, p.167).1324// 1) search for field in current klass1325if (find_local_field(name, sig, fd)) {1326if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);1327}1328// 2) search for field recursively in direct superinterfaces1329if (is_static) {1330Klass* intf = find_interface_field(name, sig, fd);1331if (intf != NULL) return intf;1332}1333// 3) apply field lookup recursively if superclass exists1334{ Klass* supr = super();1335if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);1336}1337// 4) otherwise field lookup fails1338return NULL;1339}134013411342bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1343for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1344if (fs.offset() == offset) {1345fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1346if (fd->is_static() == is_static) return true;1347}1348}1349return false;1350}135113521353bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1354Klass* klass = const_cast<InstanceKlass*>(this);1355while (klass != NULL) {1356if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {1357return true;1358}1359klass = klass->super();1360}1361return false;1362}136313641365void InstanceKlass::methods_do(void f(Method* method)) {1366int len = methods()->length();1367for (int index = 0; index < len; index++) {1368Method* m = methods()->at(index);1369assert(m->is_method(), "must be method");1370f(m);1371}1372}137313741375void InstanceKlass::do_local_static_fields(FieldClosure* cl) {1376for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1377if (fs.access_flags().is_static()) {1378fieldDescriptor& fd = fs.field_descriptor();1379cl->do_field(&fd);1380}1381}1382}138313841385void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {1386instanceKlassHandle h_this(THREAD, this);1387do_local_static_fields_impl(h_this, f, mirror, CHECK);1388}138913901391void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,1392void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {1393for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {1394if (fs.access_flags().is_static()) {1395fieldDescriptor& fd = fs.field_descriptor();1396f(&fd, mirror, CHECK);1397}1398}1399}140014011402static int compare_fields_by_offset(int* a, int* b) {1403return a[0] - b[0];1404}14051406void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {1407InstanceKlass* super = superklass();1408if (super != NULL) {1409super->do_nonstatic_fields(cl);1410}1411fieldDescriptor fd;1412int length = java_fields_count();1413// In DebugInfo nonstatic fields are sorted by offset.1414int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);1415int j = 0;1416for (int i = 0; i < length; i += 1) {1417fd.reinitialize(this, i);1418if (!fd.is_static()) {1419fields_sorted[j + 0] = fd.offset();1420fields_sorted[j + 1] = i;1421j += 2;1422}1423}1424if (j > 0) {1425length = j;1426// _sort_Fn is defined in growableArray.hpp.1427qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);1428for (int i = 0; i < length; i += 2) {1429fd.reinitialize(this, fields_sorted[i + 1]);1430assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");1431cl->do_field(&fd);1432}1433}1434FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);1435}143614371438void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {1439if (array_klasses() != NULL)1440ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);1441}14421443void InstanceKlass::array_klasses_do(void f(Klass* k)) {1444if (array_klasses() != NULL)1445ArrayKlass::cast(array_klasses())->array_klasses_do(f);1446}14471448#ifdef ASSERT1449static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {1450int len = methods->length();1451for (int index = 0; index < len; index++) {1452Method* m = methods->at(index);1453assert(m->is_method(), "must be method");1454if (m->signature() == signature && m->name() == name) {1455return index;1456}1457}1458return -1;1459}1460#endif14611462static int binary_search(Array<Method*>* methods, Symbol* name) {1463int len = methods->length();1464// methods are sorted, so do binary search1465int l = 0;1466int h = len - 1;1467while (l <= h) {1468int mid = (l + h) >> 1;1469Method* m = methods->at(mid);1470assert(m->is_method(), "must be method");1471int res = m->name()->fast_compare(name);1472if (res == 0) {1473return mid;1474} else if (res < 0) {1475l = mid + 1;1476} else {1477h = mid - 1;1478}1479}1480return -1;1481}14821483// find_method looks up the name/signature in the local methods array1484Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {1485return find_method_impl(name, signature, find_overpass, find_static, find_private);1486}14871488Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature,1489OverpassLookupMode overpass_mode,1490StaticLookupMode static_mode,1491PrivateLookupMode private_mode) const {1492return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);1493}14941495// find_instance_method looks up the name/signature in the local methods array1496// and skips over static methods1497Method* InstanceKlass::find_instance_method(Array<Method*>* methods,1498Symbol* name,1499Symbol* signature,1500PrivateLookupMode private_mode) {1501Method* meth = InstanceKlass::find_method_impl(methods, name, signature,1502find_overpass, skip_static, private_mode);1503assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");1504return meth;1505}15061507// find_instance_method looks up the name/signature in the local methods array1508// and skips over static methods1509Method* InstanceKlass::find_instance_method(Symbol* name,1510Symbol* signature,1511PrivateLookupMode private_mode) {1512return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);1513}15141515// Find looks up the name/signature in the local methods array1516// and filters on the overpass, static and private flags1517// This returns the first one found1518// note that the local methods array can have up to one overpass, one static1519// and one instance (private or not) with the same name/signature1520Method* InstanceKlass::find_local_method(Symbol* name, Symbol* signature,1521OverpassLookupMode overpass_mode,1522StaticLookupMode static_mode,1523PrivateLookupMode private_mode) const {1524return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);1525}15261527// Find looks up the name/signature in the local methods array1528// and filters on the overpass, static and private flags1529// This returns the first one found1530// note that the local methods array can have up to one overpass, one static1531// and one instance (private or not) with the same name/signature1532Method* InstanceKlass::find_local_method(Array<Method*>* methods,1533Symbol* name, Symbol* signature,1534OverpassLookupMode overpass_mode,1535StaticLookupMode static_mode,1536PrivateLookupMode private_mode) {1537return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode);1538}153915401541// find_method looks up the name/signature in the local methods array1542Method* InstanceKlass::find_method(1543Array<Method*>* methods, Symbol* name, Symbol* signature) {1544return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private);1545}15461547Method* InstanceKlass::find_method_impl(1548Array<Method*>* methods, Symbol* name, Symbol* signature,1549OverpassLookupMode overpass_mode, StaticLookupMode static_mode,1550PrivateLookupMode private_mode) {1551int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);1552return hit >= 0 ? methods->at(hit): NULL;1553}15541555bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) {1556return ((m->signature() == signature) &&1557(!skipping_overpass || !m->is_overpass()) &&1558(!skipping_static || !m->is_static()) &&1559(!skipping_private || !m->is_private()));1560}15611562// Used directly for default_methods to find the index into the1563// default_vtable_indices, and indirectly by find_method1564// find_method_index looks in the local methods array to return the index1565// of the matching name/signature. If, overpass methods are being ignored,1566// the search continues to find a potential non-overpass match. This capability1567// is important during method resolution to prefer a static method, for example,1568// over an overpass method.1569// There is the possibility in any _method's array to have the same name/signature1570// for a static method, an overpass method and a local instance method1571// To correctly catch a given method, the search criteria may need1572// to explicitly skip the other two. For local instance methods, it1573// is often necessary to skip private methods1574int InstanceKlass::find_method_index(1575Array<Method*>* methods, Symbol* name, Symbol* signature,1576OverpassLookupMode overpass_mode, StaticLookupMode static_mode,1577PrivateLookupMode private_mode) {1578bool skipping_overpass = (overpass_mode == skip_overpass);1579bool skipping_static = (static_mode == skip_static);1580bool skipping_private = (private_mode == skip_private);1581int hit = binary_search(methods, name);1582if (hit != -1) {1583Method* m = methods->at(hit);15841585// Do linear search to find matching signature. First, quick check1586// for common case, ignoring overpasses if requested.1587if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit;15881589// search downwards through overloaded methods1590int i;1591for (i = hit - 1; i >= 0; --i) {1592Method* m = methods->at(i);1593assert(m->is_method(), "must be method");1594if (m->name() != name) break;1595if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;1596}1597// search upwards1598for (i = hit + 1; i < methods->length(); ++i) {1599Method* m = methods->at(i);1600assert(m->is_method(), "must be method");1601if (m->name() != name) break;1602if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;1603}1604// not found1605#ifdef ASSERT1606int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature);1607assert(index == -1, err_msg("binary search should have found entry %d", index));1608#endif1609}1610return -1;1611}1612int InstanceKlass::find_method_by_name(Symbol* name, int* end) {1613return find_method_by_name(methods(), name, end);1614}16151616int InstanceKlass::find_method_by_name(1617Array<Method*>* methods, Symbol* name, int* end_ptr) {1618assert(end_ptr != NULL, "just checking");1619int start = binary_search(methods, name);1620int end = start + 1;1621if (start != -1) {1622while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;1623while (end < methods->length() && (methods->at(end))->name() == name) ++end;1624*end_ptr = end;1625return start;1626}1627return -1;1628}16291630// uncached_lookup_method searches both the local class methods array and all1631// superclasses methods arrays, skipping any overpass methods in superclasses.1632Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {1633OverpassLookupMode overpass_local_mode = overpass_mode;1634Klass* klass = const_cast<InstanceKlass*>(this);1635while (klass != NULL) {1636Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private);1637if (method != NULL) {1638return method;1639}1640klass = InstanceKlass::cast(klass)->super();1641overpass_local_mode = skip_overpass; // Always ignore overpass methods in superclasses1642}1643return NULL;1644}16451646#ifdef ASSERT1647// search through class hierarchy and return true if this class or1648// one of the superclasses was redefined1649bool InstanceKlass::has_redefined_this_or_super() const {1650const InstanceKlass* klass = this;1651while (klass != NULL) {1652if (klass->has_been_redefined()) {1653return true;1654}1655klass = InstanceKlass::cast(klass->super());1656}1657return false;1658}1659#endif16601661// lookup a method in the default methods list then in all transitive interfaces1662// Do NOT return private or static methods1663Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,1664Symbol* signature) const {1665Method* m = NULL;1666if (default_methods() != NULL) {1667m = find_method(default_methods(), name, signature);1668}1669// Look up interfaces1670if (m == NULL) {1671m = lookup_method_in_all_interfaces(name, signature, find_defaults);1672}1673return m;1674}16751676// lookup a method in all the interfaces that this class implements1677// Do NOT return private or static methods, new in JDK8 which are not externally visible1678// They should only be found in the initial InterfaceMethodRef1679Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,1680Symbol* signature,1681DefaultsLookupMode defaults_mode) const {1682Array<Klass*>* all_ifs = transitive_interfaces();1683int num_ifs = all_ifs->length();1684InstanceKlass *ik = NULL;1685for (int i = 0; i < num_ifs; i++) {1686ik = InstanceKlass::cast(all_ifs->at(i));1687Method* m = ik->lookup_method(name, signature);1688if (m != NULL && m->is_public() && !m->is_static() &&1689((defaults_mode != skip_defaults) || !m->is_default_method())) {1690return m;1691}1692}1693return NULL;1694}16951696/* jni_id_for_impl for jfieldIds only */1697JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {1698MutexLocker ml(JfieldIdCreation_lock);1699// Retry lookup after we got the lock1700JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);1701if (probe == NULL) {1702// Slow case, allocate new static field identifier1703probe = new JNIid(this_oop(), offset, this_oop->jni_ids());1704this_oop->set_jni_ids(probe);1705}1706return probe;1707}170817091710/* jni_id_for for jfieldIds only */1711JNIid* InstanceKlass::jni_id_for(int offset) {1712JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);1713if (probe == NULL) {1714probe = jni_id_for_impl(this, offset);1715}1716return probe;1717}17181719u2 InstanceKlass::enclosing_method_data(int offset) {1720Array<jushort>* inner_class_list = inner_classes();1721if (inner_class_list == NULL) {1722return 0;1723}1724int length = inner_class_list->length();1725if (length % inner_class_next_offset == 0) {1726return 0;1727} else {1728int index = length - enclosing_method_attribute_size;1729assert(offset < enclosing_method_attribute_size, "invalid offset");1730return inner_class_list->at(index + offset);1731}1732}17331734void InstanceKlass::set_enclosing_method_indices(u2 class_index,1735u2 method_index) {1736Array<jushort>* inner_class_list = inner_classes();1737assert (inner_class_list != NULL, "_inner_classes list is not set up");1738int length = inner_class_list->length();1739if (length % inner_class_next_offset == enclosing_method_attribute_size) {1740int index = length - enclosing_method_attribute_size;1741inner_class_list->at_put(1742index + enclosing_method_class_index_offset, class_index);1743inner_class_list->at_put(1744index + enclosing_method_method_index_offset, method_index);1745}1746}17471748// Lookup or create a jmethodID.1749// This code is called by the VMThread and JavaThreads so the1750// locking has to be done very carefully to avoid deadlocks1751// and/or other cache consistency problems.1752//1753jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {1754size_t idnum = (size_t)method_h->method_idnum();1755jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();1756size_t length = 0;1757jmethodID id = NULL;17581759// We use a double-check locking idiom here because this cache is1760// performance sensitive. In the normal system, this cache only1761// transitions from NULL to non-NULL which is safe because we use1762// release_set_methods_jmethod_ids() to advertise the new cache.1763// A partially constructed cache should never be seen by a racing1764// thread. We also use release_store_ptr() to save a new jmethodID1765// in the cache so a partially constructed jmethodID should never be1766// seen either. Cache reads of existing jmethodIDs proceed without a1767// lock, but cache writes of a new jmethodID requires uniqueness and1768// creation of the cache itself requires no leaks so a lock is1769// generally acquired in those two cases.1770//1771// If the RedefineClasses() API has been used, then this cache can1772// grow and we'll have transitions from non-NULL to bigger non-NULL.1773// Cache creation requires no leaks and we require safety between all1774// cache accesses and freeing of the old cache so a lock is generally1775// acquired when the RedefineClasses() API has been used.17761777if (jmeths != NULL) {1778// the cache already exists1779if (!ik_h->idnum_can_increment()) {1780// the cache can't grow so we can just get the current values1781get_jmethod_id_length_value(jmeths, idnum, &length, &id);1782} else {1783// cache can grow so we have to be more careful1784if (Threads::number_of_threads() == 0 ||1785SafepointSynchronize::is_at_safepoint()) {1786// we're single threaded or at a safepoint - no locking needed1787get_jmethod_id_length_value(jmeths, idnum, &length, &id);1788} else {1789MutexLocker ml(JmethodIdCreation_lock);1790get_jmethod_id_length_value(jmeths, idnum, &length, &id);1791}1792}1793}1794// implied else:1795// we need to allocate a cache so default length and id values are good17961797if (jmeths == NULL || // no cache yet1798length <= idnum || // cache is too short1799id == NULL) { // cache doesn't contain entry18001801// This function can be called by the VMThread so we have to do all1802// things that might block on a safepoint before grabbing the lock.1803// Otherwise, we can deadlock with the VMThread or have a cache1804// consistency issue. These vars keep track of what we might have1805// to free after the lock is dropped.1806jmethodID to_dealloc_id = NULL;1807jmethodID* to_dealloc_jmeths = NULL;18081809// may not allocate new_jmeths or use it if we allocate it1810jmethodID* new_jmeths = NULL;1811if (length <= idnum) {1812// allocate a new cache that might be used1813size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());1814new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);1815memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));1816// cache size is stored in element[0], other elements offset by one1817new_jmeths[0] = (jmethodID)size;1818}18191820// allocate a new jmethodID that might be used1821jmethodID new_id = NULL;1822if (method_h->is_old() && !method_h->is_obsolete()) {1823// The method passed in is old (but not obsolete), we need to use the current version1824Method* current_method = ik_h->method_with_idnum((int)idnum);1825assert(current_method != NULL, "old and but not obsolete, so should exist");1826new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);1827} else {1828// It is the current version of the method or an obsolete method,1829// use the version passed in1830new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());1831}18321833if (Threads::number_of_threads() == 0 ||1834SafepointSynchronize::is_at_safepoint()) {1835// we're single threaded or at a safepoint - no locking needed1836id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,1837&to_dealloc_id, &to_dealloc_jmeths);1838} else {1839MutexLocker ml(JmethodIdCreation_lock);1840id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,1841&to_dealloc_id, &to_dealloc_jmeths);1842}18431844// The lock has been dropped so we can free resources.1845// Free up either the old cache or the new cache if we allocated one.1846if (to_dealloc_jmeths != NULL) {1847FreeHeap(to_dealloc_jmeths);1848}1849// free up the new ID since it wasn't needed1850if (to_dealloc_id != NULL) {1851Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);1852}1853}1854return id;1855}185618571858// Common code to fetch the jmethodID from the cache or update the1859// cache with the new jmethodID. This function should never do anything1860// that causes the caller to go to a safepoint or we can deadlock with1861// the VMThread or have cache consistency issues.1862//1863jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(1864instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,1865jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,1866jmethodID** to_dealloc_jmeths_p) {1867assert(new_id != NULL, "sanity check");1868assert(to_dealloc_id_p != NULL, "sanity check");1869assert(to_dealloc_jmeths_p != NULL, "sanity check");1870assert(Threads::number_of_threads() == 0 ||1871SafepointSynchronize::is_at_safepoint() ||1872JmethodIdCreation_lock->owned_by_self(), "sanity check");18731874// reacquire the cache - we are locked, single threaded or at a safepoint1875jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();1876jmethodID id = NULL;1877size_t length = 0;18781879if (jmeths == NULL || // no cache yet1880(length = (size_t)jmeths[0]) <= idnum) { // cache is too short1881if (jmeths != NULL) {1882// copy any existing entries from the old cache1883for (size_t index = 0; index < length; index++) {1884new_jmeths[index+1] = jmeths[index+1];1885}1886*to_dealloc_jmeths_p = jmeths; // save old cache for later delete1887}1888ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);1889} else {1890// fetch jmethodID (if any) from the existing cache1891id = jmeths[idnum+1];1892*to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete1893}1894if (id == NULL) {1895// No matching jmethodID in the existing cache or we have a new1896// cache or we just grew the cache. This cache write is done here1897// by the first thread to win the foot race because a jmethodID1898// needs to be unique once it is generally available.1899id = new_id;19001901// The jmethodID cache can be read while unlocked so we have to1902// make sure the new jmethodID is complete before installing it1903// in the cache.1904OrderAccess::release_store_ptr(&jmeths[idnum+1], id);1905} else {1906*to_dealloc_id_p = new_id; // save new id for later delete1907}1908return id;1909}191019111912// Common code to get the jmethodID cache length and the jmethodID1913// value at index idnum if there is one.1914//1915void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,1916size_t idnum, size_t *length_p, jmethodID* id_p) {1917assert(cache != NULL, "sanity check");1918assert(length_p != NULL, "sanity check");1919assert(id_p != NULL, "sanity check");19201921// cache size is stored in element[0], other elements offset by one1922*length_p = (size_t)cache[0];1923if (*length_p <= idnum) { // cache is too short1924*id_p = NULL;1925} else {1926*id_p = cache[idnum+1]; // fetch jmethodID (if any)1927}1928}192919301931// Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles1932jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {1933size_t idnum = (size_t)method->method_idnum();1934jmethodID* jmeths = methods_jmethod_ids_acquire();1935size_t length; // length assigned as debugging crumb1936jmethodID id = NULL;1937if (jmeths != NULL && // If there is a cache1938(length = (size_t)jmeths[0]) > idnum) { // and if it is long enough,1939id = jmeths[idnum+1]; // Look up the id (may be NULL)1940}1941return id;1942}19431944int nmethodBucket::decrement() {1945return Atomic::add(-1, (volatile int *)&_count);1946}19471948//1949// Walk the list of dependent nmethods searching for nmethods which1950// are dependent on the changes that were passed in and mark them for1951// deoptimization. Returns the number of nmethods found.1952//1953int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {1954assert_locked_or_safepoint(CodeCache_lock);1955int found = 0;1956nmethodBucket* b = _dependencies;1957while (b != NULL) {1958nmethod* nm = b->get_nmethod();1959// since dependencies aren't removed until an nmethod becomes a zombie,1960// the dependency list may contain nmethods which aren't alive.1961if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {1962if (TraceDependencies) {1963ResourceMark rm;1964tty->print_cr("Marked for deoptimization");1965tty->print_cr(" context = %s", this->external_name());1966changes.print();1967nm->print();1968nm->print_dependencies();1969}1970nm->mark_for_deoptimization();1971found++;1972}1973b = b->next();1974}1975return found;1976}19771978void InstanceKlass::clean_dependent_nmethods() {1979assert_locked_or_safepoint(CodeCache_lock);19801981if (has_unloaded_dependent()) {1982nmethodBucket* b = _dependencies;1983nmethodBucket* last = NULL;1984while (b != NULL) {1985assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));19861987nmethodBucket* next = b->next();19881989if (b->count() == 0) {1990if (last == NULL) {1991_dependencies = next;1992} else {1993last->set_next(next);1994}1995delete b;1996// last stays the same.1997} else {1998last = b;1999}20002001b = next;2002}2003set_has_unloaded_dependent(false);2004}2005#ifdef ASSERT2006else {2007// Verification2008for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {2009assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));2010assert(b->count() != 0, "empty buckets need to be cleaned");2011}2012}2013#endif2014}20152016//2017// Add an nmethodBucket to the list of dependencies for this nmethod.2018// It's possible that an nmethod has multiple dependencies on this klass2019// so a count is kept for each bucket to guarantee that creation and2020// deletion of dependencies is consistent.2021//2022void InstanceKlass::add_dependent_nmethod(nmethod* nm) {2023assert_locked_or_safepoint(CodeCache_lock);2024nmethodBucket* b = _dependencies;2025nmethodBucket* last = NULL;2026while (b != NULL) {2027if (nm == b->get_nmethod()) {2028b->increment();2029return;2030}2031b = b->next();2032}2033_dependencies = new nmethodBucket(nm, _dependencies);2034}203520362037//2038// Decrement count of the nmethod in the dependency list and remove2039// the bucket competely when the count goes to 0. This method must2040// find a corresponding bucket otherwise there's a bug in the2041// recording of dependecies.2042//2043void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {2044assert_locked_or_safepoint(CodeCache_lock);2045nmethodBucket* b = _dependencies;2046nmethodBucket* last = NULL;2047while (b != NULL) {2048if (nm == b->get_nmethod()) {2049int val = b->decrement();2050guarantee(val >= 0, err_msg("Underflow: %d", val));2051if (val == 0) {2052if (delete_immediately) {2053if (last == NULL) {2054_dependencies = b->next();2055} else {2056last->set_next(b->next());2057}2058delete b;2059} else {2060// The deletion of this entry is deferred until a later, potentially parallel GC phase.2061set_has_unloaded_dependent(true);2062}2063}2064return;2065}2066last = b;2067b = b->next();2068}2069#ifdef ASSERT2070tty->print_cr("### %s can't find dependent nmethod:", this->external_name());2071nm->print();2072#endif // ASSERT2073ShouldNotReachHere();2074}207520762077#ifndef PRODUCT2078void InstanceKlass::print_dependent_nmethods(bool verbose) {2079nmethodBucket* b = _dependencies;2080int idx = 0;2081while (b != NULL) {2082nmethod* nm = b->get_nmethod();2083tty->print("[%d] count=%d { ", idx++, b->count());2084if (!verbose) {2085nm->print_on(tty, "nmethod");2086tty->print_cr(" } ");2087} else {2088nm->print();2089nm->print_dependencies();2090tty->print_cr("--- } ");2091}2092b = b->next();2093}2094}209520962097bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {2098nmethodBucket* b = _dependencies;2099while (b != NULL) {2100if (nm == b->get_nmethod()) {2101#ifdef ASSERT2102int count = b->count();2103assert(count >= 0, err_msg("count shouldn't be negative: %d", count));2104#endif2105return true;2106}2107b = b->next();2108}2109return false;2110}2111#endif //PRODUCT211221132114// Garbage collection21152116#ifdef ASSERT2117template <class T> void assert_is_in(T *p) {2118T heap_oop = oopDesc::load_heap_oop(p);2119if (!oopDesc::is_null(heap_oop)) {2120oop o = oopDesc::decode_heap_oop_not_null(heap_oop);2121assert(Universe::heap()->is_in(o), "should be in heap");2122}2123}2124template <class T> void assert_is_in_closed_subset(T *p) {2125T heap_oop = oopDesc::load_heap_oop(p);2126if (!oopDesc::is_null(heap_oop)) {2127oop o = oopDesc::decode_heap_oop_not_null(heap_oop);2128assert(Universe::heap()->is_in_closed_subset(o),2129err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));2130}2131}2132template <class T> void assert_is_in_reserved(T *p) {2133T heap_oop = oopDesc::load_heap_oop(p);2134if (!oopDesc::is_null(heap_oop)) {2135oop o = oopDesc::decode_heap_oop_not_null(heap_oop);2136assert(Universe::heap()->is_in_reserved(o), "should be in reserved");2137}2138}2139template <class T> void assert_nothing(T *p) {}21402141#else2142template <class T> void assert_is_in(T *p) {}2143template <class T> void assert_is_in_closed_subset(T *p) {}2144template <class T> void assert_is_in_reserved(T *p) {}2145template <class T> void assert_nothing(T *p) {}2146#endif // ASSERT21472148//2149// Macros that iterate over areas of oops which are specialized on type of2150// oop pointer either narrow or wide, depending on UseCompressedOops2151//2152// Parameters are:2153// T - type of oop to point to (either oop or narrowOop)2154// start_p - starting pointer for region to iterate over2155// count - number of oops or narrowOops to iterate over2156// do_oop - action to perform on each oop (it's arbitrary C code which2157// makes it more efficient to put in a macro rather than making2158// it a template function)2159// assert_fn - assert function which is template function because performance2160// doesn't matter when enabled.2161#define InstanceKlass_SPECIALIZED_OOP_ITERATE( \2162T, start_p, count, do_oop, \2163assert_fn) \2164{ \2165T* p = (T*)(start_p); \2166T* const end = p + (count); \2167while (p < end) { \2168(assert_fn)(p); \2169do_oop; \2170++p; \2171} \2172}21732174#define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \2175T, start_p, count, do_oop, \2176assert_fn) \2177{ \2178T* const start = (T*)(start_p); \2179T* p = start + (count); \2180while (start < p) { \2181--p; \2182(assert_fn)(p); \2183do_oop; \2184} \2185}21862187#define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \2188T, start_p, count, low, high, \2189do_oop, assert_fn) \2190{ \2191T* const l = (T*)(low); \2192T* const h = (T*)(high); \2193assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \2194mask_bits((intptr_t)h, sizeof(T)-1) == 0, \2195"bounded region must be properly aligned"); \2196T* p = (T*)(start_p); \2197T* end = p + (count); \2198if (p < l) p = l; \2199if (end > h) end = h; \2200while (p < end) { \2201(assert_fn)(p); \2202do_oop; \2203++p; \2204} \2205}220622072208// The following macros call specialized macros, passing either oop or2209// narrowOop as the specialization type. These test the UseCompressedOops2210// flag.2211#define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn) \2212{ \2213/* Compute oopmap block range. The common case \2214is nonstatic_oop_map_size == 1. */ \2215OopMapBlock* map = start_of_nonstatic_oop_maps(); \2216OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \2217if (UseCompressedOops) { \2218while (map < end_map) { \2219InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop, \2220obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \2221do_oop, assert_fn) \2222++map; \2223} \2224} else { \2225while (map < end_map) { \2226InstanceKlass_SPECIALIZED_OOP_ITERATE(oop, \2227obj->obj_field_addr<oop>(map->offset()), map->count(), \2228do_oop, assert_fn) \2229++map; \2230} \2231} \2232}22332234#define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn) \2235{ \2236OopMapBlock* const start_map = start_of_nonstatic_oop_maps(); \2237OopMapBlock* map = start_map + nonstatic_oop_map_count(); \2238if (UseCompressedOops) { \2239while (start_map < map) { \2240--map; \2241InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop, \2242obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \2243do_oop, assert_fn) \2244} \2245} else { \2246while (start_map < map) { \2247--map; \2248InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop, \2249obj->obj_field_addr<oop>(map->offset()), map->count(), \2250do_oop, assert_fn) \2251} \2252} \2253}22542255#define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop, \2256assert_fn) \2257{ \2258/* Compute oopmap block range. The common case is \2259nonstatic_oop_map_size == 1, so we accept the \2260usually non-existent extra overhead of examining \2261all the maps. */ \2262OopMapBlock* map = start_of_nonstatic_oop_maps(); \2263OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \2264if (UseCompressedOops) { \2265while (map < end_map) { \2266InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop, \2267obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \2268low, high, \2269do_oop, assert_fn) \2270++map; \2271} \2272} else { \2273while (map < end_map) { \2274InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop, \2275obj->obj_field_addr<oop>(map->offset()), map->count(), \2276low, high, \2277do_oop, assert_fn) \2278++map; \2279} \2280} \2281}22822283void InstanceKlass::oop_follow_contents(oop obj) {2284assert(obj != NULL, "can't follow the content of NULL object");2285MarkSweep::follow_klass(obj->klass());2286InstanceKlass_OOP_MAP_ITERATE( \2287obj, \2288MarkSweep::mark_and_push(p), \2289assert_is_in_closed_subset)2290}22912292#if INCLUDE_ALL_GCS2293void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,2294oop obj) {2295assert(obj != NULL, "can't follow the content of NULL object");2296PSParallelCompact::follow_klass(cm, obj->klass());2297// Only mark the header and let the scan of the meta-data mark2298// everything else.2299InstanceKlass_OOP_MAP_ITERATE( \2300obj, \2301PSParallelCompact::mark_and_push(cm, p), \2302assert_is_in)2303}2304#endif // INCLUDE_ALL_GCS23052306// closure's do_metadata() method dictates whether the given closure should be2307// applied to the klass ptr in the object header.23082309#define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix) \2310\2311int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \2312SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\2313/* header */ \2314if_do_metadata_checked(closure, nv_suffix) { \2315closure->do_klass##nv_suffix(obj->klass()); \2316} \2317InstanceKlass_OOP_MAP_ITERATE( \2318obj, \2319SpecializationStats:: \2320record_do_oop_call##nv_suffix(SpecializationStats::ik); \2321(closure)->do_oop##nv_suffix(p), \2322assert_is_in_closed_subset) \2323return size_helper(); \2324}23252326#if INCLUDE_ALL_GCS2327#define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \2328\2329int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj, \2330OopClosureType* closure) { \2331SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \2332\2333assert_should_ignore_metadata(closure, nv_suffix); \2334\2335/* instance variables */ \2336InstanceKlass_OOP_MAP_REVERSE_ITERATE( \2337obj, \2338SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\2339(closure)->do_oop##nv_suffix(p), \2340assert_is_in_closed_subset) \2341return size_helper(); \2342}2343#endif // INCLUDE_ALL_GCS23442345#define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \2346\2347int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj, \2348OopClosureType* closure, \2349MemRegion mr) { \2350SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\2351if_do_metadata_checked(closure, nv_suffix) { \2352if (mr.contains(obj)) { \2353closure->do_klass##nv_suffix(obj->klass()); \2354} \2355} \2356InstanceKlass_BOUNDED_OOP_MAP_ITERATE( \2357obj, mr.start(), mr.end(), \2358(closure)->do_oop##nv_suffix(p), \2359assert_is_in_closed_subset) \2360return size_helper(); \2361}23622363ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)2364ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)2365ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)2366ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)2367#if INCLUDE_ALL_GCS2368ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)2369ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)2370#endif // INCLUDE_ALL_GCS23712372int InstanceKlass::oop_adjust_pointers(oop obj) {2373int size = size_helper();2374InstanceKlass_OOP_MAP_ITERATE( \2375obj, \2376MarkSweep::adjust_pointer(p), \2377assert_is_in)2378return size;2379}23802381#if INCLUDE_ALL_GCS2382void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {2383InstanceKlass_OOP_MAP_REVERSE_ITERATE( \2384obj, \2385if (PSScavenge::should_scavenge(p)) { \2386pm->claim_or_forward_depth(p); \2387}, \2388assert_nothing )2389}23902391int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {2392int size = size_helper();2393InstanceKlass_OOP_MAP_ITERATE( \2394obj, \2395PSParallelCompact::adjust_pointer(p), \2396assert_is_in)2397return size;2398}23992400#endif // INCLUDE_ALL_GCS24012402void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {2403clean_implementors_list(is_alive);2404clean_method_data(is_alive);24052406clean_dependent_nmethods();2407}24082409void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {2410assert(class_loader_data()->is_alive(is_alive), "this klass should be live");2411if (is_interface()) {2412if (ClassUnloading) {2413Klass* impl = implementor();2414if (impl != NULL) {2415if (!impl->is_loader_alive(is_alive)) {2416// remove this guy2417Klass** klass = adr_implementor();2418assert(klass != NULL, "null klass");2419if (klass != NULL) {2420*klass = NULL;2421}2422}2423}2424}2425}2426}24272428void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {2429for (int m = 0; m < methods()->length(); m++) {2430MethodData* mdo = methods()->at(m)->method_data();2431if (mdo != NULL) {2432mdo->clean_method_data(is_alive);2433}2434}2435}243624372438static void remove_unshareable_in_class(Klass* k) {2439// remove klass's unshareable info2440k->remove_unshareable_info();2441}24422443void InstanceKlass::remove_unshareable_info() {2444Klass::remove_unshareable_info();2445// Unlink the class2446if (is_linked()) {2447unlink_class();2448}2449init_implementor();24502451constants()->remove_unshareable_info();24522453for (int i = 0; i < methods()->length(); i++) {2454Method* m = methods()->at(i);2455m->remove_unshareable_info();2456}24572458// do array classes also.2459array_klasses_do(remove_unshareable_in_class);2460}24612462static void restore_unshareable_in_class(Klass* k, TRAPS) {2463// Array classes have null protection domain.2464// --> see ArrayKlass::complete_create_array_klass()2465k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);2466}24672468void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {2469Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);2470instanceKlassHandle ik(THREAD, this);24712472Array<Method*>* methods = ik->methods();2473int num_methods = methods->length();2474for (int index2 = 0; index2 < num_methods; ++index2) {2475methodHandle m(THREAD, methods->at(index2));2476m->restore_unshareable_info(CHECK);2477}2478if (JvmtiExport::has_redefined_a_class()) {2479// Reinitialize vtable because RedefineClasses may have changed some2480// entries in this vtable for super classes so the CDS vtable might2481// point to old or obsolete entries. RedefineClasses doesn't fix up2482// vtables in the shared system dictionary, only the main one.2483// It also redefines the itable too so fix that too.2484ResourceMark rm(THREAD);2485ik->vtable()->initialize_vtable(false, CHECK);2486ik->itable()->initialize_itable(false, CHECK);2487}24882489// restore constant pool resolved references2490ik->constants()->restore_unshareable_info(CHECK);24912492ik->array_klasses_do(restore_unshareable_in_class, CHECK);2493}24942495// returns true IFF is_in_error_state() has been changed as a result of this call.2496bool InstanceKlass::check_sharing_error_state() {2497assert(DumpSharedSpaces, "should only be called during dumping");2498bool old_state = is_in_error_state();24992500if (!is_in_error_state()) {2501bool bad = false;2502for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {2503if (sup->is_in_error_state()) {2504bad = true;2505break;2506}2507}2508if (!bad) {2509Array<Klass*>* interfaces = transitive_interfaces();2510for (int i = 0; i < interfaces->length(); i++) {2511Klass* iface = interfaces->at(i);2512if (InstanceKlass::cast(iface)->is_in_error_state()) {2513bad = true;2514break;2515}2516}2517}25182519if (bad) {2520set_in_error_state();2521}2522}25232524return (old_state != is_in_error_state());2525}25262527static void clear_all_breakpoints(Method* m) {2528m->clear_all_breakpoints();2529}253025312532void InstanceKlass::notify_unload_class(InstanceKlass* ik) {2533// notify the debugger2534if (JvmtiExport::should_post_class_unload()) {2535JvmtiExport::post_class_unload(ik);2536}25372538// notify ClassLoadingService of class unload2539ClassLoadingService::notify_class_unloaded(ik);25402541#if INCLUDE_JFR2542assert(ik != NULL, "invariant");2543EventClassUnload event;2544event.set_unloadedClass(ik);2545event.set_definingClassLoader(ik->class_loader_data());2546event.commit();2547#endif2548}25492550void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {2551// Clean up C heap2552ik->release_C_heap_structures();2553ik->constants()->release_C_heap_structures();2554}25552556void InstanceKlass::release_C_heap_structures() {25572558// Can't release the constant pool here because the constant pool can be2559// deallocated separately from the InstanceKlass for default methods and2560// redefine classes.25612562// Deallocate oop map cache2563if (_oop_map_cache != NULL) {2564delete _oop_map_cache;2565_oop_map_cache = NULL;2566}25672568// Deallocate JNI identifiers for jfieldIDs2569JNIid::deallocate(jni_ids());2570set_jni_ids(NULL);25712572jmethodID* jmeths = methods_jmethod_ids_acquire();2573if (jmeths != (jmethodID*)NULL) {2574release_set_methods_jmethod_ids(NULL);2575FreeHeap(jmeths);2576}25772578// Deallocate MemberNameTable2579{2580Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;2581MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);2582MemberNameTable* mnt = member_names();2583if (mnt != NULL) {2584delete mnt;2585set_member_names(NULL);2586}2587}25882589// release dependencies2590nmethodBucket* b = _dependencies;2591_dependencies = NULL;2592while (b != NULL) {2593nmethodBucket* next = b->next();2594delete b;2595b = next;2596}25972598// Deallocate breakpoint records2599if (breakpoints() != 0x0) {2600methods_do(clear_all_breakpoints);2601assert(breakpoints() == 0x0, "should have cleared breakpoints");2602}26032604// deallocate the cached class file2605if (_cached_class_file != NULL) {2606os::free(_cached_class_file, mtClass);2607_cached_class_file = NULL;2608}26092610// Decrement symbol reference counts associated with the unloaded class.2611if (_name != NULL) _name->decrement_refcount();2612// unreference array name derived from this class name (arrays of an unloaded2613// class can't be referenced anymore).2614if (_array_name != NULL) _array_name->decrement_refcount();2615if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);26162617assert(_total_instanceKlass_count >= 1, "Sanity check");2618Atomic::dec(&_total_instanceKlass_count);2619}26202621void InstanceKlass::set_source_debug_extension(char* array, int length) {2622if (array == NULL) {2623_source_debug_extension = NULL;2624} else {2625// Adding one to the attribute length in order to store a null terminator2626// character could cause an overflow because the attribute length is2627// already coded with an u4 in the classfile, but in practice, it's2628// unlikely to happen.2629assert((length+1) > length, "Overflow checking");2630char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);2631for (int i = 0; i < length; i++) {2632sde[i] = array[i];2633}2634sde[length] = '\0';2635_source_debug_extension = sde;2636}2637}26382639address InstanceKlass::static_field_addr(int offset) {2640return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));2641}264226432644const char* InstanceKlass::signature_name() const {2645int hash_len = 0;2646char hash_buf[40];26472648// If this is an anonymous class, append a hash to make the name unique2649if (is_anonymous()) {2650assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");2651intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;2652sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);2653hash_len = (int)strlen(hash_buf);2654}26552656// Get the internal name as a c string2657const char* src = (const char*) (name()->as_C_string());2658const int src_length = (int)strlen(src);26592660char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);26612662// Add L as type indicator2663int dest_index = 0;2664dest[dest_index++] = 'L';26652666// Add the actual class name2667for (int src_index = 0; src_index < src_length; ) {2668dest[dest_index++] = src[src_index++];2669}26702671// If we have a hash, append it2672for (int hash_index = 0; hash_index < hash_len; ) {2673dest[dest_index++] = hash_buf[hash_index++];2674}26752676// Add the semicolon and the NULL2677dest[dest_index++] = ';';2678dest[dest_index] = '\0';2679return dest;2680}26812682// different verisons of is_same_class_package2683bool InstanceKlass::is_same_class_package(Klass* class2) {2684Klass* class1 = this;2685oop classloader1 = InstanceKlass::cast(class1)->class_loader();2686Symbol* classname1 = class1->name();26872688if (class2->oop_is_objArray()) {2689class2 = ObjArrayKlass::cast(class2)->bottom_klass();2690}2691oop classloader2;2692if (class2->oop_is_instance()) {2693classloader2 = InstanceKlass::cast(class2)->class_loader();2694} else {2695assert(class2->oop_is_typeArray(), "should be type array");2696classloader2 = NULL;2697}2698Symbol* classname2 = class2->name();26992700return InstanceKlass::is_same_class_package(classloader1, classname1,2701classloader2, classname2);2702}27032704bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {2705Klass* class1 = this;2706oop classloader1 = InstanceKlass::cast(class1)->class_loader();2707Symbol* classname1 = class1->name();27082709return InstanceKlass::is_same_class_package(classloader1, classname1,2710classloader2, classname2);2711}27122713// return true if two classes are in the same package, classloader2714// and classname information is enough to determine a class's package2715bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,2716oop class_loader2, Symbol* class_name2) {2717if (class_loader1 != class_loader2) {2718return false;2719} else if (class_name1 == class_name2) {2720return true; // skip painful bytewise comparison2721} else {2722ResourceMark rm;27232724// The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly2725// for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.2726// Otherwise, we just compare jbyte values between the strings.2727const jbyte *name1 = class_name1->base();2728const jbyte *name2 = class_name2->base();27292730const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');2731const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');27322733if ((last_slash1 == NULL) || (last_slash2 == NULL)) {2734// One of the two doesn't have a package. Only return true2735// if the other one also doesn't have a package.2736return last_slash1 == last_slash2;2737} else {2738// Skip over '['s2739if (*name1 == '[') {2740do {2741name1++;2742} while (*name1 == '[');2743if (*name1 != 'L') {2744// Something is terribly wrong. Shouldn't be here.2745return false;2746}2747}2748if (*name2 == '[') {2749do {2750name2++;2751} while (*name2 == '[');2752if (*name2 != 'L') {2753// Something is terribly wrong. Shouldn't be here.2754return false;2755}2756}27572758// Check that package part is identical2759int length1 = last_slash1 - name1;2760int length2 = last_slash2 - name2;27612762return UTF8::equal(name1, length1, name2, length2);2763}2764}2765}27662767// Returns true iff super_method can be overridden by a method in targetclassname2768// See JSL 3rd edition 8.4.6.12769// Assumes name-signature match2770// "this" is InstanceKlass of super_method which must exist2771// note that the InstanceKlass of the method in the targetclassname has not always been created yet2772bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {2773// Private methods can not be overridden2774if (super_method->is_private()) {2775return false;2776}2777// If super method is accessible, then override2778if ((super_method->is_protected()) ||2779(super_method->is_public())) {2780return true;2781}2782// Package-private methods are not inherited outside of package2783assert(super_method->is_package_private(), "must be package private");2784return(is_same_class_package(targetclassloader(), targetclassname));2785}27862787/* defined for now in jvm.cpp, for historical reasons *--2788Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,2789Symbol*& simple_name_result, TRAPS) {2790...2791}2792*/27932794// tell if two classes have the same enclosing class (at package level)2795bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,2796Klass* class2_oop, TRAPS) {2797if (class2_oop == class1()) return true;2798if (!class2_oop->oop_is_instance()) return false;2799instanceKlassHandle class2(THREAD, class2_oop);28002801// must be in same package before we try anything else2802if (!class1->is_same_class_package(class2->class_loader(), class2->name()))2803return false;28042805// As long as there is an outer1.getEnclosingClass,2806// shift the search outward.2807instanceKlassHandle outer1 = class1;2808for (;;) {2809// As we walk along, look for equalities between outer1 and class2.2810// Eventually, the walks will terminate as outer1 stops2811// at the top-level class around the original class.2812bool ignore_inner_is_member;2813Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,2814CHECK_false);2815if (next == NULL) break;2816if (next == class2()) return true;2817outer1 = instanceKlassHandle(THREAD, next);2818}28192820// Now do the same for class2.2821instanceKlassHandle outer2 = class2;2822for (;;) {2823bool ignore_inner_is_member;2824Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,2825CHECK_false);2826if (next == NULL) break;2827// Might as well check the new outer against all available values.2828if (next == class1()) return true;2829if (next == outer1()) return true;2830outer2 = instanceKlassHandle(THREAD, next);2831}28322833// If by this point we have not found an equality between the2834// two classes, we know they are in separate package members.2835return false;2836}283728382839jint InstanceKlass::compute_modifier_flags(TRAPS) const {2840jint access = access_flags().as_int();28412842// But check if it happens to be member class.2843instanceKlassHandle ik(THREAD, this);2844InnerClassesIterator iter(ik);2845for (; !iter.done(); iter.next()) {2846int ioff = iter.inner_class_info_index();2847// Inner class attribute can be zero, skip it.2848// Strange but true: JVM spec. allows null inner class refs.2849if (ioff == 0) continue;28502851// only look at classes that are already loaded2852// since we are looking for the flags for our self.2853Symbol* inner_name = ik->constants()->klass_name_at(ioff);2854if ((ik->name() == inner_name)) {2855// This is really a member class.2856access = iter.inner_access_flags();2857break;2858}2859}2860// Remember to strip ACC_SUPER bit2861return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;2862}28632864jint InstanceKlass::jvmti_class_status() const {2865jint result = 0;28662867if (is_linked()) {2868result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;2869}28702871if (is_initialized()) {2872assert(is_linked(), "Class status is not consistent");2873result |= JVMTI_CLASS_STATUS_INITIALIZED;2874}2875if (is_in_error_state()) {2876result |= JVMTI_CLASS_STATUS_ERROR;2877}2878return result;2879}28802881Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {2882itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();2883int method_table_offset_in_words = ioe->offset()/wordSize;2884int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())2885/ itableOffsetEntry::size();28862887for (int cnt = 0 ; ; cnt ++, ioe ++) {2888// If the interface isn't implemented by the receiver class,2889// the VM should throw IncompatibleClassChangeError.2890if (cnt >= nof_interfaces) {2891THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());2892}28932894Klass* ik = ioe->interface_klass();2895if (ik == holder) break;2896}28972898itableMethodEntry* ime = ioe->first_method_entry(this);2899Method* m = ime[index].method();2900if (m == NULL) {2901THROW_NULL(vmSymbols::java_lang_AbstractMethodError());2902}2903return m;2904}290529062907#if INCLUDE_JVMTI2908// update default_methods for redefineclasses for methods that are2909// not yet in the vtable due to concurrent subclass define and superinterface2910// redefinition2911// Note: those in the vtable, should have been updated via adjust_method_entries2912void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {2913// search the default_methods for uses of either obsolete or EMCP methods2914if (default_methods() != NULL) {2915for (int index = 0; index < default_methods()->length(); index ++) {2916Method* old_method = default_methods()->at(index);2917if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {2918continue; // skip uninteresting entries2919}2920assert(!old_method->is_deleted(), "default methods may not be deleted");29212922Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());29232924assert(new_method != NULL, "method_with_idnum() should not be NULL");2925assert(old_method != new_method, "sanity check");29262927default_methods()->at_put(index, new_method);2928if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {2929if (!(*trace_name_printed)) {2930// RC_TRACE_MESG macro has an embedded ResourceMark2931RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",2932external_name(),2933old_method->method_holder()->external_name()));2934*trace_name_printed = true;2935}2936RC_TRACE(0x00100000, ("default method update: %s(%s) ",2937new_method->name()->as_C_string(),2938new_method->signature()->as_C_string()));2939}2940}2941}2942}2943#endif // INCLUDE_JVMTI29442945// On-stack replacement stuff2946void InstanceKlass::add_osr_nmethod(nmethod* n) {2947#ifndef PRODUCT2948if (TieredCompilation) {2949nmethod * prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);2950assert(prev == NULL || !prev->is_in_use(),2951"redundunt OSR recompilation detected. memory leak in CodeCache!");2952}2953#endif2954// only one compilation can be active2955NEEDS_CLEANUP2956// This is a short non-blocking critical region, so the no safepoint check is ok.2957OsrList_lock->lock_without_safepoint_check();2958assert(n->is_osr_method(), "wrong kind of nmethod");2959n->set_osr_link(osr_nmethods_head());2960set_osr_nmethods_head(n);2961// Raise the highest osr level if necessary2962if (TieredCompilation) {2963Method* m = n->method();2964m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));2965}2966// Remember to unlock again2967OsrList_lock->unlock();29682969// Get rid of the osr methods for the same bci that have lower levels.2970if (TieredCompilation) {2971for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {2972nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);2973if (inv != NULL && inv->is_in_use()) {2974inv->make_not_entrant();2975}2976}2977}2978}297929802981void InstanceKlass::remove_osr_nmethod(nmethod* n) {2982// This is a short non-blocking critical region, so the no safepoint check is ok.2983OsrList_lock->lock_without_safepoint_check();2984assert(n->is_osr_method(), "wrong kind of nmethod");2985nmethod* last = NULL;2986nmethod* cur = osr_nmethods_head();2987int max_level = CompLevel_none; // Find the max comp level excluding n2988Method* m = n->method();2989// Search for match2990while(cur != NULL && cur != n) {2991if (TieredCompilation && m == cur->method()) {2992// Find max level before n2993max_level = MAX2(max_level, cur->comp_level());2994}2995last = cur;2996cur = cur->osr_link();2997}2998nmethod* next = NULL;2999if (cur == n) {3000next = cur->osr_link();3001if (last == NULL) {3002// Remove first element3003set_osr_nmethods_head(next);3004} else {3005last->set_osr_link(next);3006}3007}3008n->set_osr_link(NULL);3009if (TieredCompilation) {3010cur = next;3011while (cur != NULL) {3012// Find max level after n3013if (m == cur->method()) {3014max_level = MAX2(max_level, cur->comp_level());3015}3016cur = cur->osr_link();3017}3018m->set_highest_osr_comp_level(max_level);3019}3020// Remember to unlock again3021OsrList_lock->unlock();3022}30233024int InstanceKlass::mark_osr_nmethods(const Method* m) {3025// This is a short non-blocking critical region, so the no safepoint check is ok.3026MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);3027nmethod* osr = osr_nmethods_head();3028int found = 0;3029while (osr != NULL) {3030assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3031if (osr->method() == m) {3032osr->mark_for_deoptimization();3033found++;3034}3035osr = osr->osr_link();3036}3037return found;3038}30393040nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {3041// This is a short non-blocking critical region, so the no safepoint check is ok.3042OsrList_lock->lock_without_safepoint_check();3043nmethod* osr = osr_nmethods_head();3044nmethod* best = NULL;3045while (osr != NULL) {3046assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3047// There can be a time when a c1 osr method exists but we are waiting3048// for a c2 version. When c2 completes its osr nmethod we will trash3049// the c1 version and only be able to find the c2 version. However3050// while we overflow in the c1 code at back branches we don't want to3051// try and switch to the same code as we are already running30523053if (osr->method() == m &&3054(bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {3055if (match_level) {3056if (osr->comp_level() == comp_level) {3057// Found a match - return it.3058OsrList_lock->unlock();3059return osr;3060}3061} else {3062if (best == NULL || (osr->comp_level() > best->comp_level())) {3063if (osr->comp_level() == CompLevel_highest_tier) {3064// Found the best possible - return it.3065OsrList_lock->unlock();3066return osr;3067}3068best = osr;3069}3070}3071}3072osr = osr->osr_link();3073}3074OsrList_lock->unlock();30753076assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");3077if (best != NULL && best->comp_level() >= comp_level) {3078return best;3079}3080return NULL;3081}30823083oop InstanceKlass::add_member_name(Handle mem_name, bool intern) {3084jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);3085MutexLocker ml(MemberNameTable_lock);3086DEBUG_ONLY(No_Safepoint_Verifier nsv);30873088// Check if method has been redefined while taking out MemberNameTable_lock, if so3089// return false. We cannot cache obsolete methods. They will crash when the function3090// is called!3091Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());3092if (method->is_obsolete()) {3093return NULL;3094} else if (method->is_old()) {3095// Replace method with redefined version3096java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));3097}30983099if (_member_names == NULL) {3100_member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());3101}3102if (intern) {3103return _member_names->find_or_add_member_name(mem_name_wref);3104} else {3105return _member_names->add_member_name(mem_name_wref);3106}3107}31083109// -----------------------------------------------------------------------------------------------------3110// Printing31113112#ifndef PRODUCT31133114#define BULLET " - "31153116static const char* state_names[] = {3117"allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"3118};31193120static void print_vtable(intptr_t* start, int len, outputStream* st) {3121for (int i = 0; i < len; i++) {3122intptr_t e = start[i];3123st->print("%d : " INTPTR_FORMAT, i, e);3124if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {3125st->print(" ");3126((Metadata*)e)->print_value_on(st);3127}3128st->cr();3129}3130}31313132void InstanceKlass::print_on(outputStream* st) const {3133assert(is_klass(), "must be klass");3134Klass::print_on(st);31353136st->print(BULLET"instance size: %d", size_helper()); st->cr();3137st->print(BULLET"klass size: %d", size()); st->cr();3138st->print(BULLET"access: "); access_flags().print_on(st); st->cr();3139st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]);3140st->print(BULLET"name: "); name()->print_value_on(st); st->cr();3141st->print(BULLET"super: "); super()->print_value_on_maybe_null(st); st->cr();3142st->print(BULLET"sub: ");3143Klass* sub = subklass();3144int n;3145for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {3146if (n < MaxSubklassPrintSize) {3147sub->print_value_on(st);3148st->print(" ");3149}3150}3151if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);3152st->cr();31533154if (is_interface()) {3155st->print_cr(BULLET"nof implementors: %d", nof_implementors());3156if (nof_implementors() == 1) {3157st->print_cr(BULLET"implementor: ");3158st->print(" ");3159implementor()->print_value_on(st);3160st->cr();3161}3162}31633164st->print(BULLET"arrays: "); array_klasses()->print_value_on_maybe_null(st); st->cr();3165st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();3166if (Verbose || WizardMode) {3167Array<Method*>* method_array = methods();3168for (int i = 0; i < method_array->length(); i++) {3169st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3170}3171}3172st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();3173st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();3174if (Verbose && default_methods() != NULL) {3175Array<Method*>* method_array = default_methods();3176for (int i = 0; i < method_array->length(); i++) {3177st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3178}3179}3180if (default_vtable_indices() != NULL) {3181st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr();3182}3183st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();3184st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();3185st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();3186if (class_loader_data() != NULL) {3187st->print(BULLET"class loader data: ");3188class_loader_data()->print_value_on(st);3189st->cr();3190}3191st->print(BULLET"host class: "); host_klass()->print_value_on_maybe_null(st); st->cr();3192if (source_file_name() != NULL) {3193st->print(BULLET"source file: ");3194source_file_name()->print_value_on(st);3195st->cr();3196}3197if (source_debug_extension() != NULL) {3198st->print(BULLET"source debug extension: ");3199st->print("%s", source_debug_extension());3200st->cr();3201}3202st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr();3203st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr();3204st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr();3205st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr();3206{3207bool have_pv = false;3208// previous versions are linked together through the InstanceKlass3209for (InstanceKlass* pv_node = _previous_versions;3210pv_node != NULL;3211pv_node = pv_node->previous_versions()) {3212if (!have_pv)3213st->print(BULLET"previous version: ");3214have_pv = true;3215pv_node->constants()->print_value_on(st);3216}3217if (have_pv) st->cr();3218}32193220if (generic_signature() != NULL) {3221st->print(BULLET"generic signature: ");3222generic_signature()->print_value_on(st);3223st->cr();3224}3225st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();3226st->print(BULLET"java mirror: "); java_mirror()->print_value_on(st); st->cr();3227st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable()); st->cr();3228if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);3229st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();3230if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);3231st->print_cr(BULLET"---- static fields (%d words):", static_field_size());3232FieldPrinter print_static_field(st);3233((InstanceKlass*)this)->do_local_static_fields(&print_static_field);3234st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());3235FieldPrinter print_nonstatic_field(st);3236((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);32373238st->print(BULLET"non-static oop maps: ");3239OopMapBlock* map = start_of_nonstatic_oop_maps();3240OopMapBlock* end_map = map + nonstatic_oop_map_count();3241while (map < end_map) {3242st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));3243map++;3244}3245st->cr();3246}32473248#endif //PRODUCT32493250void InstanceKlass::print_value_on(outputStream* st) const {3251assert(is_klass(), "must be klass");3252if (Verbose || WizardMode) access_flags().print_on(st);3253name()->print_value_on(st);3254}32553256#ifndef PRODUCT32573258void FieldPrinter::do_field(fieldDescriptor* fd) {3259_st->print(BULLET);3260if (_obj == NULL) {3261fd->print_on(_st);3262_st->cr();3263} else {3264fd->print_on_for(_st, _obj);3265_st->cr();3266}3267}326832693270void InstanceKlass::oop_print_on(oop obj, outputStream* st) {3271Klass::oop_print_on(obj, st);32723273if (this == SystemDictionary::String_klass()) {3274typeArrayOop value = java_lang_String::value(obj);3275juint offset = java_lang_String::offset(obj);3276juint length = java_lang_String::length(obj);3277if (value != NULL &&3278value->is_typeArray() &&3279offset <= (juint) value->length() &&3280offset + length <= (juint) value->length()) {3281st->print(BULLET"string: ");3282java_lang_String::print(obj, st);3283st->cr();3284if (!WizardMode) return; // that is enough3285}3286}32873288st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));3289FieldPrinter print_field(st, obj);3290do_nonstatic_fields(&print_field);32913292if (this == SystemDictionary::Class_klass()) {3293st->print(BULLET"signature: ");3294java_lang_Class::print_signature(obj, st);3295st->cr();3296Klass* mirrored_klass = java_lang_Class::as_Klass(obj);3297st->print(BULLET"fake entry for mirror: ");3298mirrored_klass->print_value_on_maybe_null(st);3299st->cr();3300Klass* array_klass = java_lang_Class::array_klass(obj);3301st->print(BULLET"fake entry for array: ");3302array_klass->print_value_on_maybe_null(st);3303st->cr();3304st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));3305st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));3306Klass* real_klass = java_lang_Class::as_Klass(obj);3307if (real_klass != NULL && real_klass->oop_is_instance()) {3308InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);3309}3310} else if (this == SystemDictionary::MethodType_klass()) {3311st->print(BULLET"signature: ");3312java_lang_invoke_MethodType::print_signature(obj, st);3313st->cr();3314}3315}33163317#endif //PRODUCT33183319void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {3320st->print("a ");3321name()->print_value_on(st);3322obj->print_address_on(st);3323if (this == SystemDictionary::String_klass()3324&& java_lang_String::value(obj) != NULL) {3325ResourceMark rm;3326int len = java_lang_String::length(obj);3327int plen = (len < 24 ? len : 12);3328char* str = java_lang_String::as_utf8_string(obj, 0, plen);3329st->print(" = \"%s\"", str);3330if (len > plen)3331st->print("...[%d]", len);3332} else if (this == SystemDictionary::Class_klass()) {3333Klass* k = java_lang_Class::as_Klass(obj);3334st->print(" = ");3335if (k != NULL) {3336k->print_value_on(st);3337} else {3338const char* tname = type2name(java_lang_Class::primitive_type(obj));3339st->print("%s", tname ? tname : "type?");3340}3341} else if (this == SystemDictionary::MethodType_klass()) {3342st->print(" = ");3343java_lang_invoke_MethodType::print_signature(obj, st);3344} else if (java_lang_boxing_object::is_instance(obj)) {3345st->print(" = ");3346java_lang_boxing_object::print(obj, st);3347} else if (this == SystemDictionary::LambdaForm_klass()) {3348oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);3349if (vmentry != NULL) {3350st->print(" => ");3351vmentry->print_value_on(st);3352}3353} else if (this == SystemDictionary::MemberName_klass()) {3354Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);3355if (vmtarget != NULL) {3356st->print(" = ");3357vmtarget->print_value_on(st);3358} else {3359java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);3360st->print(".");3361java_lang_invoke_MemberName::name(obj)->print_value_on(st);3362}3363}3364}33653366const char* InstanceKlass::internal_name() const {3367return external_name();3368}33693370#if INCLUDE_SERVICES3371// Size Statistics3372void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {3373Klass::collect_statistics(sz);33743375sz->_inst_size = HeapWordSize * size_helper();3376sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());3377sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());3378sz->_nonstatic_oopmap_bytes = HeapWordSize *3379((is_interface() || is_anonymous()) ?3380align_object_offset(nonstatic_oop_map_size()) :3381nonstatic_oop_map_size());33823383int n = 0;3384n += (sz->_methods_array_bytes = sz->count_array(methods()));3385n += (sz->_method_ordering_bytes = sz->count_array(method_ordering()));3386n += (sz->_local_interfaces_bytes = sz->count_array(local_interfaces()));3387n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));3388n += (sz->_fields_bytes = sz->count_array(fields()));3389n += (sz->_inner_classes_bytes = sz->count_array(inner_classes()));3390sz->_ro_bytes += n;33913392const ConstantPool* cp = constants();3393if (cp) {3394cp->collect_statistics(sz);3395}33963397const Annotations* anno = annotations();3398if (anno) {3399anno->collect_statistics(sz);3400}34013402const Array<Method*>* methods_array = methods();3403if (methods()) {3404for (int i = 0; i < methods_array->length(); i++) {3405Method* method = methods_array->at(i);3406if (method) {3407sz->_method_count ++;3408method->collect_statistics(sz);3409}3410}3411}3412}3413#endif // INCLUDE_SERVICES34143415// Verification34163417class VerifyFieldClosure: public OopClosure {3418protected:3419template <class T> void do_oop_work(T* p) {3420oop obj = oopDesc::load_decode_heap_oop(p);3421if (!obj->is_oop_or_null()) {3422tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);3423Universe::print();3424guarantee(false, "boom");3425}3426}3427public:3428virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }3429virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }3430};34313432void InstanceKlass::verify_on(outputStream* st) {3433#ifndef PRODUCT3434// Avoid redundant verifies, this really should be in product.3435if (_verify_count == Universe::verify_count()) return;3436_verify_count = Universe::verify_count();3437#endif34383439// Verify Klass3440Klass::verify_on(st);34413442// Verify that klass is present in ClassLoaderData3443guarantee(class_loader_data()->contains_klass(this),3444"this class isn't found in class loader data");34453446// Verify vtables3447if (is_linked()) {3448ResourceMark rm;3449// $$$ This used to be done only for m/s collections. Doing it3450// always seemed a valid generalization. (DLD -- 6/00)3451vtable()->verify(st);3452}34533454// Verify first subklass3455if (subklass_oop() != NULL) {3456guarantee(subklass_oop()->is_klass(), "should be klass");3457}34583459// Verify siblings3460Klass* super = this->super();3461Klass* sib = next_sibling();3462if (sib != NULL) {3463if (sib == this) {3464fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));3465}34663467guarantee(sib->is_klass(), "should be klass");3468guarantee(sib->super() == super, "siblings should have same superklass");3469}34703471// Verify implementor fields3472Klass* im = implementor();3473if (im != NULL) {3474guarantee(is_interface(), "only interfaces should have implementor set");3475guarantee(im->is_klass(), "should be klass");3476guarantee(!im->is_interface() || im == this,3477"implementors cannot be interfaces");3478}34793480// Verify local interfaces3481if (local_interfaces()) {3482Array<Klass*>* local_interfaces = this->local_interfaces();3483for (int j = 0; j < local_interfaces->length(); j++) {3484Klass* e = local_interfaces->at(j);3485guarantee(e->is_klass() && e->is_interface(), "invalid local interface");3486}3487}34883489// Verify transitive interfaces3490if (transitive_interfaces() != NULL) {3491Array<Klass*>* transitive_interfaces = this->transitive_interfaces();3492for (int j = 0; j < transitive_interfaces->length(); j++) {3493Klass* e = transitive_interfaces->at(j);3494guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");3495}3496}34973498// Verify methods3499if (methods() != NULL) {3500Array<Method*>* methods = this->methods();3501for (int j = 0; j < methods->length(); j++) {3502guarantee(methods->at(j)->is_method(), "non-method in methods array");3503}3504for (int j = 0; j < methods->length() - 1; j++) {3505Method* m1 = methods->at(j);3506Method* m2 = methods->at(j + 1);3507guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3508}3509}35103511// Verify method ordering3512if (method_ordering() != NULL) {3513Array<int>* method_ordering = this->method_ordering();3514int length = method_ordering->length();3515if (JvmtiExport::can_maintain_original_method_order() ||3516((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {3517guarantee(length == methods()->length(), "invalid method ordering length");3518jlong sum = 0;3519for (int j = 0; j < length; j++) {3520int original_index = method_ordering->at(j);3521guarantee(original_index >= 0, "invalid method ordering index");3522guarantee(original_index < length, "invalid method ordering index");3523sum += original_index;3524}3525// Verify sum of indices 0,1,...,length-13526guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");3527} else {3528guarantee(length == 0, "invalid method ordering length");3529}3530}35313532// Verify default methods3533if (default_methods() != NULL) {3534Array<Method*>* methods = this->default_methods();3535for (int j = 0; j < methods->length(); j++) {3536guarantee(methods->at(j)->is_method(), "non-method in methods array");3537}3538for (int j = 0; j < methods->length() - 1; j++) {3539Method* m1 = methods->at(j);3540Method* m2 = methods->at(j + 1);3541guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3542}3543}35443545// Verify JNI static field identifiers3546if (jni_ids() != NULL) {3547jni_ids()->verify(this);3548}35493550// Verify other fields3551if (array_klasses() != NULL) {3552guarantee(array_klasses()->is_klass(), "should be klass");3553}3554if (constants() != NULL) {3555guarantee(constants()->is_constantPool(), "should be constant pool");3556}3557const Klass* host = host_klass();3558if (host != NULL) {3559guarantee(host->is_klass(), "should be klass");3560}3561}35623563void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {3564Klass::oop_verify_on(obj, st);3565VerifyFieldClosure blk;3566obj->oop_iterate_no_header(&blk);3567}356835693570// JNIid class for jfieldIDs only3571// Note to reviewers:3572// These JNI functions are just moved over to column 1 and not changed3573// in the compressed oops workspace.3574JNIid::JNIid(Klass* holder, int offset, JNIid* next) {3575_holder = holder;3576_offset = offset;3577_next = next;3578debug_only(_is_static_field_id = false;)3579}358035813582JNIid* JNIid::find(int offset) {3583JNIid* current = this;3584while (current != NULL) {3585if (current->offset() == offset) return current;3586current = current->next();3587}3588return NULL;3589}35903591void JNIid::deallocate(JNIid* current) {3592while (current != NULL) {3593JNIid* next = current->next();3594delete current;3595current = next;3596}3597}359835993600void JNIid::verify(Klass* holder) {3601int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();3602int end_field_offset;3603end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);36043605JNIid* current = this;3606while (current != NULL) {3607guarantee(current->holder() == holder, "Invalid klass in JNIid");3608#ifdef ASSERT3609int o = current->offset();3610if (current->is_static_field_id()) {3611guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");3612}3613#endif3614current = current->next();3615}3616}361736183619#ifdef ASSERT3620void InstanceKlass::set_init_state(ClassState state) {3621bool good_state = is_shared() ? (_init_state <= state)3622: (_init_state < state);3623assert(good_state || state == allocated, "illegal state transition");3624assert(_init_thread == NULL, "should be cleared before state change");3625_init_state = (u1)state;3626}3627#endif362836293630// RedefineClasses() support for previous versions:36313632// Purge previous versions3633void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {3634if (ik->previous_versions() != NULL) {3635// This klass has previous versions so see what we can cleanup3636// while it is safe to do so.36373638int deleted_count = 0; // leave debugging breadcrumbs3639int live_count = 0;3640ClassLoaderData* loader_data = ik->class_loader_data();3641assert(loader_data != NULL, "should never be null");36423643// RC_TRACE macro has an embedded ResourceMark3644RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));36453646// previous versions are linked together through the InstanceKlass3647InstanceKlass* pv_node = ik->previous_versions();3648InstanceKlass* last = ik;3649int version = 0;36503651// check the previous versions list3652for (; pv_node != NULL; ) {36533654ConstantPool* pvcp = pv_node->constants();3655assert(pvcp != NULL, "cp ref was unexpectedly cleared");365636573658if (!pvcp->on_stack()) {3659// If the constant pool isn't on stack, none of the methods3660// are executing. Unlink this previous_version.3661// The previous version InstanceKlass is on the ClassLoaderData deallocate list3662// so will be deallocated during the next phase of class unloading.3663pv_node = pv_node->previous_versions();3664last->link_previous_versions(pv_node);3665deleted_count++;3666version++;3667continue;3668} else {3669RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",3670pv_node));3671assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");3672guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");3673live_count++;3674}36753676// At least one method is live in this previous version so clean its MethodData.3677// Reset dead EMCP methods not to get breakpoints.3678// All methods are deallocated when all of the methods for this class are no3679// longer running.3680Array<Method*>* method_refs = pv_node->methods();3681if (method_refs != NULL) {3682RC_TRACE(0x00000200, ("purge: previous methods length=%d",3683method_refs->length()));3684for (int j = 0; j < method_refs->length(); j++) {3685Method* method = method_refs->at(j);36863687if (!method->on_stack()) {3688// no breakpoints for non-running methods3689if (method->is_running_emcp()) {3690method->set_running_emcp(false);3691}3692} else {3693assert (method->is_obsolete() || method->is_running_emcp(),3694"emcp method cannot run after emcp bit is cleared");3695// RC_TRACE macro has an embedded ResourceMark3696RC_TRACE(0x00000200,3697("purge: %s(%s): prev method @%d in version @%d is alive",3698method->name()->as_C_string(),3699method->signature()->as_C_string(), j, version));3700if (method->method_data() != NULL) {3701// Clean out any weak method links for running methods3702// (also should include not EMCP methods)3703method->method_data()->clean_weak_method_links();3704}3705}3706}3707}3708// next previous version3709last = pv_node;3710pv_node = pv_node->previous_versions();3711version++;3712}3713RC_TRACE(0x00000200,3714("purge: previous version stats: live=%d, deleted=%d", live_count,3715deleted_count));3716}37173718// Clean MethodData of this class's methods so they don't refer to3719// old methods that are no longer running.3720Array<Method*>* methods = ik->methods();3721int num_methods = methods->length();3722for (int index2 = 0; index2 < num_methods; ++index2) {3723if (methods->at(index2)->method_data() != NULL) {3724methods->at(index2)->method_data()->clean_weak_method_links();3725}3726}3727}37283729void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,3730int emcp_method_count) {3731int obsolete_method_count = old_methods->length() - emcp_method_count;37323733if (emcp_method_count != 0 && obsolete_method_count != 0 &&3734_previous_versions != NULL) {3735// We have a mix of obsolete and EMCP methods so we have to3736// clear out any matching EMCP method entries the hard way.3737int local_count = 0;3738for (int i = 0; i < old_methods->length(); i++) {3739Method* old_method = old_methods->at(i);3740if (old_method->is_obsolete()) {3741// only obsolete methods are interesting3742Symbol* m_name = old_method->name();3743Symbol* m_signature = old_method->signature();37443745// previous versions are linked together through the InstanceKlass3746int j = 0;3747for (InstanceKlass* prev_version = _previous_versions;3748prev_version != NULL;3749prev_version = prev_version->previous_versions(), j++) {37503751Array<Method*>* method_refs = prev_version->methods();3752for (int k = 0; k < method_refs->length(); k++) {3753Method* method = method_refs->at(k);37543755if (!method->is_obsolete() &&3756method->name() == m_name &&3757method->signature() == m_signature) {3758// The current RedefineClasses() call has made all EMCP3759// versions of this method obsolete so mark it as obsolete3760RC_TRACE(0x00000400,3761("add: %s(%s): flush obsolete method @%d in version @%d",3762m_name->as_C_string(), m_signature->as_C_string(), k, j));37633764method->set_is_obsolete();3765break;3766}3767}37683769// The previous loop may not find a matching EMCP method, but3770// that doesn't mean that we can optimize and not go any3771// further back in the PreviousVersion generations. The EMCP3772// method for this generation could have already been made obsolete,3773// but there still may be an older EMCP method that has not3774// been made obsolete.3775}37763777if (++local_count >= obsolete_method_count) {3778// no more obsolete methods so bail out now3779break;3780}3781}3782}3783}3784}37853786// Save the scratch_class as the previous version if any of the methods are running.3787// The previous_versions are used to set breakpoints in EMCP methods and they are3788// also used to clean MethodData links to redefined methods that are no longer running.3789void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,3790int emcp_method_count) {3791assert(Thread::current()->is_VM_thread(),3792"only VMThread can add previous versions");37933794// RC_TRACE macro has an embedded ResourceMark3795RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",3796scratch_class->external_name(), emcp_method_count));37973798// Clean out old previous versions3799purge_previous_versions(this);38003801// Mark newly obsolete methods in remaining previous versions. An EMCP method from3802// a previous redefinition may be made obsolete by this redefinition.3803Array<Method*>* old_methods = scratch_class->methods();3804mark_newly_obsolete_methods(old_methods, emcp_method_count);38053806// If the constant pool for this previous version of the class3807// is not marked as being on the stack, then none of the methods3808// in this previous version of the class are on the stack so3809// we don't need to add this as a previous version.3810ConstantPool* cp_ref = scratch_class->constants();3811if (!cp_ref->on_stack()) {3812RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));3813return;3814}38153816if (emcp_method_count != 0) {3817// At least one method is still running, check for EMCP methods3818for (int i = 0; i < old_methods->length(); i++) {3819Method* old_method = old_methods->at(i);3820if (!old_method->is_obsolete() && old_method->on_stack()) {3821// if EMCP method (not obsolete) is on the stack, mark as EMCP so that3822// we can add breakpoints for it.38233824// We set the method->on_stack bit during safepoints for class redefinition and3825// class unloading and use this bit to set the is_running_emcp bit.3826// After the safepoint, the on_stack bit is cleared and the running emcp3827// method may exit. If so, we would set a breakpoint in a method that3828// is never reached, but this won't be noticeable to the programmer.3829old_method->set_running_emcp(true);3830RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,3831old_method->name_and_sig_as_C_string(), old_method));3832} else if (!old_method->is_obsolete()) {3833RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,3834old_method->name_and_sig_as_C_string(), old_method));3835}3836}3837}38383839// Add previous version if any methods are still running.3840RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));3841assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");3842scratch_class->link_previous_versions(previous_versions());3843link_previous_versions(scratch_class());3844} // end add_previous_version()38453846Method* InstanceKlass::method_with_idnum(int idnum) {3847Method* m = NULL;3848if (idnum < methods()->length()) {3849m = methods()->at(idnum);3850}3851if (m == NULL || m->method_idnum() != idnum) {3852for (int index = 0; index < methods()->length(); ++index) {3853m = methods()->at(index);3854if (m->method_idnum() == idnum) {3855return m;3856}3857}3858// None found, return null for the caller to handle.3859return NULL;3860}3861return m;3862}386338643865Method* InstanceKlass::method_with_orig_idnum(int idnum) {3866if (idnum >= methods()->length()) {3867return NULL;3868}3869Method* m = methods()->at(idnum);3870if (m != NULL && m->orig_method_idnum() == idnum) {3871return m;3872}3873// Obsolete method idnum does not match the original idnum3874for (int index = 0; index < methods()->length(); ++index) {3875m = methods()->at(index);3876if (m->orig_method_idnum() == idnum) {3877return m;3878}3879}3880// None found, return null for the caller to handle.3881return NULL;3882}388338843885Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {3886InstanceKlass* holder = get_klass_version(version);3887if (holder == NULL) {3888return NULL; // The version of klass is gone, no method is found3889}3890Method* method = holder->method_with_orig_idnum(idnum);3891return method;3892}389338943895jint InstanceKlass::get_cached_class_file_len() {3896return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);3897}38983899unsigned char * InstanceKlass::get_cached_class_file_bytes() {3900return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);3901}390239033904