Path: blob/master/src/hotspot/share/oops/instanceKlass.cpp
64440 views
/*1* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "jvm.h"26#include "cds/archiveUtils.hpp"27#include "cds/classListWriter.hpp"28#include "cds/metaspaceShared.hpp"29#include "classfile/classFileParser.hpp"30#include "classfile/classFileStream.hpp"31#include "classfile/classLoader.hpp"32#include "classfile/classLoaderData.inline.hpp"33#include "classfile/javaClasses.hpp"34#include "classfile/moduleEntry.hpp"35#include "classfile/resolutionErrors.hpp"36#include "classfile/symbolTable.hpp"37#include "classfile/systemDictionary.hpp"38#include "classfile/systemDictionaryShared.hpp"39#include "classfile/verifier.hpp"40#include "classfile/vmClasses.hpp"41#include "classfile/vmSymbols.hpp"42#include "code/codeCache.hpp"43#include "code/dependencyContext.hpp"44#include "compiler/compilationPolicy.hpp"45#include "compiler/compileBroker.hpp"46#include "gc/shared/collectedHeap.inline.hpp"47#include "interpreter/oopMapCache.hpp"48#include "interpreter/rewriter.hpp"49#include "jvmtifiles/jvmti.h"50#include "logging/log.hpp"51#include "logging/logMessage.hpp"52#include "logging/logStream.hpp"53#include "memory/allocation.inline.hpp"54#include "memory/iterator.inline.hpp"55#include "memory/metadataFactory.hpp"56#include "memory/metaspaceClosure.hpp"57#include "memory/oopFactory.hpp"58#include "memory/resourceArea.hpp"59#include "memory/universe.hpp"60#include "oops/fieldStreams.inline.hpp"61#include "oops/constantPool.hpp"62#include "oops/instanceClassLoaderKlass.hpp"63#include "oops/instanceKlass.inline.hpp"64#include "oops/instanceMirrorKlass.hpp"65#include "oops/instanceOop.hpp"66#include "oops/klass.inline.hpp"67#include "oops/method.hpp"68#include "oops/oop.inline.hpp"69#include "oops/recordComponent.hpp"70#include "oops/symbol.hpp"71#include "prims/jvmtiExport.hpp"72#include "prims/jvmtiRedefineClasses.hpp"73#include "prims/jvmtiThreadState.hpp"74#include "prims/methodComparator.hpp"75#include "runtime/arguments.hpp"76#include "runtime/atomic.hpp"77#include "runtime/biasedLocking.hpp"78#include "runtime/fieldDescriptor.inline.hpp"79#include "runtime/handles.inline.hpp"80#include "runtime/javaCalls.hpp"81#include "runtime/mutexLocker.hpp"82#include "runtime/orderAccess.hpp"83#include "runtime/reflectionUtils.hpp"84#include "runtime/thread.inline.hpp"85#include "services/classLoadingService.hpp"86#include "services/threadService.hpp"87#include "utilities/dtrace.hpp"88#include "utilities/events.hpp"89#include "utilities/macros.hpp"90#include "utilities/stringUtils.hpp"91#ifdef COMPILER192#include "c1/c1_Compiler.hpp"93#endif94#if INCLUDE_JFR95#include "jfr/jfrEvents.hpp"96#endif979899#ifdef DTRACE_ENABLED100101102#define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED103#define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE104#define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT105#define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS106#define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED107#define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT108#define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR109#define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END110#define DTRACE_CLASSINIT_PROBE(type, thread_type) \111{ \112char* data = NULL; \113int len = 0; \114Symbol* clss_name = name(); \115if (clss_name != NULL) { \116data = (char*)clss_name->bytes(); \117len = clss_name->utf8_length(); \118} \119HOTSPOT_CLASS_INITIALIZATION_##type( \120data, len, (void*)class_loader(), thread_type); \121}122123#define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \124{ \125char* data = NULL; \126int len = 0; \127Symbol* clss_name = name(); \128if (clss_name != NULL) { \129data = (char*)clss_name->bytes(); \130len = clss_name->utf8_length(); \131} \132HOTSPOT_CLASS_INITIALIZATION_##type( \133data, len, (void*)class_loader(), thread_type, wait); \134}135136#else // ndef DTRACE_ENABLED137138#define DTRACE_CLASSINIT_PROBE(type, thread_type)139#define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)140141#endif // ndef DTRACE_ENABLED142143144static inline bool is_class_loader(const Symbol* class_name,145const ClassFileParser& parser) {146assert(class_name != NULL, "invariant");147148if (class_name == vmSymbols::java_lang_ClassLoader()) {149return true;150}151152if (vmClasses::ClassLoader_klass_loaded()) {153const Klass* const super_klass = parser.super_klass();154if (super_klass != NULL) {155if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {156return true;157}158}159}160return false;161}162163// private: called to verify that k is a static member of this nest.164// We know that k is an instance class in the same package and hence the165// same classloader.166bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {167assert(!is_hidden(), "unexpected hidden class");168if (_nest_members == NULL || _nest_members == Universe::the_empty_short_array()) {169if (log_is_enabled(Trace, class, nestmates)) {170ResourceMark rm(current);171log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",172k->external_name(), this->external_name());173}174return false;175}176177if (log_is_enabled(Trace, class, nestmates)) {178ResourceMark rm(current);179log_trace(class, nestmates)("Checking nest membership of %s in %s",180k->external_name(), this->external_name());181}182183// Check for the named class in _nest_members.184// We don't resolve, or load, any classes.185for (int i = 0; i < _nest_members->length(); i++) {186int cp_index = _nest_members->at(i);187Symbol* name = _constants->klass_name_at(cp_index);188if (name == k->name()) {189log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index);190return true;191}192}193log_trace(class, nestmates)("- class is NOT a nest member!");194return false;195}196197// Called to verify that k is a permitted subclass of this class198bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k) const {199Thread* current = Thread::current();200assert(k != NULL, "sanity check");201assert(_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array(),202"unexpected empty _permitted_subclasses array");203204if (log_is_enabled(Trace, class, sealed)) {205ResourceMark rm(current);206log_trace(class, sealed)("Checking for permitted subclass of %s in %s",207k->external_name(), this->external_name());208}209210// Check that the class and its super are in the same module.211if (k->module() != this->module()) {212ResourceMark rm(current);213log_trace(class, sealed)("Check failed for same module of permitted subclass %s and sealed class %s",214k->external_name(), this->external_name());215return false;216}217218if (!k->is_public() && !is_same_class_package(k)) {219ResourceMark rm(current);220log_trace(class, sealed)("Check failed, subclass %s not public and not in the same package as sealed class %s",221k->external_name(), this->external_name());222return false;223}224225for (int i = 0; i < _permitted_subclasses->length(); i++) {226int cp_index = _permitted_subclasses->at(i);227Symbol* name = _constants->klass_name_at(cp_index);228if (name == k->name()) {229log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index);230return true;231}232}233log_trace(class, sealed)("- class is NOT a permitted subclass!");234return false;235}236237// Return nest-host class, resolving, validating and saving it if needed.238// In cases where this is called from a thread that cannot do classloading239// (such as a native JIT thread) then we simply return NULL, which in turn240// causes the access check to return false. Such code will retry the access241// from a more suitable environment later. Otherwise the _nest_host is always242// set once this method returns.243// Any errors from nest-host resolution must be preserved so they can be queried244// from higher-level access checking code, and reported as part of access checking245// exceptions.246// VirtualMachineErrors are propagated with a NULL return.247// Under any conditions where the _nest_host can be set to non-NULL the resulting248// value of it and, if applicable, the nest host resolution/validation error,249// are idempotent.250InstanceKlass* InstanceKlass::nest_host(TRAPS) {251InstanceKlass* nest_host_k = _nest_host;252if (nest_host_k != NULL) {253return nest_host_k;254}255256ResourceMark rm(THREAD);257258// need to resolve and save our nest-host class.259if (_nest_host_index != 0) { // we have a real nest_host260// Before trying to resolve check if we're in a suitable context261bool can_resolve = THREAD->can_call_java();262if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) {263log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",264this->external_name());265return NULL; // sentinel to say "try again from a different context"266}267268log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",269this->external_name(),270_constants->klass_name_at(_nest_host_index)->as_C_string());271272Klass* k = _constants->klass_at(_nest_host_index, THREAD);273if (HAS_PENDING_EXCEPTION) {274if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {275return NULL; // propagate VMEs276}277stringStream ss;278char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string();279ss.print("Nest host resolution of %s with host %s failed: ",280this->external_name(), target_host_class);281java_lang_Throwable::print(PENDING_EXCEPTION, &ss);282const char* msg = ss.as_string(true /* on C-heap */);283constantPoolHandle cph(THREAD, constants());284SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg);285CLEAR_PENDING_EXCEPTION;286287log_trace(class, nestmates)("%s", msg);288} else {289// A valid nest-host is an instance class in the current package that lists this290// class as a nest member. If any of these conditions are not met the class is291// its own nest-host.292const char* error = NULL;293294// JVMS 5.4.4 indicates package check comes first295if (is_same_class_package(k)) {296// Now check actual membership. We can't be a member if our "host" is297// not an instance class.298if (k->is_instance_klass()) {299nest_host_k = InstanceKlass::cast(k);300bool is_member = nest_host_k->has_nest_member(THREAD, this);301if (is_member) {302_nest_host = nest_host_k; // save resolved nest-host value303304log_trace(class, nestmates)("Resolved nest-host of %s to %s",305this->external_name(), k->external_name());306return nest_host_k;307} else {308error = "current type is not listed as a nest member";309}310} else {311error = "host is not an instance class";312}313} else {314error = "types are in different packages";315}316317// something went wrong, so record what and log it318{319stringStream ss;320ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s",321this->external_name(),322this->class_loader_data()->loader_name_and_id(),323k->external_name(),324k->class_loader_data()->loader_name_and_id(),325error);326const char* msg = ss.as_string(true /* on C-heap */);327constantPoolHandle cph(THREAD, constants());328SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg);329log_trace(class, nestmates)("%s", msg);330}331}332} else {333log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",334this->external_name());335}336337// Either not in an explicit nest, or else an error occurred, so338// the nest-host is set to `this`. Any thread that sees this assignment339// will also see any setting of nest_host_error(), if applicable.340return (_nest_host = this);341}342343// Dynamic nest member support: set this class's nest host to the given class.344// This occurs as part of the class definition, as soon as the instanceKlass345// has been created and doesn't require further resolution. The code:346// lookup().defineHiddenClass(bytes_for_X, NESTMATE);347// results in:348// class_of_X.set_nest_host(lookup().lookupClass().getNestHost())349// If it has an explicit _nest_host_index or _nest_members, these will be ignored.350// We also know the "host" is a valid nest-host in the same package so we can351// assert some of those facts.352void InstanceKlass::set_nest_host(InstanceKlass* host) {353assert(is_hidden(), "must be a hidden class");354assert(host != NULL, "NULL nest host specified");355assert(_nest_host == NULL, "current class has resolved nest-host");356assert(nest_host_error() == NULL, "unexpected nest host resolution error exists: %s",357nest_host_error());358assert((host->_nest_host == NULL && host->_nest_host_index == 0) ||359(host->_nest_host == host), "proposed host is not a valid nest-host");360// Can't assert this as package is not set yet:361// assert(is_same_class_package(host), "proposed host is in wrong package");362363if (log_is_enabled(Trace, class, nestmates)) {364ResourceMark rm;365const char* msg = "";366// a hidden class does not expect a statically defined nest-host367if (_nest_host_index > 0) {368msg = "(the NestHost attribute in the current class is ignored)";369} else if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {370msg = "(the NestMembers attribute in the current class is ignored)";371}372log_trace(class, nestmates)("Injected type %s into the nest of %s %s",373this->external_name(),374host->external_name(),375msg);376}377// set dynamic nest host378_nest_host = host;379// Record dependency to keep nest host from being unloaded before this class.380ClassLoaderData* this_key = class_loader_data();381this_key->record_dependency(host);382}383384// check if 'this' and k are nestmates (same nest_host), or k is our nest_host,385// or we are k's nest_host - all of which is covered by comparing the two386// resolved_nest_hosts.387// Any exceptions (i.e. VMEs) are propagated.388bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {389390assert(this != k, "this should be handled by higher-level code");391392// Per JVMS 5.4.4 we first resolve and validate the current class, then393// the target class k.394395InstanceKlass* cur_host = nest_host(CHECK_false);396if (cur_host == NULL) {397return false;398}399400Klass* k_nest_host = k->nest_host(CHECK_false);401if (k_nest_host == NULL) {402return false;403}404405bool access = (cur_host == k_nest_host);406407ResourceMark rm(THREAD);408log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",409this->external_name(),410access ? "" : "NOT ",411k->external_name());412return access;413}414415const char* InstanceKlass::nest_host_error() {416if (_nest_host_index == 0) {417return NULL;418} else {419constantPoolHandle cph(Thread::current(), constants());420return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);421}422}423424InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {425const int size = InstanceKlass::size(parser.vtable_size(),426parser.itable_size(),427nonstatic_oop_map_size(parser.total_oop_map_count()),428parser.is_interface());429430const Symbol* const class_name = parser.class_name();431assert(class_name != NULL, "invariant");432ClassLoaderData* loader_data = parser.loader_data();433assert(loader_data != NULL, "invariant");434435InstanceKlass* ik;436437// Allocation438if (REF_NONE == parser.reference_type()) {439if (class_name == vmSymbols::java_lang_Class()) {440// mirror441ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);442}443else if (is_class_loader(class_name, parser)) {444// class loader445ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);446} else {447// normal448ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_kind_other);449}450} else {451// reference452ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);453}454455// Check for pending exception before adding to the loader data and incrementing456// class count. Can get OOM here.457if (HAS_PENDING_EXCEPTION) {458return NULL;459}460461return ik;462}463464465// copy method ordering from resource area to Metaspace466void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {467if (m != NULL) {468// allocate a new array and copy contents (memcpy?)469_method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);470for (int i = 0; i < m->length(); i++) {471_method_ordering->at_put(i, m->at(i));472}473} else {474_method_ordering = Universe::the_empty_int_array();475}476}477478// create a new array of vtable_indices for default methods479Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {480Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);481assert(default_vtable_indices() == NULL, "only create once");482set_default_vtable_indices(vtable_indices);483return vtable_indices;484}485486InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :487Klass(id),488_nest_members(NULL),489_nest_host(NULL),490_permitted_subclasses(NULL),491_record_components(NULL),492_static_field_size(parser.static_field_size()),493_nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),494_itable_len(parser.itable_size()),495_nest_host_index(0),496_init_state(allocated),497_reference_type(parser.reference_type()),498_init_thread(NULL)499{500set_vtable_length(parser.vtable_size());501set_kind(kind);502set_access_flags(parser.access_flags());503if (parser.is_hidden()) set_is_hidden();504set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),505false));506507assert(NULL == _methods, "underlying memory not zeroed?");508assert(is_instance_klass(), "is layout incorrect?");509assert(size_helper() == parser.layout_size(), "incorrect size_helper?");510511// Set biased locking bit for all instances of this class; it will be512// cleared if revocation occurs too often for this type513if (UseBiasedLocking && BiasedLocking::enabled()) {514set_prototype_header(markWord::biased_locking_prototype());515}516}517518void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,519Array<Method*>* methods) {520if (methods != NULL && methods != Universe::the_empty_method_array() &&521!methods->is_shared()) {522for (int i = 0; i < methods->length(); i++) {523Method* method = methods->at(i);524if (method == NULL) continue; // maybe null if error processing525// Only want to delete methods that are not executing for RedefineClasses.526// The previous version will point to them so they're not totally dangling527assert (!method->on_stack(), "shouldn't be called with methods on stack");528MetadataFactory::free_metadata(loader_data, method);529}530MetadataFactory::free_array<Method*>(loader_data, methods);531}532}533534void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,535const Klass* super_klass,536Array<InstanceKlass*>* local_interfaces,537Array<InstanceKlass*>* transitive_interfaces) {538// Only deallocate transitive interfaces if not empty, same as super class539// or same as local interfaces. See code in parseClassFile.540Array<InstanceKlass*>* ti = transitive_interfaces;541if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {542// check that the interfaces don't come from super class543Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL :544InstanceKlass::cast(super_klass)->transitive_interfaces();545if (ti != sti && ti != NULL && !ti->is_shared()) {546MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);547}548}549550// local interfaces can be empty551if (local_interfaces != Universe::the_empty_instance_klass_array() &&552local_interfaces != NULL && !local_interfaces->is_shared()) {553MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);554}555}556557void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,558Array<RecordComponent*>* record_components) {559if (record_components != NULL && !record_components->is_shared()) {560for (int i = 0; i < record_components->length(); i++) {561RecordComponent* record_component = record_components->at(i);562MetadataFactory::free_metadata(loader_data, record_component);563}564MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);565}566}567568// This function deallocates the metadata and C heap pointers that the569// InstanceKlass points to.570void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {571572// Orphan the mirror first, CMS thinks it's still live.573if (java_mirror() != NULL) {574java_lang_Class::set_klass(java_mirror(), NULL);575}576577// Also remove mirror from handles578loader_data->remove_handle(_java_mirror);579580// Need to take this class off the class loader data list.581loader_data->remove_class(this);582583// The array_klass for this class is created later, after error handling.584// For class redefinition, we keep the original class so this scratch class585// doesn't have an array class. Either way, assert that there is nothing586// to deallocate.587assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");588589// Release C heap allocated data that this points to, which includes590// reference counting symbol names.591// Can't release the constant pool here because the constant pool can be592// deallocated separately from the InstanceKlass for default methods and593// redefine classes.594release_C_heap_structures(/* release_constant_pool */ false);595596deallocate_methods(loader_data, methods());597set_methods(NULL);598599deallocate_record_components(loader_data, record_components());600set_record_components(NULL);601602if (method_ordering() != NULL &&603method_ordering() != Universe::the_empty_int_array() &&604!method_ordering()->is_shared()) {605MetadataFactory::free_array<int>(loader_data, method_ordering());606}607set_method_ordering(NULL);608609// default methods can be empty610if (default_methods() != NULL &&611default_methods() != Universe::the_empty_method_array() &&612!default_methods()->is_shared()) {613MetadataFactory::free_array<Method*>(loader_data, default_methods());614}615// Do NOT deallocate the default methods, they are owned by superinterfaces.616set_default_methods(NULL);617618// default methods vtable indices can be empty619if (default_vtable_indices() != NULL &&620!default_vtable_indices()->is_shared()) {621MetadataFactory::free_array<int>(loader_data, default_vtable_indices());622}623set_default_vtable_indices(NULL);624625626// This array is in Klass, but remove it with the InstanceKlass since627// this place would be the only caller and it can share memory with transitive628// interfaces.629if (secondary_supers() != NULL &&630secondary_supers() != Universe::the_empty_klass_array() &&631// see comments in compute_secondary_supers about the following cast632(address)(secondary_supers()) != (address)(transitive_interfaces()) &&633!secondary_supers()->is_shared()) {634MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());635}636set_secondary_supers(NULL);637638deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());639set_transitive_interfaces(NULL);640set_local_interfaces(NULL);641642if (fields() != NULL && !fields()->is_shared()) {643MetadataFactory::free_array<jushort>(loader_data, fields());644}645set_fields(NULL, 0);646647// If a method from a redefined class is using this constant pool, don't648// delete it, yet. The new class's previous version will point to this.649if (constants() != NULL) {650assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");651if (!constants()->is_shared()) {652MetadataFactory::free_metadata(loader_data, constants());653}654// Delete any cached resolution errors for the constant pool655SystemDictionary::delete_resolution_error(constants());656657set_constants(NULL);658}659660if (inner_classes() != NULL &&661inner_classes() != Universe::the_empty_short_array() &&662!inner_classes()->is_shared()) {663MetadataFactory::free_array<jushort>(loader_data, inner_classes());664}665set_inner_classes(NULL);666667if (nest_members() != NULL &&668nest_members() != Universe::the_empty_short_array() &&669!nest_members()->is_shared()) {670MetadataFactory::free_array<jushort>(loader_data, nest_members());671}672set_nest_members(NULL);673674if (permitted_subclasses() != NULL &&675permitted_subclasses() != Universe::the_empty_short_array() &&676!permitted_subclasses()->is_shared()) {677MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());678}679set_permitted_subclasses(NULL);680681// We should deallocate the Annotations instance if it's not in shared spaces.682if (annotations() != NULL && !annotations()->is_shared()) {683MetadataFactory::free_metadata(loader_data, annotations());684}685set_annotations(NULL);686687if (Arguments::is_dumping_archive()) {688SystemDictionaryShared::remove_dumptime_info(this);689}690}691692bool InstanceKlass::is_record() const {693return _record_components != NULL &&694is_final() &&695java_super() == vmClasses::Record_klass();696}697698bool InstanceKlass::is_sealed() const {699return _permitted_subclasses != NULL &&700_permitted_subclasses != Universe::the_empty_short_array();701}702703bool InstanceKlass::should_be_initialized() const {704return !is_initialized();705}706707klassItable InstanceKlass::itable() const {708return klassItable(const_cast<InstanceKlass*>(this));709}710711void InstanceKlass::eager_initialize(Thread *thread) {712if (!EagerInitialization) return;713714if (this->is_not_initialized()) {715// abort if the the class has a class initializer716if (this->class_initializer() != NULL) return;717718// abort if it is java.lang.Object (initialization is handled in genesis)719Klass* super_klass = super();720if (super_klass == NULL) return;721722// abort if the super class should be initialized723if (!InstanceKlass::cast(super_klass)->is_initialized()) return;724725// call body to expose the this pointer726eager_initialize_impl();727}728}729730// JVMTI spec thinks there are signers and protection domain in the731// instanceKlass. These accessors pretend these fields are there.732// The hprof specification also thinks these fields are in InstanceKlass.733oop InstanceKlass::protection_domain() const {734// return the protection_domain from the mirror735return java_lang_Class::protection_domain(java_mirror());736}737738// To remove these from requires an incompatible change and CCC request.739objArrayOop InstanceKlass::signers() const {740// return the signers from the mirror741return java_lang_Class::signers(java_mirror());742}743744oop InstanceKlass::init_lock() const {745// return the init lock from the mirror746oop lock = java_lang_Class::init_lock(java_mirror());747// Prevent reordering with any access of initialization state748OrderAccess::loadload();749assert(lock != NULL || !is_not_initialized(), // initialized or in_error state750"only fully initialized state can have a null lock");751return lock;752}753754// Set the initialization lock to null so the object can be GC'ed. Any racing755// threads to get this lock will see a null lock and will not lock.756// That's okay because they all check for initialized state after getting757// the lock and return.758void InstanceKlass::fence_and_clear_init_lock() {759// make sure previous stores are all done, notably the init_state.760OrderAccess::storestore();761java_lang_Class::clear_init_lock(java_mirror());762assert(!is_not_initialized(), "class must be initialized now");763}764765void InstanceKlass::eager_initialize_impl() {766EXCEPTION_MARK;767HandleMark hm(THREAD);768Handle h_init_lock(THREAD, init_lock());769ObjectLocker ol(h_init_lock, THREAD);770771// abort if someone beat us to the initialization772if (!is_not_initialized()) return; // note: not equivalent to is_initialized()773774ClassState old_state = init_state();775link_class_impl(THREAD);776if (HAS_PENDING_EXCEPTION) {777CLEAR_PENDING_EXCEPTION;778// Abort if linking the class throws an exception.779780// Use a test to avoid redundantly resetting the state if there's781// no change. Set_init_state() asserts that state changes make782// progress, whereas here we might just be spinning in place.783if (old_state != _init_state)784set_init_state(old_state);785} else {786// linking successfull, mark class as initialized787set_init_state(fully_initialized);788fence_and_clear_init_lock();789// trace790if (log_is_enabled(Info, class, init)) {791ResourceMark rm(THREAD);792log_info(class, init)("[Initialized %s without side effects]", external_name());793}794}795}796797798// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization799// process. The step comments refers to the procedure described in that section.800// Note: implementation moved to static method to expose the this pointer.801void InstanceKlass::initialize(TRAPS) {802if (this->should_be_initialized()) {803initialize_impl(CHECK);804// Note: at this point the class may be initialized805// OR it may be in the state of being initialized806// in case of recursive initialization!807} else {808assert(is_initialized(), "sanity check");809}810}811812813bool InstanceKlass::verify_code(TRAPS) {814// 1) Verify the bytecodes815return Verifier::verify(this, should_verify_class(), THREAD);816}817818void InstanceKlass::link_class(TRAPS) {819assert(is_loaded(), "must be loaded");820if (!is_linked()) {821link_class_impl(CHECK);822}823}824825// Called to verify that a class can link during initialization, without826// throwing a VerifyError.827bool InstanceKlass::link_class_or_fail(TRAPS) {828assert(is_loaded(), "must be loaded");829if (!is_linked()) {830link_class_impl(CHECK_false);831}832return is_linked();833}834835bool InstanceKlass::link_class_impl(TRAPS) {836if (DumpSharedSpaces && SystemDictionaryShared::has_class_failed_verification(this)) {837// This is for CDS dumping phase only -- we use the in_error_state to indicate that838// the class has failed verification. Throwing the NoClassDefFoundError here is just839// a convenient way to stop repeat attempts to verify the same (bad) class.840//841// Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown842// if we are executing Java code. This is not a problem for CDS dumping phase since843// it doesn't execute any Java code.844ResourceMark rm(THREAD);845Exceptions::fthrow(THREAD_AND_LOCATION,846vmSymbols::java_lang_NoClassDefFoundError(),847"Class %s, or one of its supertypes, failed class initialization",848external_name());849return false;850}851// return if already verified852if (is_linked()) {853return true;854}855856// Timing857// timer handles recursion858JavaThread* jt = THREAD;859860// link super class before linking this class861Klass* super_klass = super();862if (super_klass != NULL) {863if (super_klass->is_interface()) { // check if super class is an interface864ResourceMark rm(THREAD);865Exceptions::fthrow(866THREAD_AND_LOCATION,867vmSymbols::java_lang_IncompatibleClassChangeError(),868"class %s has interface %s as super class",869external_name(),870super_klass->external_name()871);872return false;873}874875InstanceKlass* ik_super = InstanceKlass::cast(super_klass);876ik_super->link_class_impl(CHECK_false);877}878879// link all interfaces implemented by this class before linking this class880Array<InstanceKlass*>* interfaces = local_interfaces();881int num_interfaces = interfaces->length();882for (int index = 0; index < num_interfaces; index++) {883InstanceKlass* interk = interfaces->at(index);884interk->link_class_impl(CHECK_false);885}886887// in case the class is linked in the process of linking its superclasses888if (is_linked()) {889return true;890}891892// trace only the link time for this klass that includes893// the verification time894PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),895ClassLoader::perf_class_link_selftime(),896ClassLoader::perf_classes_linked(),897jt->get_thread_stat()->perf_recursion_counts_addr(),898jt->get_thread_stat()->perf_timers_addr(),899PerfClassTraceTime::CLASS_LINK);900901// verification & rewriting902{903HandleMark hm(THREAD);904Handle h_init_lock(THREAD, init_lock());905ObjectLocker ol(h_init_lock, jt);906// rewritten will have been set if loader constraint error found907// on an earlier link attempt908// don't verify or rewrite if already rewritten909//910911if (!is_linked()) {912if (!is_rewritten()) {913{914bool verify_ok = verify_code(THREAD);915if (!verify_ok) {916return false;917}918}919920// Just in case a side-effect of verify linked this class already921// (which can sometimes happen since the verifier loads classes922// using custom class loaders, which are free to initialize things)923if (is_linked()) {924return true;925}926927// also sets rewritten928rewrite_class(CHECK_false);929} else if (is_shared()) {930SystemDictionaryShared::check_verification_constraints(this, CHECK_false);931}932933// relocate jsrs and link methods after they are all rewritten934link_methods(CHECK_false);935936// Initialize the vtable and interface table after937// methods have been rewritten since rewrite may938// fabricate new Method*s.939// also does loader constraint checking940//941// initialize_vtable and initialize_itable need to be rerun942// for a shared class if943// 1) the class is loaded by custom class loader or944// 2) the class is loaded by built-in class loader but failed to add archived loader constraints945bool need_init_table = true;946if (is_shared() && SystemDictionaryShared::check_linking_constraints(THREAD, this)) {947need_init_table = false;948}949if (need_init_table) {950vtable().initialize_vtable_and_check_constraints(CHECK_false);951itable().initialize_itable_and_check_constraints(CHECK_false);952}953#ifdef ASSERT954vtable().verify(tty, true);955// In case itable verification is ever added.956// itable().verify(tty, true);957#endif958if (UseVtableBasedCHA) {959MutexLocker ml(THREAD, Compile_lock);960set_init_state(linked);961962// Now flush all code that assume the class is not linked.963if (Universe::is_fully_initialized()) {964CodeCache::flush_dependents_on(this);965}966} else {967set_init_state(linked);968}969if (JvmtiExport::should_post_class_prepare()) {970JvmtiExport::post_class_prepare(THREAD, this);971}972}973}974return true;975}976977// Rewrite the byte codes of all of the methods of a class.978// The rewriter must be called exactly once. Rewriting must happen after979// verification but before the first method of the class is executed.980void InstanceKlass::rewrite_class(TRAPS) {981assert(is_loaded(), "must be loaded");982if (is_rewritten()) {983assert(is_shared(), "rewriting an unshared class?");984return;985}986Rewriter::rewrite(this, CHECK);987set_rewritten();988}989990// Now relocate and link method entry points after class is rewritten.991// This is outside is_rewritten flag. In case of an exception, it can be992// executed more than once.993void InstanceKlass::link_methods(TRAPS) {994int len = methods()->length();995for (int i = len-1; i >= 0; i--) {996methodHandle m(THREAD, methods()->at(i));997998// Set up method entry points for compiler and interpreter .999m->link_method(m, CHECK);1000}1001}10021003// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)1004void InstanceKlass::initialize_super_interfaces(TRAPS) {1005assert (has_nonstatic_concrete_methods(), "caller should have checked this");1006for (int i = 0; i < local_interfaces()->length(); ++i) {1007InstanceKlass* ik = local_interfaces()->at(i);10081009// Initialization is depth first search ie. we start with top of the inheritance tree1010// has_nonstatic_concrete_methods drives searching superinterfaces since it1011// means has_nonstatic_concrete_methods in its superinterface hierarchy1012if (ik->has_nonstatic_concrete_methods()) {1013ik->initialize_super_interfaces(CHECK);1014}10151016// Only initialize() interfaces that "declare" concrete methods.1017if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {1018ik->initialize(CHECK);1019}1020}1021}10221023void InstanceKlass::initialize_impl(TRAPS) {1024HandleMark hm(THREAD);10251026// Make sure klass is linked (verified) before initialization1027// A class could already be verified, since it has been reflected upon.1028link_class(CHECK);10291030DTRACE_CLASSINIT_PROBE(required, -1);10311032bool wait = false;10331034JavaThread* jt = THREAD;10351036// refer to the JVM book page 47 for description of steps1037// Step 11038{1039Handle h_init_lock(THREAD, init_lock());1040ObjectLocker ol(h_init_lock, jt);10411042// Step 21043// If we were to use wait() instead of waitInterruptibly() then1044// we might end up throwing IE from link/symbol resolution sites1045// that aren't expected to throw. This would wreak havoc. See 6320309.1046while (is_being_initialized() && !is_reentrant_initialization(jt)) {1047wait = true;1048jt->set_class_to_be_initialized(this);1049ol.wait_uninterruptibly(jt);1050jt->set_class_to_be_initialized(NULL);1051}10521053// Step 31054if (is_being_initialized() && is_reentrant_initialization(jt)) {1055DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);1056return;1057}10581059// Step 41060if (is_initialized()) {1061DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);1062return;1063}10641065// Step 51066if (is_in_error_state()) {1067DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);1068ResourceMark rm(THREAD);1069const char* desc = "Could not initialize class ";1070const char* className = external_name();1071size_t msglen = strlen(desc) + strlen(className) + 1;1072char* message = NEW_RESOURCE_ARRAY(char, msglen);1073if (NULL == message) {1074// Out of memory: can't create detailed error message1075THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);1076} else {1077jio_snprintf(message, msglen, "%s%s", desc, className);1078THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);1079}1080}10811082// Step 61083set_init_state(being_initialized);1084set_init_thread(jt);1085}10861087// Step 71088// Next, if C is a class rather than an interface, initialize it's super class and super1089// interfaces.1090if (!is_interface()) {1091Klass* super_klass = super();1092if (super_klass != NULL && super_klass->should_be_initialized()) {1093super_klass->initialize(THREAD);1094}1095// If C implements any interface that declares a non-static, concrete method,1096// the initialization of C triggers initialization of its super interfaces.1097// Only need to recurse if has_nonstatic_concrete_methods which includes declaring and1098// having a superinterface that declares, non-static, concrete methods1099if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {1100initialize_super_interfaces(THREAD);1101}11021103// If any exceptions, complete abruptly, throwing the same exception as above.1104if (HAS_PENDING_EXCEPTION) {1105Handle e(THREAD, PENDING_EXCEPTION);1106CLEAR_PENDING_EXCEPTION;1107{1108EXCEPTION_MARK;1109// Locks object, set state, and notify all waiting threads1110set_initialization_state_and_notify(initialization_error, THREAD);1111CLEAR_PENDING_EXCEPTION;1112}1113DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);1114THROW_OOP(e());1115}1116}111711181119// Step 81120{1121DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);1122if (class_initializer() != NULL) {1123// Timer includes any side effects of class initialization (resolution,1124// etc), but not recursive entry into call_class_initializer().1125PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),1126ClassLoader::perf_class_init_selftime(),1127ClassLoader::perf_classes_inited(),1128jt->get_thread_stat()->perf_recursion_counts_addr(),1129jt->get_thread_stat()->perf_timers_addr(),1130PerfClassTraceTime::CLASS_CLINIT);1131call_class_initializer(THREAD);1132} else {1133// The elapsed time is so small it's not worth counting.1134if (UsePerfData) {1135ClassLoader::perf_classes_inited()->inc();1136}1137call_class_initializer(THREAD);1138}1139}11401141// Step 91142if (!HAS_PENDING_EXCEPTION) {1143set_initialization_state_and_notify(fully_initialized, CHECK);1144{1145debug_only(vtable().verify(tty, true);)1146}1147}1148else {1149// Step 10 and 111150Handle e(THREAD, PENDING_EXCEPTION);1151CLEAR_PENDING_EXCEPTION;1152// JVMTI has already reported the pending exception1153// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError1154JvmtiExport::clear_detected_exception(jt);1155{1156EXCEPTION_MARK;1157set_initialization_state_and_notify(initialization_error, THREAD);1158CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below1159// JVMTI has already reported the pending exception1160// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError1161JvmtiExport::clear_detected_exception(jt);1162}1163DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);1164if (e->is_a(vmClasses::Error_klass())) {1165THROW_OOP(e());1166} else {1167JavaCallArguments args(e);1168THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),1169vmSymbols::throwable_void_signature(),1170&args);1171}1172}1173DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);1174}117511761177void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {1178Handle h_init_lock(THREAD, init_lock());1179if (h_init_lock() != NULL) {1180ObjectLocker ol(h_init_lock, THREAD);1181set_init_thread(NULL); // reset _init_thread before changing _init_state1182set_init_state(state);1183fence_and_clear_init_lock();1184ol.notify_all(CHECK);1185} else {1186assert(h_init_lock() != NULL, "The initialization state should never be set twice");1187set_init_thread(NULL); // reset _init_thread before changing _init_state1188set_init_state(state);1189}1190}11911192InstanceKlass* InstanceKlass::implementor() const {1193InstanceKlass* volatile* ik = adr_implementor();1194if (ik == NULL) {1195return NULL;1196} else {1197// This load races with inserts, and therefore needs acquire.1198InstanceKlass* ikls = Atomic::load_acquire(ik);1199if (ikls != NULL && !ikls->is_loader_alive()) {1200return NULL; // don't return unloaded class1201} else {1202return ikls;1203}1204}1205}120612071208void InstanceKlass::set_implementor(InstanceKlass* ik) {1209assert_locked_or_safepoint(Compile_lock);1210assert(is_interface(), "not interface");1211InstanceKlass* volatile* addr = adr_implementor();1212assert(addr != NULL, "null addr");1213if (addr != NULL) {1214Atomic::release_store(addr, ik);1215}1216}12171218int InstanceKlass::nof_implementors() const {1219InstanceKlass* ik = implementor();1220if (ik == NULL) {1221return 0;1222} else if (ik != this) {1223return 1;1224} else {1225return 2;1226}1227}12281229// The embedded _implementor field can only record one implementor.1230// When there are more than one implementors, the _implementor field1231// is set to the interface Klass* itself. Following are the possible1232// values for the _implementor field:1233// NULL - no implementor1234// implementor Klass* - one implementor1235// self - more than one implementor1236//1237// The _implementor field only exists for interfaces.1238void InstanceKlass::add_implementor(InstanceKlass* ik) {1239if (Universe::is_fully_initialized()) {1240assert_lock_strong(Compile_lock);1241}1242assert(is_interface(), "not interface");1243// Filter out my subinterfaces.1244// (Note: Interfaces are never on the subklass list.)1245if (ik->is_interface()) return;12461247// Filter out subclasses whose supers already implement me.1248// (Note: CHA must walk subclasses of direct implementors1249// in order to locate indirect implementors.)1250InstanceKlass* super_ik = ik->java_super();1251if (super_ik != NULL && super_ik->implements_interface(this))1252// We only need to check one immediate superclass, since the1253// implements_interface query looks at transitive_interfaces.1254// Any supers of the super have the same (or fewer) transitive_interfaces.1255return;12561257InstanceKlass* iklass = implementor();1258if (iklass == NULL) {1259set_implementor(ik);1260} else if (iklass != this && iklass != ik) {1261// There is already an implementor. Use itself as an indicator of1262// more than one implementors.1263set_implementor(this);1264}12651266// The implementor also implements the transitive_interfaces1267for (int index = 0; index < local_interfaces()->length(); index++) {1268local_interfaces()->at(index)->add_implementor(ik);1269}1270}12711272void InstanceKlass::init_implementor() {1273if (is_interface()) {1274set_implementor(NULL);1275}1276}127712781279void InstanceKlass::process_interfaces() {1280// link this class into the implementors list of every interface it implements1281for (int i = local_interfaces()->length() - 1; i >= 0; i--) {1282assert(local_interfaces()->at(i)->is_klass(), "must be a klass");1283InstanceKlass* interf = local_interfaces()->at(i);1284assert(interf->is_interface(), "expected interface");1285interf->add_implementor(this);1286}1287}12881289bool InstanceKlass::can_be_primary_super_slow() const {1290if (is_interface())1291return false;1292else1293return Klass::can_be_primary_super_slow();1294}12951296GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,1297Array<InstanceKlass*>* transitive_interfaces) {1298// The secondaries are the implemented interfaces.1299Array<InstanceKlass*>* interfaces = transitive_interfaces;1300int num_secondaries = num_extra_slots + interfaces->length();1301if (num_secondaries == 0) {1302// Must share this for correct bootstrapping!1303set_secondary_supers(Universe::the_empty_klass_array());1304return NULL;1305} else if (num_extra_slots == 0) {1306// The secondary super list is exactly the same as the transitive interfaces, so1307// let's use it instead of making a copy.1308// Redefine classes has to be careful not to delete this!1309// We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,1310// (but it's safe to do here because we won't write into _secondary_supers from this point on).1311set_secondary_supers((Array<Klass*>*)(address)interfaces);1312return NULL;1313} else {1314// Copy transitive interfaces to a temporary growable array to be constructed1315// into the secondary super list with extra slots.1316GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());1317for (int i = 0; i < interfaces->length(); i++) {1318secondaries->push(interfaces->at(i));1319}1320return secondaries;1321}1322}13231324bool InstanceKlass::implements_interface(Klass* k) const {1325if (this == k) return true;1326assert(k->is_interface(), "should be an interface class");1327for (int i = 0; i < transitive_interfaces()->length(); i++) {1328if (transitive_interfaces()->at(i) == k) {1329return true;1330}1331}1332return false;1333}13341335bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {1336// Verify direct super interface1337if (this == k) return true;1338assert(k->is_interface(), "should be an interface class");1339for (int i = 0; i < local_interfaces()->length(); i++) {1340if (local_interfaces()->at(i) == k) {1341return true;1342}1343}1344return false;1345}13461347objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {1348check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);1349int size = objArrayOopDesc::object_size(length);1350Klass* ak = array_klass(n, CHECK_NULL);1351objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,1352/* do_zero */ true, CHECK_NULL);1353return o;1354}13551356instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {1357if (TraceFinalizerRegistration) {1358tty->print("Registered ");1359i->print_value_on(tty);1360tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));1361}1362instanceHandle h_i(THREAD, i);1363// Pass the handle as argument, JavaCalls::call expects oop as jobjects1364JavaValue result(T_VOID);1365JavaCallArguments args(h_i);1366methodHandle mh (THREAD, Universe::finalizer_register_method());1367JavaCalls::call(&result, mh, &args, CHECK_NULL);1368return h_i();1369}13701371instanceOop InstanceKlass::allocate_instance(TRAPS) {1372bool has_finalizer_flag = has_finalizer(); // Query before possible GC1373int size = size_helper(); // Query before forming handle.13741375instanceOop i;13761377i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);1378if (has_finalizer_flag && !RegisterFinalizersAtInit) {1379i = register_finalizer(i, CHECK_NULL);1380}1381return i;1382}13831384instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {1385return instanceHandle(THREAD, allocate_instance(THREAD));1386}13871388void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {1389if (is_interface() || is_abstract()) {1390ResourceMark rm(THREAD);1391THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()1392: vmSymbols::java_lang_InstantiationException(), external_name());1393}1394if (this == vmClasses::Class_klass()) {1395ResourceMark rm(THREAD);1396THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()1397: vmSymbols::java_lang_IllegalAccessException(), external_name());1398}1399}14001401Klass* InstanceKlass::array_klass(int n, TRAPS) {1402// Need load-acquire for lock-free read1403if (array_klasses_acquire() == NULL) {1404ResourceMark rm(THREAD);1405JavaThread *jt = THREAD;1406{1407// Atomic creation of array_klasses1408MutexLocker ma(THREAD, MultiArray_lock);14091410// Check if update has already taken place1411if (array_klasses() == NULL) {1412ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);1413// use 'release' to pair with lock-free load1414release_set_array_klasses(k);1415}1416}1417}1418// array_klasses() will always be set at this point1419ObjArrayKlass* oak = array_klasses();1420return oak->array_klass(n, THREAD);1421}14221423Klass* InstanceKlass::array_klass_or_null(int n) {1424// Need load-acquire for lock-free read1425ObjArrayKlass* oak = array_klasses_acquire();1426if (oak == NULL) {1427return NULL;1428} else {1429return oak->array_klass_or_null(n);1430}1431}14321433Klass* InstanceKlass::array_klass(TRAPS) {1434return array_klass(1, THREAD);1435}14361437Klass* InstanceKlass::array_klass_or_null() {1438return array_klass_or_null(1);1439}14401441static int call_class_initializer_counter = 0; // for debugging14421443Method* InstanceKlass::class_initializer() const {1444Method* clinit = find_method(1445vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());1446if (clinit != NULL && clinit->has_valid_initializer_flags()) {1447return clinit;1448}1449return NULL;1450}14511452void InstanceKlass::call_class_initializer(TRAPS) {1453if (ReplayCompiles &&1454(ReplaySuppressInitializers == 1 ||1455(ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {1456// Hide the existence of the initializer for the purpose of replaying the compile1457return;1458}14591460methodHandle h_method(THREAD, class_initializer());1461assert(!is_initialized(), "we cannot initialize twice");1462LogTarget(Info, class, init) lt;1463if (lt.is_enabled()) {1464ResourceMark rm(THREAD);1465LogStream ls(lt);1466ls.print("%d Initializing ", call_class_initializer_counter++);1467name()->print_value_on(&ls);1468ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));1469}1470if (h_method() != NULL) {1471JavaCallArguments args; // No arguments1472JavaValue result(T_VOID);1473JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)1474}1475}147614771478void InstanceKlass::mask_for(const methodHandle& method, int bci,1479InterpreterOopMap* entry_for) {1480// Lazily create the _oop_map_cache at first request1481// Lock-free access requires load_acquire.1482OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);1483if (oop_map_cache == NULL) {1484MutexLocker x(OopMapCacheAlloc_lock);1485// Check if _oop_map_cache was allocated while we were waiting for this lock1486if ((oop_map_cache = _oop_map_cache) == NULL) {1487oop_map_cache = new OopMapCache();1488// Ensure _oop_map_cache is stable, since it is examined without a lock1489Atomic::release_store(&_oop_map_cache, oop_map_cache);1490}1491}1492// _oop_map_cache is constant after init; lookup below does its own locking.1493oop_map_cache->lookup(method, bci, entry_for);1494}14951496bool InstanceKlass::contains_field_offset(int offset) {1497fieldDescriptor fd;1498return find_field_from_offset(offset, false, &fd);1499}15001501bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1502for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1503Symbol* f_name = fs.name();1504Symbol* f_sig = fs.signature();1505if (f_name == name && f_sig == sig) {1506fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1507return true;1508}1509}1510return false;1511}151215131514Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1515const int n = local_interfaces()->length();1516for (int i = 0; i < n; i++) {1517Klass* intf1 = local_interfaces()->at(i);1518assert(intf1->is_interface(), "just checking type");1519// search for field in current interface1520if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {1521assert(fd->is_static(), "interface field must be static");1522return intf1;1523}1524// search for field in direct superinterfaces1525Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);1526if (intf2 != NULL) return intf2;1527}1528// otherwise field lookup fails1529return NULL;1530}153115321533Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1534// search order according to newest JVM spec (5.4.3.2, p.167).1535// 1) search for field in current klass1536if (find_local_field(name, sig, fd)) {1537return const_cast<InstanceKlass*>(this);1538}1539// 2) search for field recursively in direct superinterfaces1540{ Klass* intf = find_interface_field(name, sig, fd);1541if (intf != NULL) return intf;1542}1543// 3) apply field lookup recursively if superclass exists1544{ Klass* supr = super();1545if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);1546}1547// 4) otherwise field lookup fails1548return NULL;1549}155015511552Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {1553// search order according to newest JVM spec (5.4.3.2, p.167).1554// 1) search for field in current klass1555if (find_local_field(name, sig, fd)) {1556if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);1557}1558// 2) search for field recursively in direct superinterfaces1559if (is_static) {1560Klass* intf = find_interface_field(name, sig, fd);1561if (intf != NULL) return intf;1562}1563// 3) apply field lookup recursively if superclass exists1564{ Klass* supr = super();1565if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);1566}1567// 4) otherwise field lookup fails1568return NULL;1569}157015711572bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1573for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1574if (fs.offset() == offset) {1575fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1576if (fd->is_static() == is_static) return true;1577}1578}1579return false;1580}158115821583bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1584Klass* klass = const_cast<InstanceKlass*>(this);1585while (klass != NULL) {1586if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {1587return true;1588}1589klass = klass->super();1590}1591return false;1592}159315941595void InstanceKlass::methods_do(void f(Method* method)) {1596// Methods aren't stable until they are loaded. This can be read outside1597// a lock through the ClassLoaderData for profiling1598// Redefined scratch classes are on the list and need to be cleaned1599if (!is_loaded() && !is_scratch_class()) {1600return;1601}16021603int len = methods()->length();1604for (int index = 0; index < len; index++) {1605Method* m = methods()->at(index);1606assert(m->is_method(), "must be method");1607f(m);1608}1609}161016111612void InstanceKlass::do_local_static_fields(FieldClosure* cl) {1613for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1614if (fs.access_flags().is_static()) {1615fieldDescriptor& fd = fs.field_descriptor();1616cl->do_field(&fd);1617}1618}1619}162016211622void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {1623for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1624if (fs.access_flags().is_static()) {1625fieldDescriptor& fd = fs.field_descriptor();1626f(&fd, mirror, CHECK);1627}1628}1629}163016311632static int compare_fields_by_offset(int* a, int* b) {1633return a[0] - b[0];1634}16351636void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {1637InstanceKlass* super = superklass();1638if (super != NULL) {1639super->do_nonstatic_fields(cl);1640}1641fieldDescriptor fd;1642int length = java_fields_count();1643// In DebugInfo nonstatic fields are sorted by offset.1644int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);1645int j = 0;1646for (int i = 0; i < length; i += 1) {1647fd.reinitialize(this, i);1648if (!fd.is_static()) {1649fields_sorted[j + 0] = fd.offset();1650fields_sorted[j + 1] = i;1651j += 2;1652}1653}1654if (j > 0) {1655length = j;1656// _sort_Fn is defined in growableArray.hpp.1657qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);1658for (int i = 0; i < length; i += 2) {1659fd.reinitialize(this, fields_sorted[i + 1]);1660assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");1661cl->do_field(&fd);1662}1663}1664FREE_C_HEAP_ARRAY(int, fields_sorted);1665}166616671668void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {1669if (array_klasses() != NULL)1670array_klasses()->array_klasses_do(f, THREAD);1671}16721673void InstanceKlass::array_klasses_do(void f(Klass* k)) {1674if (array_klasses() != NULL)1675array_klasses()->array_klasses_do(f);1676}16771678#ifdef ASSERT1679static int linear_search(const Array<Method*>* methods,1680const Symbol* name,1681const Symbol* signature) {1682const int len = methods->length();1683for (int index = 0; index < len; index++) {1684const Method* const m = methods->at(index);1685assert(m->is_method(), "must be method");1686if (m->signature() == signature && m->name() == name) {1687return index;1688}1689}1690return -1;1691}1692#endif16931694bool InstanceKlass::_disable_method_binary_search = false;16951696NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) {1697int len = methods->length();1698int l = 0;1699int h = len - 1;1700while (l <= h) {1701Method* m = methods->at(l);1702if (m->name() == name) {1703return l;1704}1705l++;1706}1707return -1;1708}17091710inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) {1711if (_disable_method_binary_search) {1712assert(DynamicDumpSharedSpaces, "must be");1713// At the final stage of dynamic dumping, the methods array may not be sorted1714// by ascending addresses of their names, so we can't use binary search anymore.1715// However, methods with the same name are still laid out consecutively inside the1716// methods array, so let's look for the first one that matches.1717return linear_search(methods, name);1718}17191720int len = methods->length();1721int l = 0;1722int h = len - 1;17231724// methods are sorted by ascending addresses of their names, so do binary search1725while (l <= h) {1726int mid = (l + h) >> 1;1727Method* m = methods->at(mid);1728assert(m->is_method(), "must be method");1729int res = m->name()->fast_compare(name);1730if (res == 0) {1731return mid;1732} else if (res < 0) {1733l = mid + 1;1734} else {1735h = mid - 1;1736}1737}1738return -1;1739}17401741// find_method looks up the name/signature in the local methods array1742Method* InstanceKlass::find_method(const Symbol* name,1743const Symbol* signature) const {1744return find_method_impl(name, signature,1745OverpassLookupMode::find,1746StaticLookupMode::find,1747PrivateLookupMode::find);1748}17491750Method* InstanceKlass::find_method_impl(const Symbol* name,1751const Symbol* signature,1752OverpassLookupMode overpass_mode,1753StaticLookupMode static_mode,1754PrivateLookupMode private_mode) const {1755return InstanceKlass::find_method_impl(methods(),1756name,1757signature,1758overpass_mode,1759static_mode,1760private_mode);1761}17621763// find_instance_method looks up the name/signature in the local methods array1764// and skips over static methods1765Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,1766const Symbol* name,1767const Symbol* signature,1768PrivateLookupMode private_mode) {1769Method* const meth = InstanceKlass::find_method_impl(methods,1770name,1771signature,1772OverpassLookupMode::find,1773StaticLookupMode::skip,1774private_mode);1775assert(((meth == NULL) || !meth->is_static()),1776"find_instance_method should have skipped statics");1777return meth;1778}17791780// find_instance_method looks up the name/signature in the local methods array1781// and skips over static methods1782Method* InstanceKlass::find_instance_method(const Symbol* name,1783const Symbol* signature,1784PrivateLookupMode private_mode) const {1785return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);1786}17871788// Find looks up the name/signature in the local methods array1789// and filters on the overpass, static and private flags1790// This returns the first one found1791// note that the local methods array can have up to one overpass, one static1792// and one instance (private or not) with the same name/signature1793Method* InstanceKlass::find_local_method(const Symbol* name,1794const Symbol* signature,1795OverpassLookupMode overpass_mode,1796StaticLookupMode static_mode,1797PrivateLookupMode private_mode) const {1798return InstanceKlass::find_method_impl(methods(),1799name,1800signature,1801overpass_mode,1802static_mode,1803private_mode);1804}18051806// Find looks up the name/signature in the local methods array1807// and filters on the overpass, static and private flags1808// This returns the first one found1809// note that the local methods array can have up to one overpass, one static1810// and one instance (private or not) with the same name/signature1811Method* InstanceKlass::find_local_method(const Array<Method*>* methods,1812const Symbol* name,1813const Symbol* signature,1814OverpassLookupMode overpass_mode,1815StaticLookupMode static_mode,1816PrivateLookupMode private_mode) {1817return InstanceKlass::find_method_impl(methods,1818name,1819signature,1820overpass_mode,1821static_mode,1822private_mode);1823}18241825Method* InstanceKlass::find_method(const Array<Method*>* methods,1826const Symbol* name,1827const Symbol* signature) {1828return InstanceKlass::find_method_impl(methods,1829name,1830signature,1831OverpassLookupMode::find,1832StaticLookupMode::find,1833PrivateLookupMode::find);1834}18351836Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,1837const Symbol* name,1838const Symbol* signature,1839OverpassLookupMode overpass_mode,1840StaticLookupMode static_mode,1841PrivateLookupMode private_mode) {1842int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);1843return hit >= 0 ? methods->at(hit): NULL;1844}18451846// true if method matches signature and conforms to skipping_X conditions.1847static bool method_matches(const Method* m,1848const Symbol* signature,1849bool skipping_overpass,1850bool skipping_static,1851bool skipping_private) {1852return ((m->signature() == signature) &&1853(!skipping_overpass || !m->is_overpass()) &&1854(!skipping_static || !m->is_static()) &&1855(!skipping_private || !m->is_private()));1856}18571858// Used directly for default_methods to find the index into the1859// default_vtable_indices, and indirectly by find_method1860// find_method_index looks in the local methods array to return the index1861// of the matching name/signature. If, overpass methods are being ignored,1862// the search continues to find a potential non-overpass match. This capability1863// is important during method resolution to prefer a static method, for example,1864// over an overpass method.1865// There is the possibility in any _method's array to have the same name/signature1866// for a static method, an overpass method and a local instance method1867// To correctly catch a given method, the search criteria may need1868// to explicitly skip the other two. For local instance methods, it1869// is often necessary to skip private methods1870int InstanceKlass::find_method_index(const Array<Method*>* methods,1871const Symbol* name,1872const Symbol* signature,1873OverpassLookupMode overpass_mode,1874StaticLookupMode static_mode,1875PrivateLookupMode private_mode) {1876const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip);1877const bool skipping_static = (static_mode == StaticLookupMode::skip);1878const bool skipping_private = (private_mode == PrivateLookupMode::skip);1879const int hit = quick_search(methods, name);1880if (hit != -1) {1881const Method* const m = methods->at(hit);18821883// Do linear search to find matching signature. First, quick check1884// for common case, ignoring overpasses if requested.1885if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {1886return hit;1887}18881889// search downwards through overloaded methods1890int i;1891for (i = hit - 1; i >= 0; --i) {1892const Method* const m = methods->at(i);1893assert(m->is_method(), "must be method");1894if (m->name() != name) {1895break;1896}1897if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {1898return i;1899}1900}1901// search upwards1902for (i = hit + 1; i < methods->length(); ++i) {1903const Method* const m = methods->at(i);1904assert(m->is_method(), "must be method");1905if (m->name() != name) {1906break;1907}1908if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {1909return i;1910}1911}1912// not found1913#ifdef ASSERT1914const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :1915linear_search(methods, name, signature);1916assert(-1 == index, "binary search should have found entry %d", index);1917#endif1918}1919return -1;1920}19211922int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {1923return find_method_by_name(methods(), name, end);1924}19251926int InstanceKlass::find_method_by_name(const Array<Method*>* methods,1927const Symbol* name,1928int* end_ptr) {1929assert(end_ptr != NULL, "just checking");1930int start = quick_search(methods, name);1931int end = start + 1;1932if (start != -1) {1933while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;1934while (end < methods->length() && (methods->at(end))->name() == name) ++end;1935*end_ptr = end;1936return start;1937}1938return -1;1939}19401941// uncached_lookup_method searches both the local class methods array and all1942// superclasses methods arrays, skipping any overpass methods in superclasses,1943// and possibly skipping private methods.1944Method* InstanceKlass::uncached_lookup_method(const Symbol* name,1945const Symbol* signature,1946OverpassLookupMode overpass_mode,1947PrivateLookupMode private_mode) const {1948OverpassLookupMode overpass_local_mode = overpass_mode;1949const Klass* klass = this;1950while (klass != NULL) {1951Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,1952signature,1953overpass_local_mode,1954StaticLookupMode::find,1955private_mode);1956if (method != NULL) {1957return method;1958}1959klass = klass->super();1960overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses1961}1962return NULL;1963}19641965#ifdef ASSERT1966// search through class hierarchy and return true if this class or1967// one of the superclasses was redefined1968bool InstanceKlass::has_redefined_this_or_super() const {1969const Klass* klass = this;1970while (klass != NULL) {1971if (InstanceKlass::cast(klass)->has_been_redefined()) {1972return true;1973}1974klass = klass->super();1975}1976return false;1977}1978#endif19791980// lookup a method in the default methods list then in all transitive interfaces1981// Do NOT return private or static methods1982Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,1983Symbol* signature) const {1984Method* m = NULL;1985if (default_methods() != NULL) {1986m = find_method(default_methods(), name, signature);1987}1988// Look up interfaces1989if (m == NULL) {1990m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find);1991}1992return m;1993}19941995// lookup a method in all the interfaces that this class implements1996// Do NOT return private or static methods, new in JDK8 which are not externally visible1997// They should only be found in the initial InterfaceMethodRef1998Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,1999Symbol* signature,2000DefaultsLookupMode defaults_mode) const {2001Array<InstanceKlass*>* all_ifs = transitive_interfaces();2002int num_ifs = all_ifs->length();2003InstanceKlass *ik = NULL;2004for (int i = 0; i < num_ifs; i++) {2005ik = all_ifs->at(i);2006Method* m = ik->lookup_method(name, signature);2007if (m != NULL && m->is_public() && !m->is_static() &&2008((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) {2009return m;2010}2011}2012return NULL;2013}20142015/* jni_id_for for jfieldIds only */2016JNIid* InstanceKlass::jni_id_for(int offset) {2017MutexLocker ml(JfieldIdCreation_lock);2018JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);2019if (probe == NULL) {2020// Allocate new static field identifier2021probe = new JNIid(this, offset, jni_ids());2022set_jni_ids(probe);2023}2024return probe;2025}20262027u2 InstanceKlass::enclosing_method_data(int offset) const {2028const Array<jushort>* const inner_class_list = inner_classes();2029if (inner_class_list == NULL) {2030return 0;2031}2032const int length = inner_class_list->length();2033if (length % inner_class_next_offset == 0) {2034return 0;2035}2036const int index = length - enclosing_method_attribute_size;2037assert(offset < enclosing_method_attribute_size, "invalid offset");2038return inner_class_list->at(index + offset);2039}20402041void InstanceKlass::set_enclosing_method_indices(u2 class_index,2042u2 method_index) {2043Array<jushort>* inner_class_list = inner_classes();2044assert (inner_class_list != NULL, "_inner_classes list is not set up");2045int length = inner_class_list->length();2046if (length % inner_class_next_offset == enclosing_method_attribute_size) {2047int index = length - enclosing_method_attribute_size;2048inner_class_list->at_put(2049index + enclosing_method_class_index_offset, class_index);2050inner_class_list->at_put(2051index + enclosing_method_method_index_offset, method_index);2052}2053}20542055// Lookup or create a jmethodID.2056// This code is called by the VMThread and JavaThreads so the2057// locking has to be done very carefully to avoid deadlocks2058// and/or other cache consistency problems.2059//2060jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {2061size_t idnum = (size_t)method_h->method_idnum();2062jmethodID* jmeths = methods_jmethod_ids_acquire();2063size_t length = 0;2064jmethodID id = NULL;20652066// We use a double-check locking idiom here because this cache is2067// performance sensitive. In the normal system, this cache only2068// transitions from NULL to non-NULL which is safe because we use2069// release_set_methods_jmethod_ids() to advertise the new cache.2070// A partially constructed cache should never be seen by a racing2071// thread. We also use release_store() to save a new jmethodID2072// in the cache so a partially constructed jmethodID should never be2073// seen either. Cache reads of existing jmethodIDs proceed without a2074// lock, but cache writes of a new jmethodID requires uniqueness and2075// creation of the cache itself requires no leaks so a lock is2076// generally acquired in those two cases.2077//2078// If the RedefineClasses() API has been used, then this cache can2079// grow and we'll have transitions from non-NULL to bigger non-NULL.2080// Cache creation requires no leaks and we require safety between all2081// cache accesses and freeing of the old cache so a lock is generally2082// acquired when the RedefineClasses() API has been used.20832084if (jmeths != NULL) {2085// the cache already exists2086if (!idnum_can_increment()) {2087// the cache can't grow so we can just get the current values2088get_jmethod_id_length_value(jmeths, idnum, &length, &id);2089} else {2090// cache can grow so we have to be more careful2091if (Threads::number_of_threads() == 0 ||2092SafepointSynchronize::is_at_safepoint()) {2093// we're single threaded or at a safepoint - no locking needed2094get_jmethod_id_length_value(jmeths, idnum, &length, &id);2095} else {2096MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);2097get_jmethod_id_length_value(jmeths, idnum, &length, &id);2098}2099}2100}2101// implied else:2102// we need to allocate a cache so default length and id values are good21032104if (jmeths == NULL || // no cache yet2105length <= idnum || // cache is too short2106id == NULL) { // cache doesn't contain entry21072108// This function can be called by the VMThread so we have to do all2109// things that might block on a safepoint before grabbing the lock.2110// Otherwise, we can deadlock with the VMThread or have a cache2111// consistency issue. These vars keep track of what we might have2112// to free after the lock is dropped.2113jmethodID to_dealloc_id = NULL;2114jmethodID* to_dealloc_jmeths = NULL;21152116// may not allocate new_jmeths or use it if we allocate it2117jmethodID* new_jmeths = NULL;2118if (length <= idnum) {2119// allocate a new cache that might be used2120size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());2121new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);2122memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));2123// cache size is stored in element[0], other elements offset by one2124new_jmeths[0] = (jmethodID)size;2125}21262127// allocate a new jmethodID that might be used2128jmethodID new_id = NULL;2129if (method_h->is_old() && !method_h->is_obsolete()) {2130// The method passed in is old (but not obsolete), we need to use the current version2131Method* current_method = method_with_idnum((int)idnum);2132assert(current_method != NULL, "old and but not obsolete, so should exist");2133new_id = Method::make_jmethod_id(class_loader_data(), current_method);2134} else {2135// It is the current version of the method or an obsolete method,2136// use the version passed in2137new_id = Method::make_jmethod_id(class_loader_data(), method_h());2138}21392140if (Threads::number_of_threads() == 0 ||2141SafepointSynchronize::is_at_safepoint()) {2142// we're single threaded or at a safepoint - no locking needed2143id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,2144&to_dealloc_id, &to_dealloc_jmeths);2145} else {2146MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);2147id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,2148&to_dealloc_id, &to_dealloc_jmeths);2149}21502151// The lock has been dropped so we can free resources.2152// Free up either the old cache or the new cache if we allocated one.2153if (to_dealloc_jmeths != NULL) {2154FreeHeap(to_dealloc_jmeths);2155}2156// free up the new ID since it wasn't needed2157if (to_dealloc_id != NULL) {2158Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);2159}2160}2161return id;2162}21632164// Figure out how many jmethodIDs haven't been allocated, and make2165// sure space for them is pre-allocated. This makes getting all2166// method ids much, much faster with classes with more than 82167// methods, and has a *substantial* effect on performance with jvmti2168// code that loads all jmethodIDs for all classes.2169void InstanceKlass::ensure_space_for_methodids(int start_offset) {2170int new_jmeths = 0;2171int length = methods()->length();2172for (int index = start_offset; index < length; index++) {2173Method* m = methods()->at(index);2174jmethodID id = m->find_jmethod_id_or_null();2175if (id == NULL) {2176new_jmeths++;2177}2178}2179if (new_jmeths != 0) {2180Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);2181}2182}21832184// Common code to fetch the jmethodID from the cache or update the2185// cache with the new jmethodID. This function should never do anything2186// that causes the caller to go to a safepoint or we can deadlock with2187// the VMThread or have cache consistency issues.2188//2189jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(2190size_t idnum, jmethodID new_id,2191jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,2192jmethodID** to_dealloc_jmeths_p) {2193assert(new_id != NULL, "sanity check");2194assert(to_dealloc_id_p != NULL, "sanity check");2195assert(to_dealloc_jmeths_p != NULL, "sanity check");2196assert(Threads::number_of_threads() == 0 ||2197SafepointSynchronize::is_at_safepoint() ||2198JmethodIdCreation_lock->owned_by_self(), "sanity check");21992200// reacquire the cache - we are locked, single threaded or at a safepoint2201jmethodID* jmeths = methods_jmethod_ids_acquire();2202jmethodID id = NULL;2203size_t length = 0;22042205if (jmeths == NULL || // no cache yet2206(length = (size_t)jmeths[0]) <= idnum) { // cache is too short2207if (jmeths != NULL) {2208// copy any existing entries from the old cache2209for (size_t index = 0; index < length; index++) {2210new_jmeths[index+1] = jmeths[index+1];2211}2212*to_dealloc_jmeths_p = jmeths; // save old cache for later delete2213}2214release_set_methods_jmethod_ids(jmeths = new_jmeths);2215} else {2216// fetch jmethodID (if any) from the existing cache2217id = jmeths[idnum+1];2218*to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete2219}2220if (id == NULL) {2221// No matching jmethodID in the existing cache or we have a new2222// cache or we just grew the cache. This cache write is done here2223// by the first thread to win the foot race because a jmethodID2224// needs to be unique once it is generally available.2225id = new_id;22262227// The jmethodID cache can be read while unlocked so we have to2228// make sure the new jmethodID is complete before installing it2229// in the cache.2230Atomic::release_store(&jmeths[idnum+1], id);2231} else {2232*to_dealloc_id_p = new_id; // save new id for later delete2233}2234return id;2235}223622372238// Common code to get the jmethodID cache length and the jmethodID2239// value at index idnum if there is one.2240//2241void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,2242size_t idnum, size_t *length_p, jmethodID* id_p) {2243assert(cache != NULL, "sanity check");2244assert(length_p != NULL, "sanity check");2245assert(id_p != NULL, "sanity check");22462247// cache size is stored in element[0], other elements offset by one2248*length_p = (size_t)cache[0];2249if (*length_p <= idnum) { // cache is too short2250*id_p = NULL;2251} else {2252*id_p = cache[idnum+1]; // fetch jmethodID (if any)2253}2254}225522562257// Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles2258jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {2259size_t idnum = (size_t)method->method_idnum();2260jmethodID* jmeths = methods_jmethod_ids_acquire();2261size_t length; // length assigned as debugging crumb2262jmethodID id = NULL;2263if (jmeths != NULL && // If there is a cache2264(length = (size_t)jmeths[0]) > idnum) { // and if it is long enough,2265id = jmeths[idnum+1]; // Look up the id (may be NULL)2266}2267return id;2268}22692270inline DependencyContext InstanceKlass::dependencies() {2271DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);2272return dep_context;2273}22742275int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {2276return dependencies().mark_dependent_nmethods(changes);2277}22782279void InstanceKlass::add_dependent_nmethod(nmethod* nm) {2280dependencies().add_dependent_nmethod(nm);2281}22822283void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {2284dependencies().remove_dependent_nmethod(nm);2285}22862287void InstanceKlass::clean_dependency_context() {2288dependencies().clean_unloading_dependents();2289}22902291#ifndef PRODUCT2292void InstanceKlass::print_dependent_nmethods(bool verbose) {2293dependencies().print_dependent_nmethods(verbose);2294}22952296bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {2297return dependencies().is_dependent_nmethod(nm);2298}2299#endif //PRODUCT23002301void InstanceKlass::clean_weak_instanceklass_links() {2302clean_implementors_list();2303clean_method_data();2304}23052306void InstanceKlass::clean_implementors_list() {2307assert(is_loader_alive(), "this klass should be live");2308if (is_interface()) {2309assert (ClassUnloading, "only called for ClassUnloading");2310for (;;) {2311// Use load_acquire due to competing with inserts2312InstanceKlass* impl = Atomic::load_acquire(adr_implementor());2313if (impl != NULL && !impl->is_loader_alive()) {2314// NULL this field, might be an unloaded instance klass or NULL2315InstanceKlass* volatile* iklass = adr_implementor();2316if (Atomic::cmpxchg(iklass, impl, (InstanceKlass*)NULL) == impl) {2317// Successfully unlinking implementor.2318if (log_is_enabled(Trace, class, unload)) {2319ResourceMark rm;2320log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());2321}2322return;2323}2324} else {2325return;2326}2327}2328}2329}23302331void InstanceKlass::clean_method_data() {2332for (int m = 0; m < methods()->length(); m++) {2333MethodData* mdo = methods()->at(m)->method_data();2334if (mdo != NULL) {2335MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());2336mdo->clean_method_data(/*always_clean*/false);2337}2338}2339}23402341void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {2342Klass::metaspace_pointers_do(it);23432344if (log_is_enabled(Trace, cds)) {2345ResourceMark rm;2346log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());2347}23482349it->push(&_annotations);2350it->push((Klass**)&_array_klasses);2351if (!is_rewritten()) {2352it->push(&_constants, MetaspaceClosure::_writable);2353} else {2354it->push(&_constants);2355}2356it->push(&_inner_classes);2357#if INCLUDE_JVMTI2358it->push(&_previous_versions);2359#endif2360it->push(&_methods);2361it->push(&_default_methods);2362it->push(&_local_interfaces);2363it->push(&_transitive_interfaces);2364it->push(&_method_ordering);2365if (!is_rewritten()) {2366it->push(&_default_vtable_indices, MetaspaceClosure::_writable);2367} else {2368it->push(&_default_vtable_indices);2369}23702371// _fields might be written into by Rewriter::scan_method() -> fd.set_has_initialized_final_update()2372it->push(&_fields, MetaspaceClosure::_writable);23732374if (itable_length() > 0) {2375itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();2376int method_table_offset_in_words = ioe->offset()/wordSize;2377int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())2378/ itableOffsetEntry::size();23792380for (int i = 0; i < nof_interfaces; i ++, ioe ++) {2381if (ioe->interface_klass() != NULL) {2382it->push(ioe->interface_klass_addr());2383itableMethodEntry* ime = ioe->first_method_entry(this);2384int n = klassItable::method_count_for_interface(ioe->interface_klass());2385for (int index = 0; index < n; index ++) {2386it->push(ime[index].method_addr());2387}2388}2389}2390}23912392it->push(&_nest_members);2393it->push(&_permitted_subclasses);2394it->push(&_record_components);2395}23962397void InstanceKlass::remove_unshareable_info() {23982399if (can_be_verified_at_dumptime()) {2400// Remember this so we can avoid walking the hierarchy at runtime.2401set_verified_at_dump_time();2402}24032404Klass::remove_unshareable_info();24052406if (SystemDictionaryShared::has_class_failed_verification(this)) {2407// Classes are attempted to link during dumping and may fail,2408// but these classes are still in the dictionary and class list in CLD.2409// If the class has failed verification, there is nothing else to remove.2410return;2411}24122413// Reset to the 'allocated' state to prevent any premature accessing to2414// a shared class at runtime while the class is still being loaded and2415// restored. A class' init_state is set to 'loaded' at runtime when it's2416// being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).2417_init_state = allocated;24182419{ // Otherwise this needs to take out the Compile_lock.2420assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");2421init_implementor();2422}24232424constants()->remove_unshareable_info();24252426for (int i = 0; i < methods()->length(); i++) {2427Method* m = methods()->at(i);2428m->remove_unshareable_info();2429}24302431// do array classes also.2432if (array_klasses() != NULL) {2433array_klasses()->remove_unshareable_info();2434}24352436// These are not allocated from metaspace. They are safe to set to NULL.2437_source_debug_extension = NULL;2438_dep_context = NULL;2439_osr_nmethods_head = NULL;2440#if INCLUDE_JVMTI2441_breakpoints = NULL;2442_previous_versions = NULL;2443_cached_class_file = NULL;2444_jvmti_cached_class_field_map = NULL;2445#endif24462447_init_thread = NULL;2448_methods_jmethod_ids = NULL;2449_jni_ids = NULL;2450_oop_map_cache = NULL;2451// clear _nest_host to ensure re-load at runtime2452_nest_host = NULL;2453init_shared_package_entry();2454_dep_context_last_cleaned = 0;2455}24562457void InstanceKlass::remove_java_mirror() {2458Klass::remove_java_mirror();24592460// do array classes also.2461if (array_klasses() != NULL) {2462array_klasses()->remove_java_mirror();2463}2464}24652466void InstanceKlass::init_shared_package_entry() {2467#if !INCLUDE_CDS_JAVA_HEAP2468_package_entry = NULL;2469#else2470if (!MetaspaceShared::use_full_module_graph()) {2471_package_entry = NULL;2472} else if (DynamicDumpSharedSpaces) {2473if (!MetaspaceShared::is_in_shared_metaspace(_package_entry)) {2474_package_entry = NULL;2475}2476} else {2477if (is_shared_unregistered_class()) {2478_package_entry = NULL;2479} else {2480_package_entry = PackageEntry::get_archived_entry(_package_entry);2481}2482}2483ArchivePtrMarker::mark_pointer((address**)&_package_entry);2484#endif2485}24862487void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,2488PackageEntry* pkg_entry, TRAPS) {2489// SystemDictionary::add_to_hierarchy() sets the init_state to loaded2490// before the InstanceKlass is added to the SystemDictionary. Make2491// sure the current state is <loaded.2492assert(!is_loaded(), "invalid init state");2493assert(!shared_loading_failed(), "Must not try to load failed class again");2494set_package(loader_data, pkg_entry, CHECK);2495Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);24962497Array<Method*>* methods = this->methods();2498int num_methods = methods->length();2499for (int index = 0; index < num_methods; ++index) {2500methods->at(index)->restore_unshareable_info(CHECK);2501}2502#if INCLUDE_JVMTI2503if (JvmtiExport::has_redefined_a_class()) {2504// Reinitialize vtable because RedefineClasses may have changed some2505// entries in this vtable for super classes so the CDS vtable might2506// point to old or obsolete entries. RedefineClasses doesn't fix up2507// vtables in the shared system dictionary, only the main one.2508// It also redefines the itable too so fix that too.2509// First fix any default methods that point to a super class that may2510// have been redefined.2511bool trace_name_printed = false;2512adjust_default_methods(&trace_name_printed);2513vtable().initialize_vtable();2514itable().initialize_itable();2515}2516#endif25172518// restore constant pool resolved references2519constants()->restore_unshareable_info(CHECK);25202521if (array_klasses() != NULL) {2522// To get a consistent list of classes we need MultiArray_lock to ensure2523// array classes aren't observed while they are being restored.2524MutexLocker ml(MultiArray_lock);2525// Array classes have null protection domain.2526// --> see ArrayKlass::complete_create_array_klass()2527array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);2528}25292530// Initialize current biased locking state.2531if (UseBiasedLocking && BiasedLocking::enabled()) {2532set_prototype_header(markWord::biased_locking_prototype());2533}25342535// Initialize @ValueBased class annotation2536if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {2537set_is_value_based();2538set_prototype_header(markWord::prototype());2539}2540}25412542// Check if a class or any of its supertypes has a version older than 50.2543// CDS will not perform verification of old classes during dump time because2544// without changing the old verifier, the verification constraint cannot be2545// retrieved during dump time.2546// Verification of archived old classes will be performed during run time.2547bool InstanceKlass::can_be_verified_at_dumptime() const {2548if (major_version() < 50 /*JAVA_6_VERSION*/) {2549return false;2550}2551if (java_super() != NULL && !java_super()->can_be_verified_at_dumptime()) {2552return false;2553}2554Array<InstanceKlass*>* interfaces = local_interfaces();2555int len = interfaces->length();2556for (int i = 0; i < len; i++) {2557if (!interfaces->at(i)->can_be_verified_at_dumptime()) {2558return false;2559}2560}2561return true;2562}25632564void InstanceKlass::set_shared_class_loader_type(s2 loader_type) {2565switch (loader_type) {2566case ClassLoader::BOOT_LOADER:2567_misc_flags |= _misc_is_shared_boot_class;2568break;2569case ClassLoader::PLATFORM_LOADER:2570_misc_flags |= _misc_is_shared_platform_class;2571break;2572case ClassLoader::APP_LOADER:2573_misc_flags |= _misc_is_shared_app_class;2574break;2575default:2576ShouldNotReachHere();2577break;2578}2579}25802581void InstanceKlass::assign_class_loader_type() {2582ClassLoaderData *cld = class_loader_data();2583if (cld->is_boot_class_loader_data()) {2584set_shared_class_loader_type(ClassLoader::BOOT_LOADER);2585}2586else if (cld->is_platform_class_loader_data()) {2587set_shared_class_loader_type(ClassLoader::PLATFORM_LOADER);2588}2589else if (cld->is_system_class_loader_data()) {2590set_shared_class_loader_type(ClassLoader::APP_LOADER);2591}2592}25932594#if INCLUDE_JVMTI2595static void clear_all_breakpoints(Method* m) {2596m->clear_all_breakpoints();2597}2598#endif25992600void InstanceKlass::unload_class(InstanceKlass* ik) {2601// Release dependencies.2602ik->dependencies().remove_all_dependents();26032604// notify the debugger2605if (JvmtiExport::should_post_class_unload()) {2606JvmtiExport::post_class_unload(ik);2607}26082609// notify ClassLoadingService of class unload2610ClassLoadingService::notify_class_unloaded(ik);26112612if (Arguments::is_dumping_archive()) {2613SystemDictionaryShared::remove_dumptime_info(ik);2614}26152616if (log_is_enabled(Info, class, unload)) {2617ResourceMark rm;2618log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));2619}26202621Events::log_class_unloading(Thread::current(), ik);26222623#if INCLUDE_JFR2624assert(ik != NULL, "invariant");2625EventClassUnload event;2626event.set_unloadedClass(ik);2627event.set_definingClassLoader(ik->class_loader_data());2628event.commit();2629#endif2630}26312632static void method_release_C_heap_structures(Method* m) {2633m->release_C_heap_structures();2634}26352636// Called also by InstanceKlass::deallocate_contents, with false for release_constant_pool.2637void InstanceKlass::release_C_heap_structures(bool release_constant_pool) {2638// Clean up C heap2639Klass::release_C_heap_structures();26402641// Deallocate and call destructors for MDO mutexes2642methods_do(method_release_C_heap_structures);26432644// Deallocate oop map cache2645if (_oop_map_cache != NULL) {2646delete _oop_map_cache;2647_oop_map_cache = NULL;2648}26492650// Deallocate JNI identifiers for jfieldIDs2651JNIid::deallocate(jni_ids());2652set_jni_ids(NULL);26532654jmethodID* jmeths = methods_jmethod_ids_acquire();2655if (jmeths != (jmethodID*)NULL) {2656release_set_methods_jmethod_ids(NULL);2657FreeHeap(jmeths);2658}26592660assert(_dep_context == NULL,2661"dependencies should already be cleaned");26622663#if INCLUDE_JVMTI2664// Deallocate breakpoint records2665if (breakpoints() != 0x0) {2666methods_do(clear_all_breakpoints);2667assert(breakpoints() == 0x0, "should have cleared breakpoints");2668}26692670// deallocate the cached class file2671if (_cached_class_file != NULL) {2672os::free(_cached_class_file);2673_cached_class_file = NULL;2674}2675#endif26762677FREE_C_HEAP_ARRAY(char, _source_debug_extension);26782679if (release_constant_pool) {2680constants()->release_C_heap_structures();2681}2682}26832684void InstanceKlass::set_source_debug_extension(const char* array, int length) {2685if (array == NULL) {2686_source_debug_extension = NULL;2687} else {2688// Adding one to the attribute length in order to store a null terminator2689// character could cause an overflow because the attribute length is2690// already coded with an u4 in the classfile, but in practice, it's2691// unlikely to happen.2692assert((length+1) > length, "Overflow checking");2693char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);2694for (int i = 0; i < length; i++) {2695sde[i] = array[i];2696}2697sde[length] = '\0';2698_source_debug_extension = sde;2699}2700}27012702const char* InstanceKlass::signature_name() const {2703int hash_len = 0;2704char hash_buf[40];27052706// Get the internal name as a c string2707const char* src = (const char*) (name()->as_C_string());2708const int src_length = (int)strlen(src);27092710char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);27112712// Add L as type indicator2713int dest_index = 0;2714dest[dest_index++] = JVM_SIGNATURE_CLASS;27152716// Add the actual class name2717for (int src_index = 0; src_index < src_length; ) {2718dest[dest_index++] = src[src_index++];2719}27202721if (is_hidden()) { // Replace the last '+' with a '.'.2722for (int index = (int)src_length; index > 0; index--) {2723if (dest[index] == '+') {2724dest[index] = JVM_SIGNATURE_DOT;2725break;2726}2727}2728}27292730// If we have a hash, append it2731for (int hash_index = 0; hash_index < hash_len; ) {2732dest[dest_index++] = hash_buf[hash_index++];2733}27342735// Add the semicolon and the NULL2736dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;2737dest[dest_index] = '\0';2738return dest;2739}27402741ModuleEntry* InstanceKlass::module() const {2742if (is_hidden() &&2743in_unnamed_package() &&2744class_loader_data()->has_class_mirror_holder()) {2745// For a non-strong hidden class defined to an unnamed package,2746// its (class held) CLD will not have an unnamed module created for it.2747// Two choices to find the correct ModuleEntry:2748// 1. If hidden class is within a nest, use nest host's module2749// 2. Find the unnamed module off from the class loader2750// For now option #2 is used since a nest host is not set until2751// after the instance class is created in jvm_lookup_define_class().2752if (class_loader_data()->is_boot_class_loader_data()) {2753return ClassLoaderData::the_null_class_loader_data()->unnamed_module();2754} else {2755oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());2756assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");2757return java_lang_Module::module_entry(module);2758}2759}27602761// Class is in a named package2762if (!in_unnamed_package()) {2763return _package_entry->module();2764}27652766// Class is in an unnamed package, return its loader's unnamed module2767return class_loader_data()->unnamed_module();2768}27692770void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {27712772// ensure java/ packages only loaded by boot or platform builtin loaders2773// not needed for shared class since CDS does not archive prohibited classes.2774if (!is_shared()) {2775check_prohibited_package(name(), loader_data, CHECK);2776}27772778if (is_shared() && _package_entry != NULL) {2779if (MetaspaceShared::use_full_module_graph() && _package_entry == pkg_entry) {2780// we can use the saved package2781assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be");2782return;2783} else {2784_package_entry = NULL;2785}2786}27872788// ClassLoader::package_from_class_name has already incremented the refcount of the symbol2789// it returns, so we need to decrement it when the current function exits.2790TempNewSymbol from_class_name =2791(pkg_entry != NULL) ? NULL : ClassLoader::package_from_class_name(name());27922793Symbol* pkg_name;2794if (pkg_entry != NULL) {2795pkg_name = pkg_entry->name();2796} else {2797pkg_name = from_class_name;2798}27992800if (pkg_name != NULL && loader_data != NULL) {28012802// Find in class loader's package entry table.2803_package_entry = pkg_entry != NULL ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);28042805// If the package name is not found in the loader's package2806// entry table, it is an indication that the package has not2807// been defined. Consider it defined within the unnamed module.2808if (_package_entry == NULL) {28092810if (!ModuleEntryTable::javabase_defined()) {2811// Before java.base is defined during bootstrapping, define all packages in2812// the java.base module. If a non-java.base package is erroneously placed2813// in the java.base module it will be caught later when java.base2814// is defined by ModuleEntryTable::verify_javabase_packages check.2815assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");2816_package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());2817} else {2818assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");2819_package_entry = loader_data->packages()->lookup(pkg_name,2820loader_data->unnamed_module());2821}28222823// A package should have been successfully created2824DEBUG_ONLY(ResourceMark rm(THREAD));2825assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",2826name()->as_C_string(), loader_data->loader_name_and_id());2827}28282829if (log_is_enabled(Debug, module)) {2830ResourceMark rm(THREAD);2831ModuleEntry* m = _package_entry->module();2832log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",2833external_name(),2834pkg_name->as_C_string(),2835loader_data->loader_name_and_id(),2836(m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));2837}2838} else {2839ResourceMark rm(THREAD);2840log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",2841external_name(),2842(loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",2843UNNAMED_MODULE);2844}2845}28462847// Function set_classpath_index ensures that for a non-null _package_entry2848// of the InstanceKlass, the entry is in the boot loader's package entry table.2849// It then sets the classpath_index in the package entry record.2850//2851// The classpath_index field is used to find the entry on the boot loader class2852// path for packages with classes loaded by the boot loader from -Xbootclasspath/a2853// in an unnamed module. It is also used to indicate (for all packages whose2854// classes are loaded by the boot loader) that at least one of the package's2855// classes has been loaded.2856void InstanceKlass::set_classpath_index(s2 path_index) {2857if (_package_entry != NULL) {2858DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)2859assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");2860assert(path_index != -1, "Unexpected classpath_index");2861_package_entry->set_classpath_index(path_index);2862}2863}28642865// different versions of is_same_class_package28662867bool InstanceKlass::is_same_class_package(const Klass* class2) const {2868oop classloader1 = this->class_loader();2869PackageEntry* classpkg1 = this->package();2870if (class2->is_objArray_klass()) {2871class2 = ObjArrayKlass::cast(class2)->bottom_klass();2872}28732874oop classloader2;2875PackageEntry* classpkg2;2876if (class2->is_instance_klass()) {2877classloader2 = class2->class_loader();2878classpkg2 = class2->package();2879} else {2880assert(class2->is_typeArray_klass(), "should be type array");2881classloader2 = NULL;2882classpkg2 = NULL;2883}28842885// Same package is determined by comparing class loader2886// and package entries. Both must be the same. This rule2887// applies even to classes that are defined in the unnamed2888// package, they still must have the same class loader.2889if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {2890return true;2891}28922893return false;2894}28952896// return true if this class and other_class are in the same package. Classloader2897// and classname information is enough to determine a class's package2898bool InstanceKlass::is_same_class_package(oop other_class_loader,2899const Symbol* other_class_name) const {2900if (class_loader() != other_class_loader) {2901return false;2902}2903if (name()->fast_compare(other_class_name) == 0) {2904return true;2905}29062907{2908ResourceMark rm;29092910bool bad_class_name = false;2911TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);2912if (bad_class_name) {2913return false;2914}2915// Check that package_from_class_name() returns NULL, not "", if there is no package.2916assert(other_pkg == NULL || other_pkg->utf8_length() > 0, "package name is empty string");29172918const Symbol* const this_package_name =2919this->package() != NULL ? this->package()->name() : NULL;29202921if (this_package_name == NULL || other_pkg == NULL) {2922// One of the two doesn't have a package. Only return true if the other2923// one also doesn't have a package.2924return this_package_name == other_pkg;2925}29262927// Check if package is identical2928return this_package_name->fast_compare(other_pkg) == 0;2929}2930}29312932static bool is_prohibited_package_slow(Symbol* class_name) {2933// Caller has ResourceMark2934int length;2935jchar* unicode = class_name->as_unicode(length);2936return (length >= 5 &&2937unicode[0] == 'j' &&2938unicode[1] == 'a' &&2939unicode[2] == 'v' &&2940unicode[3] == 'a' &&2941unicode[4] == '/');2942}29432944// Only boot and platform class loaders can define classes in "java/" packages.2945void InstanceKlass::check_prohibited_package(Symbol* class_name,2946ClassLoaderData* loader_data,2947TRAPS) {2948if (!loader_data->is_boot_class_loader_data() &&2949!loader_data->is_platform_class_loader_data() &&2950class_name != NULL && class_name->utf8_length() >= 5) {2951ResourceMark rm(THREAD);2952bool prohibited;2953const u1* base = class_name->base();2954if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {2955prohibited = is_prohibited_package_slow(class_name);2956} else {2957char* name = class_name->as_C_string();2958prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/');2959}2960if (prohibited) {2961TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);2962assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");2963char* name = pkg_name->as_C_string();2964const char* class_loader_name = loader_data->loader_name_and_id();2965StringUtils::replace_no_expand(name, "/", ".");2966const char* msg_text1 = "Class loader (instance of): ";2967const char* msg_text2 = " tried to load prohibited package name: ";2968size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;2969char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);2970jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);2971THROW_MSG(vmSymbols::java_lang_SecurityException(), message);2972}2973}2974return;2975}29762977bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {2978constantPoolHandle i_cp(THREAD, constants());2979for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {2980int ioff = iter.inner_class_info_index();2981if (ioff != 0) {2982// Check to see if the name matches the class we're looking for2983// before attempting to find the class.2984if (i_cp->klass_name_at_matches(this, ioff)) {2985Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);2986if (this == inner_klass) {2987*ooff = iter.outer_class_info_index();2988*noff = iter.inner_name_index();2989return true;2990}2991}2992}2993}2994return false;2995}29962997InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {2998InstanceKlass* outer_klass = NULL;2999*inner_is_member = false;3000int ooff = 0, noff = 0;3001bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);3002if (has_inner_classes_attr) {3003constantPoolHandle i_cp(THREAD, constants());3004if (ooff != 0) {3005Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);3006if (!ok->is_instance_klass()) {3007// If the outer class is not an instance klass then it cannot have3008// declared any inner classes.3009ResourceMark rm(THREAD);3010Exceptions::fthrow(3011THREAD_AND_LOCATION,3012vmSymbols::java_lang_IncompatibleClassChangeError(),3013"%s and %s disagree on InnerClasses attribute",3014ok->external_name(),3015external_name());3016return NULL;3017}3018outer_klass = InstanceKlass::cast(ok);3019*inner_is_member = true;3020}3021if (NULL == outer_klass) {3022// It may be a local class; try for that.3023int encl_method_class_idx = enclosing_method_class_index();3024if (encl_method_class_idx != 0) {3025Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);3026outer_klass = InstanceKlass::cast(ok);3027*inner_is_member = false;3028}3029}3030}30313032// If no inner class attribute found for this class.3033if (NULL == outer_klass) return NULL;30343035// Throws an exception if outer klass has not declared k as an inner klass3036// We need evidence that each klass knows about the other, or else3037// the system could allow a spoof of an inner class to gain access rights.3038Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);3039return outer_klass;3040}30413042jint InstanceKlass::compute_modifier_flags() const {3043jint access = access_flags().as_int();30443045// But check if it happens to be member class.3046InnerClassesIterator iter(this);3047for (; !iter.done(); iter.next()) {3048int ioff = iter.inner_class_info_index();3049// Inner class attribute can be zero, skip it.3050// Strange but true: JVM spec. allows null inner class refs.3051if (ioff == 0) continue;30523053// only look at classes that are already loaded3054// since we are looking for the flags for our self.3055Symbol* inner_name = constants()->klass_name_at(ioff);3056if (name() == inner_name) {3057// This is really a member class.3058access = iter.inner_access_flags();3059break;3060}3061}3062// Remember to strip ACC_SUPER bit3063return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;3064}30653066jint InstanceKlass::jvmti_class_status() const {3067jint result = 0;30683069if (is_linked()) {3070result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;3071}30723073if (is_initialized()) {3074assert(is_linked(), "Class status is not consistent");3075result |= JVMTI_CLASS_STATUS_INITIALIZED;3076}3077if (is_in_error_state()) {3078result |= JVMTI_CLASS_STATUS_ERROR;3079}3080return result;3081}30823083Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {3084bool implements_interface; // initialized by method_at_itable_or_null3085Method* m = method_at_itable_or_null(holder, index,3086implements_interface); // out parameter3087if (m != NULL) {3088assert(implements_interface, "sanity");3089return m;3090} else if (implements_interface) {3091// Throw AbstractMethodError since corresponding itable slot is empty.3092THROW_NULL(vmSymbols::java_lang_AbstractMethodError());3093} else {3094// If the interface isn't implemented by the receiver class,3095// the VM should throw IncompatibleClassChangeError.3096ResourceMark rm(THREAD);3097stringStream ss;3098bool same_module = (module() == holder->module());3099ss.print("Receiver class %s does not implement "3100"the interface %s defining the method to be called "3101"(%s%s%s)",3102external_name(), holder->external_name(),3103(same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),3104(same_module) ? "" : "; ",3105(same_module) ? "" : holder->class_in_module_of_loader());3106THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());3107}3108}31093110Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) {3111klassItable itable(this);3112for (int i = 0; i < itable.size_offset_table(); i++) {3113itableOffsetEntry* offset_entry = itable.offset_entry(i);3114if (offset_entry->interface_klass() == holder) {3115implements_interface = true;3116itableMethodEntry* ime = offset_entry->first_method_entry(this);3117Method* m = ime[index].method();3118return m;3119}3120}3121implements_interface = false;3122return NULL; // offset entry not found3123}31243125int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) {3126assert(is_linked(), "required");3127assert(intf_method->method_holder()->is_interface(), "not an interface method");3128assert(is_subtype_of(intf_method->method_holder()), "interface not implemented");31293130int vtable_index = Method::invalid_vtable_index;3131Symbol* name = intf_method->name();3132Symbol* signature = intf_method->signature();31333134// First check in default method array3135if (!intf_method->is_abstract() && default_methods() != NULL) {3136int index = find_method_index(default_methods(),3137name, signature,3138Klass::OverpassLookupMode::find,3139Klass::StaticLookupMode::find,3140Klass::PrivateLookupMode::find);3141if (index >= 0) {3142vtable_index = default_vtable_indices()->at(index);3143}3144}3145if (vtable_index == Method::invalid_vtable_index) {3146// get vtable_index for miranda methods3147klassVtable vt = vtable();3148vtable_index = vt.index_of_miranda(name, signature);3149}3150return vtable_index;3151}31523153#if INCLUDE_JVMTI3154// update default_methods for redefineclasses for methods that are3155// not yet in the vtable due to concurrent subclass define and superinterface3156// redefinition3157// Note: those in the vtable, should have been updated via adjust_method_entries3158void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {3159// search the default_methods for uses of either obsolete or EMCP methods3160if (default_methods() != NULL) {3161for (int index = 0; index < default_methods()->length(); index ++) {3162Method* old_method = default_methods()->at(index);3163if (old_method == NULL || !old_method->is_old()) {3164continue; // skip uninteresting entries3165}3166assert(!old_method->is_deleted(), "default methods may not be deleted");3167Method* new_method = old_method->get_new_method();3168default_methods()->at_put(index, new_method);31693170if (log_is_enabled(Info, redefine, class, update)) {3171ResourceMark rm;3172if (!(*trace_name_printed)) {3173log_info(redefine, class, update)3174("adjust: klassname=%s default methods from name=%s",3175external_name(), old_method->method_holder()->external_name());3176*trace_name_printed = true;3177}3178log_debug(redefine, class, update, vtables)3179("default method update: %s(%s) ",3180new_method->name()->as_C_string(), new_method->signature()->as_C_string());3181}3182}3183}3184}3185#endif // INCLUDE_JVMTI31863187// On-stack replacement stuff3188void InstanceKlass::add_osr_nmethod(nmethod* n) {3189assert_lock_strong(CompiledMethod_lock);3190#ifndef PRODUCT3191nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);3192assert(prev == NULL || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),3193"redundant OSR recompilation detected. memory leak in CodeCache!");3194#endif3195// only one compilation can be active3196assert(n->is_osr_method(), "wrong kind of nmethod");3197n->set_osr_link(osr_nmethods_head());3198set_osr_nmethods_head(n);3199// Raise the highest osr level if necessary3200n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level()));32013202// Get rid of the osr methods for the same bci that have lower levels.3203for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {3204nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);3205if (inv != NULL && inv->is_in_use()) {3206inv->make_not_entrant();3207}3208}3209}32103211// Remove osr nmethod from the list. Return true if found and removed.3212bool InstanceKlass::remove_osr_nmethod(nmethod* n) {3213// This is a short non-blocking critical region, so the no safepoint check is ok.3214MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock3215, Mutex::_no_safepoint_check_flag);3216assert(n->is_osr_method(), "wrong kind of nmethod");3217nmethod* last = NULL;3218nmethod* cur = osr_nmethods_head();3219int max_level = CompLevel_none; // Find the max comp level excluding n3220Method* m = n->method();3221// Search for match3222bool found = false;3223while(cur != NULL && cur != n) {3224if (m == cur->method()) {3225// Find max level before n3226max_level = MAX2(max_level, cur->comp_level());3227}3228last = cur;3229cur = cur->osr_link();3230}3231nmethod* next = NULL;3232if (cur == n) {3233found = true;3234next = cur->osr_link();3235if (last == NULL) {3236// Remove first element3237set_osr_nmethods_head(next);3238} else {3239last->set_osr_link(next);3240}3241}3242n->set_osr_link(NULL);3243cur = next;3244while (cur != NULL) {3245// Find max level after n3246if (m == cur->method()) {3247max_level = MAX2(max_level, cur->comp_level());3248}3249cur = cur->osr_link();3250}3251m->set_highest_osr_comp_level(max_level);3252return found;3253}32543255int InstanceKlass::mark_osr_nmethods(const Method* m) {3256MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,3257Mutex::_no_safepoint_check_flag);3258nmethod* osr = osr_nmethods_head();3259int found = 0;3260while (osr != NULL) {3261assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3262if (osr->method() == m) {3263osr->mark_for_deoptimization();3264found++;3265}3266osr = osr->osr_link();3267}3268return found;3269}32703271nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {3272MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,3273Mutex::_no_safepoint_check_flag);3274nmethod* osr = osr_nmethods_head();3275nmethod* best = NULL;3276while (osr != NULL) {3277assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3278// There can be a time when a c1 osr method exists but we are waiting3279// for a c2 version. When c2 completes its osr nmethod we will trash3280// the c1 version and only be able to find the c2 version. However3281// while we overflow in the c1 code at back branches we don't want to3282// try and switch to the same code as we are already running32833284if (osr->method() == m &&3285(bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {3286if (match_level) {3287if (osr->comp_level() == comp_level) {3288// Found a match - return it.3289return osr;3290}3291} else {3292if (best == NULL || (osr->comp_level() > best->comp_level())) {3293if (osr->comp_level() == CompilationPolicy::highest_compile_level()) {3294// Found the best possible - return it.3295return osr;3296}3297best = osr;3298}3299}3300}3301osr = osr->osr_link();3302}33033304assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");3305if (best != NULL && best->comp_level() >= comp_level) {3306return best;3307}3308return NULL;3309}33103311// -----------------------------------------------------------------------------------------------------3312// Printing33133314#define BULLET " - "33153316static const char* state_names[] = {3317"allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"3318};33193320static void print_vtable(intptr_t* start, int len, outputStream* st) {3321for (int i = 0; i < len; i++) {3322intptr_t e = start[i];3323st->print("%d : " INTPTR_FORMAT, i, e);3324if (MetaspaceObj::is_valid((Metadata*)e)) {3325st->print(" ");3326((Metadata*)e)->print_value_on(st);3327}3328st->cr();3329}3330}33313332static void print_vtable(vtableEntry* start, int len, outputStream* st) {3333return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);3334}33353336void InstanceKlass::print_on(outputStream* st) const {3337assert(is_klass(), "must be klass");3338Klass::print_on(st);33393340st->print(BULLET"instance size: %d", size_helper()); st->cr();3341st->print(BULLET"klass size: %d", size()); st->cr();3342st->print(BULLET"access: "); access_flags().print_on(st); st->cr();3343st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]);3344st->print(BULLET"name: "); name()->print_value_on(st); st->cr();3345st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();3346st->print(BULLET"sub: ");3347Klass* sub = subklass();3348int n;3349for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {3350if (n < MaxSubklassPrintSize) {3351sub->print_value_on(st);3352st->print(" ");3353}3354}3355if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);3356st->cr();33573358if (is_interface()) {3359st->print_cr(BULLET"nof implementors: %d", nof_implementors());3360if (nof_implementors() == 1) {3361st->print_cr(BULLET"implementor: ");3362st->print(" ");3363implementor()->print_value_on(st);3364st->cr();3365}3366}33673368st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();3369st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();3370if (Verbose || WizardMode) {3371Array<Method*>* method_array = methods();3372for (int i = 0; i < method_array->length(); i++) {3373st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3374}3375}3376st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();3377st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();3378if (Verbose && default_methods() != NULL) {3379Array<Method*>* method_array = default_methods();3380for (int i = 0; i < method_array->length(); i++) {3381st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3382}3383}3384if (default_vtable_indices() != NULL) {3385st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr();3386}3387st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();3388st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();3389st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();3390if (class_loader_data() != NULL) {3391st->print(BULLET"class loader data: ");3392class_loader_data()->print_value_on(st);3393st->cr();3394}3395if (source_file_name() != NULL) {3396st->print(BULLET"source file: ");3397source_file_name()->print_value_on(st);3398st->cr();3399}3400if (source_debug_extension() != NULL) {3401st->print(BULLET"source debug extension: ");3402st->print("%s", source_debug_extension());3403st->cr();3404}3405st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr();3406st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr();3407st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr();3408st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr();3409{3410bool have_pv = false;3411// previous versions are linked together through the InstanceKlass3412for (InstanceKlass* pv_node = previous_versions();3413pv_node != NULL;3414pv_node = pv_node->previous_versions()) {3415if (!have_pv)3416st->print(BULLET"previous version: ");3417have_pv = true;3418pv_node->constants()->print_value_on(st);3419}3420if (have_pv) st->cr();3421}34223423if (generic_signature() != NULL) {3424st->print(BULLET"generic signature: ");3425generic_signature()->print_value_on(st);3426st->cr();3427}3428st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();3429st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();3430if (record_components() != NULL) {3431st->print(BULLET"record components: "); record_components()->print_value_on(st); st->cr();3432}3433st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();3434if (java_mirror() != NULL) {3435st->print(BULLET"java mirror: ");3436java_mirror()->print_value_on(st);3437st->cr();3438} else {3439st->print_cr(BULLET"java mirror: NULL");3440}3441st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();3442if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);3443st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();3444if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);3445st->print_cr(BULLET"---- static fields (%d words):", static_field_size());3446FieldPrinter print_static_field(st);3447((InstanceKlass*)this)->do_local_static_fields(&print_static_field);3448st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());3449FieldPrinter print_nonstatic_field(st);3450InstanceKlass* ik = const_cast<InstanceKlass*>(this);3451ik->do_nonstatic_fields(&print_nonstatic_field);34523453st->print(BULLET"non-static oop maps: ");3454OopMapBlock* map = start_of_nonstatic_oop_maps();3455OopMapBlock* end_map = map + nonstatic_oop_map_count();3456while (map < end_map) {3457st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));3458map++;3459}3460st->cr();3461}34623463void InstanceKlass::print_value_on(outputStream* st) const {3464assert(is_klass(), "must be klass");3465if (Verbose || WizardMode) access_flags().print_on(st);3466name()->print_value_on(st);3467}34683469void FieldPrinter::do_field(fieldDescriptor* fd) {3470_st->print(BULLET);3471if (_obj == NULL) {3472fd->print_on(_st);3473_st->cr();3474} else {3475fd->print_on_for(_st, _obj);3476_st->cr();3477}3478}347934803481void InstanceKlass::oop_print_on(oop obj, outputStream* st) {3482Klass::oop_print_on(obj, st);34833484if (this == vmClasses::String_klass()) {3485typeArrayOop value = java_lang_String::value(obj);3486juint length = java_lang_String::length(obj);3487if (value != NULL &&3488value->is_typeArray() &&3489length <= (juint) value->length()) {3490st->print(BULLET"string: ");3491java_lang_String::print(obj, st);3492st->cr();3493if (!WizardMode) return; // that is enough3494}3495}34963497st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));3498FieldPrinter print_field(st, obj);3499do_nonstatic_fields(&print_field);35003501if (this == vmClasses::Class_klass()) {3502st->print(BULLET"signature: ");3503java_lang_Class::print_signature(obj, st);3504st->cr();3505Klass* mirrored_klass = java_lang_Class::as_Klass(obj);3506st->print(BULLET"fake entry for mirror: ");3507Metadata::print_value_on_maybe_null(st, mirrored_klass);3508st->cr();3509Klass* array_klass = java_lang_Class::array_klass_acquire(obj);3510st->print(BULLET"fake entry for array: ");3511Metadata::print_value_on_maybe_null(st, array_klass);3512st->cr();3513st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));3514st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));3515Klass* real_klass = java_lang_Class::as_Klass(obj);3516if (real_klass != NULL && real_klass->is_instance_klass()) {3517InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);3518}3519} else if (this == vmClasses::MethodType_klass()) {3520st->print(BULLET"signature: ");3521java_lang_invoke_MethodType::print_signature(obj, st);3522st->cr();3523}3524}35253526#ifndef PRODUCT35273528bool InstanceKlass::verify_itable_index(int i) {3529int method_count = klassItable::method_count_for_interface(this);3530assert(i >= 0 && i < method_count, "index out of bounds");3531return true;3532}35333534#endif //PRODUCT35353536void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {3537st->print("a ");3538name()->print_value_on(st);3539obj->print_address_on(st);3540if (this == vmClasses::String_klass()3541&& java_lang_String::value(obj) != NULL) {3542ResourceMark rm;3543int len = java_lang_String::length(obj);3544int plen = (len < 24 ? len : 12);3545char* str = java_lang_String::as_utf8_string(obj, 0, plen);3546st->print(" = \"%s\"", str);3547if (len > plen)3548st->print("...[%d]", len);3549} else if (this == vmClasses::Class_klass()) {3550Klass* k = java_lang_Class::as_Klass(obj);3551st->print(" = ");3552if (k != NULL) {3553k->print_value_on(st);3554} else {3555const char* tname = type2name(java_lang_Class::primitive_type(obj));3556st->print("%s", tname ? tname : "type?");3557}3558} else if (this == vmClasses::MethodType_klass()) {3559st->print(" = ");3560java_lang_invoke_MethodType::print_signature(obj, st);3561} else if (java_lang_boxing_object::is_instance(obj)) {3562st->print(" = ");3563java_lang_boxing_object::print(obj, st);3564} else if (this == vmClasses::LambdaForm_klass()) {3565oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);3566if (vmentry != NULL) {3567st->print(" => ");3568vmentry->print_value_on(st);3569}3570} else if (this == vmClasses::MemberName_klass()) {3571Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);3572if (vmtarget != NULL) {3573st->print(" = ");3574vmtarget->print_value_on(st);3575} else {3576oop clazz = java_lang_invoke_MemberName::clazz(obj);3577oop name = java_lang_invoke_MemberName::name(obj);3578if (clazz != NULL) {3579clazz->print_value_on(st);3580} else {3581st->print("NULL");3582}3583st->print(".");3584if (name != NULL) {3585name->print_value_on(st);3586} else {3587st->print("NULL");3588}3589}3590}3591}35923593const char* InstanceKlass::internal_name() const {3594return external_name();3595}35963597void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,3598const ModuleEntry* module_entry,3599const ClassFileStream* cfs) const {3600log_to_classlist();36013602if (!log_is_enabled(Info, class, load)) {3603return;3604}36053606ResourceMark rm;3607LogMessage(class, load) msg;3608stringStream info_stream;36093610// Name and class hierarchy info3611info_stream.print("%s", external_name());36123613// Source3614if (cfs != NULL) {3615if (cfs->source() != NULL) {3616const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();3617if (module_name != NULL) {3618// When the boot loader created the stream, it didn't know the module name3619// yet. Let's format it now.3620if (cfs->from_boot_loader_modules_image()) {3621info_stream.print(" source: jrt:/%s", module_name);3622} else {3623info_stream.print(" source: %s", cfs->source());3624}3625} else {3626info_stream.print(" source: %s", cfs->source());3627}3628} else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {3629Thread* current = Thread::current();3630Klass* caller = current->is_Java_thread() ?3631current->as_Java_thread()->security_get_caller_class(1):3632NULL;3633// caller can be NULL, for example, during a JVMTI VM_Init hook3634if (caller != NULL) {3635info_stream.print(" source: instance of %s", caller->external_name());3636} else {3637// source is unknown3638}3639} else {3640oop class_loader = loader_data->class_loader();3641info_stream.print(" source: %s", class_loader->klass()->external_name());3642}3643} else {3644assert(this->is_shared(), "must be");3645if (MetaspaceShared::is_shared_dynamic((void*)this)) {3646info_stream.print(" source: shared objects file (top)");3647} else {3648info_stream.print(" source: shared objects file");3649}3650}36513652msg.info("%s", info_stream.as_string());36533654if (log_is_enabled(Debug, class, load)) {3655stringStream debug_stream;36563657// Class hierarchy info3658debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,3659p2i(this), p2i(superklass()));36603661// Interfaces3662if (local_interfaces() != NULL && local_interfaces()->length() > 0) {3663debug_stream.print(" interfaces:");3664int length = local_interfaces()->length();3665for (int i = 0; i < length; i++) {3666debug_stream.print(" " INTPTR_FORMAT,3667p2i(InstanceKlass::cast(local_interfaces()->at(i))));3668}3669}36703671// Class loader3672debug_stream.print(" loader: [");3673loader_data->print_value_on(&debug_stream);3674debug_stream.print("]");36753676// Classfile checksum3677if (cfs) {3678debug_stream.print(" bytes: %d checksum: %08x",3679cfs->length(),3680ClassLoader::crc32(0, (const char*)cfs->buffer(),3681cfs->length()));3682}36833684msg.debug("%s", debug_stream.as_string());3685}3686}36873688// Verification36893690class VerifyFieldClosure: public BasicOopIterateClosure {3691protected:3692template <class T> void do_oop_work(T* p) {3693oop obj = RawAccess<>::oop_load(p);3694if (!oopDesc::is_oop_or_null(obj)) {3695tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));3696Universe::print_on(tty);3697guarantee(false, "boom");3698}3699}3700public:3701virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }3702virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }3703};37043705void InstanceKlass::verify_on(outputStream* st) {3706#ifndef PRODUCT3707// Avoid redundant verifies, this really should be in product.3708if (_verify_count == Universe::verify_count()) return;3709_verify_count = Universe::verify_count();3710#endif37113712// Verify Klass3713Klass::verify_on(st);37143715// Verify that klass is present in ClassLoaderData3716guarantee(class_loader_data()->contains_klass(this),3717"this class isn't found in class loader data");37183719// Verify vtables3720if (is_linked()) {3721// $$$ This used to be done only for m/s collections. Doing it3722// always seemed a valid generalization. (DLD -- 6/00)3723vtable().verify(st);3724}37253726// Verify first subklass3727if (subklass() != NULL) {3728guarantee(subklass()->is_klass(), "should be klass");3729}37303731// Verify siblings3732Klass* super = this->super();3733Klass* sib = next_sibling();3734if (sib != NULL) {3735if (sib == this) {3736fatal("subclass points to itself " PTR_FORMAT, p2i(sib));3737}37383739guarantee(sib->is_klass(), "should be klass");3740guarantee(sib->super() == super, "siblings should have same superklass");3741}37423743// Verify local interfaces3744if (local_interfaces()) {3745Array<InstanceKlass*>* local_interfaces = this->local_interfaces();3746for (int j = 0; j < local_interfaces->length(); j++) {3747InstanceKlass* e = local_interfaces->at(j);3748guarantee(e->is_klass() && e->is_interface(), "invalid local interface");3749}3750}37513752// Verify transitive interfaces3753if (transitive_interfaces() != NULL) {3754Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();3755for (int j = 0; j < transitive_interfaces->length(); j++) {3756InstanceKlass* e = transitive_interfaces->at(j);3757guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");3758}3759}37603761// Verify methods3762if (methods() != NULL) {3763Array<Method*>* methods = this->methods();3764for (int j = 0; j < methods->length(); j++) {3765guarantee(methods->at(j)->is_method(), "non-method in methods array");3766}3767for (int j = 0; j < methods->length() - 1; j++) {3768Method* m1 = methods->at(j);3769Method* m2 = methods->at(j + 1);3770guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3771}3772}37733774// Verify method ordering3775if (method_ordering() != NULL) {3776Array<int>* method_ordering = this->method_ordering();3777int length = method_ordering->length();3778if (JvmtiExport::can_maintain_original_method_order() ||3779((UseSharedSpaces || Arguments::is_dumping_archive()) && length != 0)) {3780guarantee(length == methods()->length(), "invalid method ordering length");3781jlong sum = 0;3782for (int j = 0; j < length; j++) {3783int original_index = method_ordering->at(j);3784guarantee(original_index >= 0, "invalid method ordering index");3785guarantee(original_index < length, "invalid method ordering index");3786sum += original_index;3787}3788// Verify sum of indices 0,1,...,length-13789guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");3790} else {3791guarantee(length == 0, "invalid method ordering length");3792}3793}37943795// Verify default methods3796if (default_methods() != NULL) {3797Array<Method*>* methods = this->default_methods();3798for (int j = 0; j < methods->length(); j++) {3799guarantee(methods->at(j)->is_method(), "non-method in methods array");3800}3801for (int j = 0; j < methods->length() - 1; j++) {3802Method* m1 = methods->at(j);3803Method* m2 = methods->at(j + 1);3804guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3805}3806}38073808// Verify JNI static field identifiers3809if (jni_ids() != NULL) {3810jni_ids()->verify(this);3811}38123813// Verify other fields3814if (constants() != NULL) {3815guarantee(constants()->is_constantPool(), "should be constant pool");3816}3817}38183819void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {3820Klass::oop_verify_on(obj, st);3821VerifyFieldClosure blk;3822obj->oop_iterate(&blk);3823}382438253826// JNIid class for jfieldIDs only3827// Note to reviewers:3828// These JNI functions are just moved over to column 1 and not changed3829// in the compressed oops workspace.3830JNIid::JNIid(Klass* holder, int offset, JNIid* next) {3831_holder = holder;3832_offset = offset;3833_next = next;3834debug_only(_is_static_field_id = false;)3835}383638373838JNIid* JNIid::find(int offset) {3839JNIid* current = this;3840while (current != NULL) {3841if (current->offset() == offset) return current;3842current = current->next();3843}3844return NULL;3845}38463847void JNIid::deallocate(JNIid* current) {3848while (current != NULL) {3849JNIid* next = current->next();3850delete current;3851current = next;3852}3853}385438553856void JNIid::verify(Klass* holder) {3857int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();3858int end_field_offset;3859end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);38603861JNIid* current = this;3862while (current != NULL) {3863guarantee(current->holder() == holder, "Invalid klass in JNIid");3864#ifdef ASSERT3865int o = current->offset();3866if (current->is_static_field_id()) {3867guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");3868}3869#endif3870current = current->next();3871}3872}38733874void InstanceKlass::set_init_state(ClassState state) {3875#ifdef ASSERT3876bool good_state = is_shared() ? (_init_state <= state)3877: (_init_state < state);3878assert(good_state || state == allocated, "illegal state transition");3879#endif3880assert(_init_thread == NULL, "should be cleared before state change");3881_init_state = (u1)state;3882}38833884#if INCLUDE_JVMTI38853886// RedefineClasses() support for previous versions38873888// Globally, there is at least one previous version of a class to walk3889// during class unloading, which is saved because old methods in the class3890// are still running. Otherwise the previous version list is cleaned up.3891bool InstanceKlass::_has_previous_versions = false;38923893// Returns true if there are previous versions of a class for class3894// unloading only. Also resets the flag to false. purge_previous_version3895// will set the flag to true if there are any left, i.e., if there's any3896// work to do for next time. This is to avoid the expensive code cache3897// walk in CLDG::clean_deallocate_lists().3898bool InstanceKlass::has_previous_versions_and_reset() {3899bool ret = _has_previous_versions;3900log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",3901ret ? "true" : "false");3902_has_previous_versions = false;3903return ret;3904}39053906// Purge previous versions before adding new previous versions of the class and3907// during class unloading.3908void InstanceKlass::purge_previous_version_list() {3909assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");3910assert(has_been_redefined(), "Should only be called for main class");39113912// Quick exit.3913if (previous_versions() == NULL) {3914return;3915}39163917// This klass has previous versions so see what we can cleanup3918// while it is safe to do so.39193920int deleted_count = 0; // leave debugging breadcrumbs3921int live_count = 0;3922ClassLoaderData* loader_data = class_loader_data();3923assert(loader_data != NULL, "should never be null");39243925ResourceMark rm;3926log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());39273928// previous versions are linked together through the InstanceKlass3929InstanceKlass* pv_node = previous_versions();3930InstanceKlass* last = this;3931int version = 0;39323933// check the previous versions list3934for (; pv_node != NULL; ) {39353936ConstantPool* pvcp = pv_node->constants();3937assert(pvcp != NULL, "cp ref was unexpectedly cleared");39383939if (!pvcp->on_stack()) {3940// If the constant pool isn't on stack, none of the methods3941// are executing. Unlink this previous_version.3942// The previous version InstanceKlass is on the ClassLoaderData deallocate list3943// so will be deallocated during the next phase of class unloading.3944log_trace(redefine, class, iklass, purge)3945("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));3946// Unlink from previous version list.3947assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");3948InstanceKlass* next = pv_node->previous_versions();3949pv_node->link_previous_versions(NULL); // point next to NULL3950last->link_previous_versions(next);3951// Delete this node directly. Nothing is referring to it and we don't3952// want it to increase the counter for metadata to delete in CLDG.3953MetadataFactory::free_metadata(loader_data, pv_node);3954pv_node = next;3955deleted_count++;3956version++;3957continue;3958} else {3959log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));3960assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");3961guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");3962live_count++;3963// found a previous version for next time we do class unloading3964_has_previous_versions = true;3965}39663967// next previous version3968last = pv_node;3969pv_node = pv_node->previous_versions();3970version++;3971}3972log_trace(redefine, class, iklass, purge)3973("previous version stats: live=%d, deleted=%d", live_count, deleted_count);3974}39753976void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,3977int emcp_method_count) {3978int obsolete_method_count = old_methods->length() - emcp_method_count;39793980if (emcp_method_count != 0 && obsolete_method_count != 0 &&3981_previous_versions != NULL) {3982// We have a mix of obsolete and EMCP methods so we have to3983// clear out any matching EMCP method entries the hard way.3984int local_count = 0;3985for (int i = 0; i < old_methods->length(); i++) {3986Method* old_method = old_methods->at(i);3987if (old_method->is_obsolete()) {3988// only obsolete methods are interesting3989Symbol* m_name = old_method->name();3990Symbol* m_signature = old_method->signature();39913992// previous versions are linked together through the InstanceKlass3993int j = 0;3994for (InstanceKlass* prev_version = _previous_versions;3995prev_version != NULL;3996prev_version = prev_version->previous_versions(), j++) {39973998Array<Method*>* method_refs = prev_version->methods();3999for (int k = 0; k < method_refs->length(); k++) {4000Method* method = method_refs->at(k);40014002if (!method->is_obsolete() &&4003method->name() == m_name &&4004method->signature() == m_signature) {4005// The current RedefineClasses() call has made all EMCP4006// versions of this method obsolete so mark it as obsolete4007log_trace(redefine, class, iklass, add)4008("%s(%s): flush obsolete method @%d in version @%d",4009m_name->as_C_string(), m_signature->as_C_string(), k, j);40104011method->set_is_obsolete();4012break;4013}4014}40154016// The previous loop may not find a matching EMCP method, but4017// that doesn't mean that we can optimize and not go any4018// further back in the PreviousVersion generations. The EMCP4019// method for this generation could have already been made obsolete,4020// but there still may be an older EMCP method that has not4021// been made obsolete.4022}40234024if (++local_count >= obsolete_method_count) {4025// no more obsolete methods so bail out now4026break;4027}4028}4029}4030}4031}40324033// Save the scratch_class as the previous version if any of the methods are running.4034// The previous_versions are used to set breakpoints in EMCP methods and they are4035// also used to clean MethodData links to redefined methods that are no longer running.4036void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,4037int emcp_method_count) {4038assert(Thread::current()->is_VM_thread(),4039"only VMThread can add previous versions");40404041ResourceMark rm;4042log_trace(redefine, class, iklass, add)4043("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);40444045// Clean out old previous versions for this class4046purge_previous_version_list();40474048// Mark newly obsolete methods in remaining previous versions. An EMCP method from4049// a previous redefinition may be made obsolete by this redefinition.4050Array<Method*>* old_methods = scratch_class->methods();4051mark_newly_obsolete_methods(old_methods, emcp_method_count);40524053// If the constant pool for this previous version of the class4054// is not marked as being on the stack, then none of the methods4055// in this previous version of the class are on the stack so4056// we don't need to add this as a previous version.4057ConstantPool* cp_ref = scratch_class->constants();4058if (!cp_ref->on_stack()) {4059log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");4060scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);4061return;4062}40634064// Add previous version if any methods are still running.4065// Set has_previous_version flag for processing during class unloading.4066_has_previous_versions = true;4067log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");4068assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");4069scratch_class->link_previous_versions(previous_versions());4070link_previous_versions(scratch_class);4071} // end add_previous_version()40724073#endif // INCLUDE_JVMTI40744075Method* InstanceKlass::method_with_idnum(int idnum) {4076Method* m = NULL;4077if (idnum < methods()->length()) {4078m = methods()->at(idnum);4079}4080if (m == NULL || m->method_idnum() != idnum) {4081for (int index = 0; index < methods()->length(); ++index) {4082m = methods()->at(index);4083if (m->method_idnum() == idnum) {4084return m;4085}4086}4087// None found, return null for the caller to handle.4088return NULL;4089}4090return m;4091}409240934094Method* InstanceKlass::method_with_orig_idnum(int idnum) {4095if (idnum >= methods()->length()) {4096return NULL;4097}4098Method* m = methods()->at(idnum);4099if (m != NULL && m->orig_method_idnum() == idnum) {4100return m;4101}4102// Obsolete method idnum does not match the original idnum4103for (int index = 0; index < methods()->length(); ++index) {4104m = methods()->at(index);4105if (m->orig_method_idnum() == idnum) {4106return m;4107}4108}4109// None found, return null for the caller to handle.4110return NULL;4111}411241134114Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {4115InstanceKlass* holder = get_klass_version(version);4116if (holder == NULL) {4117return NULL; // The version of klass is gone, no method is found4118}4119Method* method = holder->method_with_orig_idnum(idnum);4120return method;4121}41224123#if INCLUDE_JVMTI4124JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {4125return _cached_class_file;4126}41274128jint InstanceKlass::get_cached_class_file_len() {4129return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);4130}41314132unsigned char * InstanceKlass::get_cached_class_file_bytes() {4133return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);4134}4135#endif41364137bool InstanceKlass::is_shareable() const {4138#if INCLUDE_CDS4139ClassLoaderData* loader_data = class_loader_data();4140if (!SystemDictionaryShared::is_sharing_possible(loader_data)) {4141return false;4142}41434144if (is_hidden()) {4145return false;4146}41474148if (module()->is_patched()) {4149return false;4150}41514152return true;4153#else4154return false;4155#endif4156}41574158void InstanceKlass::log_to_classlist() const {4159#if INCLUDE_CDS4160ResourceMark rm;4161if (ClassListWriter::is_enabled()) {4162if (!ClassLoader::has_jrt_entry()) {4163warning("DumpLoadedClassList and CDS are not supported in exploded build");4164DumpLoadedClassList = NULL;4165return;4166}4167if (is_shareable()) {4168ClassListWriter w;4169w.stream()->print_cr("%s", name()->as_C_string());4170w.stream()->flush();4171}4172}4173#endif // INCLUDE_CDS4174}41754176// Make a step iterating over the class hierarchy under the root class.4177// Skips subclasses if requested.4178void ClassHierarchyIterator::next() {4179assert(_current != NULL, "required");4180if (_visit_subclasses && _current->subklass() != NULL) {4181_current = _current->subklass();4182return; // visit next subclass4183}4184_visit_subclasses = true; // reset4185while (_current->next_sibling() == NULL && _current != _root) {4186_current = _current->superklass(); // backtrack; no more sibling subclasses left4187}4188if (_current == _root) {4189// Iteration is over (back at root after backtracking). Invalidate the iterator.4190_current = NULL;4191return;4192}4193_current = _current->next_sibling();4194return; // visit next sibling subclass4195}419641974198