src/share/vm/oops/klassVtable.cpp

Tue, 05 Nov 2013 17:38:04 -0800

author
kvn
date
Tue, 05 Nov 2013 17:38:04 -0800
changeset 6472
2b8e28fdf503
parent 5848
ac9cb1d5a202
child 6080
fce21ac5968d
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "classfile/systemDictionary.hpp"
    27 #include "classfile/vmSymbols.hpp"
    28 #include "gc_implementation/shared/markSweep.inline.hpp"
    29 #include "memory/gcLocker.hpp"
    30 #include "memory/resourceArea.hpp"
    31 #include "memory/universe.inline.hpp"
    32 #include "oops/instanceKlass.hpp"
    33 #include "oops/klassVtable.hpp"
    34 #include "oops/method.hpp"
    35 #include "oops/objArrayOop.hpp"
    36 #include "oops/oop.inline.hpp"
    37 #include "prims/jvmtiRedefineClassesTrace.hpp"
    38 #include "runtime/arguments.hpp"
    39 #include "runtime/handles.inline.hpp"
    40 #include "utilities/copy.hpp"
    42 inline InstanceKlass* klassVtable::ik() const {
    43   Klass* k = _klass();
    44   assert(k->oop_is_instance(), "not an InstanceKlass");
    45   return (InstanceKlass*)k;
    46 }
    49 // this function computes the vtable size (including the size needed for miranda
    50 // methods) and the number of miranda methods in this class.
    51 // Note on Miranda methods: Let's say there is a class C that implements
    52 // interface I, and none of C's superclasses implements I.
    53 // Let's say there is an abstract method m in I that neither C
    54 // nor any of its super classes implement (i.e there is no method of any access,
    55 // with the same name and signature as m), then m is a Miranda method which is
    56 // entered as a public abstract method in C's vtable.  From then on it should
    57 // treated as any other public method in C for method over-ride purposes.
    58 void klassVtable::compute_vtable_size_and_num_mirandas(
    59     int* vtable_length_ret, int* num_new_mirandas,
    60     GrowableArray<Method*>* all_mirandas, Klass* super,
    61     Array<Method*>* methods, AccessFlags class_flags,
    62     Handle classloader, Symbol* classname, Array<Klass*>* local_interfaces,
    63     TRAPS) {
    64   No_Safepoint_Verifier nsv;
    66   // set up default result values
    67   int vtable_length = 0;
    69   // start off with super's vtable length
    70   InstanceKlass* sk = (InstanceKlass*)super;
    71   vtable_length = super == NULL ? 0 : sk->vtable_length();
    73   // go thru each method in the methods table to see if it needs a new entry
    74   int len = methods->length();
    75   for (int i = 0; i < len; i++) {
    76     assert(methods->at(i)->is_method(), "must be a Method*");
    77     methodHandle mh(THREAD, methods->at(i));
    79     if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) {
    80       vtable_length += vtableEntry::size(); // we need a new entry
    81     }
    82   }
    84   GrowableArray<Method*> new_mirandas(20);
    85   // compute the number of mirandas methods that must be added to the end
    86   get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces);
    87   *num_new_mirandas = new_mirandas.length();
    89   vtable_length += *num_new_mirandas * vtableEntry::size();
    91   if (Universe::is_bootstrapping() && vtable_length == 0) {
    92     // array classes don't have their superclass set correctly during
    93     // bootstrapping
    94     vtable_length = Universe::base_vtable_size();
    95   }
    97   if (super == NULL && !Universe::is_bootstrapping() &&
    98       vtable_length != Universe::base_vtable_size()) {
    99     // Someone is attempting to redefine java.lang.Object incorrectly.  The
   100     // only way this should happen is from
   101     // SystemDictionary::resolve_from_stream(), which will detect this later
   102     // and throw a security exception.  So don't assert here to let
   103     // the exception occur.
   104     vtable_length = Universe::base_vtable_size();
   105   }
   106   assert(super != NULL || vtable_length == Universe::base_vtable_size(),
   107          "bad vtable size for class Object");
   108   assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
   109   assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
   111   *vtable_length_ret = vtable_length;
   112 }
   114 int klassVtable::index_of(Method* m, int len) const {
   115   assert(m->has_vtable_index(), "do not ask this of non-vtable methods");
   116   return m->vtable_index();
   117 }
   119 // Copy super class's vtable to the first part (prefix) of this class's vtable,
   120 // and return the number of entries copied.  Expects that 'super' is the Java
   121 // super class (arrays can have "array" super classes that must be skipped).
   122 int klassVtable::initialize_from_super(KlassHandle super) {
   123   if (super.is_null()) {
   124     return 0;
   125   } else {
   126     // copy methods from superKlass
   127     // can't inherit from array class, so must be InstanceKlass
   128     assert(super->oop_is_instance(), "must be instance klass");
   129     InstanceKlass* sk = (InstanceKlass*)super();
   130     klassVtable* superVtable = sk->vtable();
   131     assert(superVtable->length() <= _length, "vtable too short");
   132 #ifdef ASSERT
   133     superVtable->verify(tty, true);
   134 #endif
   135     superVtable->copy_vtable_to(table());
   136 #ifndef PRODUCT
   137     if (PrintVtables && Verbose) {
   138       ResourceMark rm;
   139       tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length);
   140     }
   141 #endif
   142     return superVtable->length();
   143   }
   144 }
   146 //
   147 // Revised lookup semantics   introduced 1.3 (Kestrel beta)
   148 void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {
   150   // Note:  Arrays can have intermediate array supers.  Use java_super to skip them.
   151   KlassHandle super (THREAD, klass()->java_super());
   152   int nofNewEntries = 0;
   154   if (PrintVtables && !klass()->oop_is_array()) {
   155     ResourceMark rm(THREAD);
   156     tty->print_cr("Initializing: %s", _klass->name()->as_C_string());
   157   }
   159 #ifdef ASSERT
   160   oop* end_of_obj = (oop*)_klass() + _klass()->size();
   161   oop* end_of_vtable = (oop*)&table()[_length];
   162   assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
   163 #endif
   165   if (Universe::is_bootstrapping()) {
   166     // just clear everything
   167     for (int i = 0; i < _length; i++) table()[i].clear();
   168     return;
   169   }
   171   int super_vtable_len = initialize_from_super(super);
   172   if (klass()->oop_is_array()) {
   173     assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
   174   } else {
   175     assert(_klass->oop_is_instance(), "must be InstanceKlass");
   177     Array<Method*>* methods = ik()->methods();
   178     int len = methods->length();
   179     int initialized = super_vtable_len;
   181     // Check each of this class's methods against super;
   182     // if override, replace in copy of super vtable, otherwise append to end
   183     for (int i = 0; i < len; i++) {
   184       // update_inherited_vtable can stop for gc - ensure using handles
   185       HandleMark hm(THREAD);
   186       assert(methods->at(i)->is_method(), "must be a Method*");
   187       methodHandle mh(THREAD, methods->at(i));
   189       bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, -1, checkconstraints, CHECK);
   191       if (needs_new_entry) {
   192         put_method_at(mh(), initialized);
   193         mh()->set_vtable_index(initialized); // set primary vtable index
   194         initialized++;
   195       }
   196     }
   198     // update vtable with default_methods
   199     Array<Method*>* default_methods = ik()->default_methods();
   200     if (default_methods != NULL) {
   201       len = default_methods->length();
   202       if (len > 0) {
   203         Array<int>* def_vtable_indices = NULL;
   204         if ((def_vtable_indices = ik()->default_vtable_indices()) == NULL) {
   205           def_vtable_indices = ik()->create_new_default_vtable_indices(len, CHECK);
   206         } else {
   207           assert(def_vtable_indices->length() == len, "reinit vtable len?");
   208         }
   209         for (int i = 0; i < len; i++) {
   210           HandleMark hm(THREAD);
   211           assert(default_methods->at(i)->is_method(), "must be a Method*");
   212           methodHandle mh(THREAD, default_methods->at(i));
   214           bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, i, checkconstraints, CHECK);
   216           // needs new entry
   217           if (needs_new_entry) {
   218             put_method_at(mh(), initialized);
   219             def_vtable_indices->at_put(i, initialized); //set vtable index
   220             initialized++;
   221           }
   222         }
   223       }
   224     }
   226     // add miranda methods; it will also return the updated initialized
   227     initialized = fill_in_mirandas(initialized);
   229     // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
   230     // package_private -> public/protected), the vtable might actually be smaller than our initial
   231     // calculation.
   232     assert(initialized <= _length, "vtable initialization failed");
   233     for(;initialized < _length; initialized++) {
   234       put_method_at(NULL, initialized);
   235     }
   236     NOT_PRODUCT(verify(tty, true));
   237   }
   238 }
   240 // Called for cases where a method does not override its superclass' vtable entry
   241 // For bytecodes not produced by javac together it is possible that a method does not override
   242 // the superclass's method, but might indirectly override a super-super class's vtable entry
   243 // If none found, return a null superk, else return the superk of the method this does override
   244 InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, methodHandle target_method,
   245                             int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) {
   246   InstanceKlass* superk = initialsuper;
   247   while (superk != NULL && superk->super() != NULL) {
   248     InstanceKlass* supersuperklass = InstanceKlass::cast(superk->super());
   249     klassVtable* ssVtable = supersuperklass->vtable();
   250     if (vtable_index < ssVtable->length()) {
   251       Method* super_method = ssVtable->method_at(vtable_index);
   252 #ifndef PRODUCT
   253       Symbol* name= target_method()->name();
   254       Symbol* signature = target_method()->signature();
   255       assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch");
   256 #endif
   257       if (supersuperklass->is_override(super_method, target_loader, target_classname, THREAD)) {
   258 #ifndef PRODUCT
   259         if (PrintVtables && Verbose) {
   260           ResourceMark rm(THREAD);
   261           char* sig = target_method()->name_and_sig_as_C_string();
   262           tty->print("transitive overriding superclass %s with %s::%s index %d, original flags: ",
   263            supersuperklass->internal_name(),
   264            _klass->internal_name(), sig, vtable_index);
   265            super_method->access_flags().print_on(tty);
   266            if (super_method->is_default_method()) {
   267              tty->print("default");
   268            }
   269            tty->print("overriders flags: ");
   270            target_method->access_flags().print_on(tty);
   271            if (target_method->is_default_method()) {
   272              tty->print("default");
   273            }
   274         }
   275 #endif /*PRODUCT*/
   276         break; // return found superk
   277       }
   278     } else  {
   279       // super class has no vtable entry here, stop transitive search
   280       superk = (InstanceKlass*)NULL;
   281       break;
   282     }
   283     // if no override found yet, continue to search up
   284     superk = InstanceKlass::cast(superk->super());
   285   }
   287   return superk;
   288 }
   290 // Update child's copy of super vtable for overrides
   291 // OR return true if a new vtable entry is required.
   292 // Only called for InstanceKlass's, i.e. not for arrays
   293 // If that changed, could not use _klass as handle for klass
   294 bool klassVtable::update_inherited_vtable(InstanceKlass* klass, methodHandle target_method,
   295                                           int super_vtable_len, int default_index,
   296                                           bool checkconstraints, TRAPS) {
   297   ResourceMark rm;
   298   bool allocate_new = true;
   299   assert(klass->oop_is_instance(), "must be InstanceKlass");
   301   Array<int>* def_vtable_indices = NULL;
   302   bool is_default = false;
   303   // default methods are concrete methods in superinterfaces which are added to the vtable
   304   // with their real method_holder
   305   // Since vtable and itable indices share the same storage, don't touch
   306   // the default method's real vtable/itable index
   307   // default_vtable_indices stores the vtable value relative to this inheritor
   308   if (default_index >= 0 ) {
   309     is_default = true;
   310     def_vtable_indices = klass->default_vtable_indices();
   311     assert(def_vtable_indices != NULL, "def vtable alloc?");
   312     assert(default_index <= def_vtable_indices->length(), "def vtable len?");
   313   } else {
   314     assert(klass == target_method()->method_holder(), "caller resp.");
   315     // Initialize the method's vtable index to "nonvirtual".
   316     // If we allocate a vtable entry, we will update it to a non-negative number.
   317     target_method()->set_vtable_index(Method::nonvirtual_vtable_index);
   318   }
   320   // Static and <init> methods are never in
   321   if (target_method()->is_static() || target_method()->name() ==  vmSymbols::object_initializer_name()) {
   322     return false;
   323   }
   325   if (target_method->is_final_method(klass->access_flags())) {
   326     // a final method never needs a new entry; final methods can be statically
   327     // resolved and they have to be present in the vtable only if they override
   328     // a super's method, in which case they re-use its entry
   329     allocate_new = false;
   330   } else if (klass->is_interface()) {
   331     allocate_new = false;  // see note below in needs_new_vtable_entry
   332     // An interface never allocates new vtable slots, only inherits old ones.
   333     // This method will either be assigned its own itable index later,
   334     // or be assigned an inherited vtable index in the loop below.
   335     // default methods store their vtable indices in the inheritors default_vtable_indices
   336     assert (default_index == -1, "interfaces don't store resolved default methods");
   337     target_method()->set_vtable_index(Method::pending_itable_index);
   338   }
   340   // we need a new entry if there is no superclass
   341   if (klass->super() == NULL) {
   342     return allocate_new;
   343   }
   345   // private methods in classes always have a new entry in the vtable
   346   // specification interpretation since classic has
   347   // private methods not overriding
   348   // JDK8 adds private methods in interfaces which require invokespecial
   349   if (target_method()->is_private()) {
   350     return allocate_new;
   351   }
   353   // search through the vtable and update overridden entries
   354   // Since check_signature_loaders acquires SystemDictionary_lock
   355   // which can block for gc, once we are in this loop, use handles
   356   // For classfiles built with >= jdk7, we now look for transitive overrides
   358   Symbol* name = target_method()->name();
   359   Symbol* signature = target_method()->signature();
   361   KlassHandle target_klass(THREAD, target_method()->method_holder());
   362   if (target_klass == NULL) {
   363     target_klass = _klass;
   364   }
   366   Handle target_loader(THREAD, target_klass->class_loader());
   368   Symbol* target_classname = target_klass->name();
   369   for(int i = 0; i < super_vtable_len; i++) {
   370     Method* super_method = method_at(i);
   371     // Check if method name matches
   372     if (super_method->name() == name && super_method->signature() == signature) {
   374       // get super_klass for method_holder for the found method
   375       InstanceKlass* super_klass =  super_method->method_holder();
   377       if (is_default
   378           || ((super_klass->is_override(super_method, target_loader, target_classname, THREAD))
   379           || ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
   380           && ((super_klass = find_transitive_override(super_klass,
   381                              target_method, i, target_loader,
   382                              target_classname, THREAD))
   383                              != (InstanceKlass*)NULL))))
   384         {
   385         // overriding, so no new entry
   386         allocate_new = false;
   388         if (checkconstraints) {
   389         // Override vtable entry if passes loader constraint check
   390         // if loader constraint checking requested
   391         // No need to visit his super, since he and his super
   392         // have already made any needed loader constraints.
   393         // Since loader constraints are transitive, it is enough
   394         // to link to the first super, and we get all the others.
   395           Handle super_loader(THREAD, super_klass->class_loader());
   397           if (target_loader() != super_loader()) {
   398             ResourceMark rm(THREAD);
   399             Symbol* failed_type_symbol =
   400               SystemDictionary::check_signature_loaders(signature, target_loader,
   401                                                         super_loader, true,
   402                                                         CHECK_(false));
   403             if (failed_type_symbol != NULL) {
   404               const char* msg = "loader constraint violation: when resolving "
   405                 "overridden method \"%s\" the class loader (instance"
   406                 " of %s) of the current class, %s, and its superclass loader "
   407                 "(instance of %s), have different Class objects for the type "
   408                 "%s used in the signature";
   409               char* sig = target_method()->name_and_sig_as_C_string();
   410               const char* loader1 = SystemDictionary::loader_name(target_loader());
   411               char* current = target_klass->name()->as_C_string();
   412               const char* loader2 = SystemDictionary::loader_name(super_loader());
   413               char* failed_type_name = failed_type_symbol->as_C_string();
   414               size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
   415                 strlen(current) + strlen(loader2) + strlen(failed_type_name);
   416               char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
   417               jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
   418                            failed_type_name);
   419               THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
   420             }
   421           }
   422        }
   424        put_method_at(target_method(), i);
   425        if (!is_default) {
   426          target_method()->set_vtable_index(i);
   427        } else {
   428          if (def_vtable_indices != NULL) {
   429            def_vtable_indices->at_put(default_index, i);
   430          }
   431          assert(super_method->is_default_method() || super_method->is_overpass()
   432                 || super_method->is_abstract(), "default override error");
   433        }
   436 #ifndef PRODUCT
   437         if (PrintVtables && Verbose) {
   438           ResourceMark rm(THREAD);
   439           char* sig = target_method()->name_and_sig_as_C_string();
   440           tty->print("overriding with %s::%s index %d, original flags: ",
   441            target_klass->internal_name(), sig, i);
   442            super_method->access_flags().print_on(tty);
   443            if (super_method->is_default_method()) {
   444              tty->print("default");
   445            }
   446            if (super_method->is_overpass()) {
   447              tty->print("overpass");
   448            }
   449            tty->print("overriders flags: ");
   450            target_method->access_flags().print_on(tty);
   451            if (target_method->is_default_method()) {
   452              tty->print("default");
   453            }
   454            if (target_method->is_overpass()) {
   455              tty->print("overpass");
   456            }
   457            tty->cr();
   458         }
   459 #endif /*PRODUCT*/
   460       } else {
   461         // allocate_new = true; default. We might override one entry,
   462         // but not override another. Once we override one, not need new
   463 #ifndef PRODUCT
   464         if (PrintVtables && Verbose) {
   465           ResourceMark rm(THREAD);
   466           char* sig = target_method()->name_and_sig_as_C_string();
   467           tty->print("NOT overriding with %s::%s index %d, original flags: ",
   468            target_klass->internal_name(), sig,i);
   469            super_method->access_flags().print_on(tty);
   470            if (super_method->is_default_method()) {
   471              tty->print("default");
   472            }
   473            if (super_method->is_overpass()) {
   474              tty->print("overpass");
   475            }
   476            tty->print("overriders flags: ");
   477            target_method->access_flags().print_on(tty);
   478            if (target_method->is_default_method()) {
   479              tty->print("default");
   480            }
   481            if (target_method->is_overpass()) {
   482              tty->print("overpass");
   483            }
   484            tty->cr();
   485         }
   486 #endif /*PRODUCT*/
   487       }
   488     }
   489   }
   490   return allocate_new;
   491 }
   493 void klassVtable::put_method_at(Method* m, int index) {
   494 #ifndef PRODUCT
   495   if (PrintVtables && Verbose) {
   496     ResourceMark rm;
   497     tty->print_cr("adding %s::%s at index %d", _klass->internal_name(),
   498       (m != NULL) ? m->name()->as_C_string() : "<NULL>", index);
   499   }
   500 #endif
   501   table()[index].set(m);
   502 }
   504 // Find out if a method "m" with superclass "super", loader "classloader" and
   505 // name "classname" needs a new vtable entry.  Let P be a class package defined
   506 // by "classloader" and "classname".
   507 // NOTE: The logic used here is very similar to the one used for computing
   508 // the vtables indices for a method. We cannot directly use that function because,
   509 // we allocate the InstanceKlass at load time, and that requires that the
   510 // superclass has been loaded.
   511 // However, the vtable entries are filled in at link time, and therefore
   512 // the superclass' vtable may not yet have been filled in.
   513 bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
   514                                          Klass* super,
   515                                          Handle classloader,
   516                                          Symbol* classname,
   517                                          AccessFlags class_flags,
   518                                          TRAPS) {
   519   if (class_flags.is_interface()) {
   520     // Interfaces do not use vtables, so there is no point to assigning
   521     // a vtable index to any of their methods.  If we refrain from doing this,
   522     // we can use Method::_vtable_index to hold the itable index
   523     return false;
   524   }
   526   if (target_method->is_final_method(class_flags) ||
   527       // a final method never needs a new entry; final methods can be statically
   528       // resolved and they have to be present in the vtable only if they override
   529       // a super's method, in which case they re-use its entry
   530       (target_method()->is_static()) ||
   531       // static methods don't need to be in vtable
   532       (target_method()->name() ==  vmSymbols::object_initializer_name())
   533       // <init> is never called dynamically-bound
   534       ) {
   535     return false;
   536   }
   538   // Concrete interface methods do not need new entries, they override
   539   // abstract method entries using default inheritance rules
   540   if (target_method()->method_holder() != NULL &&
   541       target_method()->method_holder()->is_interface()  &&
   542       !target_method()->is_abstract() ) {
   543     return false;
   544   }
   546   // we need a new entry if there is no superclass
   547   if (super == NULL) {
   548     return true;
   549   }
   551   // private methods in classes always have a new entry in the vtable
   552   // specification interpretation since classic has
   553   // private methods not overriding
   554   // JDK8 adds private  methods in interfaces which require invokespecial
   555   if (target_method()->is_private()) {
   556     return true;
   557   }
   559   // search through the super class hierarchy to see if we need
   560   // a new entry
   561   ResourceMark rm;
   562   Symbol* name = target_method()->name();
   563   Symbol* signature = target_method()->signature();
   564   Klass* k = super;
   565   Method* super_method = NULL;
   566   InstanceKlass *holder = NULL;
   567   Method* recheck_method =  NULL;
   568   while (k != NULL) {
   569     // lookup through the hierarchy for a method with matching name and sign.
   570     super_method = InstanceKlass::cast(k)->lookup_method(name, signature);
   571     if (super_method == NULL) {
   572       break; // we still have to search for a matching miranda method
   573     }
   574     // get the class holding the matching method
   575     // make sure you use that class for is_override
   576     InstanceKlass* superk = super_method->method_holder();
   577     // we want only instance method matches
   578     // pretend private methods are not in the super vtable
   579     // since we do override around them: e.g. a.m pub/b.m private/c.m pub,
   580     // ignore private, c.m pub does override a.m pub
   581     // For classes that were not javac'd together, we also do transitive overriding around
   582     // methods that have less accessibility
   583     if ((!super_method->is_static()) &&
   584        (!super_method->is_private())) {
   585       if (superk->is_override(super_method, classloader, classname, THREAD)) {
   586         return false;
   587       // else keep looking for transitive overrides
   588       }
   589     }
   591     // Start with lookup result and continue to search up
   592     k = superk->super(); // haven't found an override match yet; continue to look
   593   }
   595   // if the target method is public or protected it may have a matching
   596   // miranda method in the super, whose entry it should re-use.
   597   // Actually, to handle cases that javac would not generate, we need
   598   // this check for all access permissions.
   599   InstanceKlass *sk = InstanceKlass::cast(super);
   600   if (sk->has_miranda_methods()) {
   601     if (sk->lookup_method_in_all_interfaces(name, signature) != NULL) {
   602       return false;  // found a matching miranda; we do not need a new entry
   603     }
   604   }
   605   return true; // found no match; we need a new entry
   606 }
   608 // Support for miranda methods
   610 // get the vtable index of a miranda method with matching "name" and "signature"
   611 int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) {
   612   // search from the bottom, might be faster
   613   for (int i = (length() - 1); i >= 0; i--) {
   614     Method* m = table()[i].method();
   615     if (is_miranda_entry_at(i) &&
   616         m->name() == name && m->signature() == signature) {
   617       return i;
   618     }
   619   }
   620   return Method::invalid_vtable_index;
   621 }
   623 // check if an entry at an index is miranda
   624 // requires that method m at entry be declared ("held") by an interface.
   625 bool klassVtable::is_miranda_entry_at(int i) {
   626   Method* m = method_at(i);
   627   Klass* method_holder = m->method_holder();
   628   InstanceKlass *mhk = InstanceKlass::cast(method_holder);
   630   // miranda methods are public abstract instance interface methods in a class's vtable
   631   if (mhk->is_interface()) {
   632     assert(m->is_public(), "should be public");
   633     assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
   634     assert(is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super()), "should be a miranda_method");
   635     return true;
   636   }
   637   return false;
   638 }
   640 // check if a method is a miranda method, given a class's methods table,
   641 // its default_method table  and its super
   642 // "miranda" means not static, not defined by this class.
   643 // private methods in interfaces do not belong in the miranda list.
   644 // the caller must make sure that the method belongs to an interface implemented by the class
   645 // Miranda methods only include public interface instance methods
   646 // Not private methods, not static methods, not default == concrete abstract
   647 bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods,
   648                              Array<Method*>* default_methods, Klass* super) {
   649   if (m->is_static() || m->is_private()) {
   650     return false;
   651   }
   652   Symbol* name = m->name();
   653   Symbol* signature = m->signature();
   654   if (InstanceKlass::find_method(class_methods, name, signature) == NULL) {
   655     // did not find it in the method table of the current class
   656     if ((default_methods == NULL) ||
   657         InstanceKlass::find_method(default_methods, name, signature) == NULL) {
   658       if (super == NULL) {
   659         // super doesn't exist
   660         return true;
   661       }
   663       Method* mo = InstanceKlass::cast(super)->lookup_method(name, signature);
   664       if (mo == NULL || mo->access_flags().is_private() ) {
   665         // super class hierarchy does not implement it or protection is different
   666         return true;
   667       }
   668     }
   669   }
   671   return false;
   672 }
   674 // Scans current_interface_methods for miranda methods that do not
   675 // already appear in new_mirandas, or default methods,  and are also not defined-and-non-private
   676 // in super (superclass).  These mirandas are added to all_mirandas if it is
   677 // not null; in addition, those that are not duplicates of miranda methods
   678 // inherited by super from its interfaces are added to new_mirandas.
   679 // Thus, new_mirandas will be the set of mirandas that this class introduces,
   680 // all_mirandas will be the set of all mirandas applicable to this class
   681 // including all defined in superclasses.
   682 void klassVtable::add_new_mirandas_to_lists(
   683     GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas,
   684     Array<Method*>* current_interface_methods, Array<Method*>* class_methods,
   685     Array<Method*>* default_methods, Klass* super) {
   687   // iterate thru the current interface's method to see if it a miranda
   688   int num_methods = current_interface_methods->length();
   689   for (int i = 0; i < num_methods; i++) {
   690     Method* im = current_interface_methods->at(i);
   691     bool is_duplicate = false;
   692     int num_of_current_mirandas = new_mirandas->length();
   693     // check for duplicate mirandas in different interfaces we implement
   694     for (int j = 0; j < num_of_current_mirandas; j++) {
   695       Method* miranda = new_mirandas->at(j);
   696       if ((im->name() == miranda->name()) &&
   697           (im->signature() == miranda->signature())) {
   698         is_duplicate = true;
   699         break;
   700       }
   701     }
   703     if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable
   704       if (is_miranda(im, class_methods, default_methods, super)) { // is it a miranda at all?
   705         InstanceKlass *sk = InstanceKlass::cast(super);
   706         // check if it is a duplicate of a super's miranda
   707         if (sk->lookup_method_in_all_interfaces(im->name(), im->signature()) == NULL) {
   708           new_mirandas->append(im);
   709         }
   710         if (all_mirandas != NULL) {
   711           all_mirandas->append(im);
   712         }
   713       }
   714     }
   715   }
   716 }
   718 void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas,
   719                                GrowableArray<Method*>* all_mirandas,
   720                                Klass* super, Array<Method*>* class_methods,
   721                                Array<Method*>* default_methods,
   722                                Array<Klass*>* local_interfaces) {
   723   assert((new_mirandas->length() == 0) , "current mirandas must be 0");
   725   // iterate thru the local interfaces looking for a miranda
   726   int num_local_ifs = local_interfaces->length();
   727   for (int i = 0; i < num_local_ifs; i++) {
   728     InstanceKlass *ik = InstanceKlass::cast(local_interfaces->at(i));
   729     add_new_mirandas_to_lists(new_mirandas, all_mirandas,
   730                               ik->methods(), class_methods,
   731                               default_methods, super);
   732     // iterate thru each local's super interfaces
   733     Array<Klass*>* super_ifs = ik->transitive_interfaces();
   734     int num_super_ifs = super_ifs->length();
   735     for (int j = 0; j < num_super_ifs; j++) {
   736       InstanceKlass *sik = InstanceKlass::cast(super_ifs->at(j));
   737       add_new_mirandas_to_lists(new_mirandas, all_mirandas,
   738                                 sik->methods(), class_methods,
   739                                 default_methods, super);
   740     }
   741   }
   742 }
   744 // Discover miranda methods ("miranda" = "interface abstract, no binding"),
   745 // and append them into the vtable starting at index initialized,
   746 // return the new value of initialized.
   747 int klassVtable::fill_in_mirandas(int initialized) {
   748   GrowableArray<Method*> mirandas(20);
   749   get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(),
   750                ik()->default_methods(), ik()->local_interfaces());
   751   for (int i = 0; i < mirandas.length(); i++) {
   752     if (PrintVtables && Verbose) {
   753       Method* meth = mirandas.at(i);
   754       ResourceMark rm(Thread::current());
   755       if (meth != NULL) {
   756         char* sig = meth->name_and_sig_as_C_string();
   757         tty->print("fill in mirandas with %s index %d, flags: ",
   758           sig, initialized);
   759         meth->access_flags().print_on(tty);
   760         if (meth->is_default_method()) {
   761           tty->print("default");
   762         }
   763         tty->cr();
   764       }
   765     }
   766     put_method_at(mirandas.at(i), initialized);
   767     ++initialized;
   768   }
   769   return initialized;
   770 }
   772 // Copy this class's vtable to the vtable beginning at start.
   773 // Used to copy superclass vtable to prefix of subclass's vtable.
   774 void klassVtable::copy_vtable_to(vtableEntry* start) {
   775   Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
   776 }
   778 #if INCLUDE_JVMTI
   779 bool klassVtable::adjust_default_method(int vtable_index, Method* old_method, Method* new_method) {
   780   // If old_method is default, find this vtable index in default_vtable_indices
   781   // and replace that method in the _default_methods list
   782   bool updated = false;
   784   Array<Method*>* default_methods = ik()->default_methods();
   785   if (default_methods != NULL) {
   786     int len = default_methods->length();
   787     for (int idx = 0; idx < len; idx++) {
   788       if (vtable_index == ik()->default_vtable_indices()->at(idx)) {
   789         if (default_methods->at(idx) == old_method) {
   790           default_methods->at_put(idx, new_method);
   791           updated = true;
   792         }
   793         break;
   794       }
   795     }
   796   }
   797   return updated;
   798 }
   799 void klassVtable::adjust_method_entries(Method** old_methods, Method** new_methods,
   800                                         int methods_length, bool * trace_name_printed) {
   801   // search the vtable for uses of either obsolete or EMCP methods
   802   for (int j = 0; j < methods_length; j++) {
   803     Method* old_method = old_methods[j];
   804     Method* new_method = new_methods[j];
   806     // In the vast majority of cases we could get the vtable index
   807     // by using:  old_method->vtable_index()
   808     // However, there are rare cases, eg. sun.awt.X11.XDecoratedPeer.getX()
   809     // in sun.awt.X11.XFramePeer where methods occur more than once in the
   810     // vtable, so, alas, we must do an exhaustive search.
   811     for (int index = 0; index < length(); index++) {
   812       if (unchecked_method_at(index) == old_method) {
   813         put_method_at(new_method, index);
   814           // For default methods, need to update the _default_methods array
   815           // which can only have one method entry for a given signature
   816           bool updated_default = false;
   817           if (old_method->is_default_method()) {
   818             updated_default = adjust_default_method(index, old_method, new_method);
   819           }
   821         if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
   822           if (!(*trace_name_printed)) {
   823             // RC_TRACE_MESG macro has an embedded ResourceMark
   824             RC_TRACE_MESG(("adjust: klassname=%s for methods from name=%s",
   825                            klass()->external_name(),
   826                            old_method->method_holder()->external_name()));
   827             *trace_name_printed = true;
   828           }
   829           // RC_TRACE macro has an embedded ResourceMark
   830           RC_TRACE(0x00100000, ("vtable method update: %s(%s), updated default = %s",
   831                                 new_method->name()->as_C_string(),
   832                                 new_method->signature()->as_C_string(),
   833                                 updated_default ? "true" : "false"));
   834         }
   835         // cannot 'break' here; see for-loop comment above.
   836       }
   837     }
   838   }
   839 }
   841 // a vtable should never contain old or obsolete methods
   842 bool klassVtable::check_no_old_or_obsolete_entries() {
   843   for (int i = 0; i < length(); i++) {
   844     Method* m = unchecked_method_at(i);
   845     if (m != NULL &&
   846         (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
   847       return false;
   848     }
   849   }
   850   return true;
   851 }
   853 void klassVtable::dump_vtable() {
   854   tty->print_cr("vtable dump --");
   855   for (int i = 0; i < length(); i++) {
   856     Method* m = unchecked_method_at(i);
   857     if (m != NULL) {
   858       tty->print("      (%5d)  ", i);
   859       m->access_flags().print_on(tty);
   860       if (m->is_default_method()) {
   861         tty->print("default");
   862       }
   863       if (m->is_overpass()) {
   864         tty->print("overpass");
   865       }
   866       tty->print(" --  ");
   867       m->print_name(tty);
   868       tty->cr();
   869     }
   870   }
   871 }
   872 #endif // INCLUDE_JVMTI
   874 // CDS/RedefineClasses support - clear vtables so they can be reinitialized
   875 void klassVtable::clear_vtable() {
   876   for (int i = 0; i < _length; i++) table()[i].clear();
   877 }
   879 bool klassVtable::is_initialized() {
   880   return _length == 0 || table()[0].method() != NULL;
   881 }
   883 //-----------------------------------------------------------------------------------------
   884 // Itable code
   886 // Initialize a itableMethodEntry
   887 void itableMethodEntry::initialize(Method* m) {
   888   if (m == NULL) return;
   890   _method = m;
   891 }
   893 klassItable::klassItable(instanceKlassHandle klass) {
   894   _klass = klass;
   896   if (klass->itable_length() > 0) {
   897     itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();
   898     if (offset_entry  != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized
   899       // First offset entry points to the first method_entry
   900       intptr_t* method_entry  = (intptr_t *)(((address)klass()) + offset_entry->offset());
   901       intptr_t* end         = klass->end_of_itable();
   903       _table_offset      = (intptr_t*)offset_entry - (intptr_t*)klass();
   904       _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();
   905       _size_method_table = (end - method_entry)                  / itableMethodEntry::size();
   906       assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");
   907       return;
   908     }
   909   }
   911   // The length of the itable was either zero, or it has not yet been initialized.
   912   _table_offset      = 0;
   913   _size_offset_table = 0;
   914   _size_method_table = 0;
   915 }
   917 static int initialize_count = 0;
   919 // Initialization
   920 void klassItable::initialize_itable(bool checkconstraints, TRAPS) {
   921   if (_klass->is_interface()) {
   922     // This needs to go after vtable indices are assigned but
   923     // before implementors need to know the number of itable indices.
   924     assign_itable_indices_for_interface(_klass());
   925   }
   927   // Cannot be setup doing bootstrapping, interfaces don't have
   928   // itables, and klass with only ones entry have empty itables
   929   if (Universe::is_bootstrapping() ||
   930       _klass->is_interface() ||
   931       _klass->itable_length() == itableOffsetEntry::size()) return;
   933   // There's alway an extra itable entry so we can null-terminate it.
   934   guarantee(size_offset_table() >= 1, "too small");
   935   int num_interfaces = size_offset_table() - 1;
   936   if (num_interfaces > 0) {
   937     if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count,
   938                                     _klass->name()->as_C_string());
   941     // Iterate through all interfaces
   942     int i;
   943     for(i = 0; i < num_interfaces; i++) {
   944       itableOffsetEntry* ioe = offset_entry(i);
   945       HandleMark hm(THREAD);
   946       KlassHandle interf_h (THREAD, ioe->interface_klass());
   947       assert(interf_h() != NULL && ioe->offset() != 0, "bad offset entry in itable");
   948       initialize_itable_for_interface(ioe->offset(), interf_h, checkconstraints, CHECK);
   949     }
   951   }
   952   // Check that the last entry is empty
   953   itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);
   954   guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");
   955 }
   958 inline bool interface_method_needs_itable_index(Method* m) {
   959   if (m->is_static())           return false;   // e.g., Stream.empty
   960   if (m->is_initializer())      return false;   // <init> or <clinit>
   961   // If an interface redeclares a method from java.lang.Object,
   962   // it should already have a vtable index, don't touch it.
   963   // e.g., CharSequence.toString (from initialize_vtable)
   964   // if (m->has_vtable_index())  return false; // NO!
   965   return true;
   966 }
   968 int klassItable::assign_itable_indices_for_interface(Klass* klass) {
   969   // an interface does not have an itable, but its methods need to be numbered
   970   if (TraceItables) tty->print_cr("%3d: Initializing itable for interface %s", ++initialize_count,
   971                                   klass->name()->as_C_string());
   972   Array<Method*>* methods = InstanceKlass::cast(klass)->methods();
   973   int nof_methods = methods->length();
   974   int ime_num = 0;
   975   for (int i = 0; i < nof_methods; i++) {
   976     Method* m = methods->at(i);
   977     if (interface_method_needs_itable_index(m)) {
   978       assert(!m->is_final_method(), "no final interface methods");
   979       // If m is already assigned a vtable index, do not disturb it.
   980       if (!m->has_vtable_index()) {
   981         assert(m->vtable_index() == Method::pending_itable_index, "set by initialize_vtable");
   982         m->set_itable_index(ime_num);
   983         // Progress to next itable entry
   984         ime_num++;
   985       }
   986     }
   987   }
   988   assert(ime_num == method_count_for_interface(klass), "proper sizing");
   989   return ime_num;
   990 }
   992 int klassItable::method_count_for_interface(Klass* interf) {
   993   assert(interf->oop_is_instance(), "must be");
   994   assert(interf->is_interface(), "must be");
   995   Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
   996   int nof_methods = methods->length();
   997   while (nof_methods > 0) {
   998     Method* m = methods->at(nof_methods-1);
   999     if (m->has_itable_index()) {
  1000       int length = m->itable_index() + 1;
  1001 #ifdef ASSERT
  1002       while (nof_methods = 0) {
  1003         m = methods->at(--nof_methods);
  1004         assert(!m->has_itable_index() || m->itable_index() < length, "");
  1006 #endif //ASSERT
  1007       return length;  // return the rightmost itable index, plus one
  1009     nof_methods -= 1;
  1011   // no methods have itable indices
  1012   return 0;
  1016 void klassItable::initialize_itable_for_interface(int method_table_offset, KlassHandle interf_h, bool checkconstraints, TRAPS) {
  1017   Array<Method*>* methods = InstanceKlass::cast(interf_h())->methods();
  1018   int nof_methods = methods->length();
  1019   HandleMark hm;
  1020   assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
  1021   Handle interface_loader (THREAD, InstanceKlass::cast(interf_h())->class_loader());
  1023   int ime_count = method_count_for_interface(interf_h());
  1024   for (int i = 0; i < nof_methods; i++) {
  1025     Method* m = methods->at(i);
  1026     methodHandle target;
  1027     if (m->has_itable_index()) {
  1028       LinkResolver::lookup_instance_method_in_klasses(target, _klass, m->name(), m->signature(), CHECK);
  1030     if (target == NULL || !target->is_public() || target->is_abstract()) {
  1031       // Entry do not resolve. Leave it empty
  1032     } else {
  1033       // Entry did resolve, check loader constraints before initializing
  1034       // if checkconstraints requested
  1035       if (checkconstraints) {
  1036         Handle method_holder_loader (THREAD, target->method_holder()->class_loader());
  1037         if (method_holder_loader() != interface_loader()) {
  1038           ResourceMark rm(THREAD);
  1039           Symbol* failed_type_symbol =
  1040             SystemDictionary::check_signature_loaders(m->signature(),
  1041                                                       method_holder_loader,
  1042                                                       interface_loader,
  1043                                                       true, CHECK);
  1044           if (failed_type_symbol != NULL) {
  1045             const char* msg = "loader constraint violation in interface "
  1046               "itable initialization: when resolving method \"%s\" the class"
  1047               " loader (instance of %s) of the current class, %s, "
  1048               "and the class loader (instance of %s) for interface "
  1049               "%s have different Class objects for the type %s "
  1050               "used in the signature";
  1051             char* sig = target()->name_and_sig_as_C_string();
  1052             const char* loader1 = SystemDictionary::loader_name(method_holder_loader());
  1053             char* current = _klass->name()->as_C_string();
  1054             const char* loader2 = SystemDictionary::loader_name(interface_loader());
  1055             char* iface = InstanceKlass::cast(interf_h())->name()->as_C_string();
  1056             char* failed_type_name = failed_type_symbol->as_C_string();
  1057             size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
  1058               strlen(current) + strlen(loader2) + strlen(iface) +
  1059               strlen(failed_type_name);
  1060             char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
  1061             jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
  1062                          iface, failed_type_name);
  1063             THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
  1068       // ime may have moved during GC so recalculate address
  1069       int ime_num = m->itable_index();
  1070       assert(ime_num < ime_count, "oob");
  1071       itableOffsetEntry::method_entry(_klass(), method_table_offset)[ime_num].initialize(target());
  1072       if (TraceItables && Verbose) {
  1073         ResourceMark rm(THREAD);
  1074         if (target() != NULL) {
  1075           char* sig = target()->name_and_sig_as_C_string();
  1076           tty->print("interface: %s, ime_num: %d, target: %s, method_holder: %s ",
  1077                     interf_h()->internal_name(), ime_num, sig,
  1078                     target()->method_holder()->internal_name());
  1079           tty->print("target_method flags: ");
  1080           target()->access_flags().print_on(tty);
  1081           if (target()->is_default_method()) {
  1082             tty->print("default");
  1084           tty->cr();
  1091 // Update entry for specific Method*
  1092 void klassItable::initialize_with_method(Method* m) {
  1093   itableMethodEntry* ime = method_entry(0);
  1094   for(int i = 0; i < _size_method_table; i++) {
  1095     if (ime->method() == m) {
  1096       ime->initialize(m);
  1098     ime++;
  1102 #if INCLUDE_JVMTI
  1103 void klassItable::adjust_method_entries(Method** old_methods, Method** new_methods,
  1104                                         int methods_length, bool * trace_name_printed) {
  1105   // search the itable for uses of either obsolete or EMCP methods
  1106   for (int j = 0; j < methods_length; j++) {
  1107     Method* old_method = old_methods[j];
  1108     Method* new_method = new_methods[j];
  1109     itableMethodEntry* ime = method_entry(0);
  1111     // The itable can describe more than one interface and the same
  1112     // method signature can be specified by more than one interface.
  1113     // This means we have to do an exhaustive search to find all the
  1114     // old_method references.
  1115     for (int i = 0; i < _size_method_table; i++) {
  1116       if (ime->method() == old_method) {
  1117         ime->initialize(new_method);
  1119         if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
  1120           if (!(*trace_name_printed)) {
  1121             // RC_TRACE_MESG macro has an embedded ResourceMark
  1122             RC_TRACE_MESG(("adjust: name=%s",
  1123               old_method->method_holder()->external_name()));
  1124             *trace_name_printed = true;
  1126           // RC_TRACE macro has an embedded ResourceMark
  1127           RC_TRACE(0x00200000, ("itable method update: %s(%s)",
  1128             new_method->name()->as_C_string(),
  1129             new_method->signature()->as_C_string()));
  1131         // cannot 'break' here; see for-loop comment above.
  1133       ime++;
  1138 // an itable should never contain old or obsolete methods
  1139 bool klassItable::check_no_old_or_obsolete_entries() {
  1140   itableMethodEntry* ime = method_entry(0);
  1141   for (int i = 0; i < _size_method_table; i++) {
  1142     Method* m = ime->method();
  1143     if (m != NULL &&
  1144         (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
  1145       return false;
  1147     ime++;
  1149   return true;
  1152 void klassItable::dump_itable() {
  1153   itableMethodEntry* ime = method_entry(0);
  1154   tty->print_cr("itable dump --");
  1155   for (int i = 0; i < _size_method_table; i++) {
  1156     Method* m = ime->method();
  1157     if (m != NULL) {
  1158       tty->print("      (%5d)  ", i);
  1159       m->access_flags().print_on(tty);
  1160       if (m->is_default_method()) {
  1161         tty->print("default");
  1163       tty->print(" --  ");
  1164       m->print_name(tty);
  1165       tty->cr();
  1167     ime++;
  1170 #endif // INCLUDE_JVMTI
  1173 // Setup
  1174 class InterfaceVisiterClosure : public StackObj {
  1175  public:
  1176   virtual void doit(Klass* intf, int method_count) = 0;
  1177 };
  1179 // Visit all interfaces with at least one itable method
  1180 void visit_all_interfaces(Array<Klass*>* transitive_intf, InterfaceVisiterClosure *blk) {
  1181   // Handle array argument
  1182   for(int i = 0; i < transitive_intf->length(); i++) {
  1183     Klass* intf = transitive_intf->at(i);
  1184     assert(intf->is_interface(), "sanity check");
  1186     // Find no. of itable methods
  1187     int method_count = 0;
  1188     // method_count = klassItable::method_count_for_interface(intf);
  1189     Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
  1190     if (methods->length() > 0) {
  1191       for (int i = methods->length(); --i >= 0; ) {
  1192         if (interface_method_needs_itable_index(methods->at(i))) {
  1193           method_count++;
  1198     // Only count interfaces with at least one method
  1199     if (method_count > 0) {
  1200       blk->doit(intf, method_count);
  1205 class CountInterfacesClosure : public InterfaceVisiterClosure {
  1206  private:
  1207   int _nof_methods;
  1208   int _nof_interfaces;
  1209  public:
  1210    CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }
  1212    int nof_methods() const    { return _nof_methods; }
  1213    int nof_interfaces() const { return _nof_interfaces; }
  1215    void doit(Klass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }
  1216 };
  1218 class SetupItableClosure : public InterfaceVisiterClosure  {
  1219  private:
  1220   itableOffsetEntry* _offset_entry;
  1221   itableMethodEntry* _method_entry;
  1222   address            _klass_begin;
  1223  public:
  1224   SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {
  1225     _klass_begin  = klass_begin;
  1226     _offset_entry = offset_entry;
  1227     _method_entry = method_entry;
  1230   itableMethodEntry* method_entry() const { return _method_entry; }
  1232   void doit(Klass* intf, int method_count) {
  1233     int offset = ((address)_method_entry) - _klass_begin;
  1234     _offset_entry->initialize(intf, offset);
  1235     _offset_entry++;
  1236     _method_entry += method_count;
  1238 };
  1240 int klassItable::compute_itable_size(Array<Klass*>* transitive_interfaces) {
  1241   // Count no of interfaces and total number of interface methods
  1242   CountInterfacesClosure cic;
  1243   visit_all_interfaces(transitive_interfaces, &cic);
  1245   // There's alway an extra itable entry so we can null-terminate it.
  1246   int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());
  1248   // Statistics
  1249   update_stats(itable_size * HeapWordSize);
  1251   return itable_size;
  1255 // Fill out offset table and interface klasses into the itable space
  1256 void klassItable::setup_itable_offset_table(instanceKlassHandle klass) {
  1257   if (klass->itable_length() == 0) return;
  1258   assert(!klass->is_interface(), "Should have zero length itable");
  1260   // Count no of interfaces and total number of interface methods
  1261   CountInterfacesClosure cic;
  1262   visit_all_interfaces(klass->transitive_interfaces(), &cic);
  1263   int nof_methods    = cic.nof_methods();
  1264   int nof_interfaces = cic.nof_interfaces();
  1266   // Add one extra entry so we can null-terminate the table
  1267   nof_interfaces++;
  1269   assert(compute_itable_size(klass->transitive_interfaces()) ==
  1270          calc_itable_size(nof_interfaces, nof_methods),
  1271          "mismatch calculation of itable size");
  1273   // Fill-out offset table
  1274   itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();
  1275   itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);
  1276   intptr_t* end               = klass->end_of_itable();
  1277   assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)");
  1278   assert((oop*)(end) == (oop*)(ime + nof_methods),                      "wrong offset calculation (2)");
  1280   // Visit all interfaces and initialize itable offset table
  1281   SetupItableClosure sic((address)klass(), ioe, ime);
  1282   visit_all_interfaces(klass->transitive_interfaces(), &sic);
  1284 #ifdef ASSERT
  1285   ime  = sic.method_entry();
  1286   oop* v = (oop*) klass->end_of_itable();
  1287   assert( (oop*)(ime) == v, "wrong offset calculation (2)");
  1288 #endif
  1292 // inverse to itable_index
  1293 Method* klassItable::method_for_itable_index(Klass* intf, int itable_index) {
  1294   assert(InstanceKlass::cast(intf)->is_interface(), "sanity check");
  1295   assert(intf->verify_itable_index(itable_index), "");
  1296   Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
  1298   if (itable_index < 0 || itable_index >= method_count_for_interface(intf))
  1299     return NULL;                // help caller defend against bad indices
  1301   int index = itable_index;
  1302   Method* m = methods->at(index);
  1303   int index2 = -1;
  1304   while (!m->has_itable_index() ||
  1305          (index2 = m->itable_index()) != itable_index) {
  1306     assert(index2 < itable_index, "monotonic");
  1307     if (++index == methods->length())
  1308       return NULL;
  1309     m = methods->at(index);
  1311   assert(m->itable_index() == itable_index, "correct inverse");
  1313   return m;
  1316 void klassVtable::verify(outputStream* st, bool forced) {
  1317   // make sure table is initialized
  1318   if (!Universe::is_fully_initialized()) return;
  1319 #ifndef PRODUCT
  1320   // avoid redundant verifies
  1321   if (!forced && _verify_count == Universe::verify_count()) return;
  1322   _verify_count = Universe::verify_count();
  1323 #endif
  1324   oop* end_of_obj = (oop*)_klass() + _klass()->size();
  1325   oop* end_of_vtable = (oop *)&table()[_length];
  1326   if (end_of_vtable > end_of_obj) {
  1327     fatal(err_msg("klass %s: klass object too short (vtable extends beyond "
  1328                   "end)", _klass->internal_name()));
  1331   for (int i = 0; i < _length; i++) table()[i].verify(this, st);
  1332   // verify consistency with superKlass vtable
  1333   Klass* super = _klass->super();
  1334   if (super != NULL) {
  1335     InstanceKlass* sk = InstanceKlass::cast(super);
  1336     klassVtable* vt = sk->vtable();
  1337     for (int i = 0; i < vt->length(); i++) {
  1338       verify_against(st, vt, i);
  1343 void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {
  1344   vtableEntry* vte = &vt->table()[index];
  1345   if (vte->method()->name()      != table()[index].method()->name() ||
  1346       vte->method()->signature() != table()[index].method()->signature()) {
  1347     fatal("mismatched name/signature of vtable entries");
  1351 #ifndef PRODUCT
  1352 void klassVtable::print() {
  1353   ResourceMark rm;
  1354   tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());
  1355   for (int i = 0; i < length(); i++) {
  1356     table()[i].print();
  1357     tty->cr();
  1360 #endif
  1362 void vtableEntry::verify(klassVtable* vt, outputStream* st) {
  1363   NOT_PRODUCT(FlagSetting fs(IgnoreLockingAssertions, true));
  1364   assert(method() != NULL, "must have set method");
  1365   method()->verify();
  1366   // we sub_type, because it could be a miranda method
  1367   if (!vt->klass()->is_subtype_of(method()->method_holder())) {
  1368 #ifndef PRODUCT
  1369     print();
  1370 #endif
  1371     fatal(err_msg("vtableEntry " PTR_FORMAT ": method is from subclass", this));
  1375 #ifndef PRODUCT
  1377 void vtableEntry::print() {
  1378   ResourceMark rm;
  1379   tty->print("vtableEntry %s: ", method()->name()->as_C_string());
  1380   if (Verbose) {
  1381     tty->print("m %#lx ", (address)method());
  1385 class VtableStats : AllStatic {
  1386  public:
  1387   static int no_klasses;                // # classes with vtables
  1388   static int no_array_klasses;          // # array classes
  1389   static int no_instance_klasses;       // # instanceKlasses
  1390   static int sum_of_vtable_len;         // total # of vtable entries
  1391   static int sum_of_array_vtable_len;   // total # of vtable entries in array klasses only
  1392   static int fixed;                     // total fixed overhead in bytes
  1393   static int filler;                    // overhead caused by filler bytes
  1394   static int entries;                   // total bytes consumed by vtable entries
  1395   static int array_entries;             // total bytes consumed by array vtable entries
  1397   static void do_class(Klass* k) {
  1398     Klass* kl = k;
  1399     klassVtable* vt = kl->vtable();
  1400     if (vt == NULL) return;
  1401     no_klasses++;
  1402     if (kl->oop_is_instance()) {
  1403       no_instance_klasses++;
  1404       kl->array_klasses_do(do_class);
  1406     if (kl->oop_is_array()) {
  1407       no_array_klasses++;
  1408       sum_of_array_vtable_len += vt->length();
  1410     sum_of_vtable_len += vt->length();
  1413   static void compute() {
  1414     SystemDictionary::classes_do(do_class);
  1415     fixed  = no_klasses * oopSize;      // vtable length
  1416     // filler size is a conservative approximation
  1417     filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1);
  1418     entries = sizeof(vtableEntry) * sum_of_vtable_len;
  1419     array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;
  1421 };
  1423 int VtableStats::no_klasses = 0;
  1424 int VtableStats::no_array_klasses = 0;
  1425 int VtableStats::no_instance_klasses = 0;
  1426 int VtableStats::sum_of_vtable_len = 0;
  1427 int VtableStats::sum_of_array_vtable_len = 0;
  1428 int VtableStats::fixed = 0;
  1429 int VtableStats::filler = 0;
  1430 int VtableStats::entries = 0;
  1431 int VtableStats::array_entries = 0;
  1433 void klassVtable::print_statistics() {
  1434   ResourceMark rm;
  1435   HandleMark hm;
  1436   VtableStats::compute();
  1437   tty->print_cr("vtable statistics:");
  1438   tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);
  1439   int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;
  1440   tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);
  1441   tty->print_cr("%6d bytes filler overhead", VtableStats::filler);
  1442   tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);
  1443   tty->print_cr("%6d bytes total", total);
  1446 int  klassItable::_total_classes;   // Total no. of classes with itables
  1447 long klassItable::_total_size;      // Total no. of bytes used for itables
  1449 void klassItable::print_statistics() {
  1450  tty->print_cr("itable statistics:");
  1451  tty->print_cr("%6d classes with itables", _total_classes);
  1452  tty->print_cr("%6d K uses for itables (average by class: %d bytes)", _total_size / K, _total_size / _total_classes);
  1455 #endif // PRODUCT

mercurial