public class Animal{
public void say(){
System.out.println("is animal");
}
public static void main(String[] args){
Animal animal = new Dog();
run(animal);
animal = new Cat();
run(animal);
}
public static void run(Animal animal){
animal.say();
}
}
class Dog extends Animal{
public void say(){
System.out.println("is Dog");
}
}
class Cat extends Animal{
public void say(){
System.out.println("is Cat");
}
}
void klassVtable::compute_vtable_size_and_num_mirandas(
int* vtable_length_ret, int* num_new_mirandas,
GrowableArray<Method*>* all_mirandas, Klass* super,
Array<Method*>* methods, AccessFlags class_flags,
Handle classloader, Symbol* classname, Array<Klass*>* local_interfaces,
TRAPS) {
No_Safepoint_Verifier nsv;
// set up default result values
int vtable_length = 0;
// start off with super's vtable length
InstanceKlass* sk = (InstanceKlass*)super;
//获取父类 vtable 的大小,并将当前类的 vtable 的大小设置为父类 vtable 的大小。
vtable_length = super == NULL ? 0 : sk->vtable_length();
// go thru each method in the methods table to see if it needs a new entry
int len = methods->length();//方法个数
for (int i = 0; i < len; i++) {
assert(methods->at(i)->is_method(), "must be a Method*");
methodHandle mh(THREAD, methods->at(i));
/*循环遍历当前 Java 类的每一个方法 ,调用 needs_new_vtable_entry()函数进行判断,
如果判断的结果是 true ,则将 vtable 的大小增 1 */
if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) {
vtable_length += vtableEntry::size(); // we need a new entry
}
}
GrowableArray<Method*> new_mirandas(20);
// compute the number of mirandas methods that must be added to the end
get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces);
*num_new_mirandas = new_mirandas.length();
// Interfaces do not need interface methods in their vtables
// This includes miranda methods and during later processing, default methods
if (!class_flags.is_interface()) {
vtable_length += *num_new_mirandas * vtableEntry::size();
}
if (Universe::is_bootstrapping() && vtable_length == 0) {
// array classes don't have their superclass set correctly during
// bootstrapping
vtable_length = Universe::base_vtable_size();
}
if (super == NULL && !Universe::is_bootstrapping() &&
vtable_length != Universe::base_vtable_size()) {
// Someone is attempting to redefine java.lang.Object incorrectly. The
// only way this should happen is from
// SystemDictionary::resolve_from_stream(), which will detect this later
// and throw a security exception. So don't assert here to let
// the exception occur.
vtable_length = Universe::base_vtable_size();
}
assert(super != NULL || vtable_length == Universe::base_vtable_size(),
"bad vtable size for class Object");
assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
*vtable_length_ret = vtable_length;//返回虚方法个数
}
bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
Klass* super,
Handle classloader,
Symbol* classname,
AccessFlags class_flags,
TRAPS) {
/*如果 Java 方法被 final、static修饰,或者 Java 类被 final 修饰,或者 Java 方法是构造
函数<init>,则返回 false */
if (class_flags.is_interface()) {
// Interfaces do not use vtables, except for java.lang.Object methods,
// so there is no point to assigning
// a vtable index to any of their local methods. If we refrain from doing this,
// we can use Method::_vtable_index to hold the itable index
return false;
}
if (target_method->is_final_method(class_flags) ||
// a final method never needs a new entry; final methods can be statically
// resolved and they have to be present in the vtable only if they override
// a super's method, in which case they re-use its entry
(target_method()->is_static()) ||
// static methods don't need to be in vtable
(target_method()->name() == vmSymbols::object_initializer_name())
// <init> is never called dynamically-bound
) {
return false;
}
// Concrete interface methods do not need new entries, they override
// abstract method entries using default inheritance rules
if (target_method()->method_holder() != NULL &&
target_method()->method_holder()->is_interface() &&
!target_method()->is_abstract() ) {
return false;
}
// we need a new entry if there is no superclass
if (super == NULL) {
return true;
}
// private methods in classes always have a new entry in the vtable
// specification interpretation since classic has
// private methods not overriding
// JDK8 adds private methods in interfaces which require invokespecial
if (target_method()->is_private()) {
return true;
}
// Package private methods always need a new entry to root their own
// overriding. This allows transitive overriding to work.
if (target_method()->is_package_private()) {
return true;
}
// search through the super class hierarchy to see if we need
// a new entry
/*遍历父类中同名 、签名也完全相同的方法,如果父类方法的访问权限是 public 或者 protected,
并且没有 static 或 private 修饰,则说明子类重写了父类的方法,此时返回 false*/
ResourceMark rm;
Symbol* name = target_method()->name();//当前方法名
Symbol* signature = target_method()->signature();
Klass* k = super;
Method* super_method = NULL;
InstanceKlass *holder = NULL;
Method* recheck_method = NULL;
while (k != NULL) {
//test
//printf("class name = %s\n",classname->base());
// lookup through the hierarchy for a method with matching name and sign.
super_method = InstanceKlass::cast(k)->lookup_method(name, signature);//判断当前方法名与签名在父类中是否吸同名同签名的方法
if (super_method == NULL) {
break; // we still have to search for a matching miranda method
}
// get the class holding the matching method
// make sure you use that class for is_override
InstanceKlass* superk = super_method->method_holder();
// we want only instance method matches
// pretend private methods are not in the super vtable
// since we do override around them: e.g. a.m pub/b.m private/c.m pub,
// ignore private, c.m pub does override a.m pub
// For classes that were not javac'd together, we also do transitive overriding around
// methods that have less accessibility
if ((!super_method->is_static()) &&
(!super_method->is_private())) {
if (superk->is_override(super_method, classloader, classname, THREAD)) {//如果父类方法的访问权限是public或者protected,并且没有static或private修饰,则说明子类重写了父类的方法,此时返回false
return false;
// else keep looking for transitive overrides
}
}
// Start with lookup result and continue to search up
k = superk->super(); // haven't found an override match yet; continue to look
}
// if the target method is public or protected it may have a matching
// miranda method in the super, whose entry it should re-use.
// Actually, to handle cases that javac would not generate, we need
// this check for all access permissions.
InstanceKlass *sk = InstanceKlass::cast(super);
if (sk->has_miranda_methods()) {
if (sk->lookup_method_in_all_interfaces(name, signature, Klass::normal) != NULL) {
return false; // found a matching miranda; we do not need a new entry
}
}
return true; // found no match; we need a new entry
}
上面代码主要判断Java 类在运行期进行动态绑定的方法,一定会被声明为 public 或者 protected 的,并且没有 static 和 final 修饰,且Java 类上也没有 final 修饰 。
4. 当class文件被分析完成后就要创建一个内存中的instanceKlass对象来存放class信息,这时就要用到上面分析的虚表个数了vtable_size。该变量值将在创建类所对应的instanceKlass对象时被保存到该对象中的一vtable_Ien 字段中。
[C++] 纯文本查看复制代码
// We can now create the basic Klass* for this klass
_klass = InstanceKlass::allocate_instance_klass(loader_data,
vtable_size,
itable_size,
info.static_field_size,
total_oop_map_size2,
rt,
access_flags,
name,
super_klass(),
!host_klass.is_null(),
CHECK_(nullHandle));
int klassVtable::initialize_from_super(KlassHandle super) {
if (super.is_null()) {
return 0;
} else {
// copy methods from superKlass
// can't inherit from array class, so must be InstanceKlass
assert(super->oop_is_instance(), "must be instance klass");
InstanceKlass* sk = (InstanceKlass*)super();
klassVtable* superVtable = sk->vtable();
assert(superVtable->length() <= _length, "vtable too short");
#ifdef ASSERT
superVtable->verify(tty, true);
#endif
superVtable->copy_vtable_to(table());
#ifndef PRODUCT
if (PrintVtables && Verbose) {
ResourceMark rm;
tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length);
}
#endif
return superVtable->length();
}
}
//
// Revised lookup semantics introduced 1.3 (Kestrel beta)
void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {
// Note: Arrays can have intermediate array supers. Use java_super to skip them.
KlassHandle super (THREAD, klass()->java_super());
int nofNewEntries = 0;
if (PrintVtables && !klass()->oop_is_array()) {
ResourceMark rm(THREAD);
tty->print_cr("Initializing: %s", _klass->name()->as_C_string());
}
#ifdef ASSERT
oop* end_of_obj = (oop*)_klass() + _klass()->size();
oop* end_of_vtable = (oop*)&table()[_length];
assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
#endif
if (Universe::is_bootstrapping()) {
// just clear everything
for (int i = 0; i < _length; i++) table()[i].clear();
return;
}
int super_vtable_len = initialize_from_super(super);
if (klass()->oop_is_array()) {
assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
} else {
assert(_klass->oop_is_instance(), "must be InstanceKlass");
Array<Method*>* methods = ik()->methods();
int len = methods->length();
int initialized = super_vtable_len;
// Check each of this class's methods against super;
// if override, replace in copy of super vtable, otherwise append to end
for (int i = 0; i < len; i++) {
// update_inherited_vtable can stop for gc - ensure using handles
HandleMark hm(THREAD);
assert(methods->at(i)->is_method(), "must be a Method*");
methodHandle mh(THREAD, methods->at(i));
/*判断是否重写或有虚函数,如果overwrite函数,(方法名字,参数签名 完全一样),
也就是替换虚拟表相同顺序的内容*/
bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, -1, checkconstraints, CHECK);
//needs_new_entry ==true如果符合虚拟函数则顺序添加到虚拟表尾部
if (needs_new_entry) {
put_method_at(mh(), initialized);//存放函数
mh()->set_vtable_index(initialized); // set primary vtable index
initialized++;
}
}
// update vtable with default_methods
Array<Method*>* default_methods = ik()->default_methods();
if (default_methods != NULL) {
len = default_methods->length();
if (len > 0) {
Array<int>* def_vtable_indices = NULL;
if ((def_vtable_indices = ik()->default_vtable_indices()) == NULL) {
def_vtable_indices = ik()->create_new_default_vtable_indices(len, CHECK);
} else {
assert(def_vtable_indices->length() == len, "reinit vtable len?");
}
for (int i = 0; i < len; i++) {
HandleMark hm(THREAD);
assert(default_methods->at(i)->is_method(), "must be a Method*");
methodHandle mh(THREAD, default_methods->at(i));
bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, i, checkconstraints, CHECK);
// needs new entry
if (needs_new_entry) {
put_method_at(mh(), initialized);
def_vtable_indices->at_put(i, initialized); //set vtable index
initialized++;
}
}
}
}
// add miranda methods; it will also return the updated initialized
// Interfaces do not need interface methods in their vtables
// This includes miranda methods and during later processing, default methods
if (!ik()->is_interface()) {
initialized = fill_in_mirandas(initialized);
}
// In class hierarchies where the accessibility is not increasing (i.e., going from private ->
// package_private -> public/protected), the vtable might actually be smaller than our initial
// calculation.
assert(initialized <= _length, "vtable initialization failed");
for(;initialized < _length; initialized++) {
put_method_at(NULL, initialized);
}
NOT_PRODUCT(verify(tty, true));
}
}
bool klassVtable::update_inherited_vtable(InstanceKlass* klass, methodHandle target_method,
int super_vtable_len, int default_index,
bool checkconstraints, TRAPS) {
ResourceMark rm;
bool allocate_new = true;
assert(klass->oop_is_instance(), "must be InstanceKlass");
Array<int>* def_vtable_indices = NULL;
bool is_default = false;
// default methods are concrete methods in superinterfaces which are added to the vtable
// with their real method_holder
// Since vtable and itable indices share the same storage, don't touch
// the default method's real vtable/itable index
// default_vtable_indices stores the vtable value relative to this inheritor
if (default_index >= 0 ) {
is_default = true;
def_vtable_indices = klass->default_vtable_indices();
assert(def_vtable_indices != NULL, "def vtable alloc?");
assert(default_index <= def_vtable_indices->length(), "def vtable len?");
} else {
assert(klass == target_method()->method_holder(), "caller resp.");
// Initialize the method's vtable index to "nonvirtual".
// If we allocate a vtable entry, we will update it to a non-negative number.
target_method()->set_vtable_index(Method::nonvirtual_vtable_index);
}
// Static and <init> methods are never in
if (target_method()->is_static() || target_method()->name() == vmSymbols::object_initializer_name()) {
return false;
}
if (target_method->is_final_method(klass->access_flags())) {
// a final method never needs a new entry; final methods can be statically
// resolved and they have to be present in the vtable only if they override
// a super's method, in which case they re-use its entry
allocate_new = false;
} else if (klass->is_interface()) {
allocate_new = false; // see note below in needs_new_vtable_entry
// An interface never allocates new vtable slots, only inherits old ones.
// This method will either be assigned its own itable index later,
// or be assigned an inherited vtable index in the loop below.
// default methods inherited by classes store their vtable indices
// in the inheritor's default_vtable_indices
// default methods inherited by interfaces may already have a
// valid itable index, if so, don't change it
// overpass methods in an interface will be assigned an itable index later
// by an inheriting class
if (!is_default || !target_method()->has_itable_index()) {
target_method()->set_vtable_index(Method::pending_itable_index);
}
}
// we need a new entry if there is no superclass
if (klass->super() == NULL) {
return allocate_new;
}
// private methods in classes always have a new entry in the vtable
// specification interpretation since classic has
// private methods not overriding
// JDK8 adds private methods in interfaces which require invokespecial
if (target_method()->is_private()) {
return allocate_new;
}
// search through the vtable and update overridden entries
// Since check_signature_loaders acquires SystemDictionary_lock
// which can block for gc, once we are in this loop, use handles
// For classfiles built with >= jdk7, we now look for transitive overrides
Symbol* name = target_method()->name();
Symbol* signature = target_method()->signature();
const char* m_method_name = NULL;
m_method_name = name->as_C_string();
if (0 == strcmp(m_method_name, "say"))
{
printf("target_method name %s\n",m_method_name);
}
KlassHandle target_klass(THREAD, target_method()->method_holder());
if (target_klass == NULL) {
target_klass = _klass;
}
Handle target_loader(THREAD, target_klass->class_loader());
Symbol* target_classname = target_klass->name();
const char* class_name = target_classname->as_C_string();
//可以在这里判断加载目标类时断点
if (0 == strcmp(class_name, "Dog") || 0 == strcmp(class_name, "Animal") || 0 == strcmp(class_name, "Cat"))
{
printf("update_inherited_vtable %s\n",class_name);
}
for(int i = 0; i < super_vtable_len; i++) {
Method* super_method = method_at(i);
// Check if method name matches
m_method_name = super_method->name()->as_C_string();
printf("super_method name %s\n",m_method_name);
//判断方法名签名是否与父类中相同
if (super_method->name() == name && super_method->signature() == signature) {
// get super_klass for method_holder for the found method
InstanceKlass* super_klass = super_method->method_holder();
//判断是否为重写
if (is_default
|| ((super_klass->is_override(super_method, target_loader, target_classname, THREAD))
|| ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
&& ((super_klass = find_transitive_override(super_klass,
target_method, i, target_loader,
target_classname, THREAD))
!= (InstanceKlass*)NULL))))
{
// Package private methods always need a new entry to root their own
// overriding. They may also override other methods.
if (!target_method()->is_package_private()) {
allocate_new = false;
}
if (checkconstraints) {
// Override vtable entry if passes loader constraint check
// if loader constraint checking requested
// No need to visit his super, since he and his super
// have already made any needed loader constraints.
// Since loader constraints are transitive, it is enough
// to link to the first super, and we get all the others.
Handle super_loader(THREAD, super_klass->class_loader());
if (target_loader() != super_loader()) {
ResourceMark rm(THREAD);
Symbol* failed_type_symbol =
SystemDictionary::check_signature_loaders(signature, target_loader,
super_loader, true,
CHECK_(false));
if (failed_type_symbol != NULL) {
const char* msg = "loader constraint violation: when resolving "
"overridden method \"%s\" the class loader (instance"
" of %s) of the current class, %s, and its superclass loader "
"(instance of %s), have different Class objects for the type "
"%s used in the signature";
char* sig = target_method()->name_and_sig_as_C_string();
const char* loader1 = SystemDictionary::loader_name(target_loader());
char* current = target_klass->name()->as_C_string();
const char* loader2 = SystemDictionary::loader_name(super_loader());
char* failed_type_name = failed_type_symbol->as_C_string();
size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
strlen(current) + strlen(loader2) + strlen(failed_type_name);
char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
failed_type_name);
THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
}
}
}
put_method_at(target_method(), i);//替换虚函数
if (!is_default) {
target_method()->set_vtable_index(i);
} else {
if (def_vtable_indices != NULL) {
def_vtable_indices->at_put(default_index, i);
}
assert(super_method->is_default_method() || super_method->is_overpass()
|| super_method->is_abstract(), "default override error");
}
#ifndef PRODUCT
if (PrintVtables && Verbose) {
ResourceMark rm(THREAD);
char* sig = target_method()->name_and_sig_as_C_string();
tty->print("overriding with %s::%s index %d, original flags: ",
target_klass->internal_name(), sig, i);
super_method->access_flags().print_on(tty);
if (super_method->is_default_method()) {
tty->print("default ");
}
if (super_method->is_overpass()) {
tty->print("overpass");
}
tty->print("overriders flags: ");
target_method->access_flags().print_on(tty);
if (target_method->is_default_method()) {
tty->print("default ");
}
if (target_method->is_overpass()) {
tty->print("overpass");
}
tty->cr();
}
#endif /*PRODUCT*/
} else {
// allocate_new = true; default. We might override one entry,
// but not override another. Once we override one, not need new
#ifndef PRODUCT
if (PrintVtables && Verbose) {
ResourceMark rm(THREAD);
char* sig = target_method()->name_and_sig_as_C_string();
tty->print("NOT overriding with %s::%s index %d, original flags: ",
target_klass->internal_name(), sig,i);
super_method->access_flags().print_on(tty);
if (super_method->is_default_method()) {
tty->print("default ");
}
if (super_method->is_overpass()) {
tty->print("overpass");
}
tty->print("overriders flags: ");
target_method->access_flags().print_on(tty);
if (target_method->is_default_method()) {
tty->print("default ");
}
if (target_method->is_overpass()) {
tty->print("overpass");
}
tty->cr();
}
#endif /*PRODUCT*/
}
}
}
return allocate_new;//如果没有与父类中相同的函数并且满足虚函数特性就返回true
}
void klassVtable::put_method_at(Method* m, int index) {
#ifndef PRODUCT
if (PrintVtables && Verbose) {
ResourceMark rm;
const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>";
tty->print("adding %s at index %d, flags: ", sig, index);
if (m != NULL) {
m->access_flags().print_on(tty);
if (m->is_default_method()) {
tty->print("default ");
}
if (m->is_overpass()) {
tty->print("overpass");
}
}
tty->cr();
}
#endif
table()[index].set(m);// 将函数地址放入虚表
}
7.用上面的Animal文件调试分析,看看vtable内存情况。
[Asm] 纯文本查看复制代码
Animal 父类
say 0x14890250 index 5
table() 0x14890520 vtableEntry *
table()[index] {_method=0x14890250 } vtableEntry
Dog
say 0x148906e0 index 5
table() 0x14890920 vtableEntry *
table()[index] {_method=0x14890250 } vtableEntry //没有替换前与Animal中say函数地址相同
table()[index] {_method=0x148906e0 } vtableEntry //替换后为Dog的say函数地址
5
当Hotspot在运行期加载类Animal时,其 vtable 中将会有一个指针元素指向其say方法在Hotspot内部的内存首地址,当 Hotspot 加载类 Dog 时,首先类 Dog 完全继承其父类 Animal 的 vtable,因此类 Dog 便也有一个 vtable ,并且 vtable 里有一个指针指向类 Animal 的 say方法的内存地址 。Hotspot 遍历类 Dog 的所有方法,并发现say方法是 public 的,并且没有被 static 、 final 修饰,于是 HotSpot 去搜索其父类中名称相同、签名也相同的方法,结果发现父类中存在一个完全一样的方法,于是 HotSpot就会将类 Dog 的 vtable 中原本指向类Animal 的 say方法的内存地址的指针值修改成指向类Dog自己的say方法所在的内存地址 。