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