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