1 /*
   2  * Copyright (c) 1997, 2017, 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  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "gc/shared/gcLocker.hpp"
  29 #include "logging/log.hpp"
  30 #include "memory/metaspaceShared.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "memory/universe.inline.hpp"
  33 #include "oops/instanceKlass.hpp"
  34 #include "oops/klassVtable.hpp"
  35 #include "oops/method.hpp"
  36 #include "oops/objArrayOop.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "prims/jvm.h"
  39 #include "runtime/arguments.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 #include "utilities/copy.hpp"
  42 
  43 inline InstanceKlass* klassVtable::ik() const {
  44   return InstanceKlass::cast(_klass);
  45 }
  46 
  47 bool klassVtable::is_preinitialized_vtable() {
  48   return _klass->is_shared() && !MetaspaceShared::remapped_readwrite();
  49 }
  50 
  51 
  52 // this function computes the vtable size (including the size needed for miranda
  53 // methods) and the number of miranda methods in this class.
  54 // Note on Miranda methods: Let's say there is a class C that implements
  55 // interface I, and none of C's superclasses implements I.
  56 // Let's say there is an abstract method m in I that neither C
  57 // nor any of its super classes implement (i.e there is no method of any access,
  58 // with the same name and signature as m), then m is a Miranda method which is
  59 // entered as a public abstract method in C's vtable.  From then on it should
  60 // treated as any other public method in C for method over-ride purposes.
  61 void klassVtable::compute_vtable_size_and_num_mirandas(
  62     int* vtable_length_ret, int* num_new_mirandas,
  63     GrowableArray<Method*>* all_mirandas, const Klass* super,
  64     Array<Method*>* methods, AccessFlags class_flags, u2 major_version,
  65     Handle classloader, Symbol* classname, Array<Klass*>* local_interfaces,
  66     TRAPS) {
  67   NoSafepointVerifier nsv;
  68 
  69   // set up default result values
  70   int vtable_length = 0;
  71 
  72   // start off with super's vtable length
  73   vtable_length = super == NULL ? 0 : super->vtable_length();
  74 
  75   // go thru each method in the methods table to see if it needs a new entry
  76   int len = methods->length();
  77   for (int i = 0; i < len; i++) {
  78     assert(methods->at(i)->is_method(), "must be a Method*");
  79     methodHandle mh(THREAD, methods->at(i));
  80 
  81     if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, major_version, THREAD)) {
  82       vtable_length += vtableEntry::size(); // we need a new entry
  83     }
  84   }
  85 
  86   GrowableArray<Method*> new_mirandas(20);
  87   // compute the number of mirandas methods that must be added to the end
  88   get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces);
  89   *num_new_mirandas = new_mirandas.length();
  90 
  91   // Interfaces do not need interface methods in their vtables
  92   // This includes miranda methods and during later processing, default methods
  93   if (!class_flags.is_interface()) {
  94     vtable_length += *num_new_mirandas * vtableEntry::size();
  95   }
  96 
  97   if (Universe::is_bootstrapping() && vtable_length == 0) {
  98     // array classes don't have their superclass set correctly during
  99     // bootstrapping
 100     vtable_length = Universe::base_vtable_size();
 101   }
 102 
 103   if (super == NULL && vtable_length != Universe::base_vtable_size()) {
 104     if (Universe::is_bootstrapping()) {
 105       // Someone is attempting to override java.lang.Object incorrectly on the
 106       // bootclasspath.  The JVM cannot recover from this error including throwing
 107       // an exception
 108       vm_exit_during_initialization("Incompatible definition of java.lang.Object");
 109     } else {
 110       // Someone is attempting to redefine java.lang.Object incorrectly.  The
 111       // only way this should happen is from
 112       // SystemDictionary::resolve_from_stream(), which will detect this later
 113       // and throw a security exception.  So don't assert here to let
 114       // the exception occur.
 115       vtable_length = Universe::base_vtable_size();
 116     }
 117   }
 118   assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
 119   assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
 120 
 121   *vtable_length_ret = vtable_length;
 122 }
 123 
 124 int klassVtable::index_of(Method* m, int len) const {
 125   assert(m->has_vtable_index(), "do not ask this of non-vtable methods");
 126   return m->vtable_index();
 127 }
 128 
 129 // 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 Java
 131 // super class (arrays can have "array" super classes that must be skipped).
 132 int klassVtable::initialize_from_super(Klass* super) {
 133   if (super == NULL) {
 134     return 0;
 135   } else if (is_preinitialized_vtable()) {
 136     // A shared class' vtable is preinitialized at dump time. No need to copy
 137     // methods from super class for shared class, as that was already done
 138     // during archiving time. However, if Jvmti has redefined a class,
 139     // copy super class's vtable in case the super class has changed.
 140     return super->vtable().length();
 141   } else {
 142     // copy methods from superKlass
 143     klassVtable superVtable = super->vtable();
 144     assert(superVtable.length() <= _length, "vtable too short");
 145 #ifdef ASSERT
 146     superVtable.verify(tty, true);
 147 #endif
 148     superVtable.copy_vtable_to(table());
 149     if (log_develop_is_enabled(Trace, vtables)) {
 150       ResourceMark rm;
 151       log_develop_trace(vtables)("copy vtable from %s to %s size %d",
 152                                  super->internal_name(), klass()->internal_name(),
 153                                  _length);
 154     }
 155     return superVtable.length();
 156   }
 157 }
 158 
 159 //
 160 // Revised lookup semantics   introduced 1.3 (Kestrel beta)
 161 void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {
 162 
 163   // Note:  Arrays can have intermediate array supers.  Use java_super to skip them.
 164   Klass* super = _klass->java_super();
 165   int nofNewEntries = 0;
 166 
 167   bool is_shared = _klass->is_shared();
 168 
 169   if (!_klass->is_array_klass()) {
 170     ResourceMark rm(THREAD);
 171     log_develop_debug(vtables)("Initializing: %s", _klass->name()->as_C_string());
 172   }
 173 
 174 #ifdef ASSERT
 175   oop* end_of_obj = (oop*)_klass + _klass->size();
 176   oop* end_of_vtable = (oop*)&table()[_length];
 177   assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
 178 #endif
 179 
 180   if (Universe::is_bootstrapping()) {
 181     assert(!is_shared, "sanity");
 182     // just clear everything
 183     for (int i = 0; i < _length; i++) table()[i].clear();
 184     return;
 185   }
 186 
 187   int super_vtable_len = initialize_from_super(super);
 188   if (_klass->is_array_klass()) {
 189     assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
 190   } else {
 191     assert(_klass->is_instance_klass(), "must be InstanceKlass");
 192 
 193     Array<Method*>* methods = ik()->methods();
 194     int len = methods->length();
 195     int initialized = super_vtable_len;
 196 
 197     // Check each of this class's methods against super;
 198     // if override, replace in copy of super vtable, otherwise append to end
 199     for (int i = 0; i < len; i++) {
 200       // update_inherited_vtable can stop for gc - ensure using handles
 201       HandleMark hm(THREAD);
 202       assert(methods->at(i)->is_method(), "must be a Method*");
 203       methodHandle mh(THREAD, methods->at(i));
 204 
 205       bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, -1, checkconstraints, CHECK);
 206 
 207       if (needs_new_entry) {
 208         put_method_at(mh(), initialized);
 209         mh()->set_vtable_index(initialized); // set primary vtable index
 210         initialized++;
 211       }
 212     }
 213 
 214     // update vtable with default_methods
 215     Array<Method*>* default_methods = ik()->default_methods();
 216     if (default_methods != NULL) {
 217       len = default_methods->length();
 218       if (len > 0) {
 219         Array<int>* def_vtable_indices = NULL;
 220         if ((def_vtable_indices = ik()->default_vtable_indices()) == NULL) {
 221           assert(!is_shared, "shared class def_vtable_indices does not exist");
 222           def_vtable_indices = ik()->create_new_default_vtable_indices(len, CHECK);
 223         } else {
 224           assert(def_vtable_indices->length() == len, "reinit vtable len?");
 225         }
 226         for (int i = 0; i < len; i++) {
 227           HandleMark hm(THREAD);
 228           assert(default_methods->at(i)->is_method(), "must be a Method*");
 229           methodHandle mh(THREAD, default_methods->at(i));
 230           assert(!mh->is_private(), "private interface method in the default method list");
 231           bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, i, checkconstraints, CHECK);
 232 
 233           // needs new entry
 234           if (needs_new_entry) {
 235             put_method_at(mh(), initialized);
 236             if (is_preinitialized_vtable()) {
 237               // At runtime initialize_vtable is rerun for a shared class
 238               // (loaded by the non-boot loader) as part of link_class_impl().
 239               // The dumptime vtable index should be the same as the runtime index.
 240               assert(def_vtable_indices->at(i) == initialized,
 241                      "dump time vtable index is different from runtime index");
 242             } else {
 243               def_vtable_indices->at_put(i, initialized); //set vtable index
 244             }
 245             initialized++;
 246           }
 247         }
 248       }
 249     }
 250 
 251     // add miranda methods; it will also return the updated initialized
 252     // Interfaces do not need interface methods in their vtables
 253     // This includes miranda methods and during later processing, default methods
 254     if (!ik()->is_interface()) {
 255       initialized = fill_in_mirandas(initialized);
 256     }
 257 
 258     // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
 259     // package_private -> public/protected), the vtable might actually be smaller than our initial
 260     // calculation, for classfile versions for which we do not do transitive override
 261     // calculations.
 262     if (ik()->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) {
 263       assert(initialized == _length, "vtable initialization failed");
 264     } else {
 265       assert(initialized <= _length, "vtable initialization failed");
 266       for(;initialized < _length; initialized++) {
 267         table()[initialized].clear();
 268       }
 269     }
 270     NOT_PRODUCT(verify(tty, true));
 271   }
 272 }
 273 
 274 // Called for cases where a method does not override its superclass' vtable entry
 275 // For bytecodes not produced by javac together it is possible that a method does not override
 276 // the superclass's method, but might indirectly override a super-super class's vtable entry
 277 // If none found, return a null superk, else return the superk of the method this does override
 278 // For public and protected methods: if they override a superclass, they will
 279 // also be overridden themselves appropriately.
 280 // Private methods do not override and are not overridden.
 281 // Package Private methods are trickier:
 282 // e.g. P1.A, pub m
 283 // P2.B extends A, package private m
 284 // P1.C extends B, public m
 285 // P1.C.m needs to override P1.A.m and can not override P2.B.m
 286 // Therefore: all package private methods need their own vtable entries for
 287 // them to be the root of an inheritance overriding decision
 288 // Package private methods may also override other vtable entries
 289 InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, methodHandle target_method,
 290                             int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) {
 291   InstanceKlass* superk = initialsuper;
 292   while (superk != NULL && superk->super() != NULL) {
 293     InstanceKlass* supersuperklass = InstanceKlass::cast(superk->super());
 294     klassVtable ssVtable = supersuperklass->vtable();
 295     if (vtable_index < ssVtable.length()) {
 296       Method* super_method = ssVtable.method_at(vtable_index);
 297 #ifndef PRODUCT
 298       Symbol* name= target_method()->name();
 299       Symbol* signature = target_method()->signature();
 300       assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch");
 301 #endif
 302       if (supersuperklass->is_override(super_method, target_loader, target_classname, THREAD)) {
 303         if (log_develop_is_enabled(Trace, vtables)) {
 304           ResourceMark rm(THREAD);
 305           outputStream* logst = Log(vtables)::trace_stream();
 306           char* sig = target_method()->name_and_sig_as_C_string();
 307           logst->print("transitive overriding superclass %s with %s index %d, original flags: ",
 308                        supersuperklass->internal_name(),
 309                        sig, vtable_index);
 310           super_method->print_linkage_flags(logst);
 311           logst->print("overriders flags: ");
 312           target_method->print_linkage_flags(logst);
 313           logst->cr();
 314         }
 315 
 316         break; // return found superk
 317       }
 318     } else  {
 319       // super class has no vtable entry here, stop transitive search
 320       superk = (InstanceKlass*)NULL;
 321       break;
 322     }
 323     // if no override found yet, continue to search up
 324     superk = superk->super() == NULL ? NULL : InstanceKlass::cast(superk->super());
 325   }
 326 
 327   return superk;
 328 }
 329 
 330 static void log_vtables(int i, bool overrides, methodHandle target_method,
 331                         Klass* target_klass, Method* super_method,
 332                         Thread* thread) {
 333 #ifndef PRODUCT
 334   if (log_develop_is_enabled(Trace, vtables)) {
 335     ResourceMark rm(thread);
 336     outputStream* logst = Log(vtables)::trace_stream();
 337     char* sig = target_method()->name_and_sig_as_C_string();
 338     if (overrides) {
 339       logst->print("overriding with %s index %d, original flags: ",
 340                    sig, i);
 341     } else {
 342       logst->print("NOT overriding with %s index %d, original flags: ",
 343                    sig, i);
 344     }
 345     super_method->print_linkage_flags(logst);
 346     logst->print("overriders flags: ");
 347     target_method->print_linkage_flags(logst);
 348     logst->cr();
 349   }
 350 #endif
 351 }
 352 
 353 // Update child's copy of super vtable for overrides
 354 // OR return true if a new vtable entry is required.
 355 // Only called for InstanceKlass's, i.e. not for arrays
 356 // If that changed, could not use _klass as handle for klass
 357 bool klassVtable::update_inherited_vtable(InstanceKlass* klass, methodHandle target_method,
 358                                           int super_vtable_len, int default_index,
 359                                           bool checkconstraints, TRAPS) {
 360   ResourceMark rm;
 361   bool allocate_new = true;
 362   assert(klass->is_instance_klass(), "must be InstanceKlass");
 363 
 364   Array<int>* def_vtable_indices = NULL;
 365   bool is_default = false;
 366 
 367   // default methods are non-private concrete methods in superinterfaces which are added
 368   // to the vtable with their real method_holder.
 369   // Since vtable and itable indices share the same storage, don't touch
 370   // the default method's real vtable/itable index.
 371   // default_vtable_indices stores the vtable value relative to this inheritor
 372   if (default_index >= 0 ) {
 373     is_default = true;
 374     def_vtable_indices = klass->default_vtable_indices();
 375     assert(!target_method()->is_private(), "private interface method flagged as default");
 376     assert(def_vtable_indices != NULL, "def vtable alloc?");
 377     assert(default_index <= def_vtable_indices->length(), "def vtable len?");
 378   } else {
 379     assert(klass == target_method()->method_holder(), "caller resp.");
 380     // Initialize the method's vtable index to "nonvirtual".
 381     // If we allocate a vtable entry, we will update it to a non-negative number.
 382     target_method()->set_vtable_index(Method::nonvirtual_vtable_index);
 383   }
 384 
 385   // Static and <init> methods are never in
 386   if (target_method()->is_static() || target_method()->name() ==  vmSymbols::object_initializer_name()) {
 387     return false;
 388   }
 389 
 390   if (target_method->is_final_method(klass->access_flags())) {
 391     // a final method never needs a new entry; final methods can be statically
 392     // resolved and they have to be present in the vtable only if they override
 393     // a super's method, in which case they re-use its entry
 394     allocate_new = false;
 395   } else if (klass->is_interface()) {
 396     allocate_new = false;  // see note below in needs_new_vtable_entry
 397     // An interface never allocates new vtable slots, only inherits old ones.
 398     // This method will either be assigned its own itable index later,
 399     // or be assigned an inherited vtable index in the loop below.
 400     // default methods inherited by classes store their vtable indices
 401     // in the inheritor's default_vtable_indices.
 402     // default methods inherited by interfaces may already have a
 403     // valid itable index, if so, don't change it.
 404     // Overpass methods in an interface will be assigned an itable index later
 405     // by an inheriting class.
 406     // Private interface methods have no itable index and are always invoked nonvirtually,
 407     // so they retain their nonvirtual_vtable_index value, and therefore can_be_statically_bound()
 408     // will return true.
 409     if ((!is_default || !target_method()->has_itable_index()) && !target_method()->is_private()) {
 410       target_method()->set_vtable_index(Method::pending_itable_index);
 411     }
 412   }
 413 
 414   // we need a new entry if there is no superclass
 415   Klass* super = klass->super();
 416   if (super == NULL) {
 417     return allocate_new;
 418   }
 419 
 420   // private methods in classes always have a new entry in the vtable
 421   // specification interpretation since classic has
 422   // private methods not overriding
 423   // JDK8 adds private methods in interfaces which require invokespecial
 424   if (target_method()->is_private()) {
 425     return allocate_new;
 426   }
 427 
 428   // search through the vtable and update overridden entries
 429   // Since check_signature_loaders acquires SystemDictionary_lock
 430   // which can block for gc, once we are in this loop, use handles
 431   // For classfiles built with >= jdk7, we now look for transitive overrides
 432 
 433   Symbol* name = target_method()->name();
 434   Symbol* signature = target_method()->signature();
 435 
 436   Klass* target_klass = target_method()->method_holder();
 437   if (target_klass == NULL) {
 438     target_klass = _klass;
 439   }
 440 
 441   Handle target_loader(THREAD, target_klass->class_loader());
 442 
 443   Symbol* target_classname = target_klass->name();
 444   for(int i = 0; i < super_vtable_len; i++) {
 445     Method* super_method;
 446     if (is_preinitialized_vtable()) {
 447       // If this is a shared class, the vtable is already in the final state (fully
 448       // initialized). Need to look at the super's vtable.
 449       klassVtable superVtable = super->vtable();
 450       super_method = superVtable.method_at(i);
 451     } else {
 452       super_method = method_at(i);
 453     }
 454     // Check if method name matches
 455     if (super_method->name() == name && super_method->signature() == signature) {
 456 
 457       // get super_klass for method_holder for the found method
 458       InstanceKlass* super_klass =  super_method->method_holder();
 459 
 460       // Whether the method is being overridden
 461       bool overrides = false;
 462 
 463       // private methods are also never overridden
 464       if (!super_method->is_private() &&
 465           (is_default
 466           || ((super_klass->is_override(super_method, target_loader, target_classname, THREAD))
 467           || ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
 468           && ((super_klass = find_transitive_override(super_klass,
 469                              target_method, i, target_loader,
 470                              target_classname, THREAD))
 471                              != (InstanceKlass*)NULL)))))
 472         {
 473         // Package private methods always need a new entry to root their own
 474         // overriding. They may also override other methods.
 475         if (!target_method()->is_package_private()) {
 476           allocate_new = false;
 477         }
 478 
 479         if (checkconstraints) {
 480         // Override vtable entry if passes loader constraint check
 481         // if loader constraint checking requested
 482         // No need to visit his super, since he and his super
 483         // have already made any needed loader constraints.
 484         // Since loader constraints are transitive, it is enough
 485         // to link to the first super, and we get all the others.
 486           Handle super_loader(THREAD, super_klass->class_loader());
 487 
 488           if (target_loader() != super_loader()) {
 489             ResourceMark rm(THREAD);
 490             Symbol* failed_type_symbol =
 491               SystemDictionary::check_signature_loaders(signature, target_loader,
 492                                                         super_loader, true,
 493                                                         CHECK_(false));
 494             if (failed_type_symbol != NULL) {
 495               const char* msg = "loader constraint violation: when resolving "
 496                 "overridden method \"%s\" the class loader (instance"
 497                 " of %s) of the current class, %s, and its superclass loader "
 498                 "(instance of %s), have different Class objects for the type "
 499                 "%s used in the signature";
 500               char* sig = target_method()->name_and_sig_as_C_string();
 501               const char* loader1 = SystemDictionary::loader_name(target_loader());
 502               char* current = target_klass->name()->as_C_string();
 503               const char* loader2 = SystemDictionary::loader_name(super_loader());
 504               char* failed_type_name = failed_type_symbol->as_C_string();
 505               size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
 506                 strlen(current) + strlen(loader2) + strlen(failed_type_name);
 507               char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
 508               jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
 509                            failed_type_name);
 510               THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
 511             }
 512           }
 513         }
 514 
 515         put_method_at(target_method(), i);
 516         overrides = true;
 517         if (!is_default) {
 518           target_method()->set_vtable_index(i);
 519         } else {
 520           if (def_vtable_indices != NULL) {
 521             if (is_preinitialized_vtable()) {
 522               // At runtime initialize_vtable is rerun as part of link_class_impl()
 523               // for a shared class loaded by the non-boot loader.
 524               // The dumptime vtable index should be the same as the runtime index.
 525               assert(def_vtable_indices->at(default_index) == i,
 526                      "dump time vtable index is different from runtime index");
 527             } else {
 528               def_vtable_indices->at_put(default_index, i);
 529             }
 530           }
 531           assert(super_method->is_default_method() || super_method->is_overpass()
 532                  || super_method->is_abstract(), "default override error");
 533         }
 534       } else {
 535         overrides = false;
 536       }
 537       log_vtables(i, overrides, target_method, target_klass, super_method, THREAD);
 538     }
 539   }
 540   return allocate_new;
 541 }
 542 
 543 void klassVtable::put_method_at(Method* m, int index) {
 544   if (is_preinitialized_vtable()) {
 545     // At runtime initialize_vtable is rerun as part of link_class_impl()
 546     // for shared class loaded by the non-boot loader to obtain the loader
 547     // constraints based on the runtime classloaders' context. The dumptime
 548     // method at the vtable index should be the same as the runtime method.
 549     assert(table()[index].method() == m,
 550            "archived method is different from the runtime method");
 551   } else {
 552     if (log_develop_is_enabled(Trace, vtables)) {
 553       ResourceMark rm;
 554       outputStream* logst = Log(vtables)::trace_stream();
 555       const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>";
 556       logst->print("adding %s at index %d, flags: ", sig, index);
 557       if (m != NULL) {
 558         m->print_linkage_flags(logst);
 559       }
 560       logst->cr();
 561     }
 562     table()[index].set(m);
 563   }
 564 }
 565 
 566 // Find out if a method "m" with superclass "super", loader "classloader" and
 567 // name "classname" needs a new vtable entry.  Let P be a class package defined
 568 // by "classloader" and "classname".
 569 // NOTE: The logic used here is very similar to the one used for computing
 570 // the vtables indices for a method. We cannot directly use that function because,
 571 // we allocate the InstanceKlass at load time, and that requires that the
 572 // superclass has been loaded.
 573 // However, the vtable entries are filled in at link time, and therefore
 574 // the superclass' vtable may not yet have been filled in.
 575 bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
 576                                          const Klass* super,
 577                                          Handle classloader,
 578                                          Symbol* classname,
 579                                          AccessFlags class_flags,
 580                                          u2 major_version,
 581                                          TRAPS) {
 582   if (class_flags.is_interface()) {
 583     // Interfaces do not use vtables, except for java.lang.Object methods,
 584     // so there is no point to assigning
 585     // a vtable index to any of their local methods.  If we refrain from doing this,
 586     // we can use Method::_vtable_index to hold the itable index
 587     return false;
 588   }
 589 
 590   if (target_method->is_final_method(class_flags) ||
 591       // a final method never needs a new entry; final methods can be statically
 592       // resolved and they have to be present in the vtable only if they override
 593       // a super's method, in which case they re-use its entry
 594       (target_method()->is_static()) ||
 595       // static methods don't need to be in vtable
 596       (target_method()->name() ==  vmSymbols::object_initializer_name())
 597       // <init> is never called dynamically-bound
 598       ) {
 599     return false;
 600   }
 601 
 602   // Concrete interface methods do not need new entries, they override
 603   // abstract method entries using default inheritance rules
 604   if (target_method()->method_holder() != NULL &&
 605       target_method()->method_holder()->is_interface()  &&
 606       !target_method()->is_abstract()) {
 607     assert(target_method()->is_default_method() || target_method()->is_private(),
 608            "unexpected interface method type");
 609     return false;
 610   }
 611 
 612   // we need a new entry if there is no superclass
 613   if (super == NULL) {
 614     return true;
 615   }
 616 
 617   // private methods in classes always have a new entry in the vtable.
 618   // Specification interpretation since classic has private methods not overriding.
 619   if (target_method()->is_private()) {
 620     return true;
 621   }
 622 
 623   // Package private methods always need a new entry to root their own
 624   // overriding. This allows transitive overriding to work.
 625   if (target_method()->is_package_private()) {
 626     return true;
 627   }
 628 
 629   // search through the super class hierarchy to see if we need
 630   // a new entry
 631   ResourceMark rm;
 632   Symbol* name = target_method()->name();
 633   Symbol* signature = target_method()->signature();
 634   const Klass* k = super;
 635   Method* super_method = NULL;
 636   InstanceKlass *holder = NULL;
 637   Method* recheck_method =  NULL;
 638   while (k != NULL) {
 639     // lookup through the hierarchy for a method with matching name and sign.
 640     super_method = InstanceKlass::cast(k)->lookup_method(name, signature);
 641     if (super_method == NULL) {
 642       break; // we still have to search for a matching miranda method
 643     }
 644     // get the class holding the matching method
 645     // make sure you use that class for is_override
 646     InstanceKlass* superk = super_method->method_holder();
 647     // we want only instance method matches
 648     // pretend private methods are not in the super vtable
 649     // since we do override around them: e.g. a.m pub/b.m private/c.m pub,
 650     // ignore private, c.m pub does override a.m pub
 651     // For classes that were not javac'd together, we also do transitive overriding around
 652     // methods that have less accessibility
 653     if ((!super_method->is_static()) &&
 654        (!super_method->is_private())) {
 655       if (superk->is_override(super_method, classloader, classname, THREAD)) {
 656         return false;
 657       // else keep looking for transitive overrides
 658       }
 659     }
 660 
 661     // Start with lookup result and continue to search up, for versions supporting transitive override
 662     if (major_version >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) {
 663       k = superk->super(); // haven't found an override match yet; continue to look
 664     } else {
 665       break;
 666     }
 667   }
 668 
 669   // if the target method is public or protected it may have a matching
 670   // miranda method in the super, whose entry it should re-use.
 671   // Actually, to handle cases that javac would not generate, we need
 672   // this check for all access permissions.
 673   const InstanceKlass *sk = InstanceKlass::cast(super);
 674   if (sk->has_miranda_methods()) {
 675     if (sk->lookup_method_in_all_interfaces(name, signature, Klass::find_defaults) != NULL) {
 676       return false;  // found a matching miranda; we do not need a new entry
 677     }
 678   }
 679   return true; // found no match; we need a new entry
 680 }
 681 
 682 // Support for miranda methods
 683 
 684 // get the vtable index of a miranda method with matching "name" and "signature"
 685 int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) {
 686   // search from the bottom, might be faster
 687   for (int i = (length() - 1); i >= 0; i--) {
 688     Method* m = table()[i].method();
 689     if (is_miranda_entry_at(i) &&
 690         m->name() == name && m->signature() == signature) {
 691       return i;
 692     }
 693   }
 694   return Method::invalid_vtable_index;
 695 }
 696 
 697 // check if an entry at an index is miranda
 698 // requires that method m at entry be declared ("held") by an interface.
 699 bool klassVtable::is_miranda_entry_at(int i) {
 700   Method* m = method_at(i);
 701   Klass* method_holder = m->method_holder();
 702   InstanceKlass *mhk = InstanceKlass::cast(method_holder);
 703 
 704   // miranda methods are public abstract instance interface methods in a class's vtable
 705   if (mhk->is_interface()) {
 706     assert(m->is_public(), "should be public");
 707     assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
 708     if (is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super())) {
 709       return true;
 710     }
 711   }
 712   return false;
 713 }
 714 
 715 // Check if a method is a miranda method, given a class's methods array,
 716 // its default_method table and its super class.
 717 // "Miranda" means an abstract non-private method that would not be
 718 // overridden for the local class.
 719 // A "miranda" method should only include non-private interface
 720 // instance methods, i.e. not private methods, not static methods,
 721 // not default methods (concrete interface methods), not overpass methods.
 722 // If a given class already has a local (including overpass) method, a
 723 // default method, or any of its superclasses has the same which would have
 724 // overridden an abstract method, then this is not a miranda method.
 725 //
 726 // Miranda methods are checked multiple times.
 727 // Pass 1: during class load/class file parsing: before vtable size calculation:
 728 // include superinterface abstract and default methods (non-private instance).
 729 // We include potential default methods to give them space in the vtable.
 730 // During the first run, the current instanceKlass has not yet been
 731 // created, the superclasses and superinterfaces do have instanceKlasses
 732 // but may not have vtables, the default_methods list is empty, no overpasses.
 733 // This is seen by default method creation.
 734 //
 735 // Pass 2: recalculated during vtable initialization: only include abstract methods.
 736 // The goal of pass 2 is to walk through the superinterfaces to see if any of
 737 // the superinterface methods (which were all abstract pre-default methods)
 738 // need to be added to the vtable.
 739 // With the addition of default methods, we have three new challenges:
 740 // overpasses, static interface methods and private interface methods.
 741 // Static and private interface methods do not get added to the vtable and
 742 // are not seen by the method resolution process, so we skip those.
 743 // Overpass methods are already in the vtable, so vtable lookup will
 744 // find them and we don't need to add a miranda method to the end of
 745 // the vtable. So we look for overpass methods and if they are found we
 746 // return false. Note that we inherit our superclasses vtable, so
 747 // the superclass' search also needs to use find_overpass so that if
 748 // one is found we return false.
 749 // False means - we don't need a miranda method added to the vtable.
 750 //
 751 // During the second run, default_methods is set up, so concrete methods from
 752 // superinterfaces with matching names/signatures to default_methods are already
 753 // in the default_methods list and do not need to be appended to the vtable
 754 // as mirandas. Abstract methods may already have been handled via
 755 // overpasses - either local or superclass overpasses, which may be
 756 // in the vtable already.
 757 //
 758 // Pass 3: They are also checked by link resolution and selection,
 759 // for invocation on a method (not interface method) reference that
 760 // resolves to a method with an interface as its method_holder.
 761 // Used as part of walking from the bottom of the vtable to find
 762 // the vtable index for the miranda method.
 763 //
 764 // Part of the Miranda Rights in the US mean that if you do not have
 765 // an attorney one will be appointed for you.
 766 bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods,
 767                              Array<Method*>* default_methods, const Klass* super) {
 768   if (m->is_static() || m->is_private() || m->is_overpass()) {
 769     return false;
 770   }
 771   Symbol* name = m->name();
 772   Symbol* signature = m->signature();
 773 
 774   // First look in local methods to see if already covered
 775   if (InstanceKlass::find_local_method(class_methods, name, signature,
 776               Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL)
 777   {
 778     return false;
 779   }
 780 
 781   // Check local default methods
 782   if ((default_methods != NULL) &&
 783     (InstanceKlass::find_method(default_methods, name, signature) != NULL))
 784    {
 785      return false;
 786    }
 787 
 788   // Iterate on all superclasses, which should be InstanceKlasses.
 789   // Note that we explicitly look for overpasses at each level.
 790   // Overpasses may or may not exist for supers for pass 1,
 791   // they should have been created for pass 2 and later.
 792 
 793   for (const Klass* cursuper = super; cursuper != NULL; cursuper = cursuper->super())
 794   {
 795      if (InstanceKlass::cast(cursuper)->find_local_method(name, signature,
 796            Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL) {
 797        return false;
 798      }
 799   }
 800 
 801   return true;
 802 }
 803 
 804 // Scans current_interface_methods for miranda methods that do not
 805 // already appear in new_mirandas, or default methods,  and are also not defined-and-non-private
 806 // in super (superclass).  These mirandas are added to all_mirandas if it is
 807 // not null; in addition, those that are not duplicates of miranda methods
 808 // inherited by super from its interfaces are added to new_mirandas.
 809 // Thus, new_mirandas will be the set of mirandas that this class introduces,
 810 // all_mirandas will be the set of all mirandas applicable to this class
 811 // including all defined in superclasses.
 812 void klassVtable::add_new_mirandas_to_lists(
 813     GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas,
 814     Array<Method*>* current_interface_methods, Array<Method*>* class_methods,
 815     Array<Method*>* default_methods, const Klass* super) {
 816 
 817   // iterate thru the current interface's method to see if it a miranda
 818   int num_methods = current_interface_methods->length();
 819   for (int i = 0; i < num_methods; i++) {
 820     Method* im = current_interface_methods->at(i);
 821     bool is_duplicate = false;
 822     int num_of_current_mirandas = new_mirandas->length();
 823     // check for duplicate mirandas in different interfaces we implement
 824     for (int j = 0; j < num_of_current_mirandas; j++) {
 825       Method* miranda = new_mirandas->at(j);
 826       if ((im->name() == miranda->name()) &&
 827           (im->signature() == miranda->signature())) {
 828         is_duplicate = true;
 829         break;
 830       }
 831     }
 832 
 833     if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable
 834       if (is_miranda(im, class_methods, default_methods, super)) { // is it a miranda at all?
 835         const InstanceKlass *sk = InstanceKlass::cast(super);
 836         // check if it is a duplicate of a super's miranda
 837         if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::find_defaults) == NULL) {
 838           new_mirandas->append(im);
 839         }
 840         if (all_mirandas != NULL) {
 841           all_mirandas->append(im);
 842         }
 843       }
 844     }
 845   }
 846 }
 847 
 848 void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas,
 849                                GrowableArray<Method*>* all_mirandas,
 850                                const Klass* super,
 851                                Array<Method*>* class_methods,
 852                                Array<Method*>* default_methods,
 853                                Array<Klass*>* local_interfaces) {
 854   assert((new_mirandas->length() == 0) , "current mirandas must be 0");
 855 
 856   // iterate thru the local interfaces looking for a miranda
 857   int num_local_ifs = local_interfaces->length();
 858   for (int i = 0; i < num_local_ifs; i++) {
 859     InstanceKlass *ik = InstanceKlass::cast(local_interfaces->at(i));
 860     add_new_mirandas_to_lists(new_mirandas, all_mirandas,
 861                               ik->methods(), class_methods,
 862                               default_methods, super);
 863     // iterate thru each local's super interfaces
 864     Array<Klass*>* super_ifs = ik->transitive_interfaces();
 865     int num_super_ifs = super_ifs->length();
 866     for (int j = 0; j < num_super_ifs; j++) {
 867       InstanceKlass *sik = InstanceKlass::cast(super_ifs->at(j));
 868       add_new_mirandas_to_lists(new_mirandas, all_mirandas,
 869                                 sik->methods(), class_methods,
 870                                 default_methods, super);
 871     }
 872   }
 873 }
 874 
 875 // Discover miranda methods ("miranda" = "interface abstract, no binding"),
 876 // and append them into the vtable starting at index initialized,
 877 // return the new value of initialized.
 878 // Miranda methods use vtable entries, but do not get assigned a vtable_index
 879 // The vtable_index is discovered by searching from the end of the vtable
 880 int klassVtable::fill_in_mirandas(int initialized) {
 881   GrowableArray<Method*> mirandas(20);
 882   get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(),
 883                ik()->default_methods(), ik()->local_interfaces());
 884   for (int i = 0; i < mirandas.length(); i++) {
 885     if (log_develop_is_enabled(Trace, vtables)) {
 886       Method* meth = mirandas.at(i);
 887       ResourceMark rm(Thread::current());
 888       outputStream* logst = Log(vtables)::trace_stream();
 889       if (meth != NULL) {
 890         char* sig = meth->name_and_sig_as_C_string();
 891         logst->print("fill in mirandas with %s index %d, flags: ",
 892                      sig, initialized);
 893         meth->print_linkage_flags(logst);
 894         logst->cr();
 895       }
 896     }
 897     put_method_at(mirandas.at(i), initialized);
 898     ++initialized;
 899   }
 900   return initialized;
 901 }
 902 
 903 // Copy this class's vtable to the vtable beginning at start.
 904 // Used to copy superclass vtable to prefix of subclass's vtable.
 905 void klassVtable::copy_vtable_to(vtableEntry* start) {
 906   Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
 907 }
 908 
 909 #if INCLUDE_JVMTI
 910 bool klassVtable::adjust_default_method(int vtable_index, Method* old_method, Method* new_method) {
 911   // If old_method is default, find this vtable index in default_vtable_indices
 912   // and replace that method in the _default_methods list
 913   bool updated = false;
 914 
 915   Array<Method*>* default_methods = ik()->default_methods();
 916   if (default_methods != NULL) {
 917     int len = default_methods->length();
 918     for (int idx = 0; idx < len; idx++) {
 919       if (vtable_index == ik()->default_vtable_indices()->at(idx)) {
 920         if (default_methods->at(idx) == old_method) {
 921           default_methods->at_put(idx, new_method);
 922           updated = true;
 923         }
 924         break;
 925       }
 926     }
 927   }
 928   return updated;
 929 }
 930 
 931 // search the vtable for uses of either obsolete or EMCP methods
 932 void klassVtable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {
 933   int prn_enabled = 0;
 934   for (int index = 0; index < length(); index++) {
 935     Method* old_method = unchecked_method_at(index);
 936     if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
 937       continue; // skip uninteresting entries
 938     }
 939     assert(!old_method->is_deleted(), "vtable methods may not be deleted");
 940 
 941     Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
 942 
 943     assert(new_method != NULL, "method_with_idnum() should not be NULL");
 944     assert(old_method != new_method, "sanity check");
 945 
 946     put_method_at(new_method, index);
 947     // For default methods, need to update the _default_methods array
 948     // which can only have one method entry for a given signature
 949     bool updated_default = false;
 950     if (old_method->is_default_method()) {
 951       updated_default = adjust_default_method(index, old_method, new_method);
 952     }
 953 
 954     if (log_is_enabled(Info, redefine, class, update)) {
 955       ResourceMark rm;
 956       if (!(*trace_name_printed)) {
 957         log_info(redefine, class, update)
 958           ("adjust: klassname=%s for methods from name=%s",
 959            _klass->external_name(), old_method->method_holder()->external_name());
 960         *trace_name_printed = true;
 961       }
 962       log_debug(redefine, class, update, vtables)
 963         ("vtable method update: %s(%s), updated default = %s",
 964          new_method->name()->as_C_string(), new_method->signature()->as_C_string(), updated_default ? "true" : "false");
 965     }
 966   }
 967 }
 968 
 969 // a vtable should never contain old or obsolete methods
 970 bool klassVtable::check_no_old_or_obsolete_entries() {
 971   for (int i = 0; i < length(); i++) {
 972     Method* m = unchecked_method_at(i);
 973     if (m != NULL &&
 974         (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
 975       return false;
 976     }
 977   }
 978   return true;
 979 }
 980 
 981 void klassVtable::dump_vtable() {
 982   tty->print_cr("vtable dump --");
 983   for (int i = 0; i < length(); i++) {
 984     Method* m = unchecked_method_at(i);
 985     if (m != NULL) {
 986       tty->print("      (%5d)  ", i);
 987       m->access_flags().print_on(tty);
 988       if (m->is_default_method()) {
 989         tty->print("default ");
 990       }
 991       if (m->is_overpass()) {
 992         tty->print("overpass");
 993       }
 994       tty->print(" --  ");
 995       m->print_name(tty);
 996       tty->cr();
 997     }
 998   }
 999 }
1000 #endif // INCLUDE_JVMTI
1001 
1002 // CDS/RedefineClasses support - clear vtables so they can be reinitialized
1003 void klassVtable::clear_vtable() {
1004   for (int i = 0; i < _length; i++) table()[i].clear();
1005 }
1006 
1007 bool klassVtable::is_initialized() {
1008   return _length == 0 || table()[0].method() != NULL;
1009 }
1010 
1011 //-----------------------------------------------------------------------------------------
1012 // Itable code
1013 
1014 // Initialize a itableMethodEntry
1015 void itableMethodEntry::initialize(Method* m) {
1016   if (m == NULL) return;
1017 
1018 #ifdef ASSERT
1019   if (MetaspaceShared::is_in_shared_space((void*)&_method) &&
1020      !MetaspaceShared::remapped_readwrite()) {
1021     // At runtime initialize_itable is rerun as part of link_class_impl()
1022     // for a shared class loaded by the non-boot loader.
1023     // The dumptime itable method entry should be the same as the runtime entry.
1024     assert(_method == m, "sanity");
1025   }
1026 #endif
1027   _method = m;
1028 }
1029 
1030 klassItable::klassItable(InstanceKlass* klass) {
1031   _klass = klass;
1032 
1033   if (klass->itable_length() > 0) {
1034     itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();
1035     if (offset_entry  != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized
1036       // First offset entry points to the first method_entry
1037       intptr_t* method_entry  = (intptr_t *)(((address)klass) + offset_entry->offset());
1038       intptr_t* end         = klass->end_of_itable();
1039 
1040       _table_offset      = (intptr_t*)offset_entry - (intptr_t*)klass;
1041       _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();
1042       _size_method_table = (end - method_entry)                  / itableMethodEntry::size();
1043       assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");
1044       return;
1045     }
1046   }
1047 
1048   // The length of the itable was either zero, or it has not yet been initialized.
1049   _table_offset      = 0;
1050   _size_offset_table = 0;
1051   _size_method_table = 0;
1052 }
1053 
1054 static int initialize_count = 0;
1055 
1056 // Initialization
1057 void klassItable::initialize_itable(bool checkconstraints, TRAPS) {
1058   if (_klass->is_interface()) {
1059     // This needs to go after vtable indices are assigned but
1060     // before implementors need to know the number of itable indices.
1061     assign_itable_indices_for_interface(_klass);
1062   }
1063 
1064   // Cannot be setup doing bootstrapping, interfaces don't have
1065   // itables, and klass with only ones entry have empty itables
1066   if (Universe::is_bootstrapping() ||
1067       _klass->is_interface() ||
1068       _klass->itable_length() == itableOffsetEntry::size()) return;
1069 
1070   // There's alway an extra itable entry so we can null-terminate it.
1071   guarantee(size_offset_table() >= 1, "too small");
1072   int num_interfaces = size_offset_table() - 1;
1073   if (num_interfaces > 0) {
1074     log_develop_debug(itables)("%3d: Initializing itables for %s", ++initialize_count,
1075                        _klass->name()->as_C_string());
1076 
1077 
1078     // Iterate through all interfaces
1079     int i;
1080     for(i = 0; i < num_interfaces; i++) {
1081       itableOffsetEntry* ioe = offset_entry(i);
1082       HandleMark hm(THREAD);
1083       Klass* interf = ioe->interface_klass();
1084       assert(interf != NULL && ioe->offset() != 0, "bad offset entry in itable");
1085       initialize_itable_for_interface(ioe->offset(), interf, checkconstraints, CHECK);
1086     }
1087 
1088   }
1089   // Check that the last entry is empty
1090   itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);
1091   guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");
1092 }
1093 
1094 
1095 inline bool interface_method_needs_itable_index(Method* m) {
1096   if (m->is_static())           return false;   // e.g., Stream.empty
1097   if (m->is_initializer())      return false;   // <init> or <clinit>
1098   if (m->is_private())          return false;   // requires invokeSpecial
1099   // If an interface redeclares a method from java.lang.Object,
1100   // it should already have a vtable index, don't touch it.
1101   // e.g., CharSequence.toString (from initialize_vtable)
1102   // if (m->has_vtable_index())  return false; // NO!
1103   return true;
1104 }
1105 
1106 int klassItable::assign_itable_indices_for_interface(Klass* klass) {
1107   // an interface does not have an itable, but its methods need to be numbered
1108   log_develop_debug(itables)("%3d: Initializing itable indices for interface %s",
1109                              ++initialize_count, klass->name()->as_C_string());
1110   Array<Method*>* methods = InstanceKlass::cast(klass)->methods();
1111   int nof_methods = methods->length();
1112   int ime_num = 0;
1113   for (int i = 0; i < nof_methods; i++) {
1114     Method* m = methods->at(i);
1115     if (interface_method_needs_itable_index(m)) {
1116       assert(!m->is_final_method(), "no final interface methods");
1117       // If m is already assigned a vtable index, do not disturb it.
1118       if (log_develop_is_enabled(Trace, itables)) {
1119         ResourceMark rm;
1120         outputStream* logst = Log(itables)::trace_stream();
1121         assert(m != NULL, "methods can never be null");
1122         const char* sig = m->name_and_sig_as_C_string();
1123         if (m->has_vtable_index()) {
1124           logst->print("vtable index %d for method: %s, flags: ", m->vtable_index(), sig);
1125         } else {
1126           logst->print("itable index %d for method: %s, flags: ", ime_num, sig);
1127         }
1128         m->print_linkage_flags(logst);
1129         logst->cr();
1130       }
1131       if (!m->has_vtable_index()) {
1132         // A shared method could have an initialized itable_index that
1133         // is < 0.
1134         assert(m->vtable_index() == Method::pending_itable_index ||
1135                m->is_shared(),
1136                "set by initialize_vtable");
1137         m->set_itable_index(ime_num);
1138         // Progress to next itable entry
1139         ime_num++;
1140       }
1141     }
1142   }
1143   assert(ime_num == method_count_for_interface(klass), "proper sizing");
1144   return ime_num;
1145 }
1146 
1147 int klassItable::method_count_for_interface(Klass* interf) {
1148   assert(interf->is_instance_klass(), "must be");
1149   assert(interf->is_interface(), "must be");
1150   Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
1151   int nof_methods = methods->length();
1152   int length = 0;
1153   while (nof_methods > 0) {
1154     Method* m = methods->at(nof_methods-1);
1155     if (m->has_itable_index()) {
1156       length = m->itable_index() + 1;
1157       break;
1158     }
1159     nof_methods -= 1;
1160   }
1161 #ifdef ASSERT
1162   int nof_methods_copy = nof_methods;
1163   while (nof_methods_copy > 0) {
1164     Method* mm = methods->at(--nof_methods_copy);
1165     assert(!mm->has_itable_index() || mm->itable_index() < length, "");
1166   }
1167 #endif //ASSERT
1168   // return the rightmost itable index, plus one; or 0 if no methods have
1169   // itable indices
1170   return length;
1171 }
1172 
1173 
1174 void klassItable::initialize_itable_for_interface(int method_table_offset, Klass* interf, bool checkconstraints, TRAPS) {
1175   Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
1176   int nof_methods = methods->length();
1177   HandleMark hm;
1178   assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
1179   Handle interface_loader (THREAD, InstanceKlass::cast(interf)->class_loader());
1180 
1181   int ime_count = method_count_for_interface(interf);
1182   for (int i = 0; i < nof_methods; i++) {
1183     Method* m = methods->at(i);
1184     methodHandle target;
1185     if (m->has_itable_index()) {
1186       // This search must match the runtime resolution, i.e. selection search for invokeinterface
1187       // to correctly enforce loader constraints for interface method inheritance
1188       target = LinkResolver::lookup_instance_method_in_klasses(_klass, m->name(), m->signature(), CHECK);
1189     }
1190     if (target == NULL || !target->is_public() || target->is_abstract()) {
1191       // Entry does not resolve. Leave it empty for AbstractMethodError.
1192         if (!(target == NULL) && !target->is_public()) {
1193           // Stuff an IllegalAccessError throwing method in there instead.
1194           itableOffsetEntry::method_entry(_klass, method_table_offset)[m->itable_index()].
1195               initialize(Universe::throw_illegal_access_error());
1196         }
1197     } else {
1198       // Entry did resolve, check loader constraints before initializing
1199       // if checkconstraints requested
1200       if (checkconstraints) {
1201         Handle method_holder_loader (THREAD, target->method_holder()->class_loader());
1202         if (method_holder_loader() != interface_loader()) {
1203           ResourceMark rm(THREAD);
1204           Symbol* failed_type_symbol =
1205             SystemDictionary::check_signature_loaders(m->signature(),
1206                                                       method_holder_loader,
1207                                                       interface_loader,
1208                                                       true, CHECK);
1209           if (failed_type_symbol != NULL) {
1210             const char* msg = "loader constraint violation in interface "
1211               "itable initialization: when resolving method \"%s\" the class"
1212               " loader (instance of %s) of the current class, %s, "
1213               "and the class loader (instance of %s) for interface "
1214               "%s have different Class objects for the type %s "
1215               "used in the signature";
1216             char* sig = target()->name_and_sig_as_C_string();
1217             const char* loader1 = SystemDictionary::loader_name(method_holder_loader());
1218             char* current = _klass->name()->as_C_string();
1219             const char* loader2 = SystemDictionary::loader_name(interface_loader());
1220             char* iface = InstanceKlass::cast(interf)->name()->as_C_string();
1221             char* failed_type_name = failed_type_symbol->as_C_string();
1222             size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
1223               strlen(current) + strlen(loader2) + strlen(iface) +
1224               strlen(failed_type_name);
1225             char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
1226             jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
1227                          iface, failed_type_name);
1228             THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
1229           }
1230         }
1231       }
1232 
1233       // ime may have moved during GC so recalculate address
1234       int ime_num = m->itable_index();
1235       assert(ime_num < ime_count, "oob");
1236       itableOffsetEntry::method_entry(_klass, method_table_offset)[ime_num].initialize(target());
1237       if (log_develop_is_enabled(Trace, itables)) {
1238         ResourceMark rm(THREAD);
1239         if (target() != NULL) {
1240           outputStream* logst = Log(itables)::trace_stream();
1241           char* sig = target()->name_and_sig_as_C_string();
1242           logst->print("interface: %s, ime_num: %d, target: %s, method_holder: %s ",
1243                        interf->internal_name(), ime_num, sig,
1244                        target()->method_holder()->internal_name());
1245           logst->print("target_method flags: ");
1246           target()->print_linkage_flags(logst);
1247           logst->cr();
1248         }
1249       }
1250     }
1251   }
1252 }
1253 
1254 #if INCLUDE_JVMTI
1255 // search the itable for uses of either obsolete or EMCP methods
1256 void klassItable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {
1257 
1258   itableMethodEntry* ime = method_entry(0);
1259   for (int i = 0; i < _size_method_table; i++, ime++) {
1260     Method* old_method = ime->method();
1261     if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
1262       continue; // skip uninteresting entries
1263     }
1264     assert(!old_method->is_deleted(), "itable methods may not be deleted");
1265 
1266     Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
1267 
1268     assert(new_method != NULL, "method_with_idnum() should not be NULL");
1269     assert(old_method != new_method, "sanity check");
1270 
1271     ime->initialize(new_method);
1272 
1273     if (log_is_enabled(Info, redefine, class, update)) {
1274       ResourceMark rm;
1275       if (!(*trace_name_printed)) {
1276         log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
1277         *trace_name_printed = true;
1278       }
1279       log_trace(redefine, class, update, itables)
1280         ("itable method update: %s(%s)", new_method->name()->as_C_string(), new_method->signature()->as_C_string());
1281     }
1282   }
1283 }
1284 
1285 // an itable should never contain old or obsolete methods
1286 bool klassItable::check_no_old_or_obsolete_entries() {
1287   itableMethodEntry* ime = method_entry(0);
1288   for (int i = 0; i < _size_method_table; i++) {
1289     Method* m = ime->method();
1290     if (m != NULL &&
1291         (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
1292       return false;
1293     }
1294     ime++;
1295   }
1296   return true;
1297 }
1298 
1299 void klassItable::dump_itable() {
1300   itableMethodEntry* ime = method_entry(0);
1301   tty->print_cr("itable dump --");
1302   for (int i = 0; i < _size_method_table; i++) {
1303     Method* m = ime->method();
1304     if (m != NULL) {
1305       tty->print("      (%5d)  ", i);
1306       m->access_flags().print_on(tty);
1307       if (m->is_default_method()) {
1308         tty->print("default ");
1309       }
1310       tty->print(" --  ");
1311       m->print_name(tty);
1312       tty->cr();
1313     }
1314     ime++;
1315   }
1316 }
1317 #endif // INCLUDE_JVMTI
1318 
1319 // Setup
1320 class InterfaceVisiterClosure : public StackObj {
1321  public:
1322   virtual void doit(Klass* intf, int method_count) = 0;
1323 };
1324 
1325 // Visit all interfaces with at least one itable method
1326 void visit_all_interfaces(Array<Klass*>* transitive_intf, InterfaceVisiterClosure *blk) {
1327   // Handle array argument
1328   for(int i = 0; i < transitive_intf->length(); i++) {
1329     Klass* intf = transitive_intf->at(i);
1330     assert(intf->is_interface(), "sanity check");
1331 
1332     // Find no. of itable methods
1333     int method_count = 0;
1334     // method_count = klassItable::method_count_for_interface(intf);
1335     Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
1336     if (methods->length() > 0) {
1337       for (int i = methods->length(); --i >= 0; ) {
1338         if (interface_method_needs_itable_index(methods->at(i))) {
1339           method_count++;
1340         }
1341       }
1342     }
1343 
1344     // Only count interfaces with at least one method
1345     if (method_count > 0) {
1346       blk->doit(intf, method_count);
1347     }
1348   }
1349 }
1350 
1351 class CountInterfacesClosure : public InterfaceVisiterClosure {
1352  private:
1353   int _nof_methods;
1354   int _nof_interfaces;
1355  public:
1356    CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }
1357 
1358    int nof_methods() const    { return _nof_methods; }
1359    int nof_interfaces() const { return _nof_interfaces; }
1360 
1361    void doit(Klass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }
1362 };
1363 
1364 class SetupItableClosure : public InterfaceVisiterClosure  {
1365  private:
1366   itableOffsetEntry* _offset_entry;
1367   itableMethodEntry* _method_entry;
1368   address            _klass_begin;
1369  public:
1370   SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {
1371     _klass_begin  = klass_begin;
1372     _offset_entry = offset_entry;
1373     _method_entry = method_entry;
1374   }
1375 
1376   itableMethodEntry* method_entry() const { return _method_entry; }
1377 
1378   void doit(Klass* intf, int method_count) {
1379     int offset = ((address)_method_entry) - _klass_begin;
1380     _offset_entry->initialize(intf, offset);
1381     _offset_entry++;
1382     _method_entry += method_count;
1383   }
1384 };
1385 
1386 int klassItable::compute_itable_size(Array<Klass*>* transitive_interfaces) {
1387   // Count no of interfaces and total number of interface methods
1388   CountInterfacesClosure cic;
1389   visit_all_interfaces(transitive_interfaces, &cic);
1390 
1391   // There's alway an extra itable entry so we can null-terminate it.
1392   int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());
1393 
1394   // Statistics
1395   update_stats(itable_size * wordSize);
1396 
1397   return itable_size;
1398 }
1399 
1400 
1401 // Fill out offset table and interface klasses into the itable space
1402 void klassItable::setup_itable_offset_table(InstanceKlass* klass) {
1403   if (klass->itable_length() == 0) return;
1404   assert(!klass->is_interface(), "Should have zero length itable");
1405 
1406   // Count no of interfaces and total number of interface methods
1407   CountInterfacesClosure cic;
1408   visit_all_interfaces(klass->transitive_interfaces(), &cic);
1409   int nof_methods    = cic.nof_methods();
1410   int nof_interfaces = cic.nof_interfaces();
1411 
1412   // Add one extra entry so we can null-terminate the table
1413   nof_interfaces++;
1414 
1415   assert(compute_itable_size(klass->transitive_interfaces()) ==
1416          calc_itable_size(nof_interfaces, nof_methods),
1417          "mismatch calculation of itable size");
1418 
1419   // Fill-out offset table
1420   itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();
1421   itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);
1422   intptr_t* end               = klass->end_of_itable();
1423   assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)");
1424   assert((oop*)(end) == (oop*)(ime + nof_methods),                      "wrong offset calculation (2)");
1425 
1426   // Visit all interfaces and initialize itable offset table
1427   SetupItableClosure sic((address)klass, ioe, ime);
1428   visit_all_interfaces(klass->transitive_interfaces(), &sic);
1429 
1430 #ifdef ASSERT
1431   ime  = sic.method_entry();
1432   oop* v = (oop*) klass->end_of_itable();
1433   assert( (oop*)(ime) == v, "wrong offset calculation (2)");
1434 #endif
1435 }
1436 
1437 
1438 // inverse to itable_index
1439 Method* klassItable::method_for_itable_index(Klass* intf, int itable_index) {
1440   assert(InstanceKlass::cast(intf)->is_interface(), "sanity check");
1441   assert(intf->verify_itable_index(itable_index), "");
1442   Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
1443 
1444   if (itable_index < 0 || itable_index >= method_count_for_interface(intf))
1445     return NULL;                // help caller defend against bad indices
1446 
1447   int index = itable_index;
1448   Method* m = methods->at(index);
1449   int index2 = -1;
1450   while (!m->has_itable_index() ||
1451          (index2 = m->itable_index()) != itable_index) {
1452     assert(index2 < itable_index, "monotonic");
1453     if (++index == methods->length())
1454       return NULL;
1455     m = methods->at(index);
1456   }
1457   assert(m->itable_index() == itable_index, "correct inverse");
1458 
1459   return m;
1460 }
1461 
1462 void klassVtable::verify(outputStream* st, bool forced) {
1463   // make sure table is initialized
1464   if (!Universe::is_fully_initialized()) return;
1465 #ifndef PRODUCT
1466   // avoid redundant verifies
1467   if (!forced && _verify_count == Universe::verify_count()) return;
1468   _verify_count = Universe::verify_count();
1469 #endif
1470   oop* end_of_obj = (oop*)_klass + _klass->size();
1471   oop* end_of_vtable = (oop *)&table()[_length];
1472   if (end_of_vtable > end_of_obj) {
1473     fatal("klass %s: klass object too short (vtable extends beyond end)",
1474           _klass->internal_name());
1475   }
1476 
1477   for (int i = 0; i < _length; i++) table()[i].verify(this, st);
1478   // verify consistency with superKlass vtable
1479   Klass* super = _klass->super();
1480   if (super != NULL) {
1481     InstanceKlass* sk = InstanceKlass::cast(super);
1482     klassVtable vt = sk->vtable();
1483     for (int i = 0; i < vt.length(); i++) {
1484       verify_against(st, &vt, i);
1485     }
1486   }
1487 }
1488 
1489 void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {
1490   vtableEntry* vte = &vt->table()[index];
1491   if (vte->method()->name()      != table()[index].method()->name() ||
1492       vte->method()->signature() != table()[index].method()->signature()) {
1493     fatal("mismatched name/signature of vtable entries");
1494   }
1495 }
1496 
1497 #ifndef PRODUCT
1498 void klassVtable::print() {
1499   ResourceMark rm;
1500   tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());
1501   for (int i = 0; i < length(); i++) {
1502     table()[i].print();
1503     tty->cr();
1504   }
1505 }
1506 #endif
1507 
1508 void vtableEntry::verify(klassVtable* vt, outputStream* st) {
1509   NOT_PRODUCT(FlagSetting fs(IgnoreLockingAssertions, true));
1510   Klass* vtklass = vt->klass();
1511   if (vtklass->is_instance_klass() &&
1512      (InstanceKlass::cast(vtklass)->major_version() >= klassVtable::VTABLE_TRANSITIVE_OVERRIDE_VERSION)) {
1513     assert(method() != NULL, "must have set method");
1514   }
1515   if (method() != NULL) {
1516     method()->verify();
1517     // we sub_type, because it could be a miranda method
1518     if (!vtklass->is_subtype_of(method()->method_holder())) {
1519 #ifndef PRODUCT
1520       print();
1521 #endif
1522       fatal("vtableEntry " PTR_FORMAT ": method is from subclass", p2i(this));
1523     }
1524  }
1525 }
1526 
1527 #ifndef PRODUCT
1528 
1529 void vtableEntry::print() {
1530   ResourceMark rm;
1531   tty->print("vtableEntry %s: ", method()->name()->as_C_string());
1532   if (Verbose) {
1533     tty->print("m " PTR_FORMAT " ", p2i(method()));
1534   }
1535 }
1536 
1537 class VtableStats : AllStatic {
1538  public:
1539   static int no_klasses;                // # classes with vtables
1540   static int no_array_klasses;          // # array classes
1541   static int no_instance_klasses;       // # instanceKlasses
1542   static int sum_of_vtable_len;         // total # of vtable entries
1543   static int sum_of_array_vtable_len;   // total # of vtable entries in array klasses only
1544   static int fixed;                     // total fixed overhead in bytes
1545   static int filler;                    // overhead caused by filler bytes
1546   static int entries;                   // total bytes consumed by vtable entries
1547   static int array_entries;             // total bytes consumed by array vtable entries
1548 
1549   static void do_class(Klass* k) {
1550     Klass* kl = k;
1551     klassVtable vt = kl->vtable();
1552     no_klasses++;
1553     if (kl->is_instance_klass()) {
1554       no_instance_klasses++;
1555       kl->array_klasses_do(do_class);
1556     }
1557     if (kl->is_array_klass()) {
1558       no_array_klasses++;
1559       sum_of_array_vtable_len += vt.length();
1560     }
1561     sum_of_vtable_len += vt.length();
1562   }
1563 
1564   static void compute() {
1565     ClassLoaderDataGraph::classes_do(do_class);
1566     fixed  = no_klasses * oopSize;      // vtable length
1567     // filler size is a conservative approximation
1568     filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1);
1569     entries = sizeof(vtableEntry) * sum_of_vtable_len;
1570     array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;
1571   }
1572 };
1573 
1574 int VtableStats::no_klasses = 0;
1575 int VtableStats::no_array_klasses = 0;
1576 int VtableStats::no_instance_klasses = 0;
1577 int VtableStats::sum_of_vtable_len = 0;
1578 int VtableStats::sum_of_array_vtable_len = 0;
1579 int VtableStats::fixed = 0;
1580 int VtableStats::filler = 0;
1581 int VtableStats::entries = 0;
1582 int VtableStats::array_entries = 0;
1583 
1584 void klassVtable::print_statistics() {
1585   ResourceMark rm;
1586   HandleMark hm;
1587   VtableStats::compute();
1588   tty->print_cr("vtable statistics:");
1589   tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);
1590   int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;
1591   tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);
1592   tty->print_cr("%6d bytes filler overhead", VtableStats::filler);
1593   tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);
1594   tty->print_cr("%6d bytes total", total);
1595 }
1596 
1597 int  klassItable::_total_classes;   // Total no. of classes with itables
1598 long klassItable::_total_size;      // Total no. of bytes used for itables
1599 
1600 void klassItable::print_statistics() {
1601  tty->print_cr("itable statistics:");
1602  tty->print_cr("%6d classes with itables", _total_classes);
1603  tty->print_cr("%6lu K uses for itables (average by class: %ld bytes)", _total_size / K, _total_size / _total_classes);
1604 }
1605 
1606 #endif // PRODUCT