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