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