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