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