Path: blob/master/src/hotspot/share/oops/instanceKlass.cpp
40951 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.591release_C_heap_structures_internal();592593deallocate_methods(loader_data, methods());594set_methods(NULL);595596deallocate_record_components(loader_data, record_components());597set_record_components(NULL);598599if (method_ordering() != NULL &&600method_ordering() != Universe::the_empty_int_array() &&601!method_ordering()->is_shared()) {602MetadataFactory::free_array<int>(loader_data, method_ordering());603}604set_method_ordering(NULL);605606// default methods can be empty607if (default_methods() != NULL &&608default_methods() != Universe::the_empty_method_array() &&609!default_methods()->is_shared()) {610MetadataFactory::free_array<Method*>(loader_data, default_methods());611}612// Do NOT deallocate the default methods, they are owned by superinterfaces.613set_default_methods(NULL);614615// default methods vtable indices can be empty616if (default_vtable_indices() != NULL &&617!default_vtable_indices()->is_shared()) {618MetadataFactory::free_array<int>(loader_data, default_vtable_indices());619}620set_default_vtable_indices(NULL);621622623// This array is in Klass, but remove it with the InstanceKlass since624// this place would be the only caller and it can share memory with transitive625// interfaces.626if (secondary_supers() != NULL &&627secondary_supers() != Universe::the_empty_klass_array() &&628// see comments in compute_secondary_supers about the following cast629(address)(secondary_supers()) != (address)(transitive_interfaces()) &&630!secondary_supers()->is_shared()) {631MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());632}633set_secondary_supers(NULL);634635deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());636set_transitive_interfaces(NULL);637set_local_interfaces(NULL);638639if (fields() != NULL && !fields()->is_shared()) {640MetadataFactory::free_array<jushort>(loader_data, fields());641}642set_fields(NULL, 0);643644// If a method from a redefined class is using this constant pool, don't645// delete it, yet. The new class's previous version will point to this.646if (constants() != NULL) {647assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");648if (!constants()->is_shared()) {649MetadataFactory::free_metadata(loader_data, constants());650}651// Delete any cached resolution errors for the constant pool652SystemDictionary::delete_resolution_error(constants());653654set_constants(NULL);655}656657if (inner_classes() != NULL &&658inner_classes() != Universe::the_empty_short_array() &&659!inner_classes()->is_shared()) {660MetadataFactory::free_array<jushort>(loader_data, inner_classes());661}662set_inner_classes(NULL);663664if (nest_members() != NULL &&665nest_members() != Universe::the_empty_short_array() &&666!nest_members()->is_shared()) {667MetadataFactory::free_array<jushort>(loader_data, nest_members());668}669set_nest_members(NULL);670671if (permitted_subclasses() != NULL &&672permitted_subclasses() != Universe::the_empty_short_array() &&673!permitted_subclasses()->is_shared()) {674MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());675}676set_permitted_subclasses(NULL);677678// We should deallocate the Annotations instance if it's not in shared spaces.679if (annotations() != NULL && !annotations()->is_shared()) {680MetadataFactory::free_metadata(loader_data, annotations());681}682set_annotations(NULL);683684if (Arguments::is_dumping_archive()) {685SystemDictionaryShared::remove_dumptime_info(this);686}687}688689bool InstanceKlass::is_record() const {690return _record_components != NULL &&691is_final() &&692java_super() == vmClasses::Record_klass();693}694695bool InstanceKlass::is_sealed() const {696return _permitted_subclasses != NULL &&697_permitted_subclasses != Universe::the_empty_short_array();698}699700bool InstanceKlass::should_be_initialized() const {701return !is_initialized();702}703704klassItable InstanceKlass::itable() const {705return klassItable(const_cast<InstanceKlass*>(this));706}707708void InstanceKlass::eager_initialize(Thread *thread) {709if (!EagerInitialization) return;710711if (this->is_not_initialized()) {712// abort if the the class has a class initializer713if (this->class_initializer() != NULL) return;714715// abort if it is java.lang.Object (initialization is handled in genesis)716Klass* super_klass = super();717if (super_klass == NULL) return;718719// abort if the super class should be initialized720if (!InstanceKlass::cast(super_klass)->is_initialized()) return;721722// call body to expose the this pointer723eager_initialize_impl();724}725}726727// JVMTI spec thinks there are signers and protection domain in the728// instanceKlass. These accessors pretend these fields are there.729// The hprof specification also thinks these fields are in InstanceKlass.730oop InstanceKlass::protection_domain() const {731// return the protection_domain from the mirror732return java_lang_Class::protection_domain(java_mirror());733}734735// To remove these from requires an incompatible change and CCC request.736objArrayOop InstanceKlass::signers() const {737// return the signers from the mirror738return java_lang_Class::signers(java_mirror());739}740741oop InstanceKlass::init_lock() const {742// return the init lock from the mirror743oop lock = java_lang_Class::init_lock(java_mirror());744// Prevent reordering with any access of initialization state745OrderAccess::loadload();746assert(lock != NULL || !is_not_initialized(), // initialized or in_error state747"only fully initialized state can have a null lock");748return lock;749}750751// Set the initialization lock to null so the object can be GC'ed. Any racing752// threads to get this lock will see a null lock and will not lock.753// That's okay because they all check for initialized state after getting754// the lock and return.755void InstanceKlass::fence_and_clear_init_lock() {756// make sure previous stores are all done, notably the init_state.757OrderAccess::storestore();758java_lang_Class::clear_init_lock(java_mirror());759assert(!is_not_initialized(), "class must be initialized now");760}761762void InstanceKlass::eager_initialize_impl() {763EXCEPTION_MARK;764HandleMark hm(THREAD);765Handle h_init_lock(THREAD, init_lock());766ObjectLocker ol(h_init_lock, THREAD);767768// abort if someone beat us to the initialization769if (!is_not_initialized()) return; // note: not equivalent to is_initialized()770771ClassState old_state = init_state();772link_class_impl(THREAD);773if (HAS_PENDING_EXCEPTION) {774CLEAR_PENDING_EXCEPTION;775// Abort if linking the class throws an exception.776777// Use a test to avoid redundantly resetting the state if there's778// no change. Set_init_state() asserts that state changes make779// progress, whereas here we might just be spinning in place.780if (old_state != _init_state)781set_init_state(old_state);782} else {783// linking successfull, mark class as initialized784set_init_state(fully_initialized);785fence_and_clear_init_lock();786// trace787if (log_is_enabled(Info, class, init)) {788ResourceMark rm(THREAD);789log_info(class, init)("[Initialized %s without side effects]", external_name());790}791}792}793794795// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization796// process. The step comments refers to the procedure described in that section.797// Note: implementation moved to static method to expose the this pointer.798void InstanceKlass::initialize(TRAPS) {799if (this->should_be_initialized()) {800initialize_impl(CHECK);801// Note: at this point the class may be initialized802// OR it may be in the state of being initialized803// in case of recursive initialization!804} else {805assert(is_initialized(), "sanity check");806}807}808809810bool InstanceKlass::verify_code(TRAPS) {811// 1) Verify the bytecodes812return Verifier::verify(this, should_verify_class(), THREAD);813}814815void InstanceKlass::link_class(TRAPS) {816assert(is_loaded(), "must be loaded");817if (!is_linked()) {818link_class_impl(CHECK);819}820}821822// Called to verify that a class can link during initialization, without823// throwing a VerifyError.824bool InstanceKlass::link_class_or_fail(TRAPS) {825assert(is_loaded(), "must be loaded");826if (!is_linked()) {827link_class_impl(CHECK_false);828}829return is_linked();830}831832bool InstanceKlass::link_class_impl(TRAPS) {833if (DumpSharedSpaces && SystemDictionaryShared::has_class_failed_verification(this)) {834// This is for CDS dumping phase only -- we use the in_error_state to indicate that835// the class has failed verification. Throwing the NoClassDefFoundError here is just836// a convenient way to stop repeat attempts to verify the same (bad) class.837//838// Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown839// if we are executing Java code. This is not a problem for CDS dumping phase since840// it doesn't execute any Java code.841ResourceMark rm(THREAD);842Exceptions::fthrow(THREAD_AND_LOCATION,843vmSymbols::java_lang_NoClassDefFoundError(),844"Class %s, or one of its supertypes, failed class initialization",845external_name());846return false;847}848// return if already verified849if (is_linked()) {850return true;851}852853// Timing854// timer handles recursion855JavaThread* jt = THREAD;856857// link super class before linking this class858Klass* super_klass = super();859if (super_klass != NULL) {860if (super_klass->is_interface()) { // check if super class is an interface861ResourceMark rm(THREAD);862Exceptions::fthrow(863THREAD_AND_LOCATION,864vmSymbols::java_lang_IncompatibleClassChangeError(),865"class %s has interface %s as super class",866external_name(),867super_klass->external_name()868);869return false;870}871872InstanceKlass* ik_super = InstanceKlass::cast(super_klass);873ik_super->link_class_impl(CHECK_false);874}875876// link all interfaces implemented by this class before linking this class877Array<InstanceKlass*>* interfaces = local_interfaces();878int num_interfaces = interfaces->length();879for (int index = 0; index < num_interfaces; index++) {880InstanceKlass* interk = interfaces->at(index);881interk->link_class_impl(CHECK_false);882}883884// in case the class is linked in the process of linking its superclasses885if (is_linked()) {886return true;887}888889// trace only the link time for this klass that includes890// the verification time891PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),892ClassLoader::perf_class_link_selftime(),893ClassLoader::perf_classes_linked(),894jt->get_thread_stat()->perf_recursion_counts_addr(),895jt->get_thread_stat()->perf_timers_addr(),896PerfClassTraceTime::CLASS_LINK);897898// verification & rewriting899{900HandleMark hm(THREAD);901Handle h_init_lock(THREAD, init_lock());902ObjectLocker ol(h_init_lock, jt);903// rewritten will have been set if loader constraint error found904// on an earlier link attempt905// don't verify or rewrite if already rewritten906//907908if (!is_linked()) {909if (!is_rewritten()) {910{911bool verify_ok = verify_code(THREAD);912if (!verify_ok) {913return false;914}915}916917// Just in case a side-effect of verify linked this class already918// (which can sometimes happen since the verifier loads classes919// using custom class loaders, which are free to initialize things)920if (is_linked()) {921return true;922}923924// also sets rewritten925rewrite_class(CHECK_false);926} else if (is_shared()) {927SystemDictionaryShared::check_verification_constraints(this, CHECK_false);928}929930// relocate jsrs and link methods after they are all rewritten931link_methods(CHECK_false);932933// Initialize the vtable and interface table after934// methods have been rewritten since rewrite may935// fabricate new Method*s.936// also does loader constraint checking937//938// initialize_vtable and initialize_itable need to be rerun939// for a shared class if940// 1) the class is loaded by custom class loader or941// 2) the class is loaded by built-in class loader but failed to add archived loader constraints942bool need_init_table = true;943if (is_shared() && SystemDictionaryShared::check_linking_constraints(THREAD, this)) {944need_init_table = false;945}946if (need_init_table) {947vtable().initialize_vtable_and_check_constraints(CHECK_false);948itable().initialize_itable_and_check_constraints(CHECK_false);949}950#ifdef ASSERT951vtable().verify(tty, true);952// In case itable verification is ever added.953// itable().verify(tty, true);954#endif955if (UseVtableBasedCHA) {956MutexLocker ml(THREAD, Compile_lock);957set_init_state(linked);958959// Now flush all code that assume the class is not linked.960if (Universe::is_fully_initialized()) {961CodeCache::flush_dependents_on(this);962}963} else {964set_init_state(linked);965}966if (JvmtiExport::should_post_class_prepare()) {967JvmtiExport::post_class_prepare(THREAD, this);968}969}970}971return true;972}973974// Rewrite the byte codes of all of the methods of a class.975// The rewriter must be called exactly once. Rewriting must happen after976// verification but before the first method of the class is executed.977void InstanceKlass::rewrite_class(TRAPS) {978assert(is_loaded(), "must be loaded");979if (is_rewritten()) {980assert(is_shared(), "rewriting an unshared class?");981return;982}983Rewriter::rewrite(this, CHECK);984set_rewritten();985}986987// Now relocate and link method entry points after class is rewritten.988// This is outside is_rewritten flag. In case of an exception, it can be989// executed more than once.990void InstanceKlass::link_methods(TRAPS) {991int len = methods()->length();992for (int i = len-1; i >= 0; i--) {993methodHandle m(THREAD, methods()->at(i));994995// Set up method entry points for compiler and interpreter .996m->link_method(m, CHECK);997}998}9991000// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)1001void InstanceKlass::initialize_super_interfaces(TRAPS) {1002assert (has_nonstatic_concrete_methods(), "caller should have checked this");1003for (int i = 0; i < local_interfaces()->length(); ++i) {1004InstanceKlass* ik = local_interfaces()->at(i);10051006// Initialization is depth first search ie. we start with top of the inheritance tree1007// has_nonstatic_concrete_methods drives searching superinterfaces since it1008// means has_nonstatic_concrete_methods in its superinterface hierarchy1009if (ik->has_nonstatic_concrete_methods()) {1010ik->initialize_super_interfaces(CHECK);1011}10121013// Only initialize() interfaces that "declare" concrete methods.1014if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {1015ik->initialize(CHECK);1016}1017}1018}10191020void InstanceKlass::initialize_impl(TRAPS) {1021HandleMark hm(THREAD);10221023// Make sure klass is linked (verified) before initialization1024// A class could already be verified, since it has been reflected upon.1025link_class(CHECK);10261027DTRACE_CLASSINIT_PROBE(required, -1);10281029bool wait = false;10301031JavaThread* jt = THREAD;10321033// refer to the JVM book page 47 for description of steps1034// Step 11035{1036Handle h_init_lock(THREAD, init_lock());1037ObjectLocker ol(h_init_lock, jt);10381039// Step 21040// If we were to use wait() instead of waitInterruptibly() then1041// we might end up throwing IE from link/symbol resolution sites1042// that aren't expected to throw. This would wreak havoc. See 6320309.1043while (is_being_initialized() && !is_reentrant_initialization(jt)) {1044wait = true;1045jt->set_class_to_be_initialized(this);1046ol.wait_uninterruptibly(jt);1047jt->set_class_to_be_initialized(NULL);1048}10491050// Step 31051if (is_being_initialized() && is_reentrant_initialization(jt)) {1052DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);1053return;1054}10551056// Step 41057if (is_initialized()) {1058DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);1059return;1060}10611062// Step 51063if (is_in_error_state()) {1064DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);1065ResourceMark rm(THREAD);1066const char* desc = "Could not initialize class ";1067const char* className = external_name();1068size_t msglen = strlen(desc) + strlen(className) + 1;1069char* message = NEW_RESOURCE_ARRAY(char, msglen);1070if (NULL == message) {1071// Out of memory: can't create detailed error message1072THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);1073} else {1074jio_snprintf(message, msglen, "%s%s", desc, className);1075THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);1076}1077}10781079// Step 61080set_init_state(being_initialized);1081set_init_thread(jt);1082}10831084// Step 71085// Next, if C is a class rather than an interface, initialize it's super class and super1086// interfaces.1087if (!is_interface()) {1088Klass* super_klass = super();1089if (super_klass != NULL && super_klass->should_be_initialized()) {1090super_klass->initialize(THREAD);1091}1092// If C implements any interface that declares a non-static, concrete method,1093// the initialization of C triggers initialization of its super interfaces.1094// Only need to recurse if has_nonstatic_concrete_methods which includes declaring and1095// having a superinterface that declares, non-static, concrete methods1096if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {1097initialize_super_interfaces(THREAD);1098}10991100// If any exceptions, complete abruptly, throwing the same exception as above.1101if (HAS_PENDING_EXCEPTION) {1102Handle e(THREAD, PENDING_EXCEPTION);1103CLEAR_PENDING_EXCEPTION;1104{1105EXCEPTION_MARK;1106// Locks object, set state, and notify all waiting threads1107set_initialization_state_and_notify(initialization_error, THREAD);1108CLEAR_PENDING_EXCEPTION;1109}1110DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);1111THROW_OOP(e());1112}1113}111411151116// Step 81117{1118DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);1119if (class_initializer() != NULL) {1120// Timer includes any side effects of class initialization (resolution,1121// etc), but not recursive entry into call_class_initializer().1122PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),1123ClassLoader::perf_class_init_selftime(),1124ClassLoader::perf_classes_inited(),1125jt->get_thread_stat()->perf_recursion_counts_addr(),1126jt->get_thread_stat()->perf_timers_addr(),1127PerfClassTraceTime::CLASS_CLINIT);1128call_class_initializer(THREAD);1129} else {1130// The elapsed time is so small it's not worth counting.1131if (UsePerfData) {1132ClassLoader::perf_classes_inited()->inc();1133}1134call_class_initializer(THREAD);1135}1136}11371138// Step 91139if (!HAS_PENDING_EXCEPTION) {1140set_initialization_state_and_notify(fully_initialized, CHECK);1141{1142debug_only(vtable().verify(tty, true);)1143}1144}1145else {1146// Step 10 and 111147Handle e(THREAD, PENDING_EXCEPTION);1148CLEAR_PENDING_EXCEPTION;1149// JVMTI has already reported the pending exception1150// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError1151JvmtiExport::clear_detected_exception(jt);1152{1153EXCEPTION_MARK;1154set_initialization_state_and_notify(initialization_error, THREAD);1155CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below1156// JVMTI has already reported the pending exception1157// JVMTI internal flag reset is needed in order to report ExceptionInInitializerError1158JvmtiExport::clear_detected_exception(jt);1159}1160DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);1161if (e->is_a(vmClasses::Error_klass())) {1162THROW_OOP(e());1163} else {1164JavaCallArguments args(e);1165THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),1166vmSymbols::throwable_void_signature(),1167&args);1168}1169}1170DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);1171}117211731174void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {1175Handle h_init_lock(THREAD, init_lock());1176if (h_init_lock() != NULL) {1177ObjectLocker ol(h_init_lock, THREAD);1178set_init_thread(NULL); // reset _init_thread before changing _init_state1179set_init_state(state);1180fence_and_clear_init_lock();1181ol.notify_all(CHECK);1182} else {1183assert(h_init_lock() != NULL, "The initialization state should never be set twice");1184set_init_thread(NULL); // reset _init_thread before changing _init_state1185set_init_state(state);1186}1187}11881189InstanceKlass* InstanceKlass::implementor() const {1190InstanceKlass* volatile* ik = adr_implementor();1191if (ik == NULL) {1192return NULL;1193} else {1194// This load races with inserts, and therefore needs acquire.1195InstanceKlass* ikls = Atomic::load_acquire(ik);1196if (ikls != NULL && !ikls->is_loader_alive()) {1197return NULL; // don't return unloaded class1198} else {1199return ikls;1200}1201}1202}120312041205void InstanceKlass::set_implementor(InstanceKlass* ik) {1206assert_locked_or_safepoint(Compile_lock);1207assert(is_interface(), "not interface");1208InstanceKlass* volatile* addr = adr_implementor();1209assert(addr != NULL, "null addr");1210if (addr != NULL) {1211Atomic::release_store(addr, ik);1212}1213}12141215int InstanceKlass::nof_implementors() const {1216InstanceKlass* ik = implementor();1217if (ik == NULL) {1218return 0;1219} else if (ik != this) {1220return 1;1221} else {1222return 2;1223}1224}12251226// The embedded _implementor field can only record one implementor.1227// When there are more than one implementors, the _implementor field1228// is set to the interface Klass* itself. Following are the possible1229// values for the _implementor field:1230// NULL - no implementor1231// implementor Klass* - one implementor1232// self - more than one implementor1233//1234// The _implementor field only exists for interfaces.1235void InstanceKlass::add_implementor(InstanceKlass* ik) {1236if (Universe::is_fully_initialized()) {1237assert_lock_strong(Compile_lock);1238}1239assert(is_interface(), "not interface");1240// Filter out my subinterfaces.1241// (Note: Interfaces are never on the subklass list.)1242if (ik->is_interface()) return;12431244// Filter out subclasses whose supers already implement me.1245// (Note: CHA must walk subclasses of direct implementors1246// in order to locate indirect implementors.)1247InstanceKlass* super_ik = ik->java_super();1248if (super_ik != NULL && super_ik->implements_interface(this))1249// We only need to check one immediate superclass, since the1250// implements_interface query looks at transitive_interfaces.1251// Any supers of the super have the same (or fewer) transitive_interfaces.1252return;12531254InstanceKlass* iklass = implementor();1255if (iklass == NULL) {1256set_implementor(ik);1257} else if (iklass != this && iklass != ik) {1258// There is already an implementor. Use itself as an indicator of1259// more than one implementors.1260set_implementor(this);1261}12621263// The implementor also implements the transitive_interfaces1264for (int index = 0; index < local_interfaces()->length(); index++) {1265local_interfaces()->at(index)->add_implementor(ik);1266}1267}12681269void InstanceKlass::init_implementor() {1270if (is_interface()) {1271set_implementor(NULL);1272}1273}127412751276void InstanceKlass::process_interfaces() {1277// link this class into the implementors list of every interface it implements1278for (int i = local_interfaces()->length() - 1; i >= 0; i--) {1279assert(local_interfaces()->at(i)->is_klass(), "must be a klass");1280InstanceKlass* interf = local_interfaces()->at(i);1281assert(interf->is_interface(), "expected interface");1282interf->add_implementor(this);1283}1284}12851286bool InstanceKlass::can_be_primary_super_slow() const {1287if (is_interface())1288return false;1289else1290return Klass::can_be_primary_super_slow();1291}12921293GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,1294Array<InstanceKlass*>* transitive_interfaces) {1295// The secondaries are the implemented interfaces.1296Array<InstanceKlass*>* interfaces = transitive_interfaces;1297int num_secondaries = num_extra_slots + interfaces->length();1298if (num_secondaries == 0) {1299// Must share this for correct bootstrapping!1300set_secondary_supers(Universe::the_empty_klass_array());1301return NULL;1302} else if (num_extra_slots == 0) {1303// The secondary super list is exactly the same as the transitive interfaces, so1304// let's use it instead of making a copy.1305// Redefine classes has to be careful not to delete this!1306// We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,1307// (but it's safe to do here because we won't write into _secondary_supers from this point on).1308set_secondary_supers((Array<Klass*>*)(address)interfaces);1309return NULL;1310} else {1311// Copy transitive interfaces to a temporary growable array to be constructed1312// into the secondary super list with extra slots.1313GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());1314for (int i = 0; i < interfaces->length(); i++) {1315secondaries->push(interfaces->at(i));1316}1317return secondaries;1318}1319}13201321bool InstanceKlass::implements_interface(Klass* k) const {1322if (this == k) return true;1323assert(k->is_interface(), "should be an interface class");1324for (int i = 0; i < transitive_interfaces()->length(); i++) {1325if (transitive_interfaces()->at(i) == k) {1326return true;1327}1328}1329return false;1330}13311332bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {1333// Verify direct super interface1334if (this == k) return true;1335assert(k->is_interface(), "should be an interface class");1336for (int i = 0; i < local_interfaces()->length(); i++) {1337if (local_interfaces()->at(i) == k) {1338return true;1339}1340}1341return false;1342}13431344objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {1345check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);1346int size = objArrayOopDesc::object_size(length);1347Klass* ak = array_klass(n, CHECK_NULL);1348objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,1349/* do_zero */ true, CHECK_NULL);1350return o;1351}13521353instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {1354if (TraceFinalizerRegistration) {1355tty->print("Registered ");1356i->print_value_on(tty);1357tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));1358}1359instanceHandle h_i(THREAD, i);1360// Pass the handle as argument, JavaCalls::call expects oop as jobjects1361JavaValue result(T_VOID);1362JavaCallArguments args(h_i);1363methodHandle mh (THREAD, Universe::finalizer_register_method());1364JavaCalls::call(&result, mh, &args, CHECK_NULL);1365return h_i();1366}13671368instanceOop InstanceKlass::allocate_instance(TRAPS) {1369bool has_finalizer_flag = has_finalizer(); // Query before possible GC1370int size = size_helper(); // Query before forming handle.13711372instanceOop i;13731374i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);1375if (has_finalizer_flag && !RegisterFinalizersAtInit) {1376i = register_finalizer(i, CHECK_NULL);1377}1378return i;1379}13801381instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {1382return instanceHandle(THREAD, allocate_instance(THREAD));1383}13841385void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {1386if (is_interface() || is_abstract()) {1387ResourceMark rm(THREAD);1388THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()1389: vmSymbols::java_lang_InstantiationException(), external_name());1390}1391if (this == vmClasses::Class_klass()) {1392ResourceMark rm(THREAD);1393THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()1394: vmSymbols::java_lang_IllegalAccessException(), external_name());1395}1396}13971398Klass* InstanceKlass::array_klass(int n, TRAPS) {1399// Need load-acquire for lock-free read1400if (array_klasses_acquire() == NULL) {1401ResourceMark rm(THREAD);1402JavaThread *jt = THREAD;1403{1404// Atomic creation of array_klasses1405MutexLocker ma(THREAD, MultiArray_lock);14061407// Check if update has already taken place1408if (array_klasses() == NULL) {1409ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);1410// use 'release' to pair with lock-free load1411release_set_array_klasses(k);1412}1413}1414}1415// array_klasses() will always be set at this point1416ObjArrayKlass* oak = array_klasses();1417return oak->array_klass(n, THREAD);1418}14191420Klass* InstanceKlass::array_klass_or_null(int n) {1421// Need load-acquire for lock-free read1422ObjArrayKlass* oak = array_klasses_acquire();1423if (oak == NULL) {1424return NULL;1425} else {1426return oak->array_klass_or_null(n);1427}1428}14291430Klass* InstanceKlass::array_klass(TRAPS) {1431return array_klass(1, THREAD);1432}14331434Klass* InstanceKlass::array_klass_or_null() {1435return array_klass_or_null(1);1436}14371438static int call_class_initializer_counter = 0; // for debugging14391440Method* InstanceKlass::class_initializer() const {1441Method* clinit = find_method(1442vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());1443if (clinit != NULL && clinit->has_valid_initializer_flags()) {1444return clinit;1445}1446return NULL;1447}14481449void InstanceKlass::call_class_initializer(TRAPS) {1450if (ReplayCompiles &&1451(ReplaySuppressInitializers == 1 ||1452(ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {1453// Hide the existence of the initializer for the purpose of replaying the compile1454return;1455}14561457methodHandle h_method(THREAD, class_initializer());1458assert(!is_initialized(), "we cannot initialize twice");1459LogTarget(Info, class, init) lt;1460if (lt.is_enabled()) {1461ResourceMark rm(THREAD);1462LogStream ls(lt);1463ls.print("%d Initializing ", call_class_initializer_counter++);1464name()->print_value_on(&ls);1465ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));1466}1467if (h_method() != NULL) {1468JavaCallArguments args; // No arguments1469JavaValue result(T_VOID);1470JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)1471}1472}147314741475void InstanceKlass::mask_for(const methodHandle& method, int bci,1476InterpreterOopMap* entry_for) {1477// Lazily create the _oop_map_cache at first request1478// Lock-free access requires load_acquire.1479OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);1480if (oop_map_cache == NULL) {1481MutexLocker x(OopMapCacheAlloc_lock);1482// Check if _oop_map_cache was allocated while we were waiting for this lock1483if ((oop_map_cache = _oop_map_cache) == NULL) {1484oop_map_cache = new OopMapCache();1485// Ensure _oop_map_cache is stable, since it is examined without a lock1486Atomic::release_store(&_oop_map_cache, oop_map_cache);1487}1488}1489// _oop_map_cache is constant after init; lookup below does its own locking.1490oop_map_cache->lookup(method, bci, entry_for);1491}14921493bool InstanceKlass::contains_field_offset(int offset) {1494fieldDescriptor fd;1495return find_field_from_offset(offset, false, &fd);1496}14971498bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1499for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1500Symbol* f_name = fs.name();1501Symbol* f_sig = fs.signature();1502if (f_name == name && f_sig == sig) {1503fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1504return true;1505}1506}1507return false;1508}150915101511Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1512const int n = local_interfaces()->length();1513for (int i = 0; i < n; i++) {1514Klass* intf1 = local_interfaces()->at(i);1515assert(intf1->is_interface(), "just checking type");1516// search for field in current interface1517if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {1518assert(fd->is_static(), "interface field must be static");1519return intf1;1520}1521// search for field in direct superinterfaces1522Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);1523if (intf2 != NULL) return intf2;1524}1525// otherwise field lookup fails1526return NULL;1527}152815291530Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {1531// search order according to newest JVM spec (5.4.3.2, p.167).1532// 1) search for field in current klass1533if (find_local_field(name, sig, fd)) {1534return const_cast<InstanceKlass*>(this);1535}1536// 2) search for field recursively in direct superinterfaces1537{ Klass* intf = find_interface_field(name, sig, fd);1538if (intf != NULL) return intf;1539}1540// 3) apply field lookup recursively if superclass exists1541{ Klass* supr = super();1542if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);1543}1544// 4) otherwise field lookup fails1545return NULL;1546}154715481549Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {1550// search order according to newest JVM spec (5.4.3.2, p.167).1551// 1) search for field in current klass1552if (find_local_field(name, sig, fd)) {1553if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);1554}1555// 2) search for field recursively in direct superinterfaces1556if (is_static) {1557Klass* intf = find_interface_field(name, sig, fd);1558if (intf != NULL) return intf;1559}1560// 3) apply field lookup recursively if superclass exists1561{ Klass* supr = super();1562if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);1563}1564// 4) otherwise field lookup fails1565return NULL;1566}156715681569bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1570for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1571if (fs.offset() == offset) {1572fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());1573if (fd->is_static() == is_static) return true;1574}1575}1576return false;1577}157815791580bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {1581Klass* klass = const_cast<InstanceKlass*>(this);1582while (klass != NULL) {1583if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {1584return true;1585}1586klass = klass->super();1587}1588return false;1589}159015911592void InstanceKlass::methods_do(void f(Method* method)) {1593// Methods aren't stable until they are loaded. This can be read outside1594// a lock through the ClassLoaderData for profiling1595if (!is_loaded()) {1596return;1597}15981599int len = methods()->length();1600for (int index = 0; index < len; index++) {1601Method* m = methods()->at(index);1602assert(m->is_method(), "must be method");1603f(m);1604}1605}160616071608void InstanceKlass::do_local_static_fields(FieldClosure* cl) {1609for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1610if (fs.access_flags().is_static()) {1611fieldDescriptor& fd = fs.field_descriptor();1612cl->do_field(&fd);1613}1614}1615}161616171618void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {1619for (JavaFieldStream fs(this); !fs.done(); fs.next()) {1620if (fs.access_flags().is_static()) {1621fieldDescriptor& fd = fs.field_descriptor();1622f(&fd, mirror, CHECK);1623}1624}1625}162616271628static int compare_fields_by_offset(int* a, int* b) {1629return a[0] - b[0];1630}16311632void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {1633InstanceKlass* super = superklass();1634if (super != NULL) {1635super->do_nonstatic_fields(cl);1636}1637fieldDescriptor fd;1638int length = java_fields_count();1639// In DebugInfo nonstatic fields are sorted by offset.1640int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);1641int j = 0;1642for (int i = 0; i < length; i += 1) {1643fd.reinitialize(this, i);1644if (!fd.is_static()) {1645fields_sorted[j + 0] = fd.offset();1646fields_sorted[j + 1] = i;1647j += 2;1648}1649}1650if (j > 0) {1651length = j;1652// _sort_Fn is defined in growableArray.hpp.1653qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);1654for (int i = 0; i < length; i += 2) {1655fd.reinitialize(this, fields_sorted[i + 1]);1656assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");1657cl->do_field(&fd);1658}1659}1660FREE_C_HEAP_ARRAY(int, fields_sorted);1661}166216631664void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {1665if (array_klasses() != NULL)1666array_klasses()->array_klasses_do(f, THREAD);1667}16681669void InstanceKlass::array_klasses_do(void f(Klass* k)) {1670if (array_klasses() != NULL)1671array_klasses()->array_klasses_do(f);1672}16731674#ifdef ASSERT1675static int linear_search(const Array<Method*>* methods,1676const Symbol* name,1677const Symbol* signature) {1678const int len = methods->length();1679for (int index = 0; index < len; index++) {1680const Method* const m = methods->at(index);1681assert(m->is_method(), "must be method");1682if (m->signature() == signature && m->name() == name) {1683return index;1684}1685}1686return -1;1687}1688#endif16891690bool InstanceKlass::_disable_method_binary_search = false;16911692NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) {1693int len = methods->length();1694int l = 0;1695int h = len - 1;1696while (l <= h) {1697Method* m = methods->at(l);1698if (m->name() == name) {1699return l;1700}1701l++;1702}1703return -1;1704}17051706inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) {1707if (_disable_method_binary_search) {1708assert(DynamicDumpSharedSpaces, "must be");1709// At the final stage of dynamic dumping, the methods array may not be sorted1710// by ascending addresses of their names, so we can't use binary search anymore.1711// However, methods with the same name are still laid out consecutively inside the1712// methods array, so let's look for the first one that matches.1713return linear_search(methods, name);1714}17151716int len = methods->length();1717int l = 0;1718int h = len - 1;17191720// methods are sorted by ascending addresses of their names, so do binary search1721while (l <= h) {1722int mid = (l + h) >> 1;1723Method* m = methods->at(mid);1724assert(m->is_method(), "must be method");1725int res = m->name()->fast_compare(name);1726if (res == 0) {1727return mid;1728} else if (res < 0) {1729l = mid + 1;1730} else {1731h = mid - 1;1732}1733}1734return -1;1735}17361737// find_method looks up the name/signature in the local methods array1738Method* InstanceKlass::find_method(const Symbol* name,1739const Symbol* signature) const {1740return find_method_impl(name, signature,1741OverpassLookupMode::find,1742StaticLookupMode::find,1743PrivateLookupMode::find);1744}17451746Method* InstanceKlass::find_method_impl(const Symbol* name,1747const Symbol* signature,1748OverpassLookupMode overpass_mode,1749StaticLookupMode static_mode,1750PrivateLookupMode private_mode) const {1751return InstanceKlass::find_method_impl(methods(),1752name,1753signature,1754overpass_mode,1755static_mode,1756private_mode);1757}17581759// find_instance_method looks up the name/signature in the local methods array1760// and skips over static methods1761Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,1762const Symbol* name,1763const Symbol* signature,1764PrivateLookupMode private_mode) {1765Method* const meth = InstanceKlass::find_method_impl(methods,1766name,1767signature,1768OverpassLookupMode::find,1769StaticLookupMode::skip,1770private_mode);1771assert(((meth == NULL) || !meth->is_static()),1772"find_instance_method should have skipped statics");1773return meth;1774}17751776// find_instance_method looks up the name/signature in the local methods array1777// and skips over static methods1778Method* InstanceKlass::find_instance_method(const Symbol* name,1779const Symbol* signature,1780PrivateLookupMode private_mode) const {1781return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);1782}17831784// Find looks up the name/signature in the local methods array1785// and filters on the overpass, static and private flags1786// This returns the first one found1787// note that the local methods array can have up to one overpass, one static1788// and one instance (private or not) with the same name/signature1789Method* InstanceKlass::find_local_method(const Symbol* name,1790const Symbol* signature,1791OverpassLookupMode overpass_mode,1792StaticLookupMode static_mode,1793PrivateLookupMode private_mode) const {1794return InstanceKlass::find_method_impl(methods(),1795name,1796signature,1797overpass_mode,1798static_mode,1799private_mode);1800}18011802// Find looks up the name/signature in the local methods array1803// and filters on the overpass, static and private flags1804// This returns the first one found1805// note that the local methods array can have up to one overpass, one static1806// and one instance (private or not) with the same name/signature1807Method* InstanceKlass::find_local_method(const Array<Method*>* methods,1808const Symbol* name,1809const Symbol* signature,1810OverpassLookupMode overpass_mode,1811StaticLookupMode static_mode,1812PrivateLookupMode private_mode) {1813return InstanceKlass::find_method_impl(methods,1814name,1815signature,1816overpass_mode,1817static_mode,1818private_mode);1819}18201821Method* InstanceKlass::find_method(const Array<Method*>* methods,1822const Symbol* name,1823const Symbol* signature) {1824return InstanceKlass::find_method_impl(methods,1825name,1826signature,1827OverpassLookupMode::find,1828StaticLookupMode::find,1829PrivateLookupMode::find);1830}18311832Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,1833const Symbol* name,1834const Symbol* signature,1835OverpassLookupMode overpass_mode,1836StaticLookupMode static_mode,1837PrivateLookupMode private_mode) {1838int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);1839return hit >= 0 ? methods->at(hit): NULL;1840}18411842// true if method matches signature and conforms to skipping_X conditions.1843static bool method_matches(const Method* m,1844const Symbol* signature,1845bool skipping_overpass,1846bool skipping_static,1847bool skipping_private) {1848return ((m->signature() == signature) &&1849(!skipping_overpass || !m->is_overpass()) &&1850(!skipping_static || !m->is_static()) &&1851(!skipping_private || !m->is_private()));1852}18531854// Used directly for default_methods to find the index into the1855// default_vtable_indices, and indirectly by find_method1856// find_method_index looks in the local methods array to return the index1857// of the matching name/signature. If, overpass methods are being ignored,1858// the search continues to find a potential non-overpass match. This capability1859// is important during method resolution to prefer a static method, for example,1860// over an overpass method.1861// There is the possibility in any _method's array to have the same name/signature1862// for a static method, an overpass method and a local instance method1863// To correctly catch a given method, the search criteria may need1864// to explicitly skip the other two. For local instance methods, it1865// is often necessary to skip private methods1866int InstanceKlass::find_method_index(const Array<Method*>* methods,1867const Symbol* name,1868const Symbol* signature,1869OverpassLookupMode overpass_mode,1870StaticLookupMode static_mode,1871PrivateLookupMode private_mode) {1872const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip);1873const bool skipping_static = (static_mode == StaticLookupMode::skip);1874const bool skipping_private = (private_mode == PrivateLookupMode::skip);1875const int hit = quick_search(methods, name);1876if (hit != -1) {1877const Method* const m = methods->at(hit);18781879// Do linear search to find matching signature. First, quick check1880// for common case, ignoring overpasses if requested.1881if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {1882return hit;1883}18841885// search downwards through overloaded methods1886int i;1887for (i = hit - 1; i >= 0; --i) {1888const Method* const m = methods->at(i);1889assert(m->is_method(), "must be method");1890if (m->name() != name) {1891break;1892}1893if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {1894return i;1895}1896}1897// search upwards1898for (i = hit + 1; i < methods->length(); ++i) {1899const Method* const m = methods->at(i);1900assert(m->is_method(), "must be method");1901if (m->name() != name) {1902break;1903}1904if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {1905return i;1906}1907}1908// not found1909#ifdef ASSERT1910const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :1911linear_search(methods, name, signature);1912assert(-1 == index, "binary search should have found entry %d", index);1913#endif1914}1915return -1;1916}19171918int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {1919return find_method_by_name(methods(), name, end);1920}19211922int InstanceKlass::find_method_by_name(const Array<Method*>* methods,1923const Symbol* name,1924int* end_ptr) {1925assert(end_ptr != NULL, "just checking");1926int start = quick_search(methods, name);1927int end = start + 1;1928if (start != -1) {1929while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;1930while (end < methods->length() && (methods->at(end))->name() == name) ++end;1931*end_ptr = end;1932return start;1933}1934return -1;1935}19361937// uncached_lookup_method searches both the local class methods array and all1938// superclasses methods arrays, skipping any overpass methods in superclasses,1939// and possibly skipping private methods.1940Method* InstanceKlass::uncached_lookup_method(const Symbol* name,1941const Symbol* signature,1942OverpassLookupMode overpass_mode,1943PrivateLookupMode private_mode) const {1944OverpassLookupMode overpass_local_mode = overpass_mode;1945const Klass* klass = this;1946while (klass != NULL) {1947Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,1948signature,1949overpass_local_mode,1950StaticLookupMode::find,1951private_mode);1952if (method != NULL) {1953return method;1954}1955klass = klass->super();1956overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses1957}1958return NULL;1959}19601961#ifdef ASSERT1962// search through class hierarchy and return true if this class or1963// one of the superclasses was redefined1964bool InstanceKlass::has_redefined_this_or_super() const {1965const Klass* klass = this;1966while (klass != NULL) {1967if (InstanceKlass::cast(klass)->has_been_redefined()) {1968return true;1969}1970klass = klass->super();1971}1972return false;1973}1974#endif19751976// lookup a method in the default methods list then in all transitive interfaces1977// Do NOT return private or static methods1978Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,1979Symbol* signature) const {1980Method* m = NULL;1981if (default_methods() != NULL) {1982m = find_method(default_methods(), name, signature);1983}1984// Look up interfaces1985if (m == NULL) {1986m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find);1987}1988return m;1989}19901991// lookup a method in all the interfaces that this class implements1992// Do NOT return private or static methods, new in JDK8 which are not externally visible1993// They should only be found in the initial InterfaceMethodRef1994Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,1995Symbol* signature,1996DefaultsLookupMode defaults_mode) const {1997Array<InstanceKlass*>* all_ifs = transitive_interfaces();1998int num_ifs = all_ifs->length();1999InstanceKlass *ik = NULL;2000for (int i = 0; i < num_ifs; i++) {2001ik = all_ifs->at(i);2002Method* m = ik->lookup_method(name, signature);2003if (m != NULL && m->is_public() && !m->is_static() &&2004((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) {2005return m;2006}2007}2008return NULL;2009}20102011/* jni_id_for_impl for jfieldIds only */2012JNIid* InstanceKlass::jni_id_for_impl(int offset) {2013MutexLocker ml(JfieldIdCreation_lock);2014// Retry lookup after we got the lock2015JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);2016if (probe == NULL) {2017// Slow case, allocate new static field identifier2018probe = new JNIid(this, offset, jni_ids());2019set_jni_ids(probe);2020}2021return probe;2022}202320242025/* jni_id_for for jfieldIds only */2026JNIid* InstanceKlass::jni_id_for(int offset) {2027JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);2028if (probe == NULL) {2029probe = jni_id_for_impl(offset);2030}2031return probe;2032}20332034u2 InstanceKlass::enclosing_method_data(int offset) const {2035const Array<jushort>* const inner_class_list = inner_classes();2036if (inner_class_list == NULL) {2037return 0;2038}2039const int length = inner_class_list->length();2040if (length % inner_class_next_offset == 0) {2041return 0;2042}2043const int index = length - enclosing_method_attribute_size;2044assert(offset < enclosing_method_attribute_size, "invalid offset");2045return inner_class_list->at(index + offset);2046}20472048void InstanceKlass::set_enclosing_method_indices(u2 class_index,2049u2 method_index) {2050Array<jushort>* inner_class_list = inner_classes();2051assert (inner_class_list != NULL, "_inner_classes list is not set up");2052int length = inner_class_list->length();2053if (length % inner_class_next_offset == enclosing_method_attribute_size) {2054int index = length - enclosing_method_attribute_size;2055inner_class_list->at_put(2056index + enclosing_method_class_index_offset, class_index);2057inner_class_list->at_put(2058index + enclosing_method_method_index_offset, method_index);2059}2060}20612062// Lookup or create a jmethodID.2063// This code is called by the VMThread and JavaThreads so the2064// locking has to be done very carefully to avoid deadlocks2065// and/or other cache consistency problems.2066//2067jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {2068size_t idnum = (size_t)method_h->method_idnum();2069jmethodID* jmeths = methods_jmethod_ids_acquire();2070size_t length = 0;2071jmethodID id = NULL;20722073// We use a double-check locking idiom here because this cache is2074// performance sensitive. In the normal system, this cache only2075// transitions from NULL to non-NULL which is safe because we use2076// release_set_methods_jmethod_ids() to advertise the new cache.2077// A partially constructed cache should never be seen by a racing2078// thread. We also use release_store() to save a new jmethodID2079// in the cache so a partially constructed jmethodID should never be2080// seen either. Cache reads of existing jmethodIDs proceed without a2081// lock, but cache writes of a new jmethodID requires uniqueness and2082// creation of the cache itself requires no leaks so a lock is2083// generally acquired in those two cases.2084//2085// If the RedefineClasses() API has been used, then this cache can2086// grow and we'll have transitions from non-NULL to bigger non-NULL.2087// Cache creation requires no leaks and we require safety between all2088// cache accesses and freeing of the old cache so a lock is generally2089// acquired when the RedefineClasses() API has been used.20902091if (jmeths != NULL) {2092// the cache already exists2093if (!idnum_can_increment()) {2094// the cache can't grow so we can just get the current values2095get_jmethod_id_length_value(jmeths, idnum, &length, &id);2096} else {2097// cache can grow so we have to be more careful2098if (Threads::number_of_threads() == 0 ||2099SafepointSynchronize::is_at_safepoint()) {2100// we're single threaded or at a safepoint - no locking needed2101get_jmethod_id_length_value(jmeths, idnum, &length, &id);2102} else {2103MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);2104get_jmethod_id_length_value(jmeths, idnum, &length, &id);2105}2106}2107}2108// implied else:2109// we need to allocate a cache so default length and id values are good21102111if (jmeths == NULL || // no cache yet2112length <= idnum || // cache is too short2113id == NULL) { // cache doesn't contain entry21142115// This function can be called by the VMThread so we have to do all2116// things that might block on a safepoint before grabbing the lock.2117// Otherwise, we can deadlock with the VMThread or have a cache2118// consistency issue. These vars keep track of what we might have2119// to free after the lock is dropped.2120jmethodID to_dealloc_id = NULL;2121jmethodID* to_dealloc_jmeths = NULL;21222123// may not allocate new_jmeths or use it if we allocate it2124jmethodID* new_jmeths = NULL;2125if (length <= idnum) {2126// allocate a new cache that might be used2127size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());2128new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);2129memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));2130// cache size is stored in element[0], other elements offset by one2131new_jmeths[0] = (jmethodID)size;2132}21332134// allocate a new jmethodID that might be used2135jmethodID new_id = NULL;2136if (method_h->is_old() && !method_h->is_obsolete()) {2137// The method passed in is old (but not obsolete), we need to use the current version2138Method* current_method = method_with_idnum((int)idnum);2139assert(current_method != NULL, "old and but not obsolete, so should exist");2140new_id = Method::make_jmethod_id(class_loader_data(), current_method);2141} else {2142// It is the current version of the method or an obsolete method,2143// use the version passed in2144new_id = Method::make_jmethod_id(class_loader_data(), method_h());2145}21462147if (Threads::number_of_threads() == 0 ||2148SafepointSynchronize::is_at_safepoint()) {2149// we're single threaded or at a safepoint - no locking needed2150id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,2151&to_dealloc_id, &to_dealloc_jmeths);2152} else {2153MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);2154id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,2155&to_dealloc_id, &to_dealloc_jmeths);2156}21572158// The lock has been dropped so we can free resources.2159// Free up either the old cache or the new cache if we allocated one.2160if (to_dealloc_jmeths != NULL) {2161FreeHeap(to_dealloc_jmeths);2162}2163// free up the new ID since it wasn't needed2164if (to_dealloc_id != NULL) {2165Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);2166}2167}2168return id;2169}21702171// Figure out how many jmethodIDs haven't been allocated, and make2172// sure space for them is pre-allocated. This makes getting all2173// method ids much, much faster with classes with more than 82174// methods, and has a *substantial* effect on performance with jvmti2175// code that loads all jmethodIDs for all classes.2176void InstanceKlass::ensure_space_for_methodids(int start_offset) {2177int new_jmeths = 0;2178int length = methods()->length();2179for (int index = start_offset; index < length; index++) {2180Method* m = methods()->at(index);2181jmethodID id = m->find_jmethod_id_or_null();2182if (id == NULL) {2183new_jmeths++;2184}2185}2186if (new_jmeths != 0) {2187Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);2188}2189}21902191// Common code to fetch the jmethodID from the cache or update the2192// cache with the new jmethodID. This function should never do anything2193// that causes the caller to go to a safepoint or we can deadlock with2194// the VMThread or have cache consistency issues.2195//2196jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(2197size_t idnum, jmethodID new_id,2198jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,2199jmethodID** to_dealloc_jmeths_p) {2200assert(new_id != NULL, "sanity check");2201assert(to_dealloc_id_p != NULL, "sanity check");2202assert(to_dealloc_jmeths_p != NULL, "sanity check");2203assert(Threads::number_of_threads() == 0 ||2204SafepointSynchronize::is_at_safepoint() ||2205JmethodIdCreation_lock->owned_by_self(), "sanity check");22062207// reacquire the cache - we are locked, single threaded or at a safepoint2208jmethodID* jmeths = methods_jmethod_ids_acquire();2209jmethodID id = NULL;2210size_t length = 0;22112212if (jmeths == NULL || // no cache yet2213(length = (size_t)jmeths[0]) <= idnum) { // cache is too short2214if (jmeths != NULL) {2215// copy any existing entries from the old cache2216for (size_t index = 0; index < length; index++) {2217new_jmeths[index+1] = jmeths[index+1];2218}2219*to_dealloc_jmeths_p = jmeths; // save old cache for later delete2220}2221release_set_methods_jmethod_ids(jmeths = new_jmeths);2222} else {2223// fetch jmethodID (if any) from the existing cache2224id = jmeths[idnum+1];2225*to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete2226}2227if (id == NULL) {2228// No matching jmethodID in the existing cache or we have a new2229// cache or we just grew the cache. This cache write is done here2230// by the first thread to win the foot race because a jmethodID2231// needs to be unique once it is generally available.2232id = new_id;22332234// The jmethodID cache can be read while unlocked so we have to2235// make sure the new jmethodID is complete before installing it2236// in the cache.2237Atomic::release_store(&jmeths[idnum+1], id);2238} else {2239*to_dealloc_id_p = new_id; // save new id for later delete2240}2241return id;2242}224322442245// Common code to get the jmethodID cache length and the jmethodID2246// value at index idnum if there is one.2247//2248void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,2249size_t idnum, size_t *length_p, jmethodID* id_p) {2250assert(cache != NULL, "sanity check");2251assert(length_p != NULL, "sanity check");2252assert(id_p != NULL, "sanity check");22532254// cache size is stored in element[0], other elements offset by one2255*length_p = (size_t)cache[0];2256if (*length_p <= idnum) { // cache is too short2257*id_p = NULL;2258} else {2259*id_p = cache[idnum+1]; // fetch jmethodID (if any)2260}2261}226222632264// Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles2265jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {2266size_t idnum = (size_t)method->method_idnum();2267jmethodID* jmeths = methods_jmethod_ids_acquire();2268size_t length; // length assigned as debugging crumb2269jmethodID id = NULL;2270if (jmeths != NULL && // If there is a cache2271(length = (size_t)jmeths[0]) > idnum) { // and if it is long enough,2272id = jmeths[idnum+1]; // Look up the id (may be NULL)2273}2274return id;2275}22762277inline DependencyContext InstanceKlass::dependencies() {2278DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);2279return dep_context;2280}22812282int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {2283return dependencies().mark_dependent_nmethods(changes);2284}22852286void InstanceKlass::add_dependent_nmethod(nmethod* nm) {2287dependencies().add_dependent_nmethod(nm);2288}22892290void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {2291dependencies().remove_dependent_nmethod(nm);2292}22932294void InstanceKlass::clean_dependency_context() {2295dependencies().clean_unloading_dependents();2296}22972298#ifndef PRODUCT2299void InstanceKlass::print_dependent_nmethods(bool verbose) {2300dependencies().print_dependent_nmethods(verbose);2301}23022303bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {2304return dependencies().is_dependent_nmethod(nm);2305}2306#endif //PRODUCT23072308void InstanceKlass::clean_weak_instanceklass_links() {2309clean_implementors_list();2310clean_method_data();2311}23122313void InstanceKlass::clean_implementors_list() {2314assert(is_loader_alive(), "this klass should be live");2315if (is_interface()) {2316assert (ClassUnloading, "only called for ClassUnloading");2317for (;;) {2318// Use load_acquire due to competing with inserts2319InstanceKlass* impl = Atomic::load_acquire(adr_implementor());2320if (impl != NULL && !impl->is_loader_alive()) {2321// NULL this field, might be an unloaded instance klass or NULL2322InstanceKlass* volatile* iklass = adr_implementor();2323if (Atomic::cmpxchg(iklass, impl, (InstanceKlass*)NULL) == impl) {2324// Successfully unlinking implementor.2325if (log_is_enabled(Trace, class, unload)) {2326ResourceMark rm;2327log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());2328}2329return;2330}2331} else {2332return;2333}2334}2335}2336}23372338void InstanceKlass::clean_method_data() {2339for (int m = 0; m < methods()->length(); m++) {2340MethodData* mdo = methods()->at(m)->method_data();2341if (mdo != NULL) {2342MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());2343mdo->clean_method_data(/*always_clean*/false);2344}2345}2346}23472348void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {2349Klass::metaspace_pointers_do(it);23502351if (log_is_enabled(Trace, cds)) {2352ResourceMark rm;2353log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());2354}23552356it->push(&_annotations);2357it->push((Klass**)&_array_klasses);2358if (!is_rewritten()) {2359it->push(&_constants, MetaspaceClosure::_writable);2360} else {2361it->push(&_constants);2362}2363it->push(&_inner_classes);2364#if INCLUDE_JVMTI2365it->push(&_previous_versions);2366#endif2367it->push(&_methods);2368it->push(&_default_methods);2369it->push(&_local_interfaces);2370it->push(&_transitive_interfaces);2371it->push(&_method_ordering);2372if (!is_rewritten()) {2373it->push(&_default_vtable_indices, MetaspaceClosure::_writable);2374} else {2375it->push(&_default_vtable_indices);2376}2377it->push(&_fields);23782379if (itable_length() > 0) {2380itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();2381int method_table_offset_in_words = ioe->offset()/wordSize;2382int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())2383/ itableOffsetEntry::size();23842385for (int i = 0; i < nof_interfaces; i ++, ioe ++) {2386if (ioe->interface_klass() != NULL) {2387it->push(ioe->interface_klass_addr());2388itableMethodEntry* ime = ioe->first_method_entry(this);2389int n = klassItable::method_count_for_interface(ioe->interface_klass());2390for (int index = 0; index < n; index ++) {2391it->push(ime[index].method_addr());2392}2393}2394}2395}23962397it->push(&_nest_members);2398it->push(&_permitted_subclasses);2399it->push(&_record_components);2400}24012402void InstanceKlass::remove_unshareable_info() {24032404if (can_be_verified_at_dumptime()) {2405// Set the old class bit.2406set_is_shared_old_klass();2407}24082409Klass::remove_unshareable_info();24102411if (SystemDictionaryShared::has_class_failed_verification(this)) {2412// Classes are attempted to link during dumping and may fail,2413// but these classes are still in the dictionary and class list in CLD.2414// If the class has failed verification, there is nothing else to remove.2415return;2416}24172418// Reset to the 'allocated' state to prevent any premature accessing to2419// a shared class at runtime while the class is still being loaded and2420// restored. A class' init_state is set to 'loaded' at runtime when it's2421// being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).2422_init_state = allocated;24232424{ // Otherwise this needs to take out the Compile_lock.2425assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");2426init_implementor();2427}24282429constants()->remove_unshareable_info();24302431for (int i = 0; i < methods()->length(); i++) {2432Method* m = methods()->at(i);2433m->remove_unshareable_info();2434}24352436// do array classes also.2437if (array_klasses() != NULL) {2438array_klasses()->remove_unshareable_info();2439}24402441// These are not allocated from metaspace. They are safe to set to NULL.2442_source_debug_extension = NULL;2443_dep_context = NULL;2444_osr_nmethods_head = NULL;2445#if INCLUDE_JVMTI2446_breakpoints = NULL;2447_previous_versions = NULL;2448_cached_class_file = NULL;2449_jvmti_cached_class_field_map = NULL;2450#endif24512452_init_thread = NULL;2453_methods_jmethod_ids = NULL;2454_jni_ids = NULL;2455_oop_map_cache = NULL;2456// clear _nest_host to ensure re-load at runtime2457_nest_host = NULL;2458init_shared_package_entry();2459_dep_context_last_cleaned = 0;2460}24612462void InstanceKlass::remove_java_mirror() {2463Klass::remove_java_mirror();24642465// do array classes also.2466if (array_klasses() != NULL) {2467array_klasses()->remove_java_mirror();2468}2469}24702471void InstanceKlass::init_shared_package_entry() {2472#if !INCLUDE_CDS_JAVA_HEAP2473_package_entry = NULL;2474#else2475if (!MetaspaceShared::use_full_module_graph()) {2476_package_entry = NULL;2477} else if (DynamicDumpSharedSpaces) {2478if (!MetaspaceShared::is_in_shared_metaspace(_package_entry)) {2479_package_entry = NULL;2480}2481} else {2482if (is_shared_unregistered_class()) {2483_package_entry = NULL;2484} else {2485_package_entry = PackageEntry::get_archived_entry(_package_entry);2486}2487}2488ArchivePtrMarker::mark_pointer((address**)&_package_entry);2489#endif2490}24912492void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,2493PackageEntry* pkg_entry, TRAPS) {2494// SystemDictionary::add_to_hierarchy() sets the init_state to loaded2495// before the InstanceKlass is added to the SystemDictionary. Make2496// sure the current state is <loaded.2497assert(!is_loaded(), "invalid init state");2498set_package(loader_data, pkg_entry, CHECK);2499Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);25002501Array<Method*>* methods = this->methods();2502int num_methods = methods->length();2503for (int index = 0; index < num_methods; ++index) {2504methods->at(index)->restore_unshareable_info(CHECK);2505}2506#if INCLUDE_JVMTI2507if (JvmtiExport::has_redefined_a_class()) {2508// Reinitialize vtable because RedefineClasses may have changed some2509// entries in this vtable for super classes so the CDS vtable might2510// point to old or obsolete entries. RedefineClasses doesn't fix up2511// vtables in the shared system dictionary, only the main one.2512// It also redefines the itable too so fix that too.2513// First fix any default methods that point to a super class that may2514// have been redefined.2515bool trace_name_printed = false;2516adjust_default_methods(&trace_name_printed);2517vtable().initialize_vtable();2518itable().initialize_itable();2519}2520#endif25212522// restore constant pool resolved references2523constants()->restore_unshareable_info(CHECK);25242525if (array_klasses() != NULL) {2526// Array classes have null protection domain.2527// --> see ArrayKlass::complete_create_array_klass()2528array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);2529}25302531// Initialize current biased locking state.2532if (UseBiasedLocking && BiasedLocking::enabled()) {2533set_prototype_header(markWord::biased_locking_prototype());2534}25352536// Initialize @ValueBased class annotation2537if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {2538set_is_value_based();2539set_prototype_header(markWord::prototype());2540}2541}25422543// Check if a class or any of its supertypes has a version older than 50.2544// CDS will not perform verification of old classes during dump time because2545// without changing the old verifier, the verification constraint cannot be2546// retrieved during dump time.2547// Verification of archived old classes will be performed during run time.2548bool InstanceKlass::can_be_verified_at_dumptime() const {2549if (major_version() < 50 /*JAVA_6_VERSION*/) {2550return true;2551}2552if (java_super() != NULL && java_super()->can_be_verified_at_dumptime()) {2553return true;2554}2555Array<InstanceKlass*>* interfaces = local_interfaces();2556int len = interfaces->length();2557for (int i = 0; i < len; i++) {2558if (interfaces->at(i)->can_be_verified_at_dumptime()) {2559return true;2560}2561}2562return false;2563}25642565void InstanceKlass::set_shared_class_loader_type(s2 loader_type) {2566switch (loader_type) {2567case ClassLoader::BOOT_LOADER:2568_misc_flags |= _misc_is_shared_boot_class;2569break;2570case ClassLoader::PLATFORM_LOADER:2571_misc_flags |= _misc_is_shared_platform_class;2572break;2573case ClassLoader::APP_LOADER:2574_misc_flags |= _misc_is_shared_app_class;2575break;2576default:2577ShouldNotReachHere();2578break;2579}2580}25812582void InstanceKlass::assign_class_loader_type() {2583ClassLoaderData *cld = class_loader_data();2584if (cld->is_boot_class_loader_data()) {2585set_shared_class_loader_type(ClassLoader::BOOT_LOADER);2586}2587else if (cld->is_platform_class_loader_data()) {2588set_shared_class_loader_type(ClassLoader::PLATFORM_LOADER);2589}2590else if (cld->is_system_class_loader_data()) {2591set_shared_class_loader_type(ClassLoader::APP_LOADER);2592}2593}25942595#if INCLUDE_JVMTI2596static void clear_all_breakpoints(Method* m) {2597m->clear_all_breakpoints();2598}2599#endif26002601void InstanceKlass::unload_class(InstanceKlass* ik) {2602// Release dependencies.2603ik->dependencies().remove_all_dependents();26042605// notify the debugger2606if (JvmtiExport::should_post_class_unload()) {2607JvmtiExport::post_class_unload(ik);2608}26092610// notify ClassLoadingService of class unload2611ClassLoadingService::notify_class_unloaded(ik);26122613if (Arguments::is_dumping_archive()) {2614SystemDictionaryShared::remove_dumptime_info(ik);2615}26162617if (log_is_enabled(Info, class, unload)) {2618ResourceMark rm;2619log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));2620}26212622Events::log_class_unloading(Thread::current(), ik);26232624#if INCLUDE_JFR2625assert(ik != NULL, "invariant");2626EventClassUnload event;2627event.set_unloadedClass(ik);2628event.set_definingClassLoader(ik->class_loader_data());2629event.commit();2630#endif2631}26322633static void method_release_C_heap_structures(Method* m) {2634m->release_C_heap_structures();2635}26362637void InstanceKlass::release_C_heap_structures() {26382639// Clean up C heap2640release_C_heap_structures_internal();2641constants()->release_C_heap_structures();26422643// Deallocate and call destructors for MDO mutexes2644methods_do(method_release_C_heap_structures);2645}26462647void InstanceKlass::release_C_heap_structures_internal() {2648Klass::release_C_heap_structures();26492650// Can't release the constant pool here because the constant pool can be2651// deallocated separately from the InstanceKlass for default methods and2652// redefine classes.26532654// Deallocate oop map cache2655if (_oop_map_cache != NULL) {2656delete _oop_map_cache;2657_oop_map_cache = NULL;2658}26592660// Deallocate JNI identifiers for jfieldIDs2661JNIid::deallocate(jni_ids());2662set_jni_ids(NULL);26632664jmethodID* jmeths = methods_jmethod_ids_acquire();2665if (jmeths != (jmethodID*)NULL) {2666release_set_methods_jmethod_ids(NULL);2667FreeHeap(jmeths);2668}26692670assert(_dep_context == NULL,2671"dependencies should already be cleaned");26722673#if INCLUDE_JVMTI2674// Deallocate breakpoint records2675if (breakpoints() != 0x0) {2676methods_do(clear_all_breakpoints);2677assert(breakpoints() == 0x0, "should have cleared breakpoints");2678}26792680// deallocate the cached class file2681if (_cached_class_file != NULL) {2682os::free(_cached_class_file);2683_cached_class_file = NULL;2684}2685#endif26862687FREE_C_HEAP_ARRAY(char, _source_debug_extension);2688}26892690void InstanceKlass::set_source_debug_extension(const char* array, int length) {2691if (array == NULL) {2692_source_debug_extension = NULL;2693} else {2694// Adding one to the attribute length in order to store a null terminator2695// character could cause an overflow because the attribute length is2696// already coded with an u4 in the classfile, but in practice, it's2697// unlikely to happen.2698assert((length+1) > length, "Overflow checking");2699char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);2700for (int i = 0; i < length; i++) {2701sde[i] = array[i];2702}2703sde[length] = '\0';2704_source_debug_extension = sde;2705}2706}27072708const char* InstanceKlass::signature_name() const {2709int hash_len = 0;2710char hash_buf[40];27112712// Get the internal name as a c string2713const char* src = (const char*) (name()->as_C_string());2714const int src_length = (int)strlen(src);27152716char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);27172718// Add L as type indicator2719int dest_index = 0;2720dest[dest_index++] = JVM_SIGNATURE_CLASS;27212722// Add the actual class name2723for (int src_index = 0; src_index < src_length; ) {2724dest[dest_index++] = src[src_index++];2725}27262727if (is_hidden()) { // Replace the last '+' with a '.'.2728for (int index = (int)src_length; index > 0; index--) {2729if (dest[index] == '+') {2730dest[index] = JVM_SIGNATURE_DOT;2731break;2732}2733}2734}27352736// If we have a hash, append it2737for (int hash_index = 0; hash_index < hash_len; ) {2738dest[dest_index++] = hash_buf[hash_index++];2739}27402741// Add the semicolon and the NULL2742dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;2743dest[dest_index] = '\0';2744return dest;2745}27462747ModuleEntry* InstanceKlass::module() const {2748if (is_hidden() &&2749in_unnamed_package() &&2750class_loader_data()->has_class_mirror_holder()) {2751// For a non-strong hidden class defined to an unnamed package,2752// its (class held) CLD will not have an unnamed module created for it.2753// Two choices to find the correct ModuleEntry:2754// 1. If hidden class is within a nest, use nest host's module2755// 2. Find the unnamed module off from the class loader2756// For now option #2 is used since a nest host is not set until2757// after the instance class is created in jvm_lookup_define_class().2758if (class_loader_data()->is_boot_class_loader_data()) {2759return ClassLoaderData::the_null_class_loader_data()->unnamed_module();2760} else {2761oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());2762assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");2763return java_lang_Module::module_entry(module);2764}2765}27662767// Class is in a named package2768if (!in_unnamed_package()) {2769return _package_entry->module();2770}27712772// Class is in an unnamed package, return its loader's unnamed module2773return class_loader_data()->unnamed_module();2774}27752776void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {27772778// ensure java/ packages only loaded by boot or platform builtin loaders2779// not needed for shared class since CDS does not archive prohibited classes.2780if (!is_shared()) {2781check_prohibited_package(name(), loader_data, CHECK);2782}27832784if (is_shared() && _package_entry != NULL) {2785if (MetaspaceShared::use_full_module_graph() && _package_entry == pkg_entry) {2786// we can use the saved package2787assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be");2788return;2789} else {2790_package_entry = NULL;2791}2792}27932794// ClassLoader::package_from_class_name has already incremented the refcount of the symbol2795// it returns, so we need to decrement it when the current function exits.2796TempNewSymbol from_class_name =2797(pkg_entry != NULL) ? NULL : ClassLoader::package_from_class_name(name());27982799Symbol* pkg_name;2800if (pkg_entry != NULL) {2801pkg_name = pkg_entry->name();2802} else {2803pkg_name = from_class_name;2804}28052806if (pkg_name != NULL && loader_data != NULL) {28072808// Find in class loader's package entry table.2809_package_entry = pkg_entry != NULL ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);28102811// If the package name is not found in the loader's package2812// entry table, it is an indication that the package has not2813// been defined. Consider it defined within the unnamed module.2814if (_package_entry == NULL) {28152816if (!ModuleEntryTable::javabase_defined()) {2817// Before java.base is defined during bootstrapping, define all packages in2818// the java.base module. If a non-java.base package is erroneously placed2819// in the java.base module it will be caught later when java.base2820// is defined by ModuleEntryTable::verify_javabase_packages check.2821assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");2822_package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());2823} else {2824assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");2825_package_entry = loader_data->packages()->lookup(pkg_name,2826loader_data->unnamed_module());2827}28282829// A package should have been successfully created2830DEBUG_ONLY(ResourceMark rm(THREAD));2831assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",2832name()->as_C_string(), loader_data->loader_name_and_id());2833}28342835if (log_is_enabled(Debug, module)) {2836ResourceMark rm(THREAD);2837ModuleEntry* m = _package_entry->module();2838log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",2839external_name(),2840pkg_name->as_C_string(),2841loader_data->loader_name_and_id(),2842(m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));2843}2844} else {2845ResourceMark rm(THREAD);2846log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",2847external_name(),2848(loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",2849UNNAMED_MODULE);2850}2851}28522853// Function set_classpath_index ensures that for a non-null _package_entry2854// of the InstanceKlass, the entry is in the boot loader's package entry table.2855// It then sets the classpath_index in the package entry record.2856//2857// The classpath_index field is used to find the entry on the boot loader class2858// path for packages with classes loaded by the boot loader from -Xbootclasspath/a2859// in an unnamed module. It is also used to indicate (for all packages whose2860// classes are loaded by the boot loader) that at least one of the package's2861// classes has been loaded.2862void InstanceKlass::set_classpath_index(s2 path_index) {2863if (_package_entry != NULL) {2864DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)2865assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");2866assert(path_index != -1, "Unexpected classpath_index");2867_package_entry->set_classpath_index(path_index);2868}2869}28702871// different versions of is_same_class_package28722873bool InstanceKlass::is_same_class_package(const Klass* class2) const {2874oop classloader1 = this->class_loader();2875PackageEntry* classpkg1 = this->package();2876if (class2->is_objArray_klass()) {2877class2 = ObjArrayKlass::cast(class2)->bottom_klass();2878}28792880oop classloader2;2881PackageEntry* classpkg2;2882if (class2->is_instance_klass()) {2883classloader2 = class2->class_loader();2884classpkg2 = class2->package();2885} else {2886assert(class2->is_typeArray_klass(), "should be type array");2887classloader2 = NULL;2888classpkg2 = NULL;2889}28902891// Same package is determined by comparing class loader2892// and package entries. Both must be the same. This rule2893// applies even to classes that are defined in the unnamed2894// package, they still must have the same class loader.2895if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {2896return true;2897}28982899return false;2900}29012902// return true if this class and other_class are in the same package. Classloader2903// and classname information is enough to determine a class's package2904bool InstanceKlass::is_same_class_package(oop other_class_loader,2905const Symbol* other_class_name) const {2906if (class_loader() != other_class_loader) {2907return false;2908}2909if (name()->fast_compare(other_class_name) == 0) {2910return true;2911}29122913{2914ResourceMark rm;29152916bool bad_class_name = false;2917TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);2918if (bad_class_name) {2919return false;2920}2921// Check that package_from_class_name() returns NULL, not "", if there is no package.2922assert(other_pkg == NULL || other_pkg->utf8_length() > 0, "package name is empty string");29232924const Symbol* const this_package_name =2925this->package() != NULL ? this->package()->name() : NULL;29262927if (this_package_name == NULL || other_pkg == NULL) {2928// One of the two doesn't have a package. Only return true if the other2929// one also doesn't have a package.2930return this_package_name == other_pkg;2931}29322933// Check if package is identical2934return this_package_name->fast_compare(other_pkg) == 0;2935}2936}29372938static bool is_prohibited_package_slow(Symbol* class_name) {2939// Caller has ResourceMark2940int length;2941jchar* unicode = class_name->as_unicode(length);2942return (length >= 5 &&2943unicode[0] == 'j' &&2944unicode[1] == 'a' &&2945unicode[2] == 'v' &&2946unicode[3] == 'a' &&2947unicode[4] == '/');2948}29492950// Only boot and platform class loaders can define classes in "java/" packages.2951void InstanceKlass::check_prohibited_package(Symbol* class_name,2952ClassLoaderData* loader_data,2953TRAPS) {2954if (!loader_data->is_boot_class_loader_data() &&2955!loader_data->is_platform_class_loader_data() &&2956class_name != NULL && class_name->utf8_length() >= 5) {2957ResourceMark rm(THREAD);2958bool prohibited;2959const u1* base = class_name->base();2960if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {2961prohibited = is_prohibited_package_slow(class_name);2962} else {2963char* name = class_name->as_C_string();2964prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/');2965}2966if (prohibited) {2967TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);2968assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");2969char* name = pkg_name->as_C_string();2970const char* class_loader_name = loader_data->loader_name_and_id();2971StringUtils::replace_no_expand(name, "/", ".");2972const char* msg_text1 = "Class loader (instance of): ";2973const char* msg_text2 = " tried to load prohibited package name: ";2974size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;2975char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);2976jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);2977THROW_MSG(vmSymbols::java_lang_SecurityException(), message);2978}2979}2980return;2981}29822983bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {2984constantPoolHandle i_cp(THREAD, constants());2985for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {2986int ioff = iter.inner_class_info_index();2987if (ioff != 0) {2988// Check to see if the name matches the class we're looking for2989// before attempting to find the class.2990if (i_cp->klass_name_at_matches(this, ioff)) {2991Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);2992if (this == inner_klass) {2993*ooff = iter.outer_class_info_index();2994*noff = iter.inner_name_index();2995return true;2996}2997}2998}2999}3000return false;3001}30023003InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {3004InstanceKlass* outer_klass = NULL;3005*inner_is_member = false;3006int ooff = 0, noff = 0;3007bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);3008if (has_inner_classes_attr) {3009constantPoolHandle i_cp(THREAD, constants());3010if (ooff != 0) {3011Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);3012outer_klass = InstanceKlass::cast(ok);3013*inner_is_member = true;3014}3015if (NULL == outer_klass) {3016// It may be a local class; try for that.3017int encl_method_class_idx = enclosing_method_class_index();3018if (encl_method_class_idx != 0) {3019Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);3020outer_klass = InstanceKlass::cast(ok);3021*inner_is_member = false;3022}3023}3024}30253026// If no inner class attribute found for this class.3027if (NULL == outer_klass) return NULL;30283029// Throws an exception if outer klass has not declared k as an inner klass3030// We need evidence that each klass knows about the other, or else3031// the system could allow a spoof of an inner class to gain access rights.3032Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);3033return outer_klass;3034}30353036jint InstanceKlass::compute_modifier_flags() const {3037jint access = access_flags().as_int();30383039// But check if it happens to be member class.3040InnerClassesIterator iter(this);3041for (; !iter.done(); iter.next()) {3042int ioff = iter.inner_class_info_index();3043// Inner class attribute can be zero, skip it.3044// Strange but true: JVM spec. allows null inner class refs.3045if (ioff == 0) continue;30463047// only look at classes that are already loaded3048// since we are looking for the flags for our self.3049Symbol* inner_name = constants()->klass_name_at(ioff);3050if (name() == inner_name) {3051// This is really a member class.3052access = iter.inner_access_flags();3053break;3054}3055}3056// Remember to strip ACC_SUPER bit3057return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;3058}30593060jint InstanceKlass::jvmti_class_status() const {3061jint result = 0;30623063if (is_linked()) {3064result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;3065}30663067if (is_initialized()) {3068assert(is_linked(), "Class status is not consistent");3069result |= JVMTI_CLASS_STATUS_INITIALIZED;3070}3071if (is_in_error_state()) {3072result |= JVMTI_CLASS_STATUS_ERROR;3073}3074return result;3075}30763077Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {3078bool implements_interface; // initialized by method_at_itable_or_null3079Method* m = method_at_itable_or_null(holder, index,3080implements_interface); // out parameter3081if (m != NULL) {3082assert(implements_interface, "sanity");3083return m;3084} else if (implements_interface) {3085// Throw AbstractMethodError since corresponding itable slot is empty.3086THROW_NULL(vmSymbols::java_lang_AbstractMethodError());3087} else {3088// If the interface isn't implemented by the receiver class,3089// the VM should throw IncompatibleClassChangeError.3090ResourceMark rm(THREAD);3091stringStream ss;3092bool same_module = (module() == holder->module());3093ss.print("Receiver class %s does not implement "3094"the interface %s defining the method to be called "3095"(%s%s%s)",3096external_name(), holder->external_name(),3097(same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),3098(same_module) ? "" : "; ",3099(same_module) ? "" : holder->class_in_module_of_loader());3100THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());3101}3102}31033104Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) {3105klassItable itable(this);3106for (int i = 0; i < itable.size_offset_table(); i++) {3107itableOffsetEntry* offset_entry = itable.offset_entry(i);3108if (offset_entry->interface_klass() == holder) {3109implements_interface = true;3110itableMethodEntry* ime = offset_entry->first_method_entry(this);3111Method* m = ime[index].method();3112return m;3113}3114}3115implements_interface = false;3116return NULL; // offset entry not found3117}31183119int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) {3120assert(is_linked(), "required");3121assert(intf_method->method_holder()->is_interface(), "not an interface method");3122assert(is_subtype_of(intf_method->method_holder()), "interface not implemented");31233124int vtable_index = Method::invalid_vtable_index;3125Symbol* name = intf_method->name();3126Symbol* signature = intf_method->signature();31273128// First check in default method array3129if (!intf_method->is_abstract() && default_methods() != NULL) {3130int index = find_method_index(default_methods(),3131name, signature,3132Klass::OverpassLookupMode::find,3133Klass::StaticLookupMode::find,3134Klass::PrivateLookupMode::find);3135if (index >= 0) {3136vtable_index = default_vtable_indices()->at(index);3137}3138}3139if (vtable_index == Method::invalid_vtable_index) {3140// get vtable_index for miranda methods3141klassVtable vt = vtable();3142vtable_index = vt.index_of_miranda(name, signature);3143}3144return vtable_index;3145}31463147#if INCLUDE_JVMTI3148// update default_methods for redefineclasses for methods that are3149// not yet in the vtable due to concurrent subclass define and superinterface3150// redefinition3151// Note: those in the vtable, should have been updated via adjust_method_entries3152void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {3153// search the default_methods for uses of either obsolete or EMCP methods3154if (default_methods() != NULL) {3155for (int index = 0; index < default_methods()->length(); index ++) {3156Method* old_method = default_methods()->at(index);3157if (old_method == NULL || !old_method->is_old()) {3158continue; // skip uninteresting entries3159}3160assert(!old_method->is_deleted(), "default methods may not be deleted");3161Method* new_method = old_method->get_new_method();3162default_methods()->at_put(index, new_method);31633164if (log_is_enabled(Info, redefine, class, update)) {3165ResourceMark rm;3166if (!(*trace_name_printed)) {3167log_info(redefine, class, update)3168("adjust: klassname=%s default methods from name=%s",3169external_name(), old_method->method_holder()->external_name());3170*trace_name_printed = true;3171}3172log_debug(redefine, class, update, vtables)3173("default method update: %s(%s) ",3174new_method->name()->as_C_string(), new_method->signature()->as_C_string());3175}3176}3177}3178}3179#endif // INCLUDE_JVMTI31803181// On-stack replacement stuff3182void InstanceKlass::add_osr_nmethod(nmethod* n) {3183assert_lock_strong(CompiledMethod_lock);3184#ifndef PRODUCT3185nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);3186assert(prev == NULL || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),3187"redundant OSR recompilation detected. memory leak in CodeCache!");3188#endif3189// only one compilation can be active3190assert(n->is_osr_method(), "wrong kind of nmethod");3191n->set_osr_link(osr_nmethods_head());3192set_osr_nmethods_head(n);3193// Raise the highest osr level if necessary3194n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level()));31953196// Get rid of the osr methods for the same bci that have lower levels.3197for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {3198nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);3199if (inv != NULL && inv->is_in_use()) {3200inv->make_not_entrant();3201}3202}3203}32043205// Remove osr nmethod from the list. Return true if found and removed.3206bool InstanceKlass::remove_osr_nmethod(nmethod* n) {3207// This is a short non-blocking critical region, so the no safepoint check is ok.3208MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock3209, Mutex::_no_safepoint_check_flag);3210assert(n->is_osr_method(), "wrong kind of nmethod");3211nmethod* last = NULL;3212nmethod* cur = osr_nmethods_head();3213int max_level = CompLevel_none; // Find the max comp level excluding n3214Method* m = n->method();3215// Search for match3216bool found = false;3217while(cur != NULL && cur != n) {3218if (m == cur->method()) {3219// Find max level before n3220max_level = MAX2(max_level, cur->comp_level());3221}3222last = cur;3223cur = cur->osr_link();3224}3225nmethod* next = NULL;3226if (cur == n) {3227found = true;3228next = cur->osr_link();3229if (last == NULL) {3230// Remove first element3231set_osr_nmethods_head(next);3232} else {3233last->set_osr_link(next);3234}3235}3236n->set_osr_link(NULL);3237cur = next;3238while (cur != NULL) {3239// Find max level after n3240if (m == cur->method()) {3241max_level = MAX2(max_level, cur->comp_level());3242}3243cur = cur->osr_link();3244}3245m->set_highest_osr_comp_level(max_level);3246return found;3247}32483249int InstanceKlass::mark_osr_nmethods(const Method* m) {3250MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,3251Mutex::_no_safepoint_check_flag);3252nmethod* osr = osr_nmethods_head();3253int found = 0;3254while (osr != NULL) {3255assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3256if (osr->method() == m) {3257osr->mark_for_deoptimization();3258found++;3259}3260osr = osr->osr_link();3261}3262return found;3263}32643265nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {3266MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,3267Mutex::_no_safepoint_check_flag);3268nmethod* osr = osr_nmethods_head();3269nmethod* best = NULL;3270while (osr != NULL) {3271assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");3272// There can be a time when a c1 osr method exists but we are waiting3273// for a c2 version. When c2 completes its osr nmethod we will trash3274// the c1 version and only be able to find the c2 version. However3275// while we overflow in the c1 code at back branches we don't want to3276// try and switch to the same code as we are already running32773278if (osr->method() == m &&3279(bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {3280if (match_level) {3281if (osr->comp_level() == comp_level) {3282// Found a match - return it.3283return osr;3284}3285} else {3286if (best == NULL || (osr->comp_level() > best->comp_level())) {3287if (osr->comp_level() == CompilationPolicy::highest_compile_level()) {3288// Found the best possible - return it.3289return osr;3290}3291best = osr;3292}3293}3294}3295osr = osr->osr_link();3296}32973298assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");3299if (best != NULL && best->comp_level() >= comp_level) {3300return best;3301}3302return NULL;3303}33043305// -----------------------------------------------------------------------------------------------------3306// Printing33073308#ifndef PRODUCT33093310#define BULLET " - "33113312static const char* state_names[] = {3313"allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"3314};33153316static void print_vtable(intptr_t* start, int len, outputStream* st) {3317for (int i = 0; i < len; i++) {3318intptr_t e = start[i];3319st->print("%d : " INTPTR_FORMAT, i, e);3320if (MetaspaceObj::is_valid((Metadata*)e)) {3321st->print(" ");3322((Metadata*)e)->print_value_on(st);3323}3324st->cr();3325}3326}33273328static void print_vtable(vtableEntry* start, int len, outputStream* st) {3329return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);3330}33313332void InstanceKlass::print_on(outputStream* st) const {3333assert(is_klass(), "must be klass");3334Klass::print_on(st);33353336st->print(BULLET"instance size: %d", size_helper()); st->cr();3337st->print(BULLET"klass size: %d", size()); st->cr();3338st->print(BULLET"access: "); access_flags().print_on(st); st->cr();3339st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]);3340st->print(BULLET"name: "); name()->print_value_on(st); st->cr();3341st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();3342st->print(BULLET"sub: ");3343Klass* sub = subklass();3344int n;3345for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {3346if (n < MaxSubklassPrintSize) {3347sub->print_value_on(st);3348st->print(" ");3349}3350}3351if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);3352st->cr();33533354if (is_interface()) {3355st->print_cr(BULLET"nof implementors: %d", nof_implementors());3356if (nof_implementors() == 1) {3357st->print_cr(BULLET"implementor: ");3358st->print(" ");3359implementor()->print_value_on(st);3360st->cr();3361}3362}33633364st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();3365st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();3366if (Verbose || WizardMode) {3367Array<Method*>* method_array = methods();3368for (int i = 0; i < method_array->length(); i++) {3369st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3370}3371}3372st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();3373st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();3374if (Verbose && default_methods() != NULL) {3375Array<Method*>* method_array = default_methods();3376for (int i = 0; i < method_array->length(); i++) {3377st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();3378}3379}3380if (default_vtable_indices() != NULL) {3381st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr();3382}3383st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();3384st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();3385st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();3386if (class_loader_data() != NULL) {3387st->print(BULLET"class loader data: ");3388class_loader_data()->print_value_on(st);3389st->cr();3390}3391if (source_file_name() != NULL) {3392st->print(BULLET"source file: ");3393source_file_name()->print_value_on(st);3394st->cr();3395}3396if (source_debug_extension() != NULL) {3397st->print(BULLET"source debug extension: ");3398st->print("%s", source_debug_extension());3399st->cr();3400}3401st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr();3402st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr();3403st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr();3404st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr();3405{3406bool have_pv = false;3407// previous versions are linked together through the InstanceKlass3408for (InstanceKlass* pv_node = previous_versions();3409pv_node != NULL;3410pv_node = pv_node->previous_versions()) {3411if (!have_pv)3412st->print(BULLET"previous version: ");3413have_pv = true;3414pv_node->constants()->print_value_on(st);3415}3416if (have_pv) st->cr();3417}34183419if (generic_signature() != NULL) {3420st->print(BULLET"generic signature: ");3421generic_signature()->print_value_on(st);3422st->cr();3423}3424st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();3425st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();3426if (record_components() != NULL) {3427st->print(BULLET"record components: "); record_components()->print_value_on(st); st->cr();3428}3429st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();3430if (java_mirror() != NULL) {3431st->print(BULLET"java mirror: ");3432java_mirror()->print_value_on(st);3433st->cr();3434} else {3435st->print_cr(BULLET"java mirror: NULL");3436}3437st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();3438if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);3439st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();3440if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);3441st->print_cr(BULLET"---- static fields (%d words):", static_field_size());3442FieldPrinter print_static_field(st);3443((InstanceKlass*)this)->do_local_static_fields(&print_static_field);3444st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());3445FieldPrinter print_nonstatic_field(st);3446InstanceKlass* ik = const_cast<InstanceKlass*>(this);3447ik->do_nonstatic_fields(&print_nonstatic_field);34483449st->print(BULLET"non-static oop maps: ");3450OopMapBlock* map = start_of_nonstatic_oop_maps();3451OopMapBlock* end_map = map + nonstatic_oop_map_count();3452while (map < end_map) {3453st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));3454map++;3455}3456st->cr();3457}34583459#endif //PRODUCT34603461void InstanceKlass::print_value_on(outputStream* st) const {3462assert(is_klass(), "must be klass");3463if (Verbose || WizardMode) access_flags().print_on(st);3464name()->print_value_on(st);3465}34663467#ifndef PRODUCT34683469void 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}35253526bool InstanceKlass::verify_itable_index(int i) {3527int method_count = klassItable::method_count_for_interface(this);3528assert(i >= 0 && i < method_count, "index out of bounds");3529return true;3530}35313532#endif //PRODUCT35333534void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {3535st->print("a ");3536name()->print_value_on(st);3537obj->print_address_on(st);3538if (this == vmClasses::String_klass()3539&& java_lang_String::value(obj) != NULL) {3540ResourceMark rm;3541int len = java_lang_String::length(obj);3542int plen = (len < 24 ? len : 12);3543char* str = java_lang_String::as_utf8_string(obj, 0, plen);3544st->print(" = \"%s\"", str);3545if (len > plen)3546st->print("...[%d]", len);3547} else if (this == vmClasses::Class_klass()) {3548Klass* k = java_lang_Class::as_Klass(obj);3549st->print(" = ");3550if (k != NULL) {3551k->print_value_on(st);3552} else {3553const char* tname = type2name(java_lang_Class::primitive_type(obj));3554st->print("%s", tname ? tname : "type?");3555}3556} else if (this == vmClasses::MethodType_klass()) {3557st->print(" = ");3558java_lang_invoke_MethodType::print_signature(obj, st);3559} else if (java_lang_boxing_object::is_instance(obj)) {3560st->print(" = ");3561java_lang_boxing_object::print(obj, st);3562} else if (this == vmClasses::LambdaForm_klass()) {3563oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);3564if (vmentry != NULL) {3565st->print(" => ");3566vmentry->print_value_on(st);3567}3568} else if (this == vmClasses::MemberName_klass()) {3569Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);3570if (vmtarget != NULL) {3571st->print(" = ");3572vmtarget->print_value_on(st);3573} else {3574oop clazz = java_lang_invoke_MemberName::clazz(obj);3575oop name = java_lang_invoke_MemberName::name(obj);3576if (clazz != NULL) {3577clazz->print_value_on(st);3578} else {3579st->print("NULL");3580}3581st->print(".");3582if (name != NULL) {3583name->print_value_on(st);3584} else {3585st->print("NULL");3586}3587}3588}3589}35903591const char* InstanceKlass::internal_name() const {3592return external_name();3593}35943595void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,3596const ModuleEntry* module_entry,3597const ClassFileStream* cfs) const {3598log_to_classlist();35993600if (!log_is_enabled(Info, class, load)) {3601return;3602}36033604ResourceMark rm;3605LogMessage(class, load) msg;3606stringStream info_stream;36073608// Name and class hierarchy info3609info_stream.print("%s", external_name());36103611// Source3612if (cfs != NULL) {3613if (cfs->source() != NULL) {3614const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();3615if (module_name != NULL) {3616// When the boot loader created the stream, it didn't know the module name3617// yet. Let's format it now.3618if (cfs->from_boot_loader_modules_image()) {3619info_stream.print(" source: jrt:/%s", module_name);3620} else {3621info_stream.print(" source: %s", cfs->source());3622}3623} else {3624info_stream.print(" source: %s", cfs->source());3625}3626} else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {3627Thread* current = Thread::current();3628Klass* caller = current->is_Java_thread() ?3629current->as_Java_thread()->security_get_caller_class(1):3630NULL;3631// caller can be NULL, for example, during a JVMTI VM_Init hook3632if (caller != NULL) {3633info_stream.print(" source: instance of %s", caller->external_name());3634} else {3635// source is unknown3636}3637} else {3638oop class_loader = loader_data->class_loader();3639info_stream.print(" source: %s", class_loader->klass()->external_name());3640}3641} else {3642assert(this->is_shared(), "must be");3643if (MetaspaceShared::is_shared_dynamic((void*)this)) {3644info_stream.print(" source: shared objects file (top)");3645} else {3646info_stream.print(" source: shared objects file");3647}3648}36493650msg.info("%s", info_stream.as_string());36513652if (log_is_enabled(Debug, class, load)) {3653stringStream debug_stream;36543655// Class hierarchy info3656debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,3657p2i(this), p2i(superklass()));36583659// Interfaces3660if (local_interfaces() != NULL && local_interfaces()->length() > 0) {3661debug_stream.print(" interfaces:");3662int length = local_interfaces()->length();3663for (int i = 0; i < length; i++) {3664debug_stream.print(" " INTPTR_FORMAT,3665p2i(InstanceKlass::cast(local_interfaces()->at(i))));3666}3667}36683669// Class loader3670debug_stream.print(" loader: [");3671loader_data->print_value_on(&debug_stream);3672debug_stream.print("]");36733674// Classfile checksum3675if (cfs) {3676debug_stream.print(" bytes: %d checksum: %08x",3677cfs->length(),3678ClassLoader::crc32(0, (const char*)cfs->buffer(),3679cfs->length()));3680}36813682msg.debug("%s", debug_stream.as_string());3683}3684}36853686// Verification36873688class VerifyFieldClosure: public BasicOopIterateClosure {3689protected:3690template <class T> void do_oop_work(T* p) {3691oop obj = RawAccess<>::oop_load(p);3692if (!oopDesc::is_oop_or_null(obj)) {3693tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));3694Universe::print_on(tty);3695guarantee(false, "boom");3696}3697}3698public:3699virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }3700virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }3701};37023703void InstanceKlass::verify_on(outputStream* st) {3704#ifndef PRODUCT3705// Avoid redundant verifies, this really should be in product.3706if (_verify_count == Universe::verify_count()) return;3707_verify_count = Universe::verify_count();3708#endif37093710// Verify Klass3711Klass::verify_on(st);37123713// Verify that klass is present in ClassLoaderData3714guarantee(class_loader_data()->contains_klass(this),3715"this class isn't found in class loader data");37163717// Verify vtables3718if (is_linked()) {3719// $$$ This used to be done only for m/s collections. Doing it3720// always seemed a valid generalization. (DLD -- 6/00)3721vtable().verify(st);3722}37233724// Verify first subklass3725if (subklass() != NULL) {3726guarantee(subklass()->is_klass(), "should be klass");3727}37283729// Verify siblings3730Klass* super = this->super();3731Klass* sib = next_sibling();3732if (sib != NULL) {3733if (sib == this) {3734fatal("subclass points to itself " PTR_FORMAT, p2i(sib));3735}37363737guarantee(sib->is_klass(), "should be klass");3738guarantee(sib->super() == super, "siblings should have same superklass");3739}37403741// Verify local interfaces3742if (local_interfaces()) {3743Array<InstanceKlass*>* local_interfaces = this->local_interfaces();3744for (int j = 0; j < local_interfaces->length(); j++) {3745InstanceKlass* e = local_interfaces->at(j);3746guarantee(e->is_klass() && e->is_interface(), "invalid local interface");3747}3748}37493750// Verify transitive interfaces3751if (transitive_interfaces() != NULL) {3752Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();3753for (int j = 0; j < transitive_interfaces->length(); j++) {3754InstanceKlass* e = transitive_interfaces->at(j);3755guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");3756}3757}37583759// Verify methods3760if (methods() != NULL) {3761Array<Method*>* methods = this->methods();3762for (int j = 0; j < methods->length(); j++) {3763guarantee(methods->at(j)->is_method(), "non-method in methods array");3764}3765for (int j = 0; j < methods->length() - 1; j++) {3766Method* m1 = methods->at(j);3767Method* m2 = methods->at(j + 1);3768guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3769}3770}37713772// Verify method ordering3773if (method_ordering() != NULL) {3774Array<int>* method_ordering = this->method_ordering();3775int length = method_ordering->length();3776if (JvmtiExport::can_maintain_original_method_order() ||3777((UseSharedSpaces || Arguments::is_dumping_archive()) && length != 0)) {3778guarantee(length == methods()->length(), "invalid method ordering length");3779jlong sum = 0;3780for (int j = 0; j < length; j++) {3781int original_index = method_ordering->at(j);3782guarantee(original_index >= 0, "invalid method ordering index");3783guarantee(original_index < length, "invalid method ordering index");3784sum += original_index;3785}3786// Verify sum of indices 0,1,...,length-13787guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");3788} else {3789guarantee(length == 0, "invalid method ordering length");3790}3791}37923793// Verify default methods3794if (default_methods() != NULL) {3795Array<Method*>* methods = this->default_methods();3796for (int j = 0; j < methods->length(); j++) {3797guarantee(methods->at(j)->is_method(), "non-method in methods array");3798}3799for (int j = 0; j < methods->length() - 1; j++) {3800Method* m1 = methods->at(j);3801Method* m2 = methods->at(j + 1);3802guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");3803}3804}38053806// Verify JNI static field identifiers3807if (jni_ids() != NULL) {3808jni_ids()->verify(this);3809}38103811// Verify other fields3812if (constants() != NULL) {3813guarantee(constants()->is_constantPool(), "should be constant pool");3814}3815}38163817void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {3818Klass::oop_verify_on(obj, st);3819VerifyFieldClosure blk;3820obj->oop_iterate(&blk);3821}382238233824// JNIid class for jfieldIDs only3825// Note to reviewers:3826// These JNI functions are just moved over to column 1 and not changed3827// in the compressed oops workspace.3828JNIid::JNIid(Klass* holder, int offset, JNIid* next) {3829_holder = holder;3830_offset = offset;3831_next = next;3832debug_only(_is_static_field_id = false;)3833}383438353836JNIid* JNIid::find(int offset) {3837JNIid* current = this;3838while (current != NULL) {3839if (current->offset() == offset) return current;3840current = current->next();3841}3842return NULL;3843}38443845void JNIid::deallocate(JNIid* current) {3846while (current != NULL) {3847JNIid* next = current->next();3848delete current;3849current = next;3850}3851}385238533854void JNIid::verify(Klass* holder) {3855int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();3856int end_field_offset;3857end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);38583859JNIid* current = this;3860while (current != NULL) {3861guarantee(current->holder() == holder, "Invalid klass in JNIid");3862#ifdef ASSERT3863int o = current->offset();3864if (current->is_static_field_id()) {3865guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");3866}3867#endif3868current = current->next();3869}3870}38713872void InstanceKlass::set_init_state(ClassState state) {3873#ifdef ASSERT3874bool good_state = is_shared() ? (_init_state <= state)3875: (_init_state < state);3876assert(good_state || state == allocated, "illegal state transition");3877#endif3878assert(_init_thread == NULL, "should be cleared before state change");3879_init_state = (u1)state;3880}38813882#if INCLUDE_JVMTI38833884// RedefineClasses() support for previous versions38853886// Globally, there is at least one previous version of a class to walk3887// during class unloading, which is saved because old methods in the class3888// are still running. Otherwise the previous version list is cleaned up.3889bool InstanceKlass::_has_previous_versions = false;38903891// Returns true if there are previous versions of a class for class3892// unloading only. Also resets the flag to false. purge_previous_version3893// will set the flag to true if there are any left, i.e., if there's any3894// work to do for next time. This is to avoid the expensive code cache3895// walk in CLDG::clean_deallocate_lists().3896bool InstanceKlass::has_previous_versions_and_reset() {3897bool ret = _has_previous_versions;3898log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",3899ret ? "true" : "false");3900_has_previous_versions = false;3901return ret;3902}39033904// Purge previous versions before adding new previous versions of the class and3905// during class unloading.3906void InstanceKlass::purge_previous_version_list() {3907assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");3908assert(has_been_redefined(), "Should only be called for main class");39093910// Quick exit.3911if (previous_versions() == NULL) {3912return;3913}39143915// This klass has previous versions so see what we can cleanup3916// while it is safe to do so.39173918int deleted_count = 0; // leave debugging breadcrumbs3919int live_count = 0;3920ClassLoaderData* loader_data = class_loader_data();3921assert(loader_data != NULL, "should never be null");39223923ResourceMark rm;3924log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());39253926// previous versions are linked together through the InstanceKlass3927InstanceKlass* pv_node = previous_versions();3928InstanceKlass* last = this;3929int version = 0;39303931// check the previous versions list3932for (; pv_node != NULL; ) {39333934ConstantPool* pvcp = pv_node->constants();3935assert(pvcp != NULL, "cp ref was unexpectedly cleared");39363937if (!pvcp->on_stack()) {3938// If the constant pool isn't on stack, none of the methods3939// are executing. Unlink this previous_version.3940// The previous version InstanceKlass is on the ClassLoaderData deallocate list3941// so will be deallocated during the next phase of class unloading.3942log_trace(redefine, class, iklass, purge)3943("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));3944// For debugging purposes.3945pv_node->set_is_scratch_class();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");4060// For debugging purposes.4061scratch_class->set_is_scratch_class();4062scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);4063return;4064}40654066// Add previous version if any methods are still running.4067// Set has_previous_version flag for processing during class unloading.4068_has_previous_versions = true;4069log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");4070assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");4071scratch_class->link_previous_versions(previous_versions());4072link_previous_versions(scratch_class);4073} // end add_previous_version()40744075#endif // INCLUDE_JVMTI40764077Method* InstanceKlass::method_with_idnum(int idnum) {4078Method* m = NULL;4079if (idnum < methods()->length()) {4080m = methods()->at(idnum);4081}4082if (m == NULL || m->method_idnum() != idnum) {4083for (int index = 0; index < methods()->length(); ++index) {4084m = methods()->at(index);4085if (m->method_idnum() == idnum) {4086return m;4087}4088}4089// None found, return null for the caller to handle.4090return NULL;4091}4092return m;4093}409440954096Method* InstanceKlass::method_with_orig_idnum(int idnum) {4097if (idnum >= methods()->length()) {4098return NULL;4099}4100Method* m = methods()->at(idnum);4101if (m != NULL && m->orig_method_idnum() == idnum) {4102return m;4103}4104// Obsolete method idnum does not match the original idnum4105for (int index = 0; index < methods()->length(); ++index) {4106m = methods()->at(index);4107if (m->orig_method_idnum() == idnum) {4108return m;4109}4110}4111// None found, return null for the caller to handle.4112return NULL;4113}411441154116Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {4117InstanceKlass* holder = get_klass_version(version);4118if (holder == NULL) {4119return NULL; // The version of klass is gone, no method is found4120}4121Method* method = holder->method_with_orig_idnum(idnum);4122return method;4123}41244125#if INCLUDE_JVMTI4126JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {4127return _cached_class_file;4128}41294130jint InstanceKlass::get_cached_class_file_len() {4131return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);4132}41334134unsigned char * InstanceKlass::get_cached_class_file_bytes() {4135return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);4136}4137#endif41384139bool InstanceKlass::is_shareable() const {4140#if INCLUDE_CDS4141ClassLoaderData* loader_data = class_loader_data();4142if (!SystemDictionaryShared::is_sharing_possible(loader_data)) {4143return false;4144}41454146if (is_hidden()) {4147return false;4148}41494150if (module()->is_patched()) {4151return false;4152}41534154return true;4155#else4156return false;4157#endif4158}41594160void InstanceKlass::log_to_classlist() const {4161#if INCLUDE_CDS4162ResourceMark rm;4163if (ClassListWriter::is_enabled()) {4164if (!ClassLoader::has_jrt_entry()) {4165warning("DumpLoadedClassList and CDS are not supported in exploded build");4166DumpLoadedClassList = NULL;4167return;4168}4169if (is_shareable()) {4170ClassListWriter w;4171w.stream()->print_cr("%s", name()->as_C_string());4172w.stream()->flush();4173}4174}4175#endif // INCLUDE_CDS4176}41774178// Make a step iterating over the class hierarchy under the root class.4179// Skips subclasses if requested.4180void ClassHierarchyIterator::next() {4181assert(_current != NULL, "required");4182if (_visit_subclasses && _current->subklass() != NULL) {4183_current = _current->subklass();4184return; // visit next subclass4185}4186_visit_subclasses = true; // reset4187while (_current->next_sibling() == NULL && _current != _root) {4188_current = _current->superklass(); // backtrack; no more sibling subclasses left4189}4190if (_current == _root) {4191// Iteration is over (back at root after backtracking). Invalidate the iterator.4192_current = NULL;4193return;4194}4195_current = _current->next_sibling();4196return; // visit next sibling subclass4197}419841994200