Path: blob/master/src/hotspot/share/oops/klassVtable.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/metaspaceShared.hpp"27#include "classfile/classLoaderDataGraph.hpp"28#include "classfile/javaClasses.hpp"29#include "classfile/systemDictionary.hpp"30#include "classfile/vmSymbols.hpp"31#include "interpreter/linkResolver.hpp"32#include "logging/log.hpp"33#include "logging/logStream.hpp"34#include "memory/resourceArea.hpp"35#include "memory/universe.hpp"36#include "oops/instanceKlass.inline.hpp"37#include "oops/klass.inline.hpp"38#include "oops/klassVtable.hpp"39#include "oops/method.hpp"40#include "oops/objArrayOop.hpp"41#include "oops/oop.inline.hpp"42#include "runtime/flags/flagSetting.hpp"43#include "runtime/java.hpp"44#include "runtime/handles.inline.hpp"45#include "runtime/safepointVerifiers.hpp"46#include "utilities/copy.hpp"4748inline InstanceKlass* klassVtable::ik() const {49return InstanceKlass::cast(_klass);50}5152bool klassVtable::is_preinitialized_vtable() {53return _klass->is_shared() && !MetaspaceShared::remapped_readwrite() && !_klass->is_shared_old_klass();54}555657// this function computes the vtable size (including the size needed for miranda58// methods) and the number of miranda methods in this class.59// Note on Miranda methods: Let's say there is a class C that implements60// interface I, and none of C's superclasses implements I.61// Let's say there is an abstract method m in I that neither C62// nor any of its super classes implement (i.e there is no method of any access,63// with the same name and signature as m), then m is a Miranda method which is64// entered as a public abstract method in C's vtable. From then on it should65// treated as any other public method in C for method over-ride purposes.66void klassVtable::compute_vtable_size_and_num_mirandas(67int* vtable_length_ret, int* num_new_mirandas,68GrowableArray<Method*>* all_mirandas, const Klass* super,69Array<Method*>* methods, AccessFlags class_flags, u2 major_version,70Handle classloader, Symbol* classname, Array<InstanceKlass*>* local_interfaces) {71NoSafepointVerifier nsv;7273// set up default result values74int vtable_length = 0;7576// start off with super's vtable length77vtable_length = super == NULL ? 0 : super->vtable_length();7879// go thru each method in the methods table to see if it needs a new entry80int len = methods->length();81for (int i = 0; i < len; i++) {82Method* method = methods->at(i);8384if (needs_new_vtable_entry(method, super, classloader, classname, class_flags, major_version)) {85assert(!method->is_private(), "private methods should not need a vtable entry");86vtable_length += vtableEntry::size(); // we need a new entry87}88}8990GrowableArray<Method*> new_mirandas(20);91// compute the number of mirandas methods that must be added to the end92get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces,93class_flags.is_interface());94*num_new_mirandas = new_mirandas.length();9596// Interfaces do not need interface methods in their vtables97// This includes miranda methods and during later processing, default methods98if (!class_flags.is_interface()) {99vtable_length += *num_new_mirandas * vtableEntry::size();100}101102if (Universe::is_bootstrapping() && vtable_length == 0) {103// array classes don't have their superclass set correctly during104// bootstrapping105vtable_length = Universe::base_vtable_size();106}107108if (super == NULL && vtable_length != Universe::base_vtable_size()) {109if (Universe::is_bootstrapping()) {110// Someone is attempting to override java.lang.Object incorrectly on the111// bootclasspath. The JVM cannot recover from this error including throwing112// an exception113vm_exit_during_initialization("Incompatible definition of java.lang.Object");114} else {115// Someone is attempting to redefine java.lang.Object incorrectly. The116// only way this should happen is from117// SystemDictionary::resolve_from_stream(), which will detect this later118// and throw a security exception. So don't assert here to let119// the exception occur.120vtable_length = Universe::base_vtable_size();121}122}123assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");124assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");125126*vtable_length_ret = vtable_length;127}128129// Copy super class's vtable to the first part (prefix) of this class's vtable,130// and return the number of entries copied. Expects that 'super' is the Java131// super class (arrays can have "array" super classes that must be skipped).132int klassVtable::initialize_from_super(Klass* super) {133if (super == NULL) {134return 0;135} else if (is_preinitialized_vtable()) {136// A shared class' vtable is preinitialized at dump time. No need to copy137// methods from super class for shared class, as that was already done138// during archiving time. However, if Jvmti has redefined a class,139// copy super class's vtable in case the super class has changed.140return super->vtable().length();141} else {142// copy methods from superKlass143klassVtable superVtable = super->vtable();144assert(superVtable.length() <= _length, "vtable too short");145#ifdef ASSERT146superVtable.verify(tty, true);147#endif148superVtable.copy_vtable_to(table());149if (log_develop_is_enabled(Trace, vtables)) {150ResourceMark rm;151log_develop_trace(vtables)("copy vtable from %s to %s size %d",152super->internal_name(), klass()->internal_name(),153_length);154}155return superVtable.length();156}157}158159//160// Revised lookup semantics introduced 1.3 (Kestrel beta)161void klassVtable::initialize_vtable(GrowableArray<InstanceKlass*>* supers) {162163// Note: Arrays can have intermediate array supers. Use java_super to skip them.164InstanceKlass* super = _klass->java_super();165166bool is_shared = _klass->is_shared();167Thread* current = Thread::current();168169if (!_klass->is_array_klass()) {170ResourceMark rm(current);171log_develop_debug(vtables)("Initializing: %s", _klass->name()->as_C_string());172}173174#ifdef ASSERT175oop* end_of_obj = (oop*)_klass + _klass->size();176oop* end_of_vtable = (oop*)&table()[_length];177assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");178#endif179180if (Universe::is_bootstrapping()) {181assert(!is_shared, "sanity");182// just clear everything183for (int i = 0; i < _length; i++) table()[i].clear();184return;185}186187int super_vtable_len = initialize_from_super(super);188if (_klass->is_array_klass()) {189assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");190} else {191assert(_klass->is_instance_klass(), "must be InstanceKlass");192193Array<Method*>* methods = ik()->methods();194int len = methods->length();195int initialized = super_vtable_len;196197// Check each of this class's methods against super;198// if override, replace in copy of super vtable, otherwise append to end199for (int i = 0; i < len; i++) {200// update_inherited_vtable can stop for gc - ensure using handles201methodHandle mh(current, methods->at(i));202203bool needs_new_entry = update_inherited_vtable(current, mh, super_vtable_len, -1, supers);204205if (needs_new_entry) {206put_method_at(mh(), initialized);207mh->set_vtable_index(initialized); // set primary vtable index208initialized++;209}210}211212// update vtable with default_methods213Array<Method*>* default_methods = ik()->default_methods();214if (default_methods != NULL) {215len = default_methods->length();216if (len > 0) {217Array<int>* def_vtable_indices = ik()->default_vtable_indices();218assert(def_vtable_indices != NULL, "should be created");219assert(def_vtable_indices->length() == len, "reinit vtable len?");220for (int i = 0; i < len; i++) {221bool needs_new_entry;222{223// Reduce the scope of this handle so that it is fetched again.224// The methodHandle keeps it from being deleted by RedefineClasses while225// we're using it.226methodHandle mh(current, default_methods->at(i));227assert(!mh->is_private(), "private interface method in the default method list");228needs_new_entry = update_inherited_vtable(current, mh, super_vtable_len, i, supers);229}230231// needs new entry232if (needs_new_entry) {233// Refetch this default method in case of redefinition that might234// happen during constraint checking in the update_inherited_vtable call above.235Method* method = default_methods->at(i);236put_method_at(method, initialized);237if (is_preinitialized_vtable()) {238// At runtime initialize_vtable is rerun for a shared class239// (loaded by the non-boot loader) as part of link_class_impl().240// The dumptime vtable index should be the same as the runtime index.241assert(def_vtable_indices->at(i) == initialized,242"dump time vtable index is different from runtime index");243} else {244def_vtable_indices->at_put(i, initialized); //set vtable index245}246initialized++;247}248}249}250}251252// add miranda methods; it will also return the updated initialized253// Interfaces do not need interface methods in their vtables254// This includes miranda methods and during later processing, default methods255if (!ik()->is_interface()) {256initialized = fill_in_mirandas(current, initialized);257}258259// In class hierarchies where the accessibility is not increasing (i.e., going from private ->260// package_private -> public/protected), the vtable might actually be smaller than our initial261// calculation, for classfile versions for which we do not do transitive override262// calculations.263if (ik()->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) {264assert(initialized == _length, "vtable initialization failed");265} else {266assert(initialized <= _length, "vtable initialization failed");267for(;initialized < _length; initialized++) {268table()[initialized].clear();269}270}271NOT_PRODUCT(verify(tty, true));272}273}274275// Returns true iff super_method can be overridden by a method in targetclassname276// See JLS 3rd edition 8.4.6.1277// Assumes name-signature match278// Note that the InstanceKlass of the method in the targetclassname has not always been created yet279static bool can_be_overridden(Method* super_method, Handle targetclassloader, Symbol* targetclassname) {280// Private methods can not be overridden281assert(!super_method->is_private(), "shouldn't call with a private method");282283// If super method is accessible, then override284if ((super_method->is_protected()) ||285(super_method->is_public())) {286return true;287}288// Package-private methods are not inherited outside of package289assert(super_method->is_package_private(), "must be package private");290return(super_method->method_holder()->is_same_class_package(targetclassloader(), targetclassname));291}292293294// Called for cases where a method does not override its superclass' vtable entry295// For bytecodes not produced by javac together it is possible that a method does not override296// the superclass's method, but might indirectly override a super-super class's vtable entry297// If none found, return a null superk, else return the superk of the method this does override298// For public and protected methods: if they override a superclass, they will299// also be overridden themselves appropriately.300// Private methods do not override, and are not overridden and are not in the vtable.301// Package Private methods are trickier:302// e.g. P1.A, pub m303// P2.B extends A, package private m304// P1.C extends B, public m305// P1.C.m needs to override P1.A.m and can not override P2.B.m306// Therefore: all package private methods need their own vtable entries for307// them to be the root of an inheritance overriding decision308// Package private methods may also override other vtable entries309InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper,310const methodHandle& target_method,311int vtable_index,312Handle target_loader,313Symbol* target_classname) {314315InstanceKlass* superk = initialsuper;316while (superk != NULL && superk->super() != NULL) {317klassVtable ssVtable = (superk->super())->vtable();318if (vtable_index < ssVtable.length()) {319Method* super_method = ssVtable.method_at(vtable_index);320#ifndef PRODUCT321Symbol* name= target_method()->name();322Symbol* signature = target_method()->signature();323assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch");324#endif325326if (can_be_overridden(super_method, target_loader, target_classname)) {327if (log_develop_is_enabled(Trace, vtables)) {328ResourceMark rm;329LogTarget(Trace, vtables) lt;330LogStream ls(lt);331char* sig = target_method()->name_and_sig_as_C_string();332ls.print("transitive overriding superclass %s with %s index %d, original flags: ",333super_method->method_holder()->internal_name(),334sig, vtable_index);335super_method->print_linkage_flags(&ls);336ls.print("overriders flags: ");337target_method->print_linkage_flags(&ls);338ls.cr();339}340341break; // return found superk342}343} else {344// super class has no vtable entry here, stop transitive search345superk = (InstanceKlass*)NULL;346break;347}348// if no override found yet, continue to search up349superk = superk->super() == NULL ? NULL : InstanceKlass::cast(superk->super());350}351352return superk;353}354355static void log_vtables(int i, bool overrides, const methodHandle& target_method,356Klass* target_klass, Method* super_method) {357#ifndef PRODUCT358if (log_develop_is_enabled(Trace, vtables)) {359ResourceMark rm;360LogTarget(Trace, vtables) lt;361LogStream ls(lt);362char* sig = target_method()->name_and_sig_as_C_string();363if (overrides) {364ls.print("overriding with %s index %d, original flags: ",365sig, i);366} else {367ls.print("NOT overriding with %s index %d, original flags: ",368sig, i);369}370super_method->print_linkage_flags(&ls);371ls.print("overriders flags: ");372target_method->print_linkage_flags(&ls);373ls.cr();374}375#endif376}377378// Update child's copy of super vtable for overrides379// OR return true if a new vtable entry is required.380// Only called for InstanceKlass's, i.e. not for arrays381// If that changed, could not use _klass as handle for klass382bool klassVtable::update_inherited_vtable(Thread* current,383const methodHandle& target_method,384int super_vtable_len, int default_index,385GrowableArray<InstanceKlass*>* supers) {386bool allocate_new = true;387388InstanceKlass* klass = ik();389390Array<int>* def_vtable_indices = NULL;391bool is_default = false;392393// default methods are non-private concrete methods in superinterfaces which are added394// to the vtable with their real method_holder.395// Since vtable and itable indices share the same storage, don't touch396// the default method's real vtable/itable index.397// default_vtable_indices stores the vtable value relative to this inheritor398if (default_index >= 0 ) {399is_default = true;400def_vtable_indices = klass->default_vtable_indices();401assert(!target_method->is_private(), "private interface method flagged as default");402assert(def_vtable_indices != NULL, "def vtable alloc?");403assert(default_index <= def_vtable_indices->length(), "def vtable len?");404} else {405assert(klass == target_method->method_holder(), "caller resp.");406// Initialize the method's vtable index to "nonvirtual".407// If we allocate a vtable entry, we will update it to a non-negative number.408target_method->set_vtable_index(Method::nonvirtual_vtable_index);409}410411// Private, static and <init> methods are never in412if (target_method->is_private() || target_method->is_static() ||413(target_method->name()->fast_compare(vmSymbols::object_initializer_name()) == 0)) {414return false;415}416417if (target_method->is_final_method(klass->access_flags())) {418// a final method never needs a new entry; final methods can be statically419// resolved and they have to be present in the vtable only if they override420// a super's method, in which case they re-use its entry421allocate_new = false;422} else if (klass->is_interface()) {423allocate_new = false; // see note below in needs_new_vtable_entry424// An interface never allocates new vtable slots, only inherits old ones.425// This method will either be assigned its own itable index later,426// or be assigned an inherited vtable index in the loop below.427// default methods inherited by classes store their vtable indices428// in the inheritor's default_vtable_indices.429// default methods inherited by interfaces may already have a430// valid itable index, if so, don't change it.431// Overpass methods in an interface will be assigned an itable index later432// by an inheriting class.433if ((!is_default || !target_method->has_itable_index())) {434target_method->set_vtable_index(Method::pending_itable_index);435}436}437438// we need a new entry if there is no superclass439Klass* super = klass->super();440if (super == NULL) {441return allocate_new;442}443444// search through the vtable and update overridden entries445// Since check_signature_loaders acquires SystemDictionary_lock446// which can block for gc, once we are in this loop, use handles447// For classfiles built with >= jdk7, we now look for transitive overrides448449Symbol* name = target_method->name();450Symbol* signature = target_method->signature();451452Klass* target_klass = target_method->method_holder();453assert(target_klass != NULL, "impossible");454if (target_klass == NULL) {455target_klass = _klass;456}457458HandleMark hm(current);459Handle target_loader(current, target_klass->class_loader());460461Symbol* target_classname = target_klass->name();462for(int i = 0; i < super_vtable_len; i++) {463Method* super_method;464if (is_preinitialized_vtable()) {465// If this is a shared class, the vtable is already in the final state (fully466// initialized). Need to look at the super's vtable.467klassVtable superVtable = super->vtable();468super_method = superVtable.method_at(i);469} else {470super_method = method_at(i);471}472// Check if method name matches. Ignore match if klass is an interface and the473// matching method is a non-public java.lang.Object method. (See JVMS 5.4.3.4)474// This is safe because the method at this slot should never get invoked.475// (TBD: put in a method to throw NoSuchMethodError if this slot is ever used.)476if (super_method->name() == name && super_method->signature() == signature &&477(!klass->is_interface() ||478!SystemDictionary::is_nonpublic_Object_method(super_method))) {479480// get super_klass for method_holder for the found method481InstanceKlass* super_klass = super_method->method_holder();482483// Whether the method is being overridden484bool overrides = false;485486// private methods are also never overridden487if (!super_method->is_private() &&488(is_default ||489can_be_overridden(super_method, target_loader, target_classname) ||490(klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION &&491(super_klass = find_transitive_override(super_klass,492target_method, i, target_loader,493target_classname)) != NULL))) {494495// Package private methods always need a new entry to root their own496// overriding. They may also override other methods.497if (!target_method->is_package_private()) {498allocate_new = false;499}500501// Set the vtable index before the constraint check safepoint, which potentially502// redefines this method if this method is a default method belonging to a503// super class or interface.504put_method_at(target_method(), i);505// Save super for constraint checking.506if (supers != NULL) {507supers->at_put(i, super_klass);508}509510overrides = true;511if (!is_default) {512target_method->set_vtable_index(i);513} else {514if (def_vtable_indices != NULL) {515if (is_preinitialized_vtable()) {516// At runtime initialize_vtable is rerun as part of link_class_impl()517// for a shared class loaded by the non-boot loader.518// The dumptime vtable index should be the same as the runtime index.519assert(def_vtable_indices->at(default_index) == i,520"dump time vtable index is different from runtime index");521} else {522def_vtable_indices->at_put(default_index, i);523}524}525assert(super_method->is_default_method() || super_method->is_overpass()526|| super_method->is_abstract(), "default override error");527}528} else {529overrides = false;530}531log_vtables(i, overrides, target_method, target_klass, super_method);532}533}534return allocate_new;535}536537void klassVtable::put_method_at(Method* m, int index) {538assert(!m->is_private(), "private methods should not be in vtable");539JVMTI_ONLY(assert(!m->is_old() || ik()->is_being_redefined(), "old methods should not be in vtable"));540if (is_preinitialized_vtable()) {541// At runtime initialize_vtable is rerun as part of link_class_impl()542// for shared class loaded by the non-boot loader to obtain the loader543// constraints based on the runtime classloaders' context. The dumptime544// method at the vtable index should be the same as the runtime method.545assert(table()[index].method() == m,546"archived method is different from the runtime method");547} else {548if (log_develop_is_enabled(Trace, vtables)) {549ResourceMark rm;550LogTarget(Trace, vtables) lt;551LogStream ls(lt);552const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>";553ls.print("adding %s at index %d, flags: ", sig, index);554if (m != NULL) {555m->print_linkage_flags(&ls);556}557ls.cr();558}559table()[index].set(m);560}561}562563void klassVtable::check_constraints(GrowableArray<InstanceKlass*>* supers, TRAPS) {564assert(supers->length() == length(), "lengths are different");565// For each method in the vtable, check constraints against any super class566// if overridden.567for (int i = 0; i < length(); i++) {568methodHandle target_method(THREAD, unchecked_method_at(i));569InstanceKlass* super_klass = supers->at(i);570if (target_method() != NULL && super_klass != NULL) {571// Do not check loader constraints for overpass methods because overpass572// methods are created by the jvm to throw exceptions.573if (!target_method->is_overpass()) {574// Override vtable entry if passes loader constraint check575// if loader constraint checking requested576// No need to visit his super, since he and his super577// have already made any needed loader constraints.578// Since loader constraints are transitive, it is enough579// to link to the first super, and we get all the others.580Handle super_loader(THREAD, super_klass->class_loader());581InstanceKlass* target_klass = target_method->method_holder();582Handle target_loader(THREAD, target_klass->class_loader());583584if (target_loader() != super_loader()) {585ResourceMark rm(THREAD);586Symbol* failed_type_symbol =587SystemDictionary::check_signature_loaders(target_method->signature(),588_klass,589target_loader, super_loader,590true);591if (failed_type_symbol != NULL) {592stringStream ss;593ss.print("loader constraint violation for class %s: when selecting "594"overriding method '", _klass->external_name());595target_method->print_external_name(&ss),596ss.print("' the class loader %s of the "597"selected method's type %s, and the class loader %s for its super "598"type %s have different Class objects for the type %s used in the signature (%s; %s)",599target_klass->class_loader_data()->loader_name_and_id(),600target_klass->external_name(),601super_klass->class_loader_data()->loader_name_and_id(),602super_klass->external_name(),603failed_type_symbol->as_klass_external_name(),604target_klass->class_in_module_of_loader(false, true),605super_klass->class_in_module_of_loader(false, true));606THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());607}608}609}610}611}612}613614void klassVtable::initialize_vtable_and_check_constraints(TRAPS) {615// Save a superclass from each vtable entry to do constraint checking616ResourceMark rm(THREAD);617GrowableArray<InstanceKlass*>* supers = new GrowableArray<InstanceKlass*>(_length, _length, NULL);618initialize_vtable(supers);619check_constraints(supers, CHECK);620}621622623// Find out if a method "m" with superclass "super", loader "classloader" and624// name "classname" needs a new vtable entry. Let P be a class package defined625// by "classloader" and "classname".626// NOTE: The logic used here is very similar to the one used for computing627// the vtables indices for a method. We cannot directly use that function because,628// we allocate the InstanceKlass at load time, and that requires that the629// superclass has been loaded.630// However, the vtable entries are filled in at link time, and therefore631// the superclass' vtable may not yet have been filled in.632bool klassVtable::needs_new_vtable_entry(Method* target_method,633const Klass* super,634Handle classloader,635Symbol* classname,636AccessFlags class_flags,637u2 major_version) {638if (class_flags.is_interface()) {639// Interfaces do not use vtables, except for java.lang.Object methods,640// so there is no point to assigning641// a vtable index to any of their local methods. If we refrain from doing this,642// we can use Method::_vtable_index to hold the itable index643return false;644}645646if (target_method->is_final_method(class_flags) ||647// a final method never needs a new entry; final methods can be statically648// resolved and they have to be present in the vtable only if they override649// a super's method, in which case they re-use its entry650(target_method->is_private()) ||651// private methods don't need to be in vtable652(target_method->is_static()) ||653// static methods don't need to be in vtable654(target_method->name()->fast_compare(vmSymbols::object_initializer_name()) == 0)655// <init> is never called dynamically-bound656) {657return false;658}659660// Concrete interface methods do not need new entries, they override661// abstract method entries using default inheritance rules662if (target_method->method_holder() != NULL &&663target_method->method_holder()->is_interface() &&664!target_method->is_abstract()) {665assert(target_method->is_default_method(),666"unexpected interface method type");667return false;668}669670// we need a new entry if there is no superclass671if (super == NULL) {672return true;673}674675// Package private methods always need a new entry to root their own676// overriding. This allows transitive overriding to work.677if (target_method->is_package_private()) {678return true;679}680681// search through the super class hierarchy to see if we need682// a new entry683Symbol* name = target_method->name();684Symbol* signature = target_method->signature();685const Klass* k = super;686Method* super_method = NULL;687InstanceKlass *holder = NULL;688Method* recheck_method = NULL;689bool found_pkg_prvt_method = false;690while (k != NULL) {691// lookup through the hierarchy for a method with matching name and sign.692super_method = InstanceKlass::cast(k)->lookup_method(name, signature);693if (super_method == NULL) {694break; // we still have to search for a matching miranda method695}696// get the class holding the matching method697InstanceKlass* superk = super_method->method_holder();698// we want only instance method matches699// ignore private methods found via lookup_method since they do not participate in overriding,700// and since we do override around them: e.g. a.m pub/b.m private/c.m pub,701// ignore private, c.m pub does override a.m pub702// For classes that were not javac'd together, we also do transitive overriding around703// methods that have less accessibility704if (!super_method->is_static() &&705!super_method->is_private()) {706if (can_be_overridden(super_method, classloader, classname)) {707return false;708// else keep looking for transitive overrides709}710// If we get here then one of the super classes has a package private method711// that will not get overridden because it is in a different package. But,712// that package private method does "override" any matching methods in super713// interfaces, so there will be no miranda vtable entry created. So, set flag714// to TRUE for use below, in case there are no methods in super classes that715// this target method overrides.716assert(super_method->is_package_private(), "super_method must be package private");717assert(!superk->is_same_class_package(classloader(), classname),718"Must be different packages");719found_pkg_prvt_method = true;720}721722// Start with lookup result and continue to search up, for versions supporting transitive override723if (major_version >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) {724k = superk->super(); // haven't found an override match yet; continue to look725} else {726break;727}728}729730// If found_pkg_prvt_method is set, then the ONLY matching method in the731// superclasses is package private in another package. That matching method will732// prevent a miranda vtable entry from being created. Because the target method can not733// override the package private method in another package, then it needs to be the root734// for its own vtable entry.735if (found_pkg_prvt_method) {736return true;737}738739// if the target method is public or protected it may have a matching740// miranda method in the super, whose entry it should re-use.741// Actually, to handle cases that javac would not generate, we need742// this check for all access permissions.743const InstanceKlass *sk = InstanceKlass::cast(super);744if (sk->has_miranda_methods()) {745if (sk->lookup_method_in_all_interfaces(name, signature, Klass::DefaultsLookupMode::find) != NULL) {746return false; // found a matching miranda; we do not need a new entry747}748}749return true; // found no match; we need a new entry750}751752// Support for miranda methods753754// get the vtable index of a miranda method with matching "name" and "signature"755int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) {756// search from the bottom, might be faster757for (int i = (length() - 1); i >= 0; i--) {758Method* m = table()[i].method();759if (is_miranda_entry_at(i) &&760m->name() == name && m->signature() == signature) {761return i;762}763}764return Method::invalid_vtable_index;765}766767// check if an entry at an index is miranda768// requires that method m at entry be declared ("held") by an interface.769bool klassVtable::is_miranda_entry_at(int i) {770Method* m = method_at(i);771InstanceKlass* holder = m->method_holder();772773// miranda methods are public abstract instance interface methods in a class's vtable774if (holder->is_interface()) {775assert(m->is_public(), "should be public");776assert(ik()->implements_interface(holder) , "this class should implement the interface");777if (is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super(), klass()->is_interface())) {778return true;779}780}781return false;782}783784// Check if a method is a miranda method, given a class's methods array,785// its default_method table and its super class.786// "Miranda" means an abstract non-private method that would not be787// overridden for the local class.788// A "miranda" method should only include non-private interface789// instance methods, i.e. not private methods, not static methods,790// not default methods (concrete interface methods), not overpass methods.791// If a given class already has a local (including overpass) method, a792// default method, or any of its superclasses has the same which would have793// overridden an abstract method, then this is not a miranda method.794//795// Miranda methods are checked multiple times.796// Pass 1: during class load/class file parsing: before vtable size calculation:797// include superinterface abstract and default methods (non-private instance).798// We include potential default methods to give them space in the vtable.799// During the first run, the current instanceKlass has not yet been800// created, the superclasses and superinterfaces do have instanceKlasses801// but may not have vtables, the default_methods list is empty, no overpasses.802// Default method generation uses the all_mirandas array as the starter set for803// maximally-specific default method calculation. So, for both classes and804// interfaces, it is necessary that the first pass will find all non-private805// interface instance methods, whether or not they are concrete.806//807// Pass 2: recalculated during vtable initialization: only include abstract methods.808// The goal of pass 2 is to walk through the superinterfaces to see if any of809// the superinterface methods (which were all abstract pre-default methods)810// need to be added to the vtable.811// With the addition of default methods, we have three new challenges:812// overpasses, static interface methods and private interface methods.813// Static and private interface methods do not get added to the vtable and814// are not seen by the method resolution process, so we skip those.815// Overpass methods are already in the vtable, so vtable lookup will816// find them and we don't need to add a miranda method to the end of817// the vtable. So we look for overpass methods and if they are found we818// return false. Note that we inherit our superclasses vtable, so819// the superclass' search also needs to use find_overpass so that if820// one is found we return false.821// False means - we don't need a miranda method added to the vtable.822//823// During the second run, default_methods is set up, so concrete methods from824// superinterfaces with matching names/signatures to default_methods are already825// in the default_methods list and do not need to be appended to the vtable826// as mirandas. Abstract methods may already have been handled via827// overpasses - either local or superclass overpasses, which may be828// in the vtable already.829//830// Pass 3: They are also checked by link resolution and selection,831// for invocation on a method (not interface method) reference that832// resolves to a method with an interface as its method_holder.833// Used as part of walking from the bottom of the vtable to find834// the vtable index for the miranda method.835//836// Part of the Miranda Rights in the US mean that if you do not have837// an attorney one will be appointed for you.838bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods,839Array<Method*>* default_methods, const Klass* super,840bool is_interface) {841if (m->is_static() || m->is_private() || m->is_overpass()) {842return false;843}844Symbol* name = m->name();845Symbol* signature = m->signature();846847// First look in local methods to see if already covered848if (InstanceKlass::find_local_method(class_methods, name, signature,849Klass::OverpassLookupMode::find,850Klass::StaticLookupMode::skip,851Klass::PrivateLookupMode::skip) != NULL)852{853return false;854}855856// Check local default methods857if ((default_methods != NULL) &&858(InstanceKlass::find_method(default_methods, name, signature) != NULL))859{860return false;861}862863// Iterate on all superclasses, which should be InstanceKlasses.864// Note that we explicitly look for overpasses at each level.865// Overpasses may or may not exist for supers for pass 1,866// they should have been created for pass 2 and later.867868for (const Klass* cursuper = super; cursuper != NULL; cursuper = cursuper->super())869{870Method* found_mth = InstanceKlass::cast(cursuper)->find_local_method(name, signature,871Klass::OverpassLookupMode::find,872Klass::StaticLookupMode::skip,873Klass::PrivateLookupMode::skip);874// Ignore non-public methods in java.lang.Object if klass is an interface.875if (found_mth != NULL && (!is_interface ||876!SystemDictionary::is_nonpublic_Object_method(found_mth))) {877return false;878}879}880881return true;882}883884// Scans current_interface_methods for miranda methods that do not885// already appear in new_mirandas, or default methods, and are also not defined-and-non-private886// in super (superclass). These mirandas are added to all_mirandas if it is887// not null; in addition, those that are not duplicates of miranda methods888// inherited by super from its interfaces are added to new_mirandas.889// Thus, new_mirandas will be the set of mirandas that this class introduces,890// all_mirandas will be the set of all mirandas applicable to this class891// including all defined in superclasses.892void klassVtable::add_new_mirandas_to_lists(893GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas,894Array<Method*>* current_interface_methods, Array<Method*>* class_methods,895Array<Method*>* default_methods, const Klass* super, bool is_interface) {896897// iterate thru the current interface's method to see if it a miranda898int num_methods = current_interface_methods->length();899for (int i = 0; i < num_methods; i++) {900Method* im = current_interface_methods->at(i);901bool is_duplicate = false;902int num_of_current_mirandas = new_mirandas->length();903// check for duplicate mirandas in different interfaces we implement904for (int j = 0; j < num_of_current_mirandas; j++) {905Method* miranda = new_mirandas->at(j);906if ((im->name() == miranda->name()) &&907(im->signature() == miranda->signature())) {908is_duplicate = true;909break;910}911}912913if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable914if (is_miranda(im, class_methods, default_methods, super, is_interface)) { // is it a miranda at all?915const InstanceKlass *sk = InstanceKlass::cast(super);916// check if it is a duplicate of a super's miranda917if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::DefaultsLookupMode::find) == NULL) {918new_mirandas->append(im);919}920if (all_mirandas != NULL) {921all_mirandas->append(im);922}923}924}925}926}927928void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas,929GrowableArray<Method*>* all_mirandas,930const Klass* super,931Array<Method*>* class_methods,932Array<Method*>* default_methods,933Array<InstanceKlass*>* local_interfaces,934bool is_interface) {935assert((new_mirandas->length() == 0) , "current mirandas must be 0");936937// iterate thru the local interfaces looking for a miranda938int num_local_ifs = local_interfaces->length();939for (int i = 0; i < num_local_ifs; i++) {940InstanceKlass *ik = local_interfaces->at(i);941add_new_mirandas_to_lists(new_mirandas, all_mirandas,942ik->methods(), class_methods,943default_methods, super, is_interface);944// iterate thru each local's super interfaces945Array<InstanceKlass*>* super_ifs = ik->transitive_interfaces();946int num_super_ifs = super_ifs->length();947for (int j = 0; j < num_super_ifs; j++) {948InstanceKlass *sik = super_ifs->at(j);949add_new_mirandas_to_lists(new_mirandas, all_mirandas,950sik->methods(), class_methods,951default_methods, super, is_interface);952}953}954}955956// Discover miranda methods ("miranda" = "interface abstract, no binding"),957// and append them into the vtable starting at index initialized,958// return the new value of initialized.959// Miranda methods use vtable entries, but do not get assigned a vtable_index960// The vtable_index is discovered by searching from the end of the vtable961int klassVtable::fill_in_mirandas(Thread* current, int initialized) {962ResourceMark rm(current);963GrowableArray<Method*> mirandas(20);964get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(),965ik()->default_methods(), ik()->local_interfaces(),966klass()->is_interface());967for (int i = 0; i < mirandas.length(); i++) {968if (log_develop_is_enabled(Trace, vtables)) {969Method* meth = mirandas.at(i);970LogTarget(Trace, vtables) lt;971LogStream ls(lt);972if (meth != NULL) {973char* sig = meth->name_and_sig_as_C_string();974ls.print("fill in mirandas with %s index %d, flags: ",975sig, initialized);976meth->print_linkage_flags(&ls);977ls.cr();978}979}980put_method_at(mirandas.at(i), initialized);981++initialized;982}983return initialized;984}985986// Copy this class's vtable to the vtable beginning at start.987// Used to copy superclass vtable to prefix of subclass's vtable.988void klassVtable::copy_vtable_to(vtableEntry* start) {989Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());990}991992#if INCLUDE_JVMTI993bool klassVtable::adjust_default_method(int vtable_index, Method* old_method, Method* new_method) {994// If old_method is default, find this vtable index in default_vtable_indices995// and replace that method in the _default_methods list996bool updated = false;997998Array<Method*>* default_methods = ik()->default_methods();999if (default_methods != NULL) {1000int len = default_methods->length();1001for (int idx = 0; idx < len; idx++) {1002if (vtable_index == ik()->default_vtable_indices()->at(idx)) {1003if (default_methods->at(idx) == old_method) {1004default_methods->at_put(idx, new_method);1005updated = true;1006}1007break;1008}1009}1010}1011return updated;1012}10131014// search the vtable for uses of either obsolete or EMCP methods1015void klassVtable::adjust_method_entries(bool * trace_name_printed) {1016int prn_enabled = 0;1017ResourceMark rm;10181019for (int index = 0; index < length(); index++) {1020Method* old_method = unchecked_method_at(index);1021if (old_method == NULL || !old_method->is_old()) {1022continue; // skip uninteresting entries1023}1024assert(!old_method->is_deleted(), "vtable methods may not be deleted");10251026Method* new_method = old_method->get_new_method();1027put_method_at(new_method, index);10281029// For default methods, need to update the _default_methods array1030// which can only have one method entry for a given signature1031bool updated_default = false;1032if (old_method->is_default_method()) {1033updated_default = adjust_default_method(index, old_method, new_method);1034}10351036if (!(*trace_name_printed)) {1037log_info(redefine, class, update)1038("adjust: klassname=%s for methods from name=%s",1039_klass->external_name(), old_method->method_holder()->external_name());1040*trace_name_printed = true;1041}1042log_trace(redefine, class, update, vtables)1043("vtable method update: class: %s method: %s, updated default = %s",1044_klass->external_name(), new_method->external_name(), updated_default ? "true" : "false");1045}1046}10471048// a vtable should never contain old or obsolete methods1049bool klassVtable::check_no_old_or_obsolete_entries() {1050ResourceMark rm;10511052for (int i = 0; i < length(); i++) {1053Method* m = unchecked_method_at(i);1054if (m != NULL &&1055(NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {1056log_trace(redefine, class, update, vtables)1057("vtable check found old method entry: class: %s old: %d obsolete: %d, method: %s",1058_klass->external_name(), m->is_old(), m->is_obsolete(), m->external_name());1059return false;1060}1061}1062return true;1063}10641065void klassVtable::dump_vtable() {1066tty->print_cr("vtable dump --");1067for (int i = 0; i < length(); i++) {1068Method* m = unchecked_method_at(i);1069if (m != NULL) {1070tty->print(" (%5d) ", i);1071m->access_flags().print_on(tty);1072if (m->is_default_method()) {1073tty->print("default ");1074}1075if (m->is_overpass()) {1076tty->print("overpass");1077}1078tty->print(" -- ");1079m->print_name(tty);1080tty->cr();1081}1082}1083}1084#endif // INCLUDE_JVMTI10851086//-----------------------------------------------------------------------------------------1087// Itable code10881089// Initialize a itableMethodEntry1090void itableMethodEntry::initialize(InstanceKlass* klass, Method* m) {1091if (m == NULL) return;10921093#ifdef ASSERT1094if (MetaspaceShared::is_in_shared_metaspace((void*)&_method) &&1095!MetaspaceShared::remapped_readwrite() &&1096!m->method_holder()->can_be_verified_at_dumptime() &&1097!klass->can_be_verified_at_dumptime()) {1098// At runtime initialize_itable is rerun as part of link_class_impl()1099// for a shared class loaded by the non-boot loader.1100// The dumptime itable method entry should be the same as the runtime entry.1101// For a shared old class which was not linked during dump time, we can't compare the dumptime1102// itable method entry with the runtime entry.1103assert(_method == m, "sanity");1104}1105#endif1106_method = m;1107}11081109klassItable::klassItable(InstanceKlass* klass) {1110_klass = klass;11111112if (klass->itable_length() > 0) {1113itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();1114if (offset_entry != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized1115// First offset entry points to the first method_entry1116intptr_t* method_entry = (intptr_t *)(((address)klass) + offset_entry->offset());1117intptr_t* end = klass->end_of_itable();11181119_table_offset = (intptr_t*)offset_entry - (intptr_t*)klass;1120_size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();1121_size_method_table = (end - method_entry) / itableMethodEntry::size();1122assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");1123return;1124}1125}11261127// The length of the itable was either zero, or it has not yet been initialized.1128_table_offset = 0;1129_size_offset_table = 0;1130_size_method_table = 0;1131}11321133static int initialize_count = 0;11341135// Initialization1136void klassItable::initialize_itable(GrowableArray<Method*>* supers) {1137if (_klass->is_interface()) {1138// This needs to go after vtable indices are assigned but1139// before implementors need to know the number of itable indices.1140assign_itable_indices_for_interface(InstanceKlass::cast(_klass));1141}11421143// Cannot be setup doing bootstrapping, interfaces don't have1144// itables, and klass with only ones entry have empty itables1145if (Universe::is_bootstrapping() ||1146_klass->is_interface() ||1147_klass->itable_length() == itableOffsetEntry::size()) return;11481149// There's alway an extra itable entry so we can null-terminate it.1150guarantee(size_offset_table() >= 1, "too small");1151int num_interfaces = size_offset_table() - 1;1152if (num_interfaces > 0) {1153if (log_develop_is_enabled(Debug, itables)) {1154ResourceMark rm;1155log_develop_debug(itables)("%3d: Initializing itables for %s", ++initialize_count,1156_klass->name()->as_C_string());1157}11581159// Iterate through all interfaces1160for(int i = 0; i < num_interfaces; i++) {1161itableOffsetEntry* ioe = offset_entry(i);1162InstanceKlass* interf = ioe->interface_klass();1163assert(interf != NULL && ioe->offset() != 0, "bad offset entry in itable");1164initialize_itable_for_interface(ioe->offset(), interf, supers,1165(ioe->offset() - offset_entry(0)->offset())/wordSize);1166}1167}1168// Check that the last entry is empty1169itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);1170guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");1171}11721173void klassItable::check_constraints(GrowableArray<Method*>* supers, TRAPS) {11741175assert(_size_method_table == supers->length(), "wrong size");1176itableMethodEntry* ime = method_entry(0);1177for (int i = 0; i < _size_method_table; i++) {1178Method* target = ime->method();1179Method* interface_method = supers->at(i); // method overridden11801181if (target != NULL && interface_method != NULL) {1182InstanceKlass* method_holder = target->method_holder();1183InstanceKlass* interf = interface_method->method_holder();1184HandleMark hm(THREAD);1185Handle method_holder_loader(THREAD, method_holder->class_loader());1186Handle interface_loader(THREAD, interf->class_loader());11871188if (method_holder_loader() != interface_loader()) {1189ResourceMark rm(THREAD);1190Symbol* failed_type_symbol =1191SystemDictionary::check_signature_loaders(target->signature(),1192_klass,1193method_holder_loader,1194interface_loader,1195true);1196if (failed_type_symbol != NULL) {1197stringStream ss;1198ss.print("loader constraint violation in interface itable"1199" initialization for class %s: when selecting method '",1200_klass->external_name());1201interface_method->print_external_name(&ss),1202ss.print("' the class loader %s for super interface %s, and the class"1203" loader %s of the selected method's %s, %s have"1204" different Class objects for the type %s used in the signature (%s; %s)",1205interf->class_loader_data()->loader_name_and_id(),1206interf->external_name(),1207method_holder->class_loader_data()->loader_name_and_id(),1208method_holder->external_kind(),1209method_holder->external_name(),1210failed_type_symbol->as_klass_external_name(),1211interf->class_in_module_of_loader(false, true),1212method_holder->class_in_module_of_loader(false, true));1213THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());1214}1215}1216}1217ime++;1218}1219}12201221void klassItable::initialize_itable_and_check_constraints(TRAPS) {1222// Save a super interface from each itable entry to do constraint checking1223ResourceMark rm(THREAD);1224GrowableArray<Method*>* supers =1225new GrowableArray<Method*>(_size_method_table, _size_method_table, NULL);1226initialize_itable(supers);1227check_constraints(supers, CHECK);1228}12291230inline bool interface_method_needs_itable_index(Method* m) {1231if (m->is_static()) return false; // e.g., Stream.empty1232if (m->is_initializer()) return false; // <init> or <clinit>1233if (m->is_private()) return false; // uses direct call1234// If an interface redeclares a method from java.lang.Object,1235// it should already have a vtable index, don't touch it.1236// e.g., CharSequence.toString (from initialize_vtable)1237// if (m->has_vtable_index()) return false; // NO!1238return true;1239}12401241int klassItable::assign_itable_indices_for_interface(InstanceKlass* klass) {1242// an interface does not have an itable, but its methods need to be numbered1243if (log_develop_is_enabled(Trace, itables)) {1244ResourceMark rm;1245log_develop_debug(itables)("%3d: Initializing itable indices for interface %s",1246++initialize_count, klass->name()->as_C_string());1247}12481249Array<Method*>* methods = klass->methods();1250int nof_methods = methods->length();1251int ime_num = 0;1252for (int i = 0; i < nof_methods; i++) {1253Method* m = methods->at(i);1254if (interface_method_needs_itable_index(m)) {1255assert(!m->is_final_method(), "no final interface methods");1256// If m is already assigned a vtable index, do not disturb it.1257if (log_develop_is_enabled(Trace, itables)) {1258ResourceMark rm;1259LogTarget(Trace, itables) lt;1260LogStream ls(lt);1261assert(m != NULL, "methods can never be null");1262const char* sig = m->name_and_sig_as_C_string();1263if (m->has_vtable_index()) {1264ls.print("vtable index %d for method: %s, flags: ", m->vtable_index(), sig);1265} else {1266ls.print("itable index %d for method: %s, flags: ", ime_num, sig);1267}1268m->print_linkage_flags(&ls);1269ls.cr();1270}1271if (!m->has_vtable_index()) {1272// A shared method could have an initialized itable_index that1273// is < 0.1274assert(m->vtable_index() == Method::pending_itable_index ||1275m->is_shared(),1276"set by initialize_vtable");1277m->set_itable_index(ime_num);1278// Progress to next itable entry1279ime_num++;1280}1281}1282}1283assert(ime_num == method_count_for_interface(klass), "proper sizing");1284return ime_num;1285}12861287int klassItable::method_count_for_interface(InstanceKlass* interf) {1288assert(interf->is_interface(), "must be");1289Array<Method*>* methods = interf->methods();1290int nof_methods = methods->length();1291int length = 0;1292while (nof_methods > 0) {1293Method* m = methods->at(nof_methods-1);1294if (m->has_itable_index()) {1295length = m->itable_index() + 1;1296break;1297}1298nof_methods -= 1;1299}1300#ifdef ASSERT1301int nof_methods_copy = nof_methods;1302while (nof_methods_copy > 0) {1303Method* mm = methods->at(--nof_methods_copy);1304assert(!mm->has_itable_index() || mm->itable_index() < length, "");1305}1306#endif //ASSERT1307// return the rightmost itable index, plus one; or 0 if no methods have1308// itable indices1309return length;1310}131113121313void klassItable::initialize_itable_for_interface(int method_table_offset, InstanceKlass* interf,1314GrowableArray<Method*>* supers,1315int start_offset) {1316assert(interf->is_interface(), "must be");1317Array<Method*>* methods = interf->methods();1318int nof_methods = methods->length();13191320int ime_count = method_count_for_interface(interf);1321for (int i = 0; i < nof_methods; i++) {1322Method* m = methods->at(i);1323Method* target = NULL;1324if (m->has_itable_index()) {1325// This search must match the runtime resolution, i.e. selection search for invokeinterface1326// to correctly enforce loader constraints for interface method inheritance.1327// Private methods are skipped as a private class method can never be the implementation1328// of an interface method.1329// Invokespecial does not perform selection based on the receiver, so it does not use1330// the cached itable.1331target = LinkResolver::lookup_instance_method_in_klasses(_klass, m->name(), m->signature(),1332Klass::PrivateLookupMode::skip);1333}1334if (target == NULL || !target->is_public() || target->is_abstract() || target->is_overpass()) {1335assert(target == NULL || !target->is_overpass() || target->is_public(),1336"Non-public overpass method!");1337// Entry does not resolve. Leave it empty for AbstractMethodError or other error.1338if (!(target == NULL) && !target->is_public()) {1339// Stuff an IllegalAccessError throwing method in there instead.1340itableOffsetEntry::method_entry(_klass, method_table_offset)[m->itable_index()].1341initialize(_klass, Universe::throw_illegal_access_error());1342}1343} else {13441345int ime_num = m->itable_index();1346assert(ime_num < ime_count, "oob");13471348// Save super interface method to perform constraint checks.1349// The method is in the error message, that's why.1350if (supers != NULL) {1351supers->at_put(start_offset + ime_num, m);1352}13531354itableOffsetEntry::method_entry(_klass, method_table_offset)[ime_num].initialize(_klass, target);1355if (log_develop_is_enabled(Trace, itables)) {1356ResourceMark rm;1357if (target != NULL) {1358LogTarget(Trace, itables) lt;1359LogStream ls(lt);1360char* sig = target->name_and_sig_as_C_string();1361ls.print("interface: %s, ime_num: %d, target: %s, method_holder: %s ",1362interf->internal_name(), ime_num, sig,1363target->method_holder()->internal_name());1364ls.print("target_method flags: ");1365target->print_linkage_flags(&ls);1366ls.cr();1367}1368}1369}1370}1371}13721373#if INCLUDE_JVMTI1374// search the itable for uses of either obsolete or EMCP methods1375void klassItable::adjust_method_entries(bool * trace_name_printed) {1376ResourceMark rm;1377itableMethodEntry* ime = method_entry(0);13781379for (int i = 0; i < _size_method_table; i++, ime++) {1380Method* old_method = ime->method();1381if (old_method == NULL || !old_method->is_old()) {1382continue; // skip uninteresting entries1383}1384assert(!old_method->is_deleted(), "itable methods may not be deleted");1385Method* new_method = old_method->get_new_method();1386ime->initialize(_klass, new_method);13871388if (!(*trace_name_printed)) {1389log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());1390*trace_name_printed = true;1391}1392log_trace(redefine, class, update, itables)1393("itable method update: class: %s method: %s", _klass->external_name(), new_method->external_name());1394}1395}13961397// an itable should never contain old or obsolete methods1398bool klassItable::check_no_old_or_obsolete_entries() {1399ResourceMark rm;1400itableMethodEntry* ime = method_entry(0);14011402for (int i = 0; i < _size_method_table; i++) {1403Method* m = ime->method();1404if (m != NULL &&1405(NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {1406log_trace(redefine, class, update, itables)1407("itable check found old method entry: class: %s old: %d obsolete: %d, method: %s",1408_klass->external_name(), m->is_old(), m->is_obsolete(), m->external_name());1409return false;1410}1411ime++;1412}1413return true;1414}14151416void klassItable::dump_itable() {1417itableMethodEntry* ime = method_entry(0);1418tty->print_cr("itable dump --");1419for (int i = 0; i < _size_method_table; i++) {1420Method* m = ime->method();1421if (m != NULL) {1422tty->print(" (%5d) ", i);1423m->access_flags().print_on(tty);1424if (m->is_default_method()) {1425tty->print("default ");1426}1427tty->print(" -- ");1428m->print_name(tty);1429tty->cr();1430}1431ime++;1432}1433}1434#endif // INCLUDE_JVMTI14351436// Setup1437class InterfaceVisiterClosure : public StackObj {1438public:1439virtual void doit(InstanceKlass* intf, int method_count) = 0;1440};14411442// Visit all interfaces with at least one itable method1443void visit_all_interfaces(Array<InstanceKlass*>* transitive_intf, InterfaceVisiterClosure *blk) {1444// Handle array argument1445for(int i = 0; i < transitive_intf->length(); i++) {1446InstanceKlass* intf = transitive_intf->at(i);1447assert(intf->is_interface(), "sanity check");14481449// Find no. of itable methods1450int method_count = 0;1451// method_count = klassItable::method_count_for_interface(intf);1452Array<Method*>* methods = intf->methods();1453if (methods->length() > 0) {1454for (int i = methods->length(); --i >= 0; ) {1455if (interface_method_needs_itable_index(methods->at(i))) {1456method_count++;1457}1458}1459}14601461// Visit all interfaces which either have any methods or can participate in receiver type check.1462// We do not bother to count methods in transitive interfaces, although that would allow us to skip1463// this step in the rare case of a zero-method interface extending another zero-method interface.1464if (method_count > 0 || intf->transitive_interfaces()->length() > 0) {1465blk->doit(intf, method_count);1466}1467}1468}14691470class CountInterfacesClosure : public InterfaceVisiterClosure {1471private:1472int _nof_methods;1473int _nof_interfaces;1474public:1475CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }14761477int nof_methods() const { return _nof_methods; }1478int nof_interfaces() const { return _nof_interfaces; }14791480void doit(InstanceKlass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }1481};14821483class SetupItableClosure : public InterfaceVisiterClosure {1484private:1485itableOffsetEntry* _offset_entry;1486itableMethodEntry* _method_entry;1487address _klass_begin;1488public:1489SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {1490_klass_begin = klass_begin;1491_offset_entry = offset_entry;1492_method_entry = method_entry;1493}14941495itableMethodEntry* method_entry() const { return _method_entry; }14961497void doit(InstanceKlass* intf, int method_count) {1498int offset = ((address)_method_entry) - _klass_begin;1499_offset_entry->initialize(intf, offset);1500_offset_entry++;1501_method_entry += method_count;1502}1503};15041505int klassItable::compute_itable_size(Array<InstanceKlass*>* transitive_interfaces) {1506// Count no of interfaces and total number of interface methods1507CountInterfacesClosure cic;1508visit_all_interfaces(transitive_interfaces, &cic);15091510// There's alway an extra itable entry so we can null-terminate it.1511int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());15121513// Statistics1514update_stats(itable_size * wordSize);15151516return itable_size;1517}151815191520// Fill out offset table and interface klasses into the itable space1521void klassItable::setup_itable_offset_table(InstanceKlass* klass) {1522if (klass->itable_length() == 0) return;1523assert(!klass->is_interface(), "Should have zero length itable");15241525// Count no of interfaces and total number of interface methods1526CountInterfacesClosure cic;1527visit_all_interfaces(klass->transitive_interfaces(), &cic);1528int nof_methods = cic.nof_methods();1529int nof_interfaces = cic.nof_interfaces();15301531// Add one extra entry so we can null-terminate the table1532nof_interfaces++;15331534assert(compute_itable_size(klass->transitive_interfaces()) ==1535calc_itable_size(nof_interfaces, nof_methods),1536"mismatch calculation of itable size");15371538// Fill-out offset table1539itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();1540itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);1541intptr_t* end = klass->end_of_itable();1542assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)");1543assert((oop*)(end) == (oop*)(ime + nof_methods), "wrong offset calculation (2)");15441545// Visit all interfaces and initialize itable offset table1546SetupItableClosure sic((address)klass, ioe, ime);1547visit_all_interfaces(klass->transitive_interfaces(), &sic);15481549#ifdef ASSERT1550ime = sic.method_entry();1551oop* v = (oop*) klass->end_of_itable();1552assert( (oop*)(ime) == v, "wrong offset calculation (2)");1553#endif1554}15551556void klassVtable::verify(outputStream* st, bool forced) {1557// make sure table is initialized1558if (!Universe::is_fully_initialized()) return;1559#ifndef PRODUCT1560// avoid redundant verifies1561if (!forced && _verify_count == Universe::verify_count()) return;1562_verify_count = Universe::verify_count();1563#endif1564oop* end_of_obj = (oop*)_klass + _klass->size();1565oop* end_of_vtable = (oop *)&table()[_length];1566if (end_of_vtable > end_of_obj) {1567ResourceMark rm;1568fatal("klass %s: klass object too short (vtable extends beyond end)",1569_klass->internal_name());1570}15711572for (int i = 0; i < _length; i++) table()[i].verify(this, st);1573// verify consistency with superKlass vtable1574Klass* super = _klass->super();1575if (super != NULL) {1576InstanceKlass* sk = InstanceKlass::cast(super);1577klassVtable vt = sk->vtable();1578for (int i = 0; i < vt.length(); i++) {1579verify_against(st, &vt, i);1580}1581}1582}15831584void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {1585vtableEntry* vte = &vt->table()[index];1586if (vte->method()->name() != table()[index].method()->name() ||1587vte->method()->signature() != table()[index].method()->signature()) {1588fatal("mismatched name/signature of vtable entries");1589}1590}15911592#ifndef PRODUCT1593void klassVtable::print() {1594ResourceMark rm;1595tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());1596for (int i = 0; i < length(); i++) {1597table()[i].print();1598tty->cr();1599}1600}1601#endif16021603void vtableEntry::verify(klassVtable* vt, outputStream* st) {1604Klass* vtklass = vt->klass();1605if (vtklass->is_instance_klass() &&1606(InstanceKlass::cast(vtklass)->major_version() >= klassVtable::VTABLE_TRANSITIVE_OVERRIDE_VERSION)) {1607assert(method() != NULL, "must have set method");1608}1609if (method() != NULL) {1610method()->verify();1611// we sub_type, because it could be a miranda method1612if (!vtklass->is_subtype_of(method()->method_holder())) {1613#ifndef PRODUCT1614print();1615#endif1616fatal("vtableEntry " PTR_FORMAT ": method is from subclass", p2i(this));1617}1618}1619}16201621#ifndef PRODUCT16221623void vtableEntry::print() {1624ResourceMark rm;1625tty->print("vtableEntry %s: ", method()->name()->as_C_string());1626if (Verbose) {1627tty->print("m " PTR_FORMAT " ", p2i(method()));1628}1629}16301631class VtableStats : AllStatic {1632public:1633static int no_klasses; // # classes with vtables1634static int no_array_klasses; // # array classes1635static int no_instance_klasses; // # instanceKlasses1636static int sum_of_vtable_len; // total # of vtable entries1637static int sum_of_array_vtable_len; // total # of vtable entries in array klasses only1638static int fixed; // total fixed overhead in bytes1639static int filler; // overhead caused by filler bytes1640static int entries; // total bytes consumed by vtable entries1641static int array_entries; // total bytes consumed by array vtable entries16421643static void do_class(Klass* k) {1644Klass* kl = k;1645klassVtable vt = kl->vtable();1646no_klasses++;1647if (kl->is_instance_klass()) {1648no_instance_klasses++;1649kl->array_klasses_do(do_class);1650}1651if (kl->is_array_klass()) {1652no_array_klasses++;1653sum_of_array_vtable_len += vt.length();1654}1655sum_of_vtable_len += vt.length();1656}16571658static void compute() {1659LockedClassesDo locked_do_class(&do_class);1660ClassLoaderDataGraph::classes_do(&locked_do_class);1661fixed = no_klasses * oopSize; // vtable length1662// filler size is a conservative approximation1663filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1);1664entries = sizeof(vtableEntry) * sum_of_vtable_len;1665array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;1666}1667};16681669int VtableStats::no_klasses = 0;1670int VtableStats::no_array_klasses = 0;1671int VtableStats::no_instance_klasses = 0;1672int VtableStats::sum_of_vtable_len = 0;1673int VtableStats::sum_of_array_vtable_len = 0;1674int VtableStats::fixed = 0;1675int VtableStats::filler = 0;1676int VtableStats::entries = 0;1677int VtableStats::array_entries = 0;16781679void klassVtable::print_statistics() {1680ResourceMark rm;1681VtableStats::compute();1682tty->print_cr("vtable statistics:");1683tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);1684int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;1685tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);1686tty->print_cr("%6d bytes filler overhead", VtableStats::filler);1687tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);1688tty->print_cr("%6d bytes total", total);1689}16901691int klassItable::_total_classes; // Total no. of classes with itables1692size_t klassItable::_total_size; // Total no. of bytes used for itables16931694void klassItable::print_statistics() {1695tty->print_cr("itable statistics:");1696tty->print_cr("%6d classes with itables", _total_classes);1697tty->print_cr(SIZE_FORMAT_W(6) " K uses for itables (average by class: " SIZE_FORMAT " bytes)",1698_total_size / K, _total_size / _total_classes);1699}17001701#endif // PRODUCT170217031704