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