1 /*
   2  * Copyright (c) 1997, 2026, 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/aotClassInitializer.hpp"
  26 #include "cds/aotLinkedClassBulkLoader.hpp"
  27 #include "cds/aotMetaspace.hpp"
  28 #include "cds/archiveUtils.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/cdsEnumKlass.hpp"
  31 #include "cds/classListWriter.hpp"
  32 #include "cds/heapShared.hpp"
  33 #include "classfile/classFileParser.hpp"
  34 #include "classfile/classFileStream.hpp"
  35 #include "classfile/classLoader.hpp"
  36 #include "classfile/classLoaderData.inline.hpp"
  37 #include "classfile/javaClasses.hpp"
  38 #include "classfile/moduleEntry.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/systemDictionaryShared.hpp"
  41 #include "classfile/verifier.hpp"
  42 #include "classfile/vmClasses.hpp"
  43 #include "classfile/vmSymbols.hpp"
  44 #include "code/codeCache.hpp"
  45 #include "code/dependencyContext.hpp"
  46 #include "compiler/compilationPolicy.hpp"
  47 #include "compiler/compileBroker.hpp"
  48 #include "gc/shared/collectedHeap.inline.hpp"
  49 #include "interpreter/bytecodeStream.hpp"
  50 #include "interpreter/oopMapCache.hpp"
  51 #include "interpreter/rewriter.hpp"
  52 #include "jvm.h"
  53 #include "jvmtifiles/jvmti.h"
  54 #include "klass.inline.hpp"
  55 #include "logging/log.hpp"
  56 #include "logging/logMessage.hpp"
  57 #include "logging/logStream.hpp"
  58 #include "memory/allocation.inline.hpp"
  59 #include "memory/iterator.inline.hpp"
  60 #include "memory/metadataFactory.hpp"
  61 #include "memory/metaspaceClosure.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "oops/constantPool.hpp"
  66 #include "oops/fieldStreams.inline.hpp"
  67 #include "oops/instanceClassLoaderKlass.hpp"
  68 #include "oops/instanceKlass.inline.hpp"
  69 #include "oops/instanceMirrorKlass.hpp"
  70 #include "oops/instanceOop.hpp"
  71 #include "oops/instanceStackChunkKlass.hpp"
  72 #include "oops/klass.inline.hpp"
  73 #include "oops/method.hpp"
  74 #include "oops/oop.inline.hpp"
  75 #include "oops/recordComponent.hpp"
  76 #include "oops/symbol.hpp"
  77 #include "prims/jvmtiExport.hpp"
  78 #include "prims/jvmtiRedefineClasses.hpp"
  79 #include "prims/jvmtiThreadState.hpp"
  80 #include "prims/methodComparator.hpp"
  81 #include "runtime/arguments.hpp"
  82 #include "runtime/atomicAccess.hpp"
  83 #include "runtime/deoptimization.hpp"
  84 #include "runtime/fieldDescriptor.inline.hpp"
  85 #include "runtime/handles.inline.hpp"
  86 #include "runtime/javaCalls.hpp"
  87 #include "runtime/javaThread.inline.hpp"
  88 #include "runtime/mutexLocker.hpp"
  89 #include "runtime/orderAccess.hpp"
  90 #include "runtime/os.inline.hpp"
  91 #include "runtime/reflection.hpp"
  92 #include "runtime/synchronizer.hpp"
  93 #include "runtime/threads.hpp"
  94 #include "services/classLoadingService.hpp"
  95 #include "services/finalizerService.hpp"
  96 #include "services/threadService.hpp"
  97 #include "utilities/dtrace.hpp"
  98 #include "utilities/events.hpp"
  99 #include "utilities/macros.hpp"
 100 #include "utilities/nativeStackPrinter.hpp"
 101 #include "utilities/stringUtils.hpp"
 102 #ifdef COMPILER1
 103 #include "c1/c1_Compiler.hpp"
 104 #endif
 105 #if INCLUDE_JFR
 106 #include "jfr/jfrEvents.hpp"
 107 #endif
 108 
 109 #ifdef DTRACE_ENABLED
 110 
 111 
 112 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
 113 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
 114 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
 115 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
 116 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
 117 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
 118 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
 119 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
 120 #define DTRACE_CLASSINIT_PROBE(type, thread_type)                \
 121   {                                                              \
 122     char* data = nullptr;                                        \
 123     int len = 0;                                                 \
 124     Symbol* clss_name = name();                                  \
 125     if (clss_name != nullptr) {                                  \
 126       data = (char*)clss_name->bytes();                          \
 127       len = clss_name->utf8_length();                            \
 128     }                                                            \
 129     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 130       data, len, (void*)class_loader(), thread_type);            \
 131   }
 132 
 133 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)     \
 134   {                                                              \
 135     char* data = nullptr;                                        \
 136     int len = 0;                                                 \
 137     Symbol* clss_name = name();                                  \
 138     if (clss_name != nullptr) {                                  \
 139       data = (char*)clss_name->bytes();                          \
 140       len = clss_name->utf8_length();                            \
 141     }                                                            \
 142     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 143       data, len, (void*)class_loader(), thread_type, wait);      \
 144   }
 145 
 146 #else //  ndef DTRACE_ENABLED
 147 
 148 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
 149 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
 150 
 151 #endif //  ndef DTRACE_ENABLED
 152 
 153 bool InstanceKlass::_finalization_enabled = true;
 154 static int call_class_initializer_counter = 0;   // for debugging
 155 
 156 static inline bool is_class_loader(const Symbol* class_name,
 157                                    const ClassFileParser& parser) {
 158   assert(class_name != nullptr, "invariant");
 159 
 160   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 161     return true;
 162   }
 163 
 164   if (vmClasses::ClassLoader_klass_is_loaded()) {
 165     const Klass* const super_klass = parser.super_klass();
 166     if (super_klass != nullptr) {
 167       if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
 168         return true;
 169       }
 170     }
 171   }
 172   return false;
 173 }
 174 
 175 static inline bool is_stack_chunk_class(const Symbol* class_name,
 176                                         const ClassLoaderData* loader_data) {
 177   return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
 178           loader_data->is_the_null_class_loader_data());
 179 }
 180 
 181 // private: called to verify that k is a static member of this nest.
 182 // We know that k is an instance class in the same package and hence the
 183 // same classloader.
 184 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
 185   assert(!is_hidden(), "unexpected hidden class");
 186   if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
 187     if (log_is_enabled(Trace, class, nestmates)) {
 188       ResourceMark rm(current);
 189       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 190                                   k->external_name(), this->external_name());
 191     }
 192     return false;
 193   }
 194 
 195   if (log_is_enabled(Trace, class, nestmates)) {
 196     ResourceMark rm(current);
 197     log_trace(class, nestmates)("Checking nest membership of %s in %s",
 198                                 k->external_name(), this->external_name());
 199   }
 200 
 201   // Check for the named class in _nest_members.
 202   // We don't resolve, or load, any classes.
 203   for (int i = 0; i < _nest_members->length(); i++) {
 204     int cp_index = _nest_members->at(i);
 205     Symbol* name = _constants->klass_name_at(cp_index);
 206     if (name == k->name()) {
 207       log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index);
 208       return true;
 209     }
 210   }
 211   log_trace(class, nestmates)("- class is NOT a nest member!");
 212   return false;
 213 }
 214 
 215 // Called to verify that k is a permitted subclass of this class.
 216 // The incoming stringStream is used to format the messages for error logging and for the caller
 217 // to use for exception throwing.
 218 bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k, stringStream& ss) const {
 219   Thread* current = Thread::current();
 220   assert(k != nullptr, "sanity check");
 221   assert(_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array(),
 222          "unexpected empty _permitted_subclasses array");
 223 
 224   if (log_is_enabled(Trace, class, sealed)) {
 225     ResourceMark rm(current);
 226     log_trace(class, sealed)("Checking for permitted subclass %s in %s",
 227                              k->external_name(), this->external_name());
 228   }
 229 
 230   // Check that the class and its super are in the same module.
 231   if (k->module() != this->module()) {
 232     ss.print("Failed same module check: subclass %s is in module '%s' with loader %s, "
 233              "and sealed class %s is in module '%s' with loader %s",
 234              k->external_name(),
 235              k->module()->name_as_C_string(),
 236              k->module()->loader_data()->loader_name_and_id(),
 237              this->external_name(),
 238              this->module()->name_as_C_string(),
 239              this->module()->loader_data()->loader_name_and_id());
 240     log_trace(class, sealed)(" - %s", ss.as_string());
 241     return false;
 242   }
 243 
 244   if (!k->is_public() && !is_same_class_package(k)) {
 245     ss.print("Failed same package check: non-public subclass %s is in package '%s' with classloader %s, "
 246              "and sealed class %s is in package '%s' with classloader %s",
 247              k->external_name(),
 248              k->package() != nullptr ? k->package()->name()->as_C_string() : "unnamed",
 249              k->module()->loader_data()->loader_name_and_id(),
 250              this->external_name(),
 251              this->package() != nullptr ? this->package()->name()->as_C_string() : "unnamed",
 252              this->module()->loader_data()->loader_name_and_id());
 253     log_trace(class, sealed)(" - %s", ss.as_string());
 254     return false;
 255   }
 256 
 257   for (int i = 0; i < _permitted_subclasses->length(); i++) {
 258     int cp_index = _permitted_subclasses->at(i);
 259     Symbol* name = _constants->klass_name_at(cp_index);
 260     if (name == k->name()) {
 261       log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index);
 262       return true;
 263     }
 264   }
 265 
 266   ss.print("Failed listed permitted subclass check: class %s is not a permitted subclass of %s",
 267            k->external_name(), this->external_name());
 268   log_trace(class, sealed)(" - %s", ss.as_string());
 269   return false;
 270 }
 271 
 272 // Return nest-host class, resolving, validating and saving it if needed.
 273 // In cases where this is called from a thread that cannot do classloading
 274 // (such as a native JIT thread) then we simply return null, which in turn
 275 // causes the access check to return false. Such code will retry the access
 276 // from a more suitable environment later. Otherwise the _nest_host is always
 277 // set once this method returns.
 278 // Any errors from nest-host resolution must be preserved so they can be queried
 279 // from higher-level access checking code, and reported as part of access checking
 280 // exceptions.
 281 // VirtualMachineErrors are propagated with a null return.
 282 // Under any conditions where the _nest_host can be set to non-null the resulting
 283 // value of it and, if applicable, the nest host resolution/validation error,
 284 // are idempotent.
 285 InstanceKlass* InstanceKlass::nest_host(TRAPS) {
 286   InstanceKlass* nest_host_k = _nest_host;
 287   if (nest_host_k != nullptr) {
 288     return nest_host_k;
 289   }
 290 
 291   ResourceMark rm(THREAD);
 292 
 293   // need to resolve and save our nest-host class.
 294   if (_nest_host_index != 0) { // we have a real nest_host
 295     // Before trying to resolve check if we're in a suitable context
 296     bool can_resolve = THREAD->can_call_java();
 297     if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) {
 298       log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
 299                                   this->external_name());
 300       return nullptr; // sentinel to say "try again from a different context"
 301     }
 302 
 303     log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
 304                                 this->external_name(),
 305                                 _constants->klass_name_at(_nest_host_index)->as_C_string());
 306 
 307     Klass* k = _constants->klass_at(_nest_host_index, THREAD);
 308     if (HAS_PENDING_EXCEPTION) {
 309       if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
 310         return nullptr; // propagate VMEs
 311       }
 312       stringStream ss;
 313       char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string();
 314       ss.print("Nest host resolution of %s with host %s failed: ",
 315                this->external_name(), target_host_class);
 316       java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
 317       constantPoolHandle cph(THREAD, constants());
 318       SystemDictionary::add_nest_host_error(cph, _nest_host_index, ss);
 319       CLEAR_PENDING_EXCEPTION;
 320 
 321       log_trace(class, nestmates)("%s", ss.base());
 322     } else {
 323       // A valid nest-host is an instance class in the current package that lists this
 324       // class as a nest member. If any of these conditions are not met the class is
 325       // its own nest-host.
 326       const char* error = nullptr;
 327 
 328       // JVMS 5.4.4 indicates package check comes first
 329       if (is_same_class_package(k)) {
 330         // Now check actual membership. We can't be a member if our "host" is
 331         // not an instance class.
 332         if (k->is_instance_klass()) {
 333           nest_host_k = InstanceKlass::cast(k);
 334           bool is_member = nest_host_k->has_nest_member(THREAD, this);
 335           if (is_member) {
 336             _nest_host = nest_host_k; // save resolved nest-host value
 337 
 338             log_trace(class, nestmates)("Resolved nest-host of %s to %s",
 339                                         this->external_name(), k->external_name());
 340             return nest_host_k;
 341           } else {
 342             error = "current type is not listed as a nest member";
 343           }
 344         } else {
 345           error = "host is not an instance class";
 346         }
 347       } else {
 348         error = "types are in different packages";
 349       }
 350 
 351       // something went wrong, so record what and log it
 352       {
 353         stringStream ss;
 354         ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s",
 355                  this->external_name(),
 356                  this->class_loader_data()->loader_name_and_id(),
 357                  k->external_name(),
 358                  k->class_loader_data()->loader_name_and_id(),
 359                  error);
 360         constantPoolHandle cph(THREAD, constants());
 361         SystemDictionary::add_nest_host_error(cph, _nest_host_index, ss);
 362         log_trace(class, nestmates)("%s", ss.base());
 363       }
 364     }
 365   } else {
 366     log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
 367                                 this->external_name());
 368   }
 369 
 370   // Either not in an explicit nest, or else an error occurred, so
 371   // the nest-host is set to `this`. Any thread that sees this assignment
 372   // will also see any setting of nest_host_error(), if applicable.
 373   return (_nest_host = this);
 374 }
 375 
 376 // Dynamic nest member support: set this class's nest host to the given class.
 377 // This occurs as part of the class definition, as soon as the instanceKlass
 378 // has been created and doesn't require further resolution. The code:
 379 //    lookup().defineHiddenClass(bytes_for_X, NESTMATE);
 380 // results in:
 381 //    class_of_X.set_nest_host(lookup().lookupClass().getNestHost())
 382 // If it has an explicit _nest_host_index or _nest_members, these will be ignored.
 383 // We also know the "host" is a valid nest-host in the same package so we can
 384 // assert some of those facts.
 385 void InstanceKlass::set_nest_host(InstanceKlass* host) {
 386   assert(is_hidden(), "must be a hidden class");
 387   assert(host != nullptr, "null nest host specified");
 388   assert(_nest_host == nullptr, "current class has resolved nest-host");
 389   assert(nest_host_error() == nullptr, "unexpected nest host resolution error exists: %s",
 390          nest_host_error());
 391   assert((host->_nest_host == nullptr && host->_nest_host_index == 0) ||
 392          (host->_nest_host == host), "proposed host is not a valid nest-host");
 393   // Can't assert this as package is not set yet:
 394   // assert(is_same_class_package(host), "proposed host is in wrong package");
 395 
 396   if (log_is_enabled(Trace, class, nestmates)) {
 397     ResourceMark rm;
 398     const char* msg = "";
 399     // a hidden class does not expect a statically defined nest-host
 400     if (_nest_host_index > 0) {
 401       msg = "(the NestHost attribute in the current class is ignored)";
 402     } else if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
 403       msg = "(the NestMembers attribute in the current class is ignored)";
 404     }
 405     log_trace(class, nestmates)("Injected type %s into the nest of %s %s",
 406                                 this->external_name(),
 407                                 host->external_name(),
 408                                 msg);
 409   }
 410   // set dynamic nest host
 411   _nest_host = host;
 412   // Record dependency to keep nest host from being unloaded before this class.
 413   ClassLoaderData* this_key = class_loader_data();
 414   assert(this_key != nullptr, "sanity");
 415   this_key->record_dependency(host);
 416 }
 417 
 418 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
 419 // or we are k's nest_host - all of which is covered by comparing the two
 420 // resolved_nest_hosts.
 421 // Any exceptions (i.e. VMEs) are propagated.
 422 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
 423 
 424   assert(this != k, "this should be handled by higher-level code");
 425 
 426   // Per JVMS 5.4.4 we first resolve and validate the current class, then
 427   // the target class k.
 428 
 429   InstanceKlass* cur_host = nest_host(CHECK_false);
 430   if (cur_host == nullptr) {
 431     return false;
 432   }
 433 
 434   Klass* k_nest_host = k->nest_host(CHECK_false);
 435   if (k_nest_host == nullptr) {
 436     return false;
 437   }
 438 
 439   bool access = (cur_host == k_nest_host);
 440 
 441   ResourceMark rm(THREAD);
 442   log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 443                               this->external_name(),
 444                               access ? "" : "NOT ",
 445                               k->external_name());
 446   return access;
 447 }
 448 
 449 const char* InstanceKlass::nest_host_error() {
 450   if (_nest_host_index == 0) {
 451     return nullptr;
 452   } else {
 453     constantPoolHandle cph(Thread::current(), constants());
 454     return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
 455   }
 456 }
 457 
 458 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 459   const int size = InstanceKlass::size(parser.vtable_size(),
 460                                        parser.itable_size(),
 461                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 462                                        parser.is_interface());
 463 
 464   const Symbol* const class_name = parser.class_name();
 465   assert(class_name != nullptr, "invariant");
 466   ClassLoaderData* loader_data = parser.loader_data();
 467   assert(loader_data != nullptr, "invariant");
 468 
 469   InstanceKlass* ik;
 470 
 471   // Allocation
 472   if (parser.is_instance_ref_klass()) {
 473     // java.lang.ref.Reference
 474     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 475   } else if (class_name == vmSymbols::java_lang_Class()) {
 476     // mirror - java.lang.Class
 477     ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 478   } else if (is_stack_chunk_class(class_name, loader_data)) {
 479     // stack chunk
 480     ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
 481   } else if (is_class_loader(class_name, parser)) {
 482     // class loader - java.lang.ClassLoader
 483     ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 484   } else {
 485     // normal
 486     ik = new (loader_data, size, THREAD) InstanceKlass(parser);
 487   }
 488 
 489   assert(ik == nullptr || CompressedKlassPointers::is_encodable(ik),
 490          "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
 491 
 492   // Check for pending exception before adding to the loader data and incrementing
 493   // class count.  Can get OOM here.
 494   if (HAS_PENDING_EXCEPTION) {
 495     return nullptr;
 496   }
 497 
 498   return ik;
 499 }
 500 
 501 
 502 // copy method ordering from resource area to Metaspace
 503 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 504   if (m != nullptr) {
 505     // allocate a new array and copy contents (memcpy?)
 506     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 507     for (int i = 0; i < m->length(); i++) {
 508       _method_ordering->at_put(i, m->at(i));
 509     }
 510   } else {
 511     _method_ordering = Universe::the_empty_int_array();
 512   }
 513 }
 514 
 515 // create a new array of vtable_indices for default methods
 516 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 517   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 518   assert(default_vtable_indices() == nullptr, "only create once");
 519   set_default_vtable_indices(vtable_indices);
 520   return vtable_indices;
 521 }
 522 
 523 
 524 InstanceKlass::InstanceKlass() {
 525   assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
 526 }
 527 
 528 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) :
 529   Klass(kind),
 530   _nest_members(nullptr),
 531   _nest_host(nullptr),
 532   _permitted_subclasses(nullptr),
 533   _record_components(nullptr),
 534   _static_field_size(parser.static_field_size()),
 535   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 536   _itable_len(parser.itable_size()),
 537   _nest_host_index(0),
 538   _init_state(allocated),
 539   _reference_type(reference_type),
 540   _init_thread(nullptr)
 541 {
 542   set_vtable_length(parser.vtable_size());
 543   set_access_flags(parser.access_flags());
 544   if (parser.is_hidden()) set_is_hidden();
 545   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 546                                                     false));
 547 
 548   assert(nullptr == _methods, "underlying memory not zeroed?");
 549   assert(is_instance_klass(), "is layout incorrect?");
 550   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 551 }
 552 
 553 void InstanceKlass::set_is_cloneable() {
 554   if (name() == vmSymbols::java_lang_invoke_MemberName()) {
 555     assert(is_final(), "no subclasses allowed");
 556     // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
 557   } else if (reference_type() != REF_NONE) {
 558     // Reference cloning should not be intrinsified and always happen in JVM_Clone.
 559   } else {
 560     set_is_cloneable_fast();
 561   }
 562 }
 563 
 564 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 565                                        Array<Method*>* methods) {
 566   if (methods != nullptr && methods != Universe::the_empty_method_array() &&
 567       !methods->in_aot_cache()) {
 568     for (int i = 0; i < methods->length(); i++) {
 569       Method* method = methods->at(i);
 570       if (method == nullptr) continue;  // maybe null if error processing
 571       // Only want to delete methods that are not executing for RedefineClasses.
 572       // The previous version will point to them so they're not totally dangling
 573       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 574       MetadataFactory::free_metadata(loader_data, method);
 575     }
 576     MetadataFactory::free_array<Method*>(loader_data, methods);
 577   }
 578 }
 579 
 580 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 581                                           const InstanceKlass* super_klass,
 582                                           Array<InstanceKlass*>* local_interfaces,
 583                                           Array<InstanceKlass*>* transitive_interfaces) {
 584   // Only deallocate transitive interfaces if not empty, same as super class
 585   // or same as local interfaces.  See code in parseClassFile.
 586   Array<InstanceKlass*>* ti = transitive_interfaces;
 587   if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
 588     // check that the interfaces don't come from super class
 589     Array<InstanceKlass*>* sti = (super_klass == nullptr) ? nullptr :
 590                     super_klass->transitive_interfaces();
 591     if (ti != sti && ti != nullptr && !ti->in_aot_cache()) {
 592       MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
 593     }
 594   }
 595 
 596   // local interfaces can be empty
 597   if (local_interfaces != Universe::the_empty_instance_klass_array() &&
 598       local_interfaces != nullptr && !local_interfaces->in_aot_cache()) {
 599     MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
 600   }
 601 }
 602 
 603 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
 604                                                  Array<RecordComponent*>* record_components) {
 605   if (record_components != nullptr && !record_components->in_aot_cache()) {
 606     for (int i = 0; i < record_components->length(); i++) {
 607       RecordComponent* record_component = record_components->at(i);
 608       MetadataFactory::free_metadata(loader_data, record_component);
 609     }
 610     MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
 611   }
 612 }
 613 
 614 // This function deallocates the metadata and C heap pointers that the
 615 // InstanceKlass points to.
 616 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 617   // Orphan the mirror first, CMS thinks it's still live.
 618   if (java_mirror() != nullptr) {
 619     java_lang_Class::set_klass(java_mirror(), nullptr);
 620   }
 621 
 622   // Also remove mirror from handles
 623   loader_data->remove_handle(_java_mirror);
 624 
 625   // Need to take this class off the class loader data list.
 626   loader_data->remove_class(this);
 627 
 628   // The array_klass for this class is created later, after error handling.
 629   // For class redefinition, we keep the original class so this scratch class
 630   // doesn't have an array class.  Either way, assert that there is nothing
 631   // to deallocate.
 632   assert(array_klasses() == nullptr, "array classes shouldn't be created for this class yet");
 633 
 634   // Release C heap allocated data that this points to, which includes
 635   // reference counting symbol names.
 636   // Can't release the constant pool or MethodData C heap data here because the constant
 637   // pool can be deallocated separately from the InstanceKlass for default methods and
 638   // redefine classes.  MethodData can also be released separately.
 639   release_C_heap_structures(/* release_sub_metadata */ false);
 640 
 641   deallocate_methods(loader_data, methods());
 642   set_methods(nullptr);
 643 
 644   deallocate_record_components(loader_data, record_components());
 645   set_record_components(nullptr);
 646 
 647   if (method_ordering() != nullptr &&
 648       method_ordering() != Universe::the_empty_int_array() &&
 649       !method_ordering()->in_aot_cache()) {
 650     MetadataFactory::free_array<int>(loader_data, method_ordering());
 651   }
 652   set_method_ordering(nullptr);
 653 
 654   // default methods can be empty
 655   if (default_methods() != nullptr &&
 656       default_methods() != Universe::the_empty_method_array() &&
 657       !default_methods()->in_aot_cache()) {
 658     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 659   }
 660   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 661   set_default_methods(nullptr);
 662 
 663   // default methods vtable indices can be empty
 664   if (default_vtable_indices() != nullptr &&
 665       !default_vtable_indices()->in_aot_cache()) {
 666     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 667   }
 668   set_default_vtable_indices(nullptr);
 669 
 670 
 671   // This array is in Klass, but remove it with the InstanceKlass since
 672   // this place would be the only caller and it can share memory with transitive
 673   // interfaces.
 674   if (secondary_supers() != nullptr &&
 675       secondary_supers() != Universe::the_empty_klass_array() &&
 676       // see comments in compute_secondary_supers about the following cast
 677       (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
 678       !secondary_supers()->in_aot_cache()) {
 679     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 680   }
 681   set_secondary_supers(nullptr, SECONDARY_SUPERS_BITMAP_EMPTY);
 682 
 683   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 684   set_transitive_interfaces(nullptr);
 685   set_local_interfaces(nullptr);
 686 
 687   if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
 688     MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
 689   }
 690   set_fieldinfo_stream(nullptr);
 691 
 692   if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
 693     MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
 694   }
 695   set_fieldinfo_search_table(nullptr);
 696 
 697   if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
 698     MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
 699   }
 700   set_fields_status(nullptr);
 701 
 702   // If a method from a redefined class is using this constant pool, don't
 703   // delete it, yet.  The new class's previous version will point to this.
 704   if (constants() != nullptr) {
 705     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 706     if (!constants()->in_aot_cache()) {
 707       HeapShared::remove_scratch_resolved_references(constants());
 708       MetadataFactory::free_metadata(loader_data, constants());
 709     }
 710     // Delete any cached resolution errors for the constant pool
 711     SystemDictionary::delete_resolution_error(constants());
 712 
 713     set_constants(nullptr);
 714   }
 715 
 716   if (inner_classes() != nullptr &&
 717       inner_classes() != Universe::the_empty_short_array() &&
 718       !inner_classes()->in_aot_cache()) {
 719     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 720   }
 721   set_inner_classes(nullptr);
 722 
 723   if (nest_members() != nullptr &&
 724       nest_members() != Universe::the_empty_short_array() &&
 725       !nest_members()->in_aot_cache()) {
 726     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 727   }
 728   set_nest_members(nullptr);
 729 
 730   if (permitted_subclasses() != nullptr &&
 731       permitted_subclasses() != Universe::the_empty_short_array() &&
 732       !permitted_subclasses()->in_aot_cache()) {
 733     MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
 734   }
 735   set_permitted_subclasses(nullptr);
 736 
 737   // We should deallocate the Annotations instance if it's not in shared spaces.
 738   if (annotations() != nullptr && !annotations()->in_aot_cache()) {
 739     MetadataFactory::free_metadata(loader_data, annotations());
 740   }
 741   set_annotations(nullptr);
 742 
 743   SystemDictionaryShared::handle_class_unloading(this);
 744 
 745 #if INCLUDE_CDS_JAVA_HEAP
 746   if (CDSConfig::is_dumping_heap()) {
 747     HeapShared::remove_scratch_objects(this);
 748   }
 749 #endif
 750 }
 751 
 752 bool InstanceKlass::is_record() const {
 753   return _record_components != nullptr &&
 754          is_final() &&
 755          super() == vmClasses::Record_klass();
 756 }
 757 
 758 bool InstanceKlass::is_sealed() const {
 759   return _permitted_subclasses != nullptr &&
 760          _permitted_subclasses != Universe::the_empty_short_array();
 761 }
 762 
 763 // JLS 8.9: An enum class is either implicitly final and derives
 764 // from java.lang.Enum, or else is implicitly sealed to its
 765 // anonymous subclasses. This query detects both kinds.
 766 // It does not validate the finality or
 767 // sealing conditions: it merely checks for a super of Enum.
 768 // This is sufficient for recognizing well-formed enums.
 769 bool InstanceKlass::is_enum_subclass() const {
 770   InstanceKlass* s = super();
 771   return (s == vmClasses::Enum_klass() ||
 772           (s != nullptr && s->super() == vmClasses::Enum_klass()));
 773 }
 774 
 775 bool InstanceKlass::should_be_initialized() const {
 776   return !is_initialized();
 777 }
 778 
 779 klassItable InstanceKlass::itable() const {
 780   return klassItable(const_cast<InstanceKlass*>(this));
 781 }
 782 
 783 // JVMTI spec thinks there are signers and protection domain in the
 784 // instanceKlass.  These accessors pretend these fields are there.
 785 // The hprof specification also thinks these fields are in InstanceKlass.
 786 oop InstanceKlass::protection_domain() const {
 787   // return the protection_domain from the mirror
 788   return java_lang_Class::protection_domain(java_mirror());
 789 }
 790 
 791 objArrayOop InstanceKlass::signers() const {
 792   // return the signers from the mirror
 793   return java_lang_Class::signers(java_mirror());
 794 }
 795 
 796 oop InstanceKlass::init_lock() const {
 797   // return the init lock from the mirror
 798   oop lock = java_lang_Class::init_lock(java_mirror());
 799   // Prevent reordering with any access of initialization state
 800   OrderAccess::loadload();
 801   assert(lock != nullptr || !is_not_initialized(), // initialized or in_error state
 802          "only fully initialized state can have a null lock");
 803   return lock;
 804 }
 805 
 806 // Set the initialization lock to null so the object can be GC'ed. Any racing
 807 // threads to get this lock will see a null lock and will not lock.
 808 // That's okay because they all check for initialized state after getting
 809 // the lock and return. For preempted vthreads we keep the oop protected
 810 // in the ObjectMonitor (see ObjectMonitor::set_object_strong()).
 811 void InstanceKlass::fence_and_clear_init_lock() {
 812   // make sure previous stores are all done, notably the init_state.
 813   OrderAccess::storestore();
 814   java_lang_Class::clear_init_lock(java_mirror());
 815   assert(!is_not_initialized(), "class must be initialized now");
 816 }
 817 
 818 class PreemptableInitCall {
 819   JavaThread* _thread;
 820   bool _previous;
 821   DEBUG_ONLY(InstanceKlass* _previous_klass;)
 822  public:
 823   PreemptableInitCall(JavaThread* thread, InstanceKlass* ik) : _thread(nullptr) {
 824     if (thread->is_vthread_mounted()) {
 825       _thread = thread;
 826       _previous = _thread->at_preemptable_init();
 827       _thread->set_at_preemptable_init(true);
 828       DEBUG_ONLY(_previous_klass = _thread->preempt_init_klass();)
 829       DEBUG_ONLY(_thread->set_preempt_init_klass(ik));
 830     }
 831   }
 832   ~PreemptableInitCall() {
 833     if (_thread != nullptr) {
 834       _thread->set_at_preemptable_init(_previous);
 835       DEBUG_ONLY(_thread->set_preempt_init_klass(_previous_klass));
 836     }
 837   }
 838 };
 839 
 840 void InstanceKlass::initialize_preemptable(TRAPS) {
 841   if (this->should_be_initialized()) {
 842     PreemptableInitCall pic(THREAD, this);
 843     initialize_impl(THREAD);
 844   } else {
 845     assert(is_initialized(), "sanity check");
 846   }
 847 }
 848 
 849 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 850 // process. The step comments refers to the procedure described in that section.
 851 // Note: implementation moved to static method to expose the this pointer.
 852 void InstanceKlass::initialize(TRAPS) {
 853   if (this->should_be_initialized()) {
 854     initialize_impl(CHECK);
 855     // Note: at this point the class may be initialized
 856     //       OR it may be in the state of being initialized
 857     //       in case of recursive initialization!
 858   } else {
 859     assert(is_initialized(), "sanity check");
 860   }
 861 }
 862 
 863 #ifdef ASSERT
 864 void InstanceKlass::assert_no_clinit_will_run_for_aot_initialized_class() const {
 865   assert(has_aot_initialized_mirror(), "must be");
 866 
 867   InstanceKlass* s = super();
 868   if (s != nullptr) {
 869     DEBUG_ONLY(ResourceMark rm);
 870     assert(s->is_initialized(), "super class %s of aot-inited class %s must have been initialized",
 871            s->external_name(), external_name());
 872     s->assert_no_clinit_will_run_for_aot_initialized_class();
 873   }
 874 
 875   Array<InstanceKlass*>* interfaces = local_interfaces();
 876   int len = interfaces->length();
 877   for (int i = 0; i < len; i++) {
 878     InstanceKlass* intf = interfaces->at(i);
 879     if (!intf->is_initialized()) {
 880       ResourceMark rm;
 881       // Note: an interface needs to be marked as is_initialized() only if
 882       // - it has a <clinit>
 883       // - it has declared a default method.
 884       assert(!intf->interface_needs_clinit_execution_as_super(/*also_check_supers*/false),
 885              "uninitialized super interface %s of aot-inited class %s must not have <clinit>",
 886              intf->external_name(), external_name());
 887     }
 888   }
 889 }
 890 #endif
 891 
 892 #if INCLUDE_CDS
 893 // early_init -- we are moving this class into the fully_initialized state before the
 894 // JVM is able to execute any bytecodes. See AOTLinkedClassBulkLoader::is_initializing_classes_early().
 895 void InstanceKlass::initialize_with_aot_initialized_mirror(bool early_init, TRAPS) {
 896   assert(has_aot_initialized_mirror(), "must be");
 897   assert(CDSConfig::is_loading_heap(), "must be");
 898   assert(CDSConfig::is_using_aot_linked_classes(), "must be");
 899   assert_no_clinit_will_run_for_aot_initialized_class();
 900 
 901   if (is_initialized()) {
 902     return;
 903   }
 904 
 905   if (log_is_enabled(Info, aot, init)) {
 906     ResourceMark rm;
 907     log_info(aot, init)("%s (aot-inited%s)", external_name(), early_init ? ", early" : "");
 908   }
 909 
 910   if (is_runtime_setup_required()) {
 911     assert(!early_init, "must not call");
 912     // Need to take the slow path, which will call the runtimeSetup() function instead
 913     // of <clinit>
 914     initialize(CHECK);
 915     return;
 916   }
 917 
 918   LogTarget(Info, class, init) lt;
 919   if (lt.is_enabled()) {
 920     ResourceMark rm(THREAD);
 921     LogStream ls(lt);
 922     ls.print("%d Initializing ", call_class_initializer_counter++);
 923     name()->print_value_on(&ls);
 924     ls.print_cr("(aot-inited) (" PTR_FORMAT ") by thread \"%s\"",
 925                 p2i(this), THREAD->name());
 926   }
 927 
 928   if (early_init) {
 929     precond(AOTLinkedClassBulkLoader::is_initializing_classes_early());
 930     precond(is_linked());
 931     precond(init_thread() == nullptr);
 932     set_init_state(fully_initialized);
 933     fence_and_clear_init_lock();
 934     return;
 935   }
 936 
 937   link_class(CHECK);
 938 
 939 #ifdef ASSERT
 940   {
 941     Handle h_init_lock(THREAD, init_lock());
 942     ObjectLocker ol(h_init_lock, THREAD);
 943     assert(!is_initialized(), "sanity");
 944     assert(!is_being_initialized(), "sanity");
 945     assert(!is_in_error_state(), "sanity");
 946   }
 947 #endif
 948 
 949   set_init_thread(THREAD);
 950   set_initialization_state_and_notify(fully_initialized, CHECK);
 951 }
 952 #endif
 953 
 954 bool InstanceKlass::verify_code(TRAPS) {
 955   // 1) Verify the bytecodes
 956   return Verifier::verify(this, should_verify_class(), THREAD);
 957 }
 958 
 959 void InstanceKlass::link_class(TRAPS) {
 960   assert(is_loaded(), "must be loaded");
 961   if (!is_linked()) {
 962     link_class_impl(CHECK);
 963   }
 964 }
 965 
 966 // Called to verify that a class can link during initialization, without
 967 // throwing a VerifyError.
 968 bool InstanceKlass::link_class_or_fail(TRAPS) {
 969   assert(is_loaded(), "must be loaded");
 970   if (!is_linked()) {
 971     link_class_impl(CHECK_false);
 972   }
 973   return is_linked();
 974 }
 975 
 976 bool InstanceKlass::link_class_impl(TRAPS) {
 977   if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
 978     // This is for CDS static dump only -- we use the in_error_state to indicate that
 979     // the class has failed verification. Throwing the NoClassDefFoundError here is just
 980     // a convenient way to stop repeat attempts to verify the same (bad) class.
 981     //
 982     // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
 983     // if we are executing Java code. This is not a problem for CDS dumping phase since
 984     // it doesn't execute any Java code.
 985     ResourceMark rm(THREAD);
 986     // Names are all known to be < 64k so we know this formatted message is not excessively large.
 987     Exceptions::fthrow(THREAD_AND_LOCATION,
 988                        vmSymbols::java_lang_NoClassDefFoundError(),
 989                        "Class %s, or one of its supertypes, failed class initialization",
 990                        external_name());
 991     return false;
 992   }
 993   // return if already verified
 994   if (is_linked()) {
 995     return true;
 996   }
 997 
 998   // Timing
 999   // timer handles recursion
1000   JavaThread* jt = THREAD;
1001 
1002   // link super class before linking this class
1003   InstanceKlass* super_klass = super();
1004   if (super_klass != nullptr) {
1005     if (super_klass->is_interface()) {  // check if super class is an interface
1006       ResourceMark rm(THREAD);
1007       // Names are all known to be < 64k so we know this formatted message is not excessively large.
1008       Exceptions::fthrow(
1009         THREAD_AND_LOCATION,
1010         vmSymbols::java_lang_IncompatibleClassChangeError(),
1011         "class %s has interface %s as super class",
1012         external_name(),
1013         super_klass->external_name()
1014       );
1015       return false;
1016     }
1017 
1018     super_klass->link_class_impl(CHECK_false);
1019   }
1020 
1021   // link all interfaces implemented by this class before linking this class
1022   Array<InstanceKlass*>* interfaces = local_interfaces();
1023   int num_interfaces = interfaces->length();
1024   for (int index = 0; index < num_interfaces; index++) {
1025     InstanceKlass* interk = interfaces->at(index);
1026     interk->link_class_impl(CHECK_false);
1027   }
1028 
1029   // in case the class is linked in the process of linking its superclasses
1030   if (is_linked()) {
1031     return true;
1032   }
1033 
1034   // trace only the link time for this klass that includes
1035   // the verification time
1036   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1037                              ClassLoader::perf_class_link_selftime(),
1038                              ClassLoader::perf_classes_linked(),
1039                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1040                              jt->get_thread_stat()->perf_timers_addr(),
1041                              PerfClassTraceTime::CLASS_LINK);
1042 
1043   // verification & rewriting
1044   {
1045     HandleMark hm(THREAD);
1046     Handle h_init_lock(THREAD, init_lock());
1047     ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1048     // Don't allow preemption if we link/initialize classes below,
1049     // since that would release this monitor while we are in the
1050     // middle of linking this class.
1051     NoPreemptMark npm(THREAD);
1052 
1053     // rewritten will have been set if loader constraint error found
1054     // on an earlier link attempt
1055     // don't verify or rewrite if already rewritten
1056     //
1057 
1058     if (!is_linked()) {
1059       if (!is_rewritten()) {
1060         if (in_aot_cache()) {
1061           assert(!verified_at_dump_time(), "must be");
1062         }
1063         {
1064           bool verify_ok = verify_code(THREAD);
1065           if (!verify_ok) {
1066             return false;
1067           }
1068         }
1069 
1070         // Just in case a side-effect of verify linked this class already
1071         // (which can sometimes happen since the verifier loads classes
1072         // using custom class loaders, which are free to initialize things)
1073         if (is_linked()) {
1074           return true;
1075         }
1076 
1077         // also sets rewritten
1078         rewrite_class(CHECK_false);
1079       } else if (in_aot_cache()) {
1080         SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
1081       }
1082 
1083       // relocate jsrs and link methods after they are all rewritten
1084       link_methods(CHECK_false);
1085 
1086       // Initialize the vtable and interface table after
1087       // methods have been rewritten since rewrite may
1088       // fabricate new Method*s.
1089       // also does loader constraint checking
1090       //
1091       // initialize_vtable and initialize_itable need to be rerun
1092       // for a shared class if
1093       // 1) the class is loaded by custom class loader or
1094       // 2) the class is loaded by built-in class loader but failed to add archived loader constraints or
1095       // 3) the class was not verified during dump time
1096       bool need_init_table = true;
1097       if (in_aot_cache() && verified_at_dump_time() &&
1098           SystemDictionaryShared::check_linking_constraints(THREAD, this)) {
1099         need_init_table = false;
1100       }
1101       if (need_init_table) {
1102         vtable().initialize_vtable_and_check_constraints(CHECK_false);
1103         itable().initialize_itable_and_check_constraints(CHECK_false);
1104       }
1105 #ifdef ASSERT
1106       vtable().verify(tty, true);
1107       // In case itable verification is ever added.
1108       // itable().verify(tty, true);
1109 #endif
1110       if (Universe::is_fully_initialized()) {
1111         DeoptimizationScope deopt_scope;
1112         {
1113           // Now mark all code that assumes the class is not linked.
1114           // Set state under the Compile_lock also.
1115           MutexLocker ml(THREAD, Compile_lock);
1116 
1117           set_init_state(linked);
1118           CodeCache::mark_dependents_on(&deopt_scope, this);
1119         }
1120         // Perform the deopt handshake outside Compile_lock.
1121         deopt_scope.deoptimize_marked();
1122       } else {
1123         set_init_state(linked);
1124       }
1125       if (JvmtiExport::should_post_class_prepare()) {
1126         JvmtiExport::post_class_prepare(THREAD, this);
1127       }
1128     }
1129   }
1130 
1131   if (log_is_enabled(Info, class, link))  {
1132     ResourceMark rm(THREAD);
1133     log_info(class, link)("Linked class %s", external_name());
1134   }
1135 
1136   return true;
1137 }
1138 
1139 // Rewrite the byte codes of all of the methods of a class.
1140 // The rewriter must be called exactly once. Rewriting must happen after
1141 // verification but before the first method of the class is executed.
1142 void InstanceKlass::rewrite_class(TRAPS) {
1143   assert(is_loaded(), "must be loaded");
1144   if (is_rewritten()) {
1145     assert(in_aot_cache(), "rewriting an unshared class?");
1146     return;
1147   }
1148   Rewriter::rewrite(this, CHECK);
1149   set_rewritten();
1150 }
1151 
1152 // Now relocate and link method entry points after class is rewritten.
1153 // This is outside is_rewritten flag. In case of an exception, it can be
1154 // executed more than once.
1155 void InstanceKlass::link_methods(TRAPS) {
1156   PerfTraceTime timer(ClassLoader::perf_ik_link_methods_time());
1157 
1158   int len = methods()->length();
1159   for (int i = len-1; i >= 0; i--) {
1160     methodHandle m(THREAD, methods()->at(i));
1161 
1162     // Set up method entry points for compiler and interpreter    .
1163     m->link_method(m, CHECK);
1164   }
1165 }
1166 
1167 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1168 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1169   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1170   for (int i = 0; i < local_interfaces()->length(); ++i) {
1171     InstanceKlass* ik = local_interfaces()->at(i);
1172 
1173     // Initialization is depth first search ie. we start with top of the inheritance tree
1174     // has_nonstatic_concrete_methods drives searching superinterfaces since it
1175     // means has_nonstatic_concrete_methods in its superinterface hierarchy
1176     if (ik->has_nonstatic_concrete_methods()) {
1177       ik->initialize_super_interfaces(CHECK);
1178     }
1179 
1180     // Only initialize() interfaces that "declare" concrete methods.
1181     if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
1182       ik->initialize(CHECK);
1183     }
1184   }
1185 }
1186 
1187 using InitializationErrorTable = HashTable<const InstanceKlass*, OopHandle, 107, AnyObj::C_HEAP, mtClass>;
1188 static InitializationErrorTable* _initialization_error_table;
1189 
1190 void InstanceKlass::add_initialization_error(JavaThread* current, Handle exception) {
1191   // Create the same exception with a message indicating the thread name,
1192   // and the StackTraceElements.
1193   Handle init_error = java_lang_Throwable::create_initialization_error(current, exception);
1194   ResourceMark rm(current);
1195   if (init_error.is_null()) {
1196     log_trace(class, init)("Unable to create the desired initialization error for class %s", external_name());
1197 
1198     // We failed to create the new exception, most likely due to either out-of-memory or
1199     // a stackoverflow error. If the original exception was either of those then we save
1200     // the shared, pre-allocated, stackless, instance of that exception.
1201     if (exception->klass() == vmClasses::StackOverflowError_klass()) {
1202       log_debug(class, init)("Using shared StackOverflowError as initialization error for class %s", external_name());
1203       init_error = Handle(current, Universe::class_init_stack_overflow_error());
1204     } else if (exception->klass() == vmClasses::OutOfMemoryError_klass()) {
1205       log_debug(class, init)("Using shared OutOfMemoryError as initialization error for class %s", external_name());
1206       init_error = Handle(current, Universe::class_init_out_of_memory_error());
1207     } else {
1208       return;
1209     }
1210   }
1211 
1212   MutexLocker ml(current, ClassInitError_lock);
1213   OopHandle elem = OopHandle(Universe::vm_global(), init_error());
1214   bool created;
1215   if (_initialization_error_table == nullptr) {
1216     _initialization_error_table = new (mtClass) InitializationErrorTable();
1217   }
1218   _initialization_error_table->put_if_absent(this, elem, &created);
1219   assert(created, "Initialization is single threaded");
1220   log_trace(class, init)("Initialization error added for class %s", external_name());
1221 }
1222 
1223 oop InstanceKlass::get_initialization_error(JavaThread* current) {
1224   MutexLocker ml(current, ClassInitError_lock);
1225   if (_initialization_error_table == nullptr) {
1226     return nullptr;
1227   }
1228   OopHandle* h = _initialization_error_table->get(this);
1229   return (h != nullptr) ? h->resolve() : nullptr;
1230 }
1231 
1232 // Need to remove entries for unloaded classes.
1233 void InstanceKlass::clean_initialization_error_table() {
1234   struct InitErrorTableCleaner {
1235     bool do_entry(const InstanceKlass* ik, OopHandle h) {
1236       if (!ik->is_loader_alive()) {
1237         h.release(Universe::vm_global());
1238         return true;
1239       } else {
1240         return false;
1241       }
1242     }
1243   };
1244 
1245   assert_locked_or_safepoint(ClassInitError_lock);
1246   InitErrorTableCleaner cleaner;
1247   if (_initialization_error_table != nullptr) {
1248     _initialization_error_table->unlink(&cleaner);
1249   }
1250 }
1251 
1252 class ThreadWaitingForClassInit : public StackObj {
1253   JavaThread* _thread;
1254  public:
1255   ThreadWaitingForClassInit(JavaThread* thread, InstanceKlass* ik) : _thread(thread) {
1256     _thread->set_class_to_be_initialized(ik);
1257   }
1258   ~ThreadWaitingForClassInit() {
1259     _thread->set_class_to_be_initialized(nullptr);
1260   }
1261 };
1262 
1263 void InstanceKlass::initialize_impl(TRAPS) {
1264   HandleMark hm(THREAD);
1265 
1266   // Make sure klass is linked (verified) before initialization
1267   // A class could already be verified, since it has been reflected upon.
1268   link_class(CHECK);
1269 
1270   DTRACE_CLASSINIT_PROBE(required, -1);
1271 
1272   bool wait = false;
1273 
1274   JavaThread* jt = THREAD;
1275 
1276   bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1277 
1278   // refer to the JVM book page 47 for description of steps
1279   // Step 1
1280   {
1281     Handle h_init_lock(THREAD, init_lock());
1282     ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE);
1283 
1284     // Step 2
1285     // If we were to use wait() instead of waitInterruptibly() then
1286     // we might end up throwing IE from link/symbol resolution sites
1287     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
1288     while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1289       if (debug_logging_enabled) {
1290         ResourceMark rm(jt);
1291         log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1292                                jt->name(), external_name(), init_thread_name());
1293       }
1294       wait = true;
1295       ThreadWaitingForClassInit twcl(THREAD, this);
1296       ol.wait_uninterruptibly(CHECK_PREEMPTABLE);
1297     }
1298 
1299     // Step 3
1300     if (is_being_initialized() && is_reentrant_initialization(jt)) {
1301       if (debug_logging_enabled) {
1302         ResourceMark rm(jt);
1303         log_debug(class, init)("Thread \"%s\" recursively initializing %s",
1304                                jt->name(), external_name());
1305       }
1306       DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
1307       return;
1308     }
1309 
1310     // Step 4
1311     if (is_initialized()) {
1312       if (debug_logging_enabled) {
1313         ResourceMark rm(jt);
1314         log_debug(class, init)("Thread \"%s\" found %s already initialized",
1315                                jt->name(), external_name());
1316       }
1317       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
1318       return;
1319     }
1320 
1321     // Step 5
1322     if (is_in_error_state()) {
1323       if (debug_logging_enabled) {
1324         ResourceMark rm(jt);
1325         log_debug(class, init)("Thread \"%s\" found %s is in error state",
1326                                jt->name(), external_name());
1327       }
1328 
1329       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1330       ResourceMark rm(THREAD);
1331       Handle cause(THREAD, get_initialization_error(THREAD));
1332 
1333       stringStream ss;
1334       ss.print("Could not initialize class %s", external_name());
1335       if (cause.is_null()) {
1336         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1337       } else {
1338         THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1339                         ss.as_string(), cause);
1340       }
1341     } else {
1342 
1343       // Step 6
1344       set_init_state(being_initialized);
1345       set_init_thread(jt);
1346       if (debug_logging_enabled) {
1347         ResourceMark rm(jt);
1348         log_debug(class, init)("Thread \"%s\" is initializing %s",
1349                                jt->name(), external_name());
1350       }
1351     }
1352   }
1353 
1354   // Block preemption once we are the initializer thread. Unmounting now
1355   // would complicate the reentrant case (identity is platform thread).
1356   NoPreemptMark npm(THREAD);
1357 
1358   // Step 7
1359   // Next, if C is a class rather than an interface, initialize it's super class and super
1360   // interfaces.
1361   if (!is_interface()) {
1362     Klass* super_klass = super();
1363     if (super_klass != nullptr && super_klass->should_be_initialized()) {
1364       super_klass->initialize(THREAD);
1365     }
1366     // If C implements any interface that declares a non-static, concrete method,
1367     // the initialization of C triggers initialization of its super interfaces.
1368     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1369     // having a superinterface that declares, non-static, concrete methods
1370     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1371       initialize_super_interfaces(THREAD);
1372     }
1373 
1374     // If any exceptions, complete abruptly, throwing the same exception as above.
1375     if (HAS_PENDING_EXCEPTION) {
1376       Handle e(THREAD, PENDING_EXCEPTION);
1377       CLEAR_PENDING_EXCEPTION;
1378       {
1379         EXCEPTION_MARK;
1380         add_initialization_error(THREAD, e);
1381         // Locks object, set state, and notify all waiting threads
1382         set_initialization_state_and_notify(initialization_error, THREAD);
1383         CLEAR_PENDING_EXCEPTION;
1384       }
1385       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1386       THROW_OOP(e());
1387     }
1388   }
1389 
1390 
1391   // Step 8
1392   {
1393     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1394     if (class_initializer() != nullptr) {
1395       // Timer includes any side effects of class initialization (resolution,
1396       // etc), but not recursive entry into call_class_initializer().
1397       PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1398                                ClassLoader::perf_class_init_selftime(),
1399                                ClassLoader::perf_classes_inited(),
1400                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1401                                jt->get_thread_stat()->perf_timers_addr(),
1402                                PerfClassTraceTime::CLASS_CLINIT);
1403       call_class_initializer(THREAD);
1404     } else {
1405       // The elapsed time is so small it's not worth counting.
1406       if (UsePerfData) {
1407         ClassLoader::perf_classes_inited()->inc();
1408       }
1409       call_class_initializer(THREAD);
1410     }
1411   }
1412 
1413   // Step 9
1414   if (!HAS_PENDING_EXCEPTION) {
1415     set_initialization_state_and_notify(fully_initialized, CHECK);
1416     DEBUG_ONLY(vtable().verify(tty, true);)
1417     CompilationPolicy::replay_training_at_init(this, THREAD);
1418   }
1419   else {
1420     // Step 10 and 11
1421     Handle e(THREAD, PENDING_EXCEPTION);
1422     CLEAR_PENDING_EXCEPTION;
1423     // JVMTI has already reported the pending exception
1424     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1425     JvmtiExport::clear_detected_exception(jt);
1426     {
1427       EXCEPTION_MARK;
1428       add_initialization_error(THREAD, e);
1429       set_initialization_state_and_notify(initialization_error, THREAD);
1430       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1431       // JVMTI has already reported the pending exception
1432       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1433       JvmtiExport::clear_detected_exception(jt);
1434     }
1435     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1436     if (e->is_a(vmClasses::Error_klass())) {
1437       THROW_OOP(e());
1438     } else {
1439       JavaCallArguments args(e);
1440       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1441                 vmSymbols::throwable_void_signature(),
1442                 &args);
1443     }
1444   }
1445   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1446 }
1447 
1448 
1449 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1450   Handle h_init_lock(THREAD, init_lock());
1451   if (h_init_lock() != nullptr) {
1452     ObjectLocker ol(h_init_lock, THREAD);
1453     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1454     set_init_state(state);
1455     fence_and_clear_init_lock();
1456     ol.notify_all(CHECK);
1457   } else {
1458     assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1459     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1460     set_init_state(state);
1461   }
1462 }
1463 
1464 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1465 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1466 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1467   assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1468 
1469   DeoptimizationScope deopt_scope;
1470   {
1471     MutexLocker ml(current, Compile_lock);
1472 
1473     set_init_state(InstanceKlass::loaded);
1474     // make sure init_state store is already done.
1475     // The compiler reads the hierarchy outside of the Compile_lock.
1476     // Access ordering is used to add to hierarchy.
1477 
1478     // Link into hierarchy.
1479     append_to_sibling_list();                    // add to superklass/sibling list
1480     process_interfaces();                        // handle all "implements" declarations
1481 
1482     // Now mark all code that depended on old class hierarchy.
1483     // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1484     if (Universe::is_fully_initialized()) {
1485       CodeCache::mark_dependents_on(&deopt_scope, this);
1486     }
1487   }
1488   // Perform the deopt handshake outside Compile_lock.
1489   deopt_scope.deoptimize_marked();
1490 }
1491 
1492 
1493 InstanceKlass* InstanceKlass::implementor() const {
1494   InstanceKlass* volatile* ik = adr_implementor();
1495   if (ik == nullptr) {
1496     return nullptr;
1497   } else {
1498     // This load races with inserts, and therefore needs acquire.
1499     InstanceKlass* ikls = AtomicAccess::load_acquire(ik);
1500     if (ikls != nullptr && !ikls->is_loader_alive()) {
1501       return nullptr;  // don't return unloaded class
1502     } else {
1503       return ikls;
1504     }
1505   }
1506 }
1507 
1508 
1509 void InstanceKlass::set_implementor(InstanceKlass* ik) {
1510   assert_locked_or_safepoint(Compile_lock);
1511   assert(is_interface(), "not interface");
1512   InstanceKlass* volatile* addr = adr_implementor();
1513   assert(addr != nullptr, "null addr");
1514   if (addr != nullptr) {
1515     AtomicAccess::release_store(addr, ik);
1516   }
1517 }
1518 
1519 int  InstanceKlass::nof_implementors() const {
1520   InstanceKlass* ik = implementor();
1521   if (ik == nullptr) {
1522     return 0;
1523   } else if (ik != this) {
1524     return 1;
1525   } else {
1526     return 2;
1527   }
1528 }
1529 
1530 // The embedded _implementor field can only record one implementor.
1531 // When there are more than one implementors, the _implementor field
1532 // is set to the interface Klass* itself. Following are the possible
1533 // values for the _implementor field:
1534 //   null                  - no implementor
1535 //   implementor Klass*    - one implementor
1536 //   self                  - more than one implementor
1537 //
1538 // The _implementor field only exists for interfaces.
1539 void InstanceKlass::add_implementor(InstanceKlass* ik) {
1540   if (Universe::is_fully_initialized()) {
1541     assert_lock_strong(Compile_lock);
1542   }
1543   assert(is_interface(), "not interface");
1544   // Filter out my subinterfaces.
1545   // (Note: Interfaces are never on the subklass list.)
1546   if (ik->is_interface()) return;
1547 
1548   // Filter out subclasses whose supers already implement me.
1549   // (Note: CHA must walk subclasses of direct implementors
1550   // in order to locate indirect implementors.)
1551   InstanceKlass* super_ik = ik->super();
1552   if (super_ik != nullptr && super_ik->implements_interface(this))
1553     // We only need to check one immediate superclass, since the
1554     // implements_interface query looks at transitive_interfaces.
1555     // Any supers of the super have the same (or fewer) transitive_interfaces.
1556     return;
1557 
1558   InstanceKlass* iklass = implementor();
1559   if (iklass == nullptr) {
1560     set_implementor(ik);
1561   } else if (iklass != this && iklass != ik) {
1562     // There is already an implementor. Use itself as an indicator of
1563     // more than one implementors.
1564     set_implementor(this);
1565   }
1566 
1567   // The implementor also implements the transitive_interfaces
1568   for (int index = 0; index < local_interfaces()->length(); index++) {
1569     local_interfaces()->at(index)->add_implementor(ik);
1570   }
1571 }
1572 
1573 void InstanceKlass::init_implementor() {
1574   if (is_interface()) {
1575     set_implementor(nullptr);
1576   }
1577 }
1578 
1579 
1580 void InstanceKlass::process_interfaces() {
1581   // link this class into the implementors list of every interface it implements
1582   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1583     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1584     InstanceKlass* interf = local_interfaces()->at(i);
1585     assert(interf->is_interface(), "expected interface");
1586     interf->add_implementor(this);
1587   }
1588 }
1589 
1590 bool InstanceKlass::can_be_primary_super_slow() const {
1591   if (is_interface())
1592     return false;
1593   else
1594     return Klass::can_be_primary_super_slow();
1595 }
1596 
1597 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1598                                                                Array<InstanceKlass*>* transitive_interfaces) {
1599   // The secondaries are the implemented interfaces.
1600   // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1601   // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1602   Array<Klass*>* interfaces = (Array<Klass*>*)(address)transitive_interfaces;
1603   int num_secondaries = num_extra_slots + interfaces->length();
1604   if (num_secondaries == 0) {
1605     // Must share this for correct bootstrapping!
1606     set_secondary_supers(Universe::the_empty_klass_array(), Universe::the_empty_klass_bitmap());
1607     return nullptr;
1608   } else if (num_extra_slots == 0 && interfaces->length() <= 1) {
1609     // We will reuse the transitive interfaces list if we're certain
1610     // it's in hash order.
1611     uintx bitmap = compute_secondary_supers_bitmap(interfaces);
1612     set_secondary_supers(interfaces, bitmap);
1613     return nullptr;
1614   }
1615   // Copy transitive interfaces to a temporary growable array to be constructed
1616   // into the secondary super list with extra slots.
1617   GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1618   for (int i = 0; i < interfaces->length(); i++) {
1619     secondaries->push(interfaces->at(i));
1620   }
1621   return secondaries;
1622 }
1623 
1624 bool InstanceKlass::implements_interface(Klass* k) const {
1625   if (this == k) return true;
1626   assert(k->is_interface(), "should be an interface class");
1627   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1628     if (transitive_interfaces()->at(i) == k) {
1629       return true;
1630     }
1631   }
1632   return false;
1633 }
1634 
1635 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1636   // Verify direct super interface
1637   if (this == k) return true;
1638   assert(k->is_interface(), "should be an interface class");
1639   for (int i = 0; i < local_interfaces()->length(); i++) {
1640     if (local_interfaces()->at(i) == k) {
1641       return true;
1642     }
1643   }
1644   return false;
1645 }
1646 
1647 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1648   if (TraceFinalizerRegistration) {
1649     tty->print("Registered ");
1650     i->print_value_on(tty);
1651     tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1652   }
1653   instanceHandle h_i(THREAD, i);
1654   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1655   JavaValue result(T_VOID);
1656   JavaCallArguments args(h_i);
1657   methodHandle mh(THREAD, Universe::finalizer_register_method());
1658   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1659   MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1660   return h_i();
1661 }
1662 
1663 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1664   assert(!is_abstract() && !is_interface(), "Should not create this object");
1665   size_t size = size_helper();  // Query before forming handle.
1666   return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1667 }
1668 
1669 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {
1670   Klass* k = java_lang_Class::as_Klass(java_class);
1671   if (k == nullptr) {
1672     ResourceMark rm(THREAD);
1673     THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1674   }
1675   InstanceKlass* ik = cast(k);
1676   ik->check_valid_for_instantiation(false, CHECK_NULL);
1677   ik->initialize(CHECK_NULL);
1678   return ik->allocate_instance(THREAD);
1679 }
1680 
1681 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1682   return instanceHandle(THREAD, allocate_instance(THREAD));
1683 }
1684 
1685 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1686   if (is_interface() || is_abstract()) {
1687     ResourceMark rm(THREAD);
1688     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1689               : vmSymbols::java_lang_InstantiationException(), external_name());
1690   }
1691   if (this == vmClasses::Class_klass()) {
1692     ResourceMark rm(THREAD);
1693     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1694               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1695   }
1696 }
1697 
1698 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1699   // Need load-acquire for lock-free read
1700   if (array_klasses_acquire() == nullptr) {
1701 
1702     // Recursively lock array allocation
1703     RecursiveLocker rl(MultiArray_lock, THREAD);
1704 
1705     // Check if another thread created the array klass while we were waiting for the lock.
1706     if (array_klasses() == nullptr) {
1707       ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1708       // use 'release' to pair with lock-free load
1709       release_set_array_klasses(k);
1710     }
1711   }
1712 
1713   // array_klasses() will always be set at this point
1714   ObjArrayKlass* ak = array_klasses();
1715   assert(ak != nullptr, "should be set");
1716   return ak->array_klass(n, THREAD);
1717 }
1718 
1719 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1720   // Need load-acquire for lock-free read
1721   ObjArrayKlass* oak = array_klasses_acquire();
1722   if (oak == nullptr) {
1723     return nullptr;
1724   } else {
1725     return oak->array_klass_or_null(n);
1726   }
1727 }
1728 
1729 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1730   return array_klass(1, THREAD);
1731 }
1732 
1733 ArrayKlass* InstanceKlass::array_klass_or_null() {
1734   return array_klass_or_null(1);
1735 }
1736 
1737 Method* InstanceKlass::class_initializer() const {
1738   Method* clinit = find_method(
1739       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1740   if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1741     return clinit;
1742   }
1743   return nullptr;
1744 }
1745 
1746 void InstanceKlass::call_class_initializer(TRAPS) {
1747   if (ReplayCompiles &&
1748       (ReplaySuppressInitializers == 1 ||
1749        (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1750     // Hide the existence of the initializer for the purpose of replaying the compile
1751     return;
1752   }
1753 
1754 #if INCLUDE_CDS
1755   // This is needed to ensure the consistency of the archived heap objects.
1756   if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1757     AOTClassInitializer::call_runtime_setup(THREAD, this);
1758     return;
1759   } else if (has_archived_enum_objs()) {
1760     assert(in_aot_cache(), "must be");
1761     bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1762     if (initialized) {
1763       return;
1764     }
1765   }
1766 #endif
1767 
1768   methodHandle h_method(THREAD, class_initializer());
1769   assert(!is_initialized(), "we cannot initialize twice");
1770   LogTarget(Info, class, init) lt;
1771   if (lt.is_enabled()) {
1772     ResourceMark rm(THREAD);
1773     LogStream ls(lt);
1774     ls.print("%d Initializing ", call_class_initializer_counter++);
1775     name()->print_value_on(&ls);
1776     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1777                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1778                 THREAD->name());
1779   }
1780   if (h_method() != nullptr) {
1781     ThreadInClassInitializer ticl(THREAD, this); // Track class being initialized
1782     JavaCallArguments args; // No arguments
1783     JavaValue result(T_VOID);
1784     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1785   }
1786 }
1787 
1788 // If a class that implements this interface is initialized, is the JVM required
1789 // to first execute a <clinit> method declared in this interface,
1790 // or (if also_check_supers==true) any of the super types of this interface?
1791 //
1792 // JVMS 5.5. Initialization, step 7: Next, if C is a class rather than
1793 // an interface, then let SC be its superclass and let SI1, ..., SIn
1794 // be all superinterfaces of C (whether direct or indirect) that
1795 // declare at least one non-abstract, non-static method.
1796 //
1797 // So when an interface is initialized, it does not look at its
1798 // supers. But a proper class will ensure that all of its supers have
1799 // run their <clinit> methods, except that it disregards interfaces
1800 // that lack a non-static concrete method (i.e., a default method).
1801 // Therefore, you should probably call this method only when the
1802 // current class is a super of some proper class, not an interface.
1803 bool InstanceKlass::interface_needs_clinit_execution_as_super(bool also_check_supers) const {
1804   assert(is_interface(), "must be");
1805 
1806   if (!has_nonstatic_concrete_methods()) {
1807     // quick check: no nonstatic concrete methods are declared by this or any super interfaces
1808     return false;
1809   }
1810 
1811   // JVMS 5.5. Initialization
1812   // ...If C is an interface that declares a non-abstract,
1813   // non-static method, the initialization of a class that
1814   // implements C directly or indirectly.
1815   if (declares_nonstatic_concrete_methods() && class_initializer() != nullptr) {
1816     return true;
1817   }
1818   if (also_check_supers) {
1819     Array<InstanceKlass*>* all_ifs = transitive_interfaces();
1820     for (int i = 0; i < all_ifs->length(); ++i) {
1821       InstanceKlass* super_intf = all_ifs->at(i);
1822       if (super_intf->declares_nonstatic_concrete_methods() && super_intf->class_initializer() != nullptr) {
1823         return true;
1824       }
1825     }
1826   }
1827   return false;
1828 }
1829 
1830 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1831   InterpreterOopMap* entry_for) {
1832   // Lazily create the _oop_map_cache at first request.
1833   // Load_acquire is needed to safely get instance published with CAS by another thread.
1834   OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
1835   if (oop_map_cache == nullptr) {
1836     // Try to install new instance atomically.
1837     oop_map_cache = new OopMapCache();
1838     OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1839     if (other != nullptr) {
1840       // Someone else managed to install before us, ditch local copy and use the existing one.
1841       delete oop_map_cache;
1842       oop_map_cache = other;
1843     }
1844   }
1845   // _oop_map_cache is constant after init; lookup below does its own locking.
1846   oop_map_cache->lookup(method, bci, entry_for);
1847 }
1848 
1849 bool InstanceKlass::contains_field_offset(int offset) {
1850   fieldDescriptor fd;
1851   return find_field_from_offset(offset, false, &fd);
1852 }
1853 
1854 FieldInfo InstanceKlass::field(int index) const {
1855   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1856     if (fs.index() == index) {
1857       return fs.to_FieldInfo();
1858     }
1859   }
1860   fatal("Field not found");
1861   return FieldInfo();
1862 }
1863 
1864 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1865   JavaFieldStream fs(this);
1866   if (fs.lookup(name, sig)) {
1867     assert(fs.name() == name, "name must match");
1868     assert(fs.signature() == sig, "signature must match");
1869     fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1870     return true;
1871   }
1872   return false;
1873 }
1874 
1875 
1876 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1877   const int n = local_interfaces()->length();
1878   for (int i = 0; i < n; i++) {
1879     InstanceKlass* intf1 = local_interfaces()->at(i);
1880     assert(intf1->is_interface(), "just checking type");
1881     // search for field in current interface
1882     if (intf1->find_local_field(name, sig, fd)) {
1883       assert(fd->is_static(), "interface field must be static");
1884       return intf1;
1885     }
1886     // search for field in direct superinterfaces
1887     Klass* intf2 = intf1->find_interface_field(name, sig, fd);
1888     if (intf2 != nullptr) return intf2;
1889   }
1890   // otherwise field lookup fails
1891   return nullptr;
1892 }
1893 
1894 
1895 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1896   // search order according to newest JVM spec (5.4.3.2, p.167).
1897   // 1) search for field in current klass
1898   if (find_local_field(name, sig, fd)) {
1899     return const_cast<InstanceKlass*>(this);
1900   }
1901   // 2) search for field recursively in direct superinterfaces
1902   { Klass* intf = find_interface_field(name, sig, fd);
1903     if (intf != nullptr) return intf;
1904   }
1905   // 3) apply field lookup recursively if superclass exists
1906   { InstanceKlass* supr = super();
1907     if (supr != nullptr) return supr->find_field(name, sig, fd);
1908   }
1909   // 4) otherwise field lookup fails
1910   return nullptr;
1911 }
1912 
1913 
1914 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1915   // search order according to newest JVM spec (5.4.3.2, p.167).
1916   // 1) search for field in current klass
1917   if (find_local_field(name, sig, fd)) {
1918     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1919   }
1920   // 2) search for field recursively in direct superinterfaces
1921   if (is_static) {
1922     Klass* intf = find_interface_field(name, sig, fd);
1923     if (intf != nullptr) return intf;
1924   }
1925   // 3) apply field lookup recursively if superclass exists
1926   { InstanceKlass* supr = super();
1927     if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
1928   }
1929   // 4) otherwise field lookup fails
1930   return nullptr;
1931 }
1932 
1933 
1934 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1935   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1936     if (fs.offset() == offset) {
1937       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1938       if (fd->is_static() == is_static) return true;
1939     }
1940   }
1941   return false;
1942 }
1943 
1944 
1945 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1946   const InstanceKlass* klass = this;
1947   while (klass != nullptr) {
1948     if (klass->find_local_field_from_offset(offset, is_static, fd)) {
1949       return true;
1950     }
1951     klass = klass->super();
1952   }
1953   return false;
1954 }
1955 
1956 
1957 void InstanceKlass::methods_do(void f(Method* method)) {
1958   // Methods aren't stable until they are loaded.  This can be read outside
1959   // a lock through the ClassLoaderData for profiling
1960   // Redefined scratch classes are on the list and need to be cleaned
1961   if (!is_loaded() && !is_scratch_class()) {
1962     return;
1963   }
1964 
1965   int len = methods()->length();
1966   for (int index = 0; index < len; index++) {
1967     Method* m = methods()->at(index);
1968     assert(m->is_method(), "must be method");
1969     f(m);
1970   }
1971 }
1972 
1973 
1974 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1975   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1976     if (fs.access_flags().is_static()) {
1977       fieldDescriptor& fd = fs.field_descriptor();
1978       cl->do_field(&fd);
1979     }
1980   }
1981 }
1982 
1983 
1984 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1985   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1986     if (fs.access_flags().is_static()) {
1987       fieldDescriptor& fd = fs.field_descriptor();
1988       f(&fd, mirror, CHECK);
1989     }
1990   }
1991 }
1992 
1993 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1994   InstanceKlass* super = this->super();
1995   if (super != nullptr) {
1996     super->do_nonstatic_fields(cl);
1997   }
1998   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1999     fieldDescriptor& fd = fs.field_descriptor();
2000     if (!fd.is_static()) {
2001       cl->do_field(&fd);
2002     }
2003   }
2004 }
2005 
2006 static int compare_fields_by_offset(FieldInfo* a, FieldInfo* b) {
2007   return a->offset() - b->offset();
2008 }
2009 
2010 void InstanceKlass::print_nonstatic_fields(FieldClosure* cl) {
2011   InstanceKlass* super = this->super();
2012   if (super != nullptr) {
2013     super->print_nonstatic_fields(cl);
2014   }
2015   ResourceMark rm;
2016   // In DebugInfo nonstatic fields are sorted by offset.
2017   GrowableArray<FieldInfo> fields_sorted;
2018   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2019     if (!fs.access_flags().is_static()) {
2020       fields_sorted.push(fs.to_FieldInfo());
2021     }
2022   }
2023   int length = fields_sorted.length();
2024   if (length > 0) {
2025     fields_sorted.sort(compare_fields_by_offset);
2026     fieldDescriptor fd;
2027     for (int i = 0; i < length; i++) {
2028       fd.reinitialize(this, fields_sorted.at(i));
2029       assert(!fd.is_static() && fd.offset() == checked_cast<int>(fields_sorted.at(i).offset()), "only nonstatic fields");
2030       cl->do_field(&fd);
2031     }
2032   }
2033 }
2034 
2035 #ifdef ASSERT
2036 static int linear_search(const Array<Method*>* methods,
2037                          const Symbol* name,
2038                          const Symbol* signature) {
2039   const int len = methods->length();
2040   for (int index = 0; index < len; index++) {
2041     const Method* const m = methods->at(index);
2042     assert(m->is_method(), "must be method");
2043     if (m->signature() == signature && m->name() == name) {
2044        return index;
2045     }
2046   }
2047   return -1;
2048 }
2049 #endif
2050 
2051 bool InstanceKlass::_disable_method_binary_search = false;
2052 
2053 NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) {
2054   int len = methods->length();
2055   int l = 0;
2056   int h = len - 1;
2057   while (l <= h) {
2058     Method* m = methods->at(l);
2059     if (m->name() == name) {
2060       return l;
2061     }
2062     l++;
2063   }
2064   return -1;
2065 }
2066 
2067 inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) {
2068   if (_disable_method_binary_search) {
2069     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
2070     // At the final stage of dynamic dumping, the methods array may not be sorted
2071     // by ascending addresses of their names, so we can't use binary search anymore.
2072     // However, methods with the same name are still laid out consecutively inside the
2073     // methods array, so let's look for the first one that matches.
2074     return linear_search(methods, name);
2075   }
2076 
2077   int len = methods->length();
2078   int l = 0;
2079   int h = len - 1;
2080 
2081   // methods are sorted by ascending addresses of their names, so do binary search
2082   while (l <= h) {
2083     int mid = (l + h) >> 1;
2084     Method* m = methods->at(mid);
2085     assert(m->is_method(), "must be method");
2086     int res = m->name()->fast_compare(name);
2087     if (res == 0) {
2088       return mid;
2089     } else if (res < 0) {
2090       l = mid + 1;
2091     } else {
2092       h = mid - 1;
2093     }
2094   }
2095   return -1;
2096 }
2097 
2098 // find_method looks up the name/signature in the local methods array
2099 Method* InstanceKlass::find_method(const Symbol* name,
2100                                    const Symbol* signature) const {
2101   return find_method_impl(name, signature,
2102                           OverpassLookupMode::find,
2103                           StaticLookupMode::find,
2104                           PrivateLookupMode::find);
2105 }
2106 
2107 Method* InstanceKlass::find_method_impl(const Symbol* name,
2108                                         const Symbol* signature,
2109                                         OverpassLookupMode overpass_mode,
2110                                         StaticLookupMode static_mode,
2111                                         PrivateLookupMode private_mode) const {
2112   return InstanceKlass::find_method_impl(methods(),
2113                                          name,
2114                                          signature,
2115                                          overpass_mode,
2116                                          static_mode,
2117                                          private_mode);
2118 }
2119 
2120 // find_instance_method looks up the name/signature in the local methods array
2121 // and skips over static methods
2122 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
2123                                             const Symbol* name,
2124                                             const Symbol* signature,
2125                                             PrivateLookupMode private_mode) {
2126   Method* const meth = InstanceKlass::find_method_impl(methods,
2127                                                  name,
2128                                                  signature,
2129                                                  OverpassLookupMode::find,
2130                                                  StaticLookupMode::skip,
2131                                                  private_mode);
2132   assert(((meth == nullptr) || !meth->is_static()),
2133     "find_instance_method should have skipped statics");
2134   return meth;
2135 }
2136 
2137 // find_instance_method looks up the name/signature in the local methods array
2138 // and skips over static methods
2139 Method* InstanceKlass::find_instance_method(const Symbol* name,
2140                                             const Symbol* signature,
2141                                             PrivateLookupMode private_mode) const {
2142   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
2143 }
2144 
2145 // Find looks up the name/signature in the local methods array
2146 // and filters on the overpass, static and private flags
2147 // This returns the first one found
2148 // note that the local methods array can have up to one overpass, one static
2149 // and one instance (private or not) with the same name/signature
2150 Method* InstanceKlass::find_local_method(const Symbol* name,
2151                                          const Symbol* signature,
2152                                          OverpassLookupMode overpass_mode,
2153                                          StaticLookupMode static_mode,
2154                                          PrivateLookupMode private_mode) const {
2155   return InstanceKlass::find_method_impl(methods(),
2156                                          name,
2157                                          signature,
2158                                          overpass_mode,
2159                                          static_mode,
2160                                          private_mode);
2161 }
2162 
2163 // Find looks up the name/signature in the local methods array
2164 // and filters on the overpass, static and private flags
2165 // This returns the first one found
2166 // note that the local methods array can have up to one overpass, one static
2167 // and one instance (private or not) with the same name/signature
2168 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
2169                                          const Symbol* name,
2170                                          const Symbol* signature,
2171                                          OverpassLookupMode overpass_mode,
2172                                          StaticLookupMode static_mode,
2173                                          PrivateLookupMode private_mode) {
2174   return InstanceKlass::find_method_impl(methods,
2175                                          name,
2176                                          signature,
2177                                          overpass_mode,
2178                                          static_mode,
2179                                          private_mode);
2180 }
2181 
2182 Method* InstanceKlass::find_method(const Array<Method*>* methods,
2183                                    const Symbol* name,
2184                                    const Symbol* signature) {
2185   return InstanceKlass::find_method_impl(methods,
2186                                          name,
2187                                          signature,
2188                                          OverpassLookupMode::find,
2189                                          StaticLookupMode::find,
2190                                          PrivateLookupMode::find);
2191 }
2192 
2193 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
2194                                         const Symbol* name,
2195                                         const Symbol* signature,
2196                                         OverpassLookupMode overpass_mode,
2197                                         StaticLookupMode static_mode,
2198                                         PrivateLookupMode private_mode) {
2199   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
2200   return hit >= 0 ? methods->at(hit): nullptr;
2201 }
2202 
2203 // true if method matches signature and conforms to skipping_X conditions.
2204 static bool method_matches(const Method* m,
2205                            const Symbol* signature,
2206                            bool skipping_overpass,
2207                            bool skipping_static,
2208                            bool skipping_private) {
2209   return ((m->signature() == signature) &&
2210     (!skipping_overpass || !m->is_overpass()) &&
2211     (!skipping_static || !m->is_static()) &&
2212     (!skipping_private || !m->is_private()));
2213 }
2214 
2215 // Used directly for default_methods to find the index into the
2216 // default_vtable_indices, and indirectly by find_method
2217 // find_method_index looks in the local methods array to return the index
2218 // of the matching name/signature. If, overpass methods are being ignored,
2219 // the search continues to find a potential non-overpass match.  This capability
2220 // is important during method resolution to prefer a static method, for example,
2221 // over an overpass method.
2222 // There is the possibility in any _method's array to have the same name/signature
2223 // for a static method, an overpass method and a local instance method
2224 // To correctly catch a given method, the search criteria may need
2225 // to explicitly skip the other two. For local instance methods, it
2226 // is often necessary to skip private methods
2227 int InstanceKlass::find_method_index(const Array<Method*>* methods,
2228                                      const Symbol* name,
2229                                      const Symbol* signature,
2230                                      OverpassLookupMode overpass_mode,
2231                                      StaticLookupMode static_mode,
2232                                      PrivateLookupMode private_mode) {
2233   const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip);
2234   const bool skipping_static = (static_mode == StaticLookupMode::skip);
2235   const bool skipping_private = (private_mode == PrivateLookupMode::skip);
2236   const int hit = quick_search(methods, name);
2237   if (hit != -1) {
2238     const Method* const m = methods->at(hit);
2239 
2240     // Do linear search to find matching signature.  First, quick check
2241     // for common case, ignoring overpasses if requested.
2242     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2243       return hit;
2244     }
2245 
2246     // search downwards through overloaded methods
2247     int i;
2248     for (i = hit - 1; i >= 0; --i) {
2249         const Method* const m = methods->at(i);
2250         assert(m->is_method(), "must be method");
2251         if (m->name() != name) {
2252           break;
2253         }
2254         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2255           return i;
2256         }
2257     }
2258     // search upwards
2259     for (i = hit + 1; i < methods->length(); ++i) {
2260         const Method* const m = methods->at(i);
2261         assert(m->is_method(), "must be method");
2262         if (m->name() != name) {
2263           break;
2264         }
2265         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2266           return i;
2267         }
2268     }
2269     // not found
2270 #ifdef ASSERT
2271     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
2272       linear_search(methods, name, signature);
2273     assert(-1 == index, "binary search should have found entry %d", index);
2274 #endif
2275   }
2276   return -1;
2277 }
2278 
2279 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
2280   return find_method_by_name(methods(), name, end);
2281 }
2282 
2283 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
2284                                        const Symbol* name,
2285                                        int* end_ptr) {
2286   assert(end_ptr != nullptr, "just checking");
2287   int start = quick_search(methods, name);
2288   int end = start + 1;
2289   if (start != -1) {
2290     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
2291     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
2292     *end_ptr = end;
2293     return start;
2294   }
2295   return -1;
2296 }
2297 
2298 // uncached_lookup_method searches both the local class methods array and all
2299 // superclasses methods arrays, skipping any overpass methods in superclasses,
2300 // and possibly skipping private methods.
2301 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2302                                               const Symbol* signature,
2303                                               OverpassLookupMode overpass_mode,
2304                                               PrivateLookupMode private_mode) const {
2305   OverpassLookupMode overpass_local_mode = overpass_mode;
2306   const InstanceKlass* klass = this;
2307   while (klass != nullptr) {
2308     Method* const method = klass->find_method_impl(name,
2309                                                    signature,
2310                                                    overpass_local_mode,
2311                                                    StaticLookupMode::find,
2312                                                    private_mode);
2313     if (method != nullptr) {
2314       return method;
2315     }
2316     klass = klass->super();
2317     overpass_local_mode = OverpassLookupMode::skip;   // Always ignore overpass methods in superclasses
2318   }
2319   return nullptr;
2320 }
2321 
2322 #ifdef ASSERT
2323 // search through class hierarchy and return true if this class or
2324 // one of the superclasses was redefined
2325 bool InstanceKlass::has_redefined_this_or_super() const {
2326   const InstanceKlass* klass = this;
2327   while (klass != nullptr) {
2328     if (klass->has_been_redefined()) {
2329       return true;
2330     }
2331     klass = klass->super();
2332   }
2333   return false;
2334 }
2335 #endif
2336 
2337 // lookup a method in the default methods list then in all transitive interfaces
2338 // Do NOT return private or static methods
2339 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
2340                                                          Symbol* signature) const {
2341   Method* m = nullptr;
2342   if (default_methods() != nullptr) {
2343     m = find_method(default_methods(), name, signature);
2344   }
2345   // Look up interfaces
2346   if (m == nullptr) {
2347     m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find);
2348   }
2349   return m;
2350 }
2351 
2352 // lookup a method in all the interfaces that this class implements
2353 // Do NOT return private or static methods, new in JDK8 which are not externally visible
2354 // They should only be found in the initial InterfaceMethodRef
2355 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
2356                                                        Symbol* signature,
2357                                                        DefaultsLookupMode defaults_mode) const {
2358   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2359   int num_ifs = all_ifs->length();
2360   InstanceKlass *ik = nullptr;
2361   for (int i = 0; i < num_ifs; i++) {
2362     ik = all_ifs->at(i);
2363     Method* m = ik->lookup_method(name, signature);
2364     if (m != nullptr && m->is_public() && !m->is_static() &&
2365         ((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) {
2366       return m;
2367     }
2368   }
2369   return nullptr;
2370 }
2371 
2372 PrintClassClosure::PrintClassClosure(outputStream* st, bool verbose)
2373   :_st(st), _verbose(verbose) {
2374   ResourceMark rm;
2375   _st->print("%-18s  ", "KlassAddr");
2376   _st->print("%-4s  ", "Size");
2377   _st->print("%-20s  ", "State");
2378   _st->print("%-7s  ", "Flags");
2379   _st->print("%-5s  ", "ClassName");
2380   _st->cr();
2381 }
2382 
2383 void PrintClassClosure::do_klass(Klass* k)  {
2384   ResourceMark rm;
2385   // klass pointer
2386   _st->print(PTR_FORMAT "  ", p2i(k));
2387   // klass size
2388   _st->print("%4d  ", k->size());
2389   // initialization state
2390   if (k->is_instance_klass()) {
2391     _st->print("%-20s  ",InstanceKlass::cast(k)->init_state_name());
2392   } else {
2393     _st->print("%-20s  ","");
2394   }
2395   // misc flags(Changes should synced with ClassesDCmd::ClassesDCmd help doc)
2396   char buf[10];
2397   int i = 0;
2398   if (k->has_finalizer()) buf[i++] = 'F';
2399   if (k->is_instance_klass()) {
2400     InstanceKlass* ik = InstanceKlass::cast(k);
2401     if (ik->has_final_method()) buf[i++] = 'f';
2402     if (ik->is_rewritten()) buf[i++] = 'W';
2403     if (ik->is_contended()) buf[i++] = 'C';
2404     if (ik->has_been_redefined()) buf[i++] = 'R';
2405     if (ik->in_aot_cache()) buf[i++] = 'S';
2406   }
2407   buf[i++] = '\0';
2408   _st->print("%-7s  ", buf);
2409   // klass name
2410   _st->print("%-5s  ", k->external_name());
2411   // end
2412   _st->cr();
2413   if (_verbose) {
2414     k->print_on(_st);
2415   }
2416 }
2417 
2418 /* jni_id_for for jfieldIds only */
2419 JNIid* InstanceKlass::jni_id_for(int offset) {
2420   MutexLocker ml(JfieldIdCreation_lock);
2421   JNIid* probe = jni_ids() == nullptr ? nullptr : jni_ids()->find(offset);
2422   if (probe == nullptr) {
2423     // Allocate new static field identifier
2424     probe = new JNIid(this, offset, jni_ids());
2425     set_jni_ids(probe);
2426   }
2427   return probe;
2428 }
2429 
2430 u2 InstanceKlass::enclosing_method_data(int offset) const {
2431   const Array<jushort>* const inner_class_list = inner_classes();
2432   if (inner_class_list == nullptr) {
2433     return 0;
2434   }
2435   const int length = inner_class_list->length();
2436   if (length % inner_class_next_offset == 0) {
2437     return 0;
2438   }
2439   const int index = length - enclosing_method_attribute_size;
2440   assert(offset < enclosing_method_attribute_size, "invalid offset");
2441   return inner_class_list->at(index + offset);
2442 }
2443 
2444 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2445                                                  u2 method_index) {
2446   Array<jushort>* inner_class_list = inner_classes();
2447   assert (inner_class_list != nullptr, "_inner_classes list is not set up");
2448   int length = inner_class_list->length();
2449   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2450     int index = length - enclosing_method_attribute_size;
2451     inner_class_list->at_put(
2452       index + enclosing_method_class_index_offset, class_index);
2453     inner_class_list->at_put(
2454       index + enclosing_method_method_index_offset, method_index);
2455   }
2456 }
2457 
2458 jmethodID InstanceKlass::update_jmethod_id(jmethodID* jmeths, Method* method, int idnum) {
2459   if (method->is_old() && !method->is_obsolete()) {
2460     // If the method passed in is old (but not obsolete), use the current version.
2461     method = method_with_idnum((int)idnum);
2462     assert(method != nullptr, "old and but not obsolete, so should exist");
2463   }
2464   jmethodID new_id = Method::make_jmethod_id(class_loader_data(), method);
2465   AtomicAccess::release_store(&jmeths[idnum + 1], new_id);
2466   return new_id;
2467 }
2468 
2469 // Allocate the jmethodID cache.
2470 static jmethodID* create_jmethod_id_cache(size_t size) {
2471   jmethodID* jmeths = NEW_C_HEAP_ARRAY(jmethodID, size + 1, mtClass);
2472   memset(jmeths, 0, (size + 1) * sizeof(jmethodID));
2473   // cache size is stored in element[0], other elements offset by one
2474   jmeths[0] = (jmethodID)size;
2475   return jmeths;
2476 }
2477 
2478 // When reading outside a lock, use this.
2479 jmethodID* InstanceKlass::methods_jmethod_ids_acquire() const {
2480   return AtomicAccess::load_acquire(&_methods_jmethod_ids);
2481 }
2482 
2483 void InstanceKlass::release_set_methods_jmethod_ids(jmethodID* jmeths) {
2484   AtomicAccess::release_store(&_methods_jmethod_ids, jmeths);
2485 }
2486 
2487 // Lookup or create a jmethodID.
2488 jmethodID InstanceKlass::get_jmethod_id(Method* method) {
2489   int idnum = method->method_idnum();
2490   jmethodID* jmeths = methods_jmethod_ids_acquire();
2491 
2492   // We use a double-check locking idiom here because this cache is
2493   // performance sensitive. In the normal system, this cache only
2494   // transitions from null to non-null which is safe because we use
2495   // release_set_methods_jmethod_ids() to advertise the new cache.
2496   // A partially constructed cache should never be seen by a racing
2497   // thread. We also use release_store() to save a new jmethodID
2498   // in the cache so a partially constructed jmethodID should never be
2499   // seen either. Cache reads of existing jmethodIDs proceed without a
2500   // lock, but cache writes of a new jmethodID requires uniqueness and
2501   // creation of the cache itself requires no leaks so a lock is
2502   // acquired in those two cases.
2503   //
2504   // If the RedefineClasses() API has been used, then this cache grows
2505   // in the redefinition safepoint.
2506 
2507   if (jmeths == nullptr) {
2508     MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2509     jmeths = _methods_jmethod_ids;
2510     // Still null?
2511     if (jmeths == nullptr) {
2512       size_t size = idnum_allocated_count();
2513       assert(size > (size_t)idnum, "should already have space");
2514       jmeths = create_jmethod_id_cache(size);
2515       jmethodID new_id = update_jmethod_id(jmeths, method, idnum);
2516 
2517       // publish jmeths
2518       release_set_methods_jmethod_ids(jmeths);
2519       return new_id;
2520     }
2521   }
2522 
2523   jmethodID id = AtomicAccess::load_acquire(&jmeths[idnum + 1]);
2524   if (id == nullptr) {
2525     MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2526     id = jmeths[idnum + 1];
2527     // Still null?
2528     if (id == nullptr) {
2529       return update_jmethod_id(jmeths, method, idnum);
2530     }
2531   }
2532   return id;
2533 }
2534 
2535 void InstanceKlass::update_methods_jmethod_cache() {
2536   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2537   jmethodID* cache = _methods_jmethod_ids;
2538   if (cache != nullptr) {
2539     size_t size = idnum_allocated_count();
2540     size_t old_size = (size_t)cache[0];
2541     if (old_size < size + 1) {
2542       // Allocate a larger one and copy entries to the new one.
2543       // They've already been updated to point to new methods where applicable (i.e., not obsolete).
2544       jmethodID* new_cache = create_jmethod_id_cache(size);
2545 
2546       for (int i = 1; i <= (int)old_size; i++) {
2547         new_cache[i] = cache[i];
2548       }
2549       _methods_jmethod_ids = new_cache;
2550       FREE_C_HEAP_ARRAY(cache);
2551     }
2552   }
2553 }
2554 
2555 // Make a jmethodID for all methods in this class.  This makes getting all method
2556 // ids much, much faster with classes with more than 8
2557 // methods, and has a *substantial* effect on performance with jvmti
2558 // code that loads all jmethodIDs for all classes.
2559 void InstanceKlass::make_methods_jmethod_ids() {
2560   MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2561   jmethodID* jmeths = _methods_jmethod_ids;
2562   if (jmeths == nullptr) {
2563     jmeths = create_jmethod_id_cache(idnum_allocated_count());
2564     release_set_methods_jmethod_ids(jmeths);
2565   }
2566 
2567   int length = methods()->length();
2568   for (int index = 0; index < length; index++) {
2569     Method* m = methods()->at(index);
2570     int idnum = m->method_idnum();
2571     assert(!m->is_old(), "should not have old methods or I'm confused");
2572     jmethodID id = AtomicAccess::load_acquire(&jmeths[idnum + 1]);
2573     if (!m->is_overpass() &&  // skip overpasses
2574         id == nullptr) {
2575       id = Method::make_jmethod_id(class_loader_data(), m);
2576       AtomicAccess::release_store(&jmeths[idnum + 1], id);
2577     }
2578   }
2579 }
2580 
2581 // Lookup a jmethodID, null if not found.  Do no blocking, no allocations, no handles
2582 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2583   int idnum = method->method_idnum();
2584   jmethodID* jmeths = methods_jmethod_ids_acquire();
2585   return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2586 }
2587 
2588 inline DependencyContext InstanceKlass::dependencies() {
2589   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2590   return dep_context;
2591 }
2592 
2593 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2594   dependencies().mark_dependent_nmethods(deopt_scope, changes);
2595 }
2596 
2597 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2598   assert_lock_strong(CodeCache_lock);
2599   dependencies().add_dependent_nmethod(nm);
2600 }
2601 
2602 void InstanceKlass::clean_dependency_context() {
2603   dependencies().clean_unloading_dependents();
2604 }
2605 
2606 #ifndef PRODUCT
2607 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2608   dependencies().print_dependent_nmethods(verbose);
2609 }
2610 
2611 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2612   return dependencies().is_dependent_nmethod(nm);
2613 }
2614 #endif //PRODUCT
2615 
2616 void InstanceKlass::clean_weak_instanceklass_links() {
2617   clean_implementors_list();
2618   clean_method_data();
2619 }
2620 
2621 void InstanceKlass::clean_implementors_list() {
2622   assert(is_loader_alive(), "this klass should be live");
2623   if (is_interface()) {
2624     assert (ClassUnloading, "only called for ClassUnloading");
2625     for (;;) {
2626       // Use load_acquire due to competing with inserts
2627       InstanceKlass* volatile* iklass = adr_implementor();
2628       assert(iklass != nullptr, "Klass must not be null");
2629       InstanceKlass* impl = AtomicAccess::load_acquire(iklass);
2630       if (impl != nullptr && !impl->is_loader_alive()) {
2631         // null this field, might be an unloaded instance klass or null
2632         if (AtomicAccess::cmpxchg(iklass, impl, (InstanceKlass*)nullptr) == impl) {
2633           // Successfully unlinking implementor.
2634           if (log_is_enabled(Trace, class, unload)) {
2635             ResourceMark rm;
2636             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2637           }
2638           return;
2639         }
2640       } else {
2641         return;
2642       }
2643     }
2644   }
2645 }
2646 
2647 void InstanceKlass::clean_method_data() {
2648   for (int m = 0; m < methods()->length(); m++) {
2649     MethodData* mdo = methods()->at(m)->method_data();
2650     if (mdo != nullptr) {
2651       mdo->clean_method_data(/*always_clean*/false);
2652     }
2653   }
2654 }
2655 
2656 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2657   Klass::metaspace_pointers_do(it);
2658 
2659   if (log_is_enabled(Trace, aot)) {
2660     ResourceMark rm;
2661     log_trace(aot)("Iter(InstanceKlass): %p (%s)", this, external_name());
2662   }
2663 
2664   it->push(&_annotations);
2665   it->push((Klass**)&_array_klasses);
2666   if (!is_rewritten()) {
2667     it->push(&_constants, MetaspaceClosure::_writable);
2668   } else {
2669     it->push(&_constants);
2670   }
2671   it->push(&_inner_classes);
2672 #if INCLUDE_JVMTI
2673   it->push(&_previous_versions);
2674 #endif
2675 #if INCLUDE_CDS
2676   // For "old" classes with methods containing the jsr bytecode, the _methods array will
2677   // be rewritten during runtime (see Rewriter::rewrite_jsrs()) but they cannot be safely
2678   // checked here with ByteCodeStream. All methods that can't be verified are made writable.
2679   // The length check on the _methods is necessary because classes which don't have any
2680   // methods share the Universe::_the_empty_method_array which is in the RO region.
2681   if (_methods != nullptr && _methods->length() > 0 && !can_be_verified_at_dumptime()) {
2682     // To handle jsr bytecode, new Method* maybe stored into _methods
2683     it->push(&_methods, MetaspaceClosure::_writable);
2684   } else {
2685 #endif
2686     it->push(&_methods);
2687 #if INCLUDE_CDS
2688   }
2689 #endif
2690   it->push(&_default_methods);
2691   it->push(&_local_interfaces);
2692   it->push(&_transitive_interfaces);
2693   it->push(&_method_ordering);
2694   if (!is_rewritten()) {
2695     it->push(&_default_vtable_indices, MetaspaceClosure::_writable);
2696   } else {
2697     it->push(&_default_vtable_indices);
2698   }
2699 
2700   it->push(&_fieldinfo_stream);
2701   it->push(&_fieldinfo_search_table);
2702   // _fields_status might be written into by Rewriter::scan_method() -> fd.set_has_initialized_final_update()
2703   it->push(&_fields_status, MetaspaceClosure::_writable);
2704 
2705   if (itable_length() > 0) {
2706     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2707     int method_table_offset_in_words = ioe->offset()/wordSize;
2708     int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2709 
2710     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2711                          / itableOffsetEntry::size();
2712 
2713     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2714       if (ioe->interface_klass() != nullptr) {
2715         it->push(ioe->interface_klass_addr());
2716         itableMethodEntry* ime = ioe->first_method_entry(this);
2717         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2718         for (int index = 0; index < n; index ++) {
2719           it->push(ime[index].method_addr());
2720         }
2721       }
2722     }
2723   }
2724 
2725   it->push(&_nest_host);
2726   it->push(&_nest_members);
2727   it->push(&_permitted_subclasses);
2728   it->push(&_record_components);
2729 
2730   if (CDSConfig::is_dumping_full_module_graph() && !defined_by_other_loaders()) {
2731     it->push(&_package_entry);
2732   }
2733 }
2734 
2735 #if INCLUDE_CDS
2736 void InstanceKlass::remove_unshareable_info() {
2737 
2738   if (is_linked()) {
2739     assert(can_be_verified_at_dumptime(), "must be");
2740     // Remember this so we can avoid walking the hierarchy at runtime.
2741     set_verified_at_dump_time();
2742   }
2743 
2744   _misc_flags.set_has_init_deps_processed(false);
2745 
2746   Klass::remove_unshareable_info();
2747 
2748   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2749     // Classes are attempted to link during dumping and may fail,
2750     // but these classes are still in the dictionary and class list in CLD.
2751     // If the class has failed verification, there is nothing else to remove.
2752     return;
2753   }
2754 
2755   // Reset to the 'allocated' state to prevent any premature accessing to
2756   // a shared class at runtime while the class is still being loaded and
2757   // restored. A class' init_state is set to 'loaded' at runtime when it's
2758   // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2759   _init_state = allocated;
2760 
2761   { // Otherwise this needs to take out the Compile_lock.
2762     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2763     init_implementor();
2764   }
2765 
2766   // Call remove_unshareable_info() on other objects that belong to this class, except
2767   // for constants()->remove_unshareable_info(), which is called in a separate pass in
2768   // ArchiveBuilder::make_klasses_shareable(),
2769 
2770   for (int i = 0; i < methods()->length(); i++) {
2771     Method* m = methods()->at(i);
2772     m->remove_unshareable_info();
2773   }
2774 
2775   // do array classes also.
2776   if (array_klasses() != nullptr) {
2777     array_klasses()->remove_unshareable_info();
2778   }
2779 
2780   // These are not allocated from metaspace. They are safe to set to null.
2781   _source_debug_extension = nullptr;
2782   _dep_context = nullptr;
2783   _osr_nmethods_head = nullptr;
2784 #if INCLUDE_JVMTI
2785   _breakpoints = nullptr;
2786   _previous_versions = nullptr;
2787   _cached_class_file = nullptr;
2788   _jvmti_cached_class_field_map = nullptr;
2789 #endif
2790 
2791   _init_thread = nullptr;
2792   _methods_jmethod_ids = nullptr;
2793   _jni_ids = nullptr;
2794   _oop_map_cache = nullptr;
2795   if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2796     // keep _nest_host
2797   } else {
2798     // clear _nest_host to ensure re-load at runtime
2799     _nest_host = nullptr;
2800   }
2801   init_shared_package_entry();
2802   _dep_context_last_cleaned = 0;
2803   DEBUG_ONLY(_shared_class_load_count = 0);
2804 
2805   remove_unshareable_flags();
2806 
2807   DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2808 }
2809 
2810 void InstanceKlass::remove_unshareable_flags() {
2811   // clear all the flags/stats that shouldn't be in the archived version
2812   assert(!is_scratch_class(), "must be");
2813   assert(!has_been_redefined(), "must be");
2814 #if INCLUDE_JVMTI
2815   set_is_being_redefined(false);
2816 #endif
2817   set_has_resolved_methods(false);
2818 }
2819 
2820 void InstanceKlass::remove_java_mirror() {
2821   Klass::remove_java_mirror();
2822 
2823   // do array classes also.
2824   if (array_klasses() != nullptr) {
2825     array_klasses()->remove_java_mirror();
2826   }
2827 }
2828 
2829 void InstanceKlass::init_shared_package_entry() {
2830   assert(CDSConfig::is_dumping_archive(), "must be");
2831   if (!CDSConfig::is_dumping_full_module_graph() || defined_by_other_loaders()) {
2832     _package_entry = nullptr;
2833   }
2834 }
2835 
2836 void InstanceKlass::compute_has_loops_flag_for_methods() {
2837   Array<Method*>* methods = this->methods();
2838   for (int index = 0; index < methods->length(); ++index) {
2839     Method* m = methods->at(index);
2840     if (!m->is_overpass()) { // work around JDK-8305771
2841       m->compute_has_loops_flag();
2842     }
2843   }
2844 }
2845 
2846 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2847                                              PackageEntry* pkg_entry, TRAPS) {
2848   // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2849   // before the InstanceKlass is added to the SystemDictionary. Make
2850   // sure the current state is <loaded.
2851   assert(!is_loaded(), "invalid init state");
2852   assert(!shared_loading_failed(), "Must not try to load failed class again");
2853   set_package(loader_data, pkg_entry, CHECK);
2854   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2855 
2856   Array<Method*>* methods = this->methods();
2857   int num_methods = methods->length();
2858   for (int index = 0; index < num_methods; ++index) {
2859     methods->at(index)->restore_unshareable_info(CHECK);
2860   }
2861 #if INCLUDE_JVMTI
2862   if (JvmtiExport::has_redefined_a_class()) {
2863     // Reinitialize vtable because RedefineClasses may have changed some
2864     // entries in this vtable for super classes so the CDS vtable might
2865     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2866     // vtables in the shared system dictionary, only the main one.
2867     // It also redefines the itable too so fix that too.
2868     // First fix any default methods that point to a super class that may
2869     // have been redefined.
2870     bool trace_name_printed = false;
2871     adjust_default_methods(&trace_name_printed);
2872     if (verified_at_dump_time()) {
2873       // Initialize vtable and itable for classes which can be verified at dump time.
2874       // Unlinked classes such as old classes with major version < 50 cannot be verified
2875       // at dump time.
2876       vtable().initialize_vtable();
2877       itable().initialize_itable();
2878     }
2879   }
2880 #endif // INCLUDE_JVMTI
2881 
2882   // restore constant pool resolved references
2883   constants()->restore_unshareable_info(CHECK);
2884 
2885   if (array_klasses() != nullptr) {
2886     // To get a consistent list of classes we need MultiArray_lock to ensure
2887     // array classes aren't observed while they are being restored.
2888     RecursiveLocker rl(MultiArray_lock, THREAD);
2889     assert(this == array_klasses()->bottom_klass(), "sanity");
2890     // Array classes have null protection domain.
2891     // --> see ArrayKlass::complete_create_array_klass()
2892     array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2893   }
2894 
2895   // Initialize @ValueBased class annotation if not already set in the archived klass.
2896   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2897     set_is_value_based();
2898   }
2899 
2900   DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2901 }
2902 
2903 bool InstanceKlass::can_be_verified_at_dumptime() const {
2904   if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
2905     // This is a class that was dumped into the base archive, so we know
2906     // it was verified at dump time.
2907     return true;
2908   }
2909 
2910   if (CDSConfig::is_preserving_verification_constraints()) {
2911     return true;
2912   }
2913 
2914   if (CDSConfig::is_old_class_for_verifier(this)) {
2915     // The old verifier does not save verification constraints, so at run time
2916     // SystemDictionaryShared::check_verification_constraints() will not work for this class.
2917     return false;
2918   }
2919 
2920   if (CDSConfig::is_dumping_final_static_archive() && fail_over_verified()) {
2921     // This is a class with version >50 but was verified with the old verifier in the training run,
2922     // which had -XX:+AOTClassLinking. However, we are now in the assembly run with -XX:-AOTClassLinking.
2923     // As SystemDictionaryShared::check_verification_constraints() does not support this case,
2924     // we must exclude this class.
2925     assert(!CDSConfig::is_dumping_aot_linked_classes(), "must be");
2926     return false;
2927   }
2928 
2929   if (super() != nullptr && !super()->can_be_verified_at_dumptime()) {
2930     return false;
2931   }
2932   Array<InstanceKlass*>* interfaces = local_interfaces();
2933   int len = interfaces->length();
2934   for (int i = 0; i < len; i++) {
2935     if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2936       return false;
2937     }
2938   }
2939   return true;
2940 }
2941 
2942 #endif // INCLUDE_CDS
2943 
2944 #if INCLUDE_JVMTI
2945 static void clear_all_breakpoints(Method* m) {
2946   m->clear_all_breakpoints();
2947 }
2948 #endif
2949 
2950 void InstanceKlass::unload_class(InstanceKlass* ik) {
2951 
2952   if (ik->is_scratch_class()) {
2953     assert(ik->dependencies().is_empty(), "dependencies should be empty for scratch classes");
2954     return;
2955   }
2956   assert(ik->is_loaded(), "class should be loaded " PTR_FORMAT, p2i(ik));
2957 
2958   // Release dependencies.
2959   ik->dependencies().remove_all_dependents();
2960 
2961   // notify the debugger
2962   if (JvmtiExport::should_post_class_unload()) {
2963     JvmtiExport::post_class_unload(ik);
2964   }
2965 
2966   // notify ClassLoadingService of class unload
2967   ClassLoadingService::notify_class_unloaded(ik);
2968 
2969   SystemDictionaryShared::handle_class_unloading(ik);
2970 
2971   if (log_is_enabled(Info, class, unload)) {
2972     ResourceMark rm;
2973     log_info(class, unload)("unloading class %s " PTR_FORMAT, ik->external_name(), p2i(ik));
2974   }
2975 
2976   Events::log_class_unloading(Thread::current(), ik);
2977 
2978 #if INCLUDE_JFR
2979   assert(ik != nullptr, "invariant");
2980   EventClassUnload event;
2981   event.set_unloadedClass(ik);
2982   event.set_definingClassLoader(ik->class_loader_data());
2983   event.commit();
2984 #endif
2985 }
2986 
2987 static void method_release_C_heap_structures(Method* m) {
2988   m->release_C_heap_structures();
2989 }
2990 
2991 // Called also by InstanceKlass::deallocate_contents, with false for release_sub_metadata.
2992 void InstanceKlass::release_C_heap_structures(bool release_sub_metadata) {
2993   // Clean up C heap
2994   Klass::release_C_heap_structures();
2995 
2996   // Deallocate and call destructors for MDO mutexes
2997   if (release_sub_metadata) {
2998     methods_do(method_release_C_heap_structures);
2999   }
3000 
3001   // Deallocate oop map cache
3002   if (_oop_map_cache != nullptr) {
3003     delete _oop_map_cache;
3004     _oop_map_cache = nullptr;
3005   }
3006 
3007   // Deallocate JNI identifiers for jfieldIDs
3008   JNIid::deallocate(jni_ids());
3009   set_jni_ids(nullptr);
3010 
3011   jmethodID* jmeths = _methods_jmethod_ids;
3012   if (jmeths != nullptr) {
3013     release_set_methods_jmethod_ids(nullptr);
3014     FreeHeap(jmeths);
3015   }
3016 
3017   assert(_dep_context == nullptr,
3018          "dependencies should already be cleaned");
3019 
3020 #if INCLUDE_JVMTI
3021   // Deallocate breakpoint records
3022   if (breakpoints() != nullptr) {
3023     methods_do(clear_all_breakpoints);
3024     assert(breakpoints() == nullptr, "should have cleared breakpoints");
3025   }
3026 
3027   // deallocate the cached class file
3028   if (_cached_class_file != nullptr) {
3029     os::free(_cached_class_file);
3030     _cached_class_file = nullptr;
3031   }
3032 #endif
3033 
3034   FREE_C_HEAP_ARRAY(_source_debug_extension);
3035 
3036   if (release_sub_metadata) {
3037     constants()->release_C_heap_structures();
3038   }
3039 }
3040 
3041 // The constant pool is on stack if any of the methods are executing or
3042 // referenced by handles.
3043 bool InstanceKlass::on_stack() const {
3044   return _constants->on_stack();
3045 }
3046 
3047 Symbol* InstanceKlass::source_file_name() const               { return _constants->source_file_name(); }
3048 u2 InstanceKlass::source_file_name_index() const              { return _constants->source_file_name_index(); }
3049 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3050 
3051 // minor and major version numbers of class file
3052 u2 InstanceKlass::minor_version() const                 { return _constants->minor_version(); }
3053 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3054 u2 InstanceKlass::major_version() const                 { return _constants->major_version(); }
3055 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3056 
3057 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3058   for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3059     if (ik->constants()->version() == version) {
3060       return ik;
3061     }
3062   }
3063   return nullptr;
3064 }
3065 
3066 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3067   if (array == nullptr) {
3068     _source_debug_extension = nullptr;
3069   } else {
3070     // Adding one to the attribute length in order to store a null terminator
3071     // character could cause an overflow because the attribute length is
3072     // already coded with an u4 in the classfile, but in practice, it's
3073     // unlikely to happen.
3074     assert((length+1) > length, "Overflow checking");
3075     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3076     for (int i = 0; i < length; i++) {
3077       sde[i] = array[i];
3078     }
3079     sde[length] = '\0';
3080     _source_debug_extension = sde;
3081   }
3082 }
3083 
3084 Symbol* InstanceKlass::generic_signature() const                   { return _constants->generic_signature(); }
3085 u2 InstanceKlass::generic_signature_index() const                  { return _constants->generic_signature_index(); }
3086 void InstanceKlass::set_generic_signature_index(u2 sig_index)      { _constants->set_generic_signature_index(sig_index); }
3087 
3088 const char* InstanceKlass::signature_name() const {
3089 
3090   // Get the internal name as a c string
3091   const char* src = (const char*) (name()->as_C_string());
3092   const int src_length = (int)strlen(src);
3093 
3094   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3095 
3096   // Add L as type indicator
3097   int dest_index = 0;
3098   dest[dest_index++] = JVM_SIGNATURE_CLASS;
3099 
3100   // Add the actual class name
3101   for (int src_index = 0; src_index < src_length; ) {
3102     dest[dest_index++] = src[src_index++];
3103   }
3104 
3105   if (is_hidden()) { // Replace the last '+' with a '.'.
3106     for (int index = (int)src_length; index > 0; index--) {
3107       if (dest[index] == '+') {
3108         dest[index] = JVM_SIGNATURE_DOT;
3109         break;
3110       }
3111     }
3112   }
3113 
3114   // Add the semicolon and the null
3115   dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3116   dest[dest_index] = '\0';
3117   return dest;
3118 }
3119 
3120 ModuleEntry* InstanceKlass::module() const {
3121   if (is_hidden() &&
3122       in_unnamed_package() &&
3123       class_loader_data()->has_class_mirror_holder()) {
3124     // For a non-strong hidden class defined to an unnamed package,
3125     // its (class held) CLD will not have an unnamed module created for it.
3126     // Two choices to find the correct ModuleEntry:
3127     // 1. If hidden class is within a nest, use nest host's module
3128     // 2. Find the unnamed module off from the class loader
3129     // For now option #2 is used since a nest host is not set until
3130     // after the instance class is created in jvm_lookup_define_class().
3131     if (class_loader_data()->is_boot_class_loader_data()) {
3132       return ClassLoaderData::the_null_class_loader_data()->unnamed_module();
3133     } else {
3134       oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());
3135       assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");
3136       return java_lang_Module::module_entry(module);
3137     }
3138   }
3139 
3140   // Class is in a named package
3141   if (!in_unnamed_package()) {
3142     return _package_entry->module();
3143   }
3144 
3145   // Class is in an unnamed package, return its loader's unnamed module
3146   return class_loader_data()->unnamed_module();
3147 }
3148 
3149 bool InstanceKlass::in_javabase_module() const {
3150   return module()->name() == vmSymbols::java_base();
3151 }
3152 
3153 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {
3154 
3155   // ensure java/ packages only loaded by boot or platform builtin loaders
3156   // not needed for shared class since CDS does not archive prohibited classes.
3157   if (!in_aot_cache()) {
3158     check_prohibited_package(name(), loader_data, CHECK);
3159   }
3160 
3161   if (in_aot_cache() && _package_entry != nullptr) {
3162     if (CDSConfig::is_using_full_module_graph() && _package_entry == pkg_entry) {
3163       // we can use the saved package
3164       assert(AOTMetaspace::in_aot_cache(_package_entry), "must be");
3165       return;
3166     } else {
3167       _package_entry = nullptr;
3168     }
3169   }
3170 
3171   // ClassLoader::package_from_class_name has already incremented the refcount of the symbol
3172   // it returns, so we need to decrement it when the current function exits.
3173   TempNewSymbol from_class_name =
3174       (pkg_entry != nullptr) ? nullptr : ClassLoader::package_from_class_name(name());
3175 
3176   Symbol* pkg_name;
3177   if (pkg_entry != nullptr) {
3178     pkg_name = pkg_entry->name();
3179   } else {
3180     pkg_name = from_class_name;
3181   }
3182 
3183   if (pkg_name != nullptr && loader_data != nullptr) {
3184 
3185     // Find in class loader's package entry table.
3186     _package_entry = pkg_entry != nullptr ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);
3187 
3188     // If the package name is not found in the loader's package
3189     // entry table, it is an indication that the package has not
3190     // been defined. Consider it defined within the unnamed module.
3191     if (_package_entry == nullptr) {
3192 
3193       if (!ModuleEntryTable::javabase_defined()) {
3194         // Before java.base is defined during bootstrapping, define all packages in
3195         // the java.base module.  If a non-java.base package is erroneously placed
3196         // in the java.base module it will be caught later when java.base
3197         // is defined by ModuleEntryTable::verify_javabase_packages check.
3198         assert(ModuleEntryTable::javabase_moduleEntry() != nullptr, JAVA_BASE_NAME " module is null");
3199         _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, ModuleEntryTable::javabase_moduleEntry());
3200       } else {
3201         assert(loader_data->unnamed_module() != nullptr, "unnamed module is null");
3202         _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, loader_data->unnamed_module());
3203       }
3204 
3205       // A package should have been successfully created
3206       DEBUG_ONLY(ResourceMark rm(THREAD));
3207       assert(_package_entry != nullptr, "Package entry for class %s not found, loader %s",
3208              name()->as_C_string(), loader_data->loader_name_and_id());
3209     }
3210 
3211     if (log_is_enabled(Debug, module)) {
3212       ResourceMark rm(THREAD);
3213       ModuleEntry* m = _package_entry->module();
3214       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
3215                         external_name(),
3216                         pkg_name->as_C_string(),
3217                         loader_data->loader_name_and_id(),
3218                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
3219     }
3220   } else {
3221     ResourceMark rm(THREAD);
3222     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
3223                       external_name(),
3224                       (loader_data != nullptr) ? loader_data->loader_name_and_id() : "null",
3225                       UNNAMED_MODULE);
3226   }
3227 }
3228 
3229 // Function set_classpath_index ensures that for a non-null _package_entry
3230 // of the InstanceKlass, the entry is in the boot loader's package entry table.
3231 // It then sets the classpath_index in the package entry record.
3232 //
3233 // The classpath_index field is used to find the entry on the boot loader class
3234 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
3235 // in an unnamed module.  It is also used to indicate (for all packages whose
3236 // classes are loaded by the boot loader) that at least one of the package's
3237 // classes has been loaded.
3238 void InstanceKlass::set_classpath_index(s2 path_index) {
3239   if (_package_entry != nullptr) {
3240     DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)
3241     assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");
3242     assert(path_index != -1, "Unexpected classpath_index");
3243     _package_entry->set_classpath_index(path_index);
3244   }
3245 }
3246 
3247 // different versions of is_same_class_package
3248 
3249 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
3250   oop classloader1 = this->class_loader();
3251   PackageEntry* classpkg1 = this->package();
3252   if (class2->is_objArray_klass()) {
3253     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
3254   }
3255 
3256   oop classloader2;
3257   PackageEntry* classpkg2;
3258   if (class2->is_instance_klass()) {
3259     classloader2 = class2->class_loader();
3260     classpkg2 = class2->package();
3261   } else {
3262     assert(class2->is_typeArray_klass(), "should be type array");
3263     classloader2 = nullptr;
3264     classpkg2 = nullptr;
3265   }
3266 
3267   // Same package is determined by comparing class loader
3268   // and package entries. Both must be the same. This rule
3269   // applies even to classes that are defined in the unnamed
3270   // package, they still must have the same class loader.
3271   if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {
3272     return true;
3273   }
3274 
3275   return false;
3276 }
3277 
3278 // return true if this class and other_class are in the same package. Classloader
3279 // and classname information is enough to determine a class's package
3280 bool InstanceKlass::is_same_class_package(oop other_class_loader,
3281                                           const Symbol* other_class_name) const {
3282   if (class_loader() != other_class_loader) {
3283     return false;
3284   }
3285   if (name()->fast_compare(other_class_name) == 0) {
3286      return true;
3287   }
3288 
3289   {
3290     ResourceMark rm;
3291 
3292     bool bad_class_name = false;
3293     TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);
3294     if (bad_class_name) {
3295       return false;
3296     }
3297     // Check that package_from_class_name() returns null, not "", if there is no package.
3298     assert(other_pkg == nullptr || other_pkg->utf8_length() > 0, "package name is empty string");
3299 
3300     const Symbol* const this_package_name =
3301       this->package() != nullptr ? this->package()->name() : nullptr;
3302 
3303     if (this_package_name == nullptr || other_pkg == nullptr) {
3304       // One of the two doesn't have a package.  Only return true if the other
3305       // one also doesn't have a package.
3306       return this_package_name == other_pkg;
3307     }
3308 
3309     // Check if package is identical
3310     return this_package_name->fast_compare(other_pkg) == 0;
3311   }
3312 }
3313 
3314 static bool is_prohibited_package_slow(Symbol* class_name) {
3315   // Caller has ResourceMark
3316   int length;
3317   jchar* unicode = class_name->as_unicode(length);
3318   return (length >= 5 &&
3319           unicode[0] == 'j' &&
3320           unicode[1] == 'a' &&
3321           unicode[2] == 'v' &&
3322           unicode[3] == 'a' &&
3323           unicode[4] == '/');
3324 }
3325 
3326 // Only boot and platform class loaders can define classes in "java/" packages.
3327 void InstanceKlass::check_prohibited_package(Symbol* class_name,
3328                                              ClassLoaderData* loader_data,
3329                                              TRAPS) {
3330   if (!loader_data->is_boot_class_loader_data() &&
3331       !loader_data->is_platform_class_loader_data() &&
3332       class_name != nullptr && class_name->utf8_length() >= 5) {
3333     ResourceMark rm(THREAD);
3334     bool prohibited;
3335     const u1* base = class_name->base();
3336     if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {
3337       prohibited = is_prohibited_package_slow(class_name);
3338     } else {
3339       char* name = class_name->as_C_string();
3340       prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/');
3341     }
3342     if (prohibited) {
3343       TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
3344       assert(pkg_name != nullptr, "Error in parsing package name starting with 'java/'");
3345       char* name = pkg_name->as_C_string();
3346       const char* class_loader_name = loader_data->loader_name_and_id();
3347       StringUtils::replace_no_expand(name, "/", ".");
3348       const char* msg_text1 = "Class loader (instance of): ";
3349       const char* msg_text2 = " tried to load prohibited package name: ";
3350       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
3351       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
3352       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
3353       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
3354     }
3355   }
3356   return;
3357 }
3358 
3359 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3360   constantPoolHandle i_cp(THREAD, constants());
3361   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3362     int ioff = iter.inner_class_info_index();
3363     if (ioff != 0) {
3364       // Check to see if the name matches the class we're looking for
3365       // before attempting to find the class.
3366       if (i_cp->klass_name_at_matches(this, ioff)) {
3367         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3368         if (this == inner_klass) {
3369           *ooff = iter.outer_class_info_index();
3370           *noff = iter.inner_name_index();
3371           return true;
3372         }
3373       }
3374     }
3375   }
3376   return false;
3377 }
3378 
3379 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3380   InstanceKlass* outer_klass = nullptr;
3381   *inner_is_member = false;
3382   int ooff = 0, noff = 0;
3383   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3384   if (has_inner_classes_attr) {
3385     constantPoolHandle i_cp(THREAD, constants());
3386     if (ooff != 0) {
3387       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3388       if (!ok->is_instance_klass()) {
3389         // If the outer class is not an instance klass then it cannot have
3390         // declared any inner classes.
3391         ResourceMark rm(THREAD);
3392         // Names are all known to be < 64k so we know this formatted message is not excessively large.
3393         Exceptions::fthrow(
3394           THREAD_AND_LOCATION,
3395           vmSymbols::java_lang_IncompatibleClassChangeError(),
3396           "%s and %s disagree on InnerClasses attribute",
3397           ok->external_name(),
3398           external_name());
3399         return nullptr;
3400       }
3401       outer_klass = InstanceKlass::cast(ok);
3402       *inner_is_member = true;
3403     }
3404     if (nullptr == outer_klass) {
3405       // It may be a local class; try for that.
3406       int encl_method_class_idx = enclosing_method_class_index();
3407       if (encl_method_class_idx != 0) {
3408         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
3409         outer_klass = InstanceKlass::cast(ok);
3410         *inner_is_member = false;
3411       }
3412     }
3413   }
3414 
3415   // If no inner class attribute found for this class.
3416   if (nullptr == outer_klass) return nullptr;
3417 
3418   // Throws an exception if outer klass has not declared k as an inner klass
3419   // We need evidence that each klass knows about the other, or else
3420   // the system could allow a spoof of an inner class to gain access rights.
3421   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
3422   return outer_klass;
3423 }
3424 
3425 u2 InstanceKlass::compute_modifier_flags() const {
3426   u2 access = access_flags().as_unsigned_short();
3427 
3428   // But check if it happens to be member class.
3429   InnerClassesIterator iter(this);
3430   for (; !iter.done(); iter.next()) {
3431     int ioff = iter.inner_class_info_index();
3432     // Inner class attribute can be zero, skip it.
3433     // Strange but true:  JVM spec. allows null inner class refs.
3434     if (ioff == 0) continue;
3435 
3436     // only look at classes that are already loaded
3437     // since we are looking for the flags for our self.
3438     Symbol* inner_name = constants()->klass_name_at(ioff);
3439     if (name() == inner_name) {
3440       // This is really a member class.
3441       access = iter.inner_access_flags();
3442       break;
3443     }
3444   }
3445   // Remember to strip ACC_SUPER bit
3446   return (access & (~JVM_ACC_SUPER));
3447 }
3448 
3449 jint InstanceKlass::jvmti_class_status() const {
3450   jint result = 0;
3451 
3452   if (is_linked()) {
3453     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3454   }
3455 
3456   if (is_initialized()) {
3457     assert(is_linked(), "Class status is not consistent");
3458     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3459   }
3460   if (is_in_error_state()) {
3461     result |= JVMTI_CLASS_STATUS_ERROR;
3462   }
3463   return result;
3464 }
3465 
3466 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3467   bool implements_interface; // initialized by method_at_itable_or_null
3468   Method* m = method_at_itable_or_null(holder, index,
3469                                        implements_interface); // out parameter
3470   if (m != nullptr) {
3471     assert(implements_interface, "sanity");
3472     return m;
3473   } else if (implements_interface) {
3474     // Throw AbstractMethodError since corresponding itable slot is empty.
3475     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3476   } else {
3477     // If the interface isn't implemented by the receiver class,
3478     // the VM should throw IncompatibleClassChangeError.
3479     ResourceMark rm(THREAD);
3480     stringStream ss;
3481     bool same_module = (module() == holder->module());
3482     ss.print("Receiver class %s does not implement "
3483              "the interface %s defining the method to be called "
3484              "(%s%s%s)",
3485              external_name(), holder->external_name(),
3486              (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3487              (same_module) ? "" : "; ",
3488              (same_module) ? "" : holder->class_in_module_of_loader());
3489     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3490   }
3491 }
3492 
3493 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) {
3494   klassItable itable(this);
3495   for (int i = 0; i < itable.size_offset_table(); i++) {
3496     itableOffsetEntry* offset_entry = itable.offset_entry(i);
3497     if (offset_entry->interface_klass() == holder) {
3498       implements_interface = true;
3499       itableMethodEntry* ime = offset_entry->first_method_entry(this);
3500       Method* m = ime[index].method();
3501       return m;
3502     }
3503   }
3504   implements_interface = false;
3505   return nullptr; // offset entry not found
3506 }
3507 
3508 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) {
3509   assert(is_linked(), "required");
3510   assert(intf_method->method_holder()->is_interface(), "not an interface method");
3511   assert(is_subtype_of(intf_method->method_holder()), "interface not implemented");
3512 
3513   int vtable_index = Method::invalid_vtable_index;
3514   Symbol* name = intf_method->name();
3515   Symbol* signature = intf_method->signature();
3516 
3517   // First check in default method array
3518   if (!intf_method->is_abstract() && default_methods() != nullptr) {
3519     int index = find_method_index(default_methods(),
3520                                   name, signature,
3521                                   Klass::OverpassLookupMode::find,
3522                                   Klass::StaticLookupMode::find,
3523                                   Klass::PrivateLookupMode::find);
3524     if (index >= 0) {
3525       vtable_index = default_vtable_indices()->at(index);
3526     }
3527   }
3528   if (vtable_index == Method::invalid_vtable_index) {
3529     // get vtable_index for miranda methods
3530     klassVtable vt = vtable();
3531     vtable_index = vt.index_of_miranda(name, signature);
3532   }
3533   return vtable_index;
3534 }
3535 
3536 #if INCLUDE_JVMTI
3537 // update default_methods for redefineclasses for methods that are
3538 // not yet in the vtable due to concurrent subclass define and superinterface
3539 // redefinition
3540 // Note: those in the vtable, should have been updated via adjust_method_entries
3541 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3542   // search the default_methods for uses of either obsolete or EMCP methods
3543   if (default_methods() != nullptr) {
3544     for (int index = 0; index < default_methods()->length(); index ++) {
3545       Method* old_method = default_methods()->at(index);
3546       if (old_method == nullptr || !old_method->is_old()) {
3547         continue; // skip uninteresting entries
3548       }
3549       assert(!old_method->is_deleted(), "default methods may not be deleted");
3550       Method* new_method = old_method->get_new_method();
3551       default_methods()->at_put(index, new_method);
3552 
3553       if (log_is_enabled(Info, redefine, class, update)) {
3554         ResourceMark rm;
3555         if (!(*trace_name_printed)) {
3556           log_info(redefine, class, update)
3557             ("adjust: klassname=%s default methods from name=%s",
3558              external_name(), old_method->method_holder()->external_name());
3559           *trace_name_printed = true;
3560         }
3561         log_debug(redefine, class, update, vtables)
3562           ("default method update: %s(%s) ",
3563            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3564       }
3565     }
3566   }
3567 }
3568 #endif // INCLUDE_JVMTI
3569 
3570 // On-stack replacement stuff
3571 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3572   assert_lock_strong(NMethodState_lock);
3573 #ifndef PRODUCT
3574   nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3575   assert(prev == nullptr || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),
3576       "redundant OSR recompilation detected. memory leak in CodeCache!");
3577 #endif
3578   // only one compilation can be active
3579   assert(n->is_osr_method(), "wrong kind of nmethod");
3580   n->set_osr_link(osr_nmethods_head());
3581   set_osr_nmethods_head(n);
3582   // Raise the highest osr level if necessary
3583   n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level()));
3584 
3585   // Get rid of the osr methods for the same bci that have lower levels.
3586   for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3587     nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3588     if (inv != nullptr && inv->is_in_use()) {
3589       inv->make_not_entrant(nmethod::InvalidationReason::OSR_INVALIDATION_OF_LOWER_LEVEL);
3590     }
3591   }
3592 }
3593 
3594 // Remove osr nmethod from the list. Return true if found and removed.
3595 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3596   // This is a short non-blocking critical region, so the no safepoint check is ok.
3597   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
3598   assert(n->is_osr_method(), "wrong kind of nmethod");
3599   nmethod* last = nullptr;
3600   nmethod* cur  = osr_nmethods_head();
3601   int max_level = CompLevel_none;  // Find the max comp level excluding n
3602   Method* m = n->method();
3603   // Search for match
3604   bool found = false;
3605   while(cur != nullptr && cur != n) {
3606     if (m == cur->method()) {
3607       // Find max level before n
3608       max_level = MAX2(max_level, cur->comp_level());
3609     }
3610     last = cur;
3611     cur = cur->osr_link();
3612   }
3613   nmethod* next = nullptr;
3614   if (cur == n) {
3615     found = true;
3616     next = cur->osr_link();
3617     if (last == nullptr) {
3618       // Remove first element
3619       set_osr_nmethods_head(next);
3620     } else {
3621       last->set_osr_link(next);
3622     }
3623   }
3624   n->set_osr_link(nullptr);
3625   cur = next;
3626   while (cur != nullptr) {
3627     // Find max level after n
3628     if (m == cur->method()) {
3629       max_level = MAX2(max_level, cur->comp_level());
3630     }
3631     cur = cur->osr_link();
3632   }
3633   m->set_highest_osr_comp_level(max_level);
3634   return found;
3635 }
3636 
3637 int InstanceKlass::mark_osr_nmethods(DeoptimizationScope* deopt_scope, const Method* m) {
3638   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
3639   nmethod* osr = osr_nmethods_head();
3640   int found = 0;
3641   while (osr != nullptr) {
3642     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3643     if (osr->method() == m) {
3644       deopt_scope->mark(osr);
3645       found++;
3646     }
3647     osr = osr->osr_link();
3648   }
3649   return found;
3650 }
3651 
3652 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3653   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
3654   nmethod* osr = osr_nmethods_head();
3655   nmethod* best = nullptr;
3656   while (osr != nullptr) {
3657     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3658     // There can be a time when a c1 osr method exists but we are waiting
3659     // for a c2 version. When c2 completes its osr nmethod we will trash
3660     // the c1 version and only be able to find the c2 version. However
3661     // while we overflow in the c1 code at back branches we don't want to
3662     // try and switch to the same code as we are already running
3663 
3664     if (osr->method() == m &&
3665         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3666       if (match_level) {
3667         if (osr->comp_level() == comp_level) {
3668           // Found a match - return it.
3669           return osr;
3670         }
3671       } else {
3672         if (best == nullptr || (osr->comp_level() > best->comp_level())) {
3673           if (osr->comp_level() == CompilationPolicy::highest_compile_level()) {
3674             // Found the best possible - return it.
3675             return osr;
3676           }
3677           best = osr;
3678         }
3679       }
3680     }
3681     osr = osr->osr_link();
3682   }
3683 
3684   assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3685   if (best != nullptr && best->comp_level() >= comp_level) {
3686     return best;
3687   }
3688   return nullptr;
3689 }
3690 
3691 // -----------------------------------------------------------------------------------------------------
3692 // Printing
3693 
3694 #define BULLET  " - "
3695 
3696 static const char* state_names[] = {
3697   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3698 };
3699 
3700 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3701   for (int i = 0; i < len; i++) {
3702     intptr_t e = start[i];
3703     st->print("%d : " INTPTR_FORMAT, i, e);
3704     if (MetaspaceObj::is_valid((Metadata*)e)) {
3705       st->print(" ");
3706       ((Metadata*)e)->print_value_on(st);
3707     }
3708     st->cr();
3709   }
3710 }
3711 
3712 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3713   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3714 }
3715 
3716 const char* InstanceKlass::init_state_name() const {
3717   return state_names[init_state()];
3718 }
3719 
3720 void InstanceKlass::print_class_flags(outputStream* st) const {
3721   AccessFlags flags(compute_modifier_flags());
3722   if (flags.is_public    ()) st->print("public ");
3723   if (flags.is_private   ()) st->print("private ");
3724   if (flags.is_protected ()) st->print("protected ");
3725   if (flags.is_static    ()) st->print("static ");
3726   if (flags.is_final     ()) st->print("final ");
3727   if (flags.is_interface ()) st->print("interface ");
3728   if (flags.is_abstract  ()) st->print("abstract ");
3729   if (flags.is_annotation()) st->print("annotation ");
3730   if (flags.is_enum      ()) st->print("enum ");
3731   if (flags.is_synthetic ()) st->print("synthetic ");
3732 }
3733 
3734 void InstanceKlass::print_on(outputStream* st) const {
3735   assert(is_klass(), "must be klass");
3736   Klass::print_on(st);
3737 
3738   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3739   st->print(BULLET"klass size:        %d", size());                               st->cr();
3740   st->print(BULLET"access:            "); print_class_flags(st);                  st->cr();
3741   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3742   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3743   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3744   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3745   st->print(BULLET"sub:               ");
3746   Klass* sub = subklass();
3747   int n;
3748   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3749     if (n < MaxSubklassPrintSize) {
3750       sub->print_value_on(st);
3751       st->print("   ");
3752     }
3753   }
3754   if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3755   st->cr();
3756 
3757   if (is_interface()) {
3758     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3759     if (nof_implementors() == 1) {
3760       st->print_cr(BULLET"implementor:    ");
3761       st->print("   ");
3762       implementor()->print_value_on(st);
3763       st->cr();
3764     }
3765   }
3766 
3767   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3768   st->print(BULLET"methods:           "); methods()->print_value_on(st);               st->cr();
3769   if (Verbose || WizardMode) {
3770     Array<Method*>* method_array = methods();
3771     for (int i = 0; i < method_array->length(); i++) {
3772       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3773     }
3774   }
3775   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3776   if (default_methods() != nullptr) {
3777     st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);    st->cr();
3778     if (Verbose) {
3779       Array<Method*>* method_array = default_methods();
3780       for (int i = 0; i < method_array->length(); i++) {
3781         st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3782       }
3783     }
3784   }
3785   print_on_maybe_null(st, BULLET"default vtable indices:   ", default_vtable_indices());
3786   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3787   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3788 
3789   st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3790 
3791   st->print(BULLET"hash_slot:         %d", hash_slot()); st->cr();
3792   st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3793 
3794   if (secondary_supers() != nullptr) {
3795     if (Verbose) {
3796       bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3797       st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3798       for (int i = 0; i < _secondary_supers->length(); i++) {
3799         ResourceMark rm; // for external_name()
3800         Klass* secondary_super = _secondary_supers->at(i);
3801         st->print(BULLET"%2d:", i);
3802         if (is_hashed) {
3803           int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3804           int distance = (i - home_slot) & SECONDARY_SUPERS_TABLE_MASK;
3805           st->print(" dist:%02d:", distance);
3806         }
3807         st->print_cr(" %p %s", secondary_super, secondary_super->external_name());
3808       }
3809     }
3810   }
3811   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3812 
3813   print_on_maybe_null(st, BULLET"class loader data:  ", class_loader_data());
3814   print_on_maybe_null(st, BULLET"source file:       ", source_file_name());
3815   if (source_debug_extension() != nullptr) {
3816     st->print(BULLET"source debug extension:       ");
3817     st->print("%s", source_debug_extension());
3818     st->cr();
3819   }
3820   print_on_maybe_null(st, BULLET"class annotations:       ", class_annotations());
3821   print_on_maybe_null(st, BULLET"class type annotations:  ", class_type_annotations());
3822   print_on_maybe_null(st, BULLET"field annotations:       ", fields_annotations());
3823   print_on_maybe_null(st, BULLET"field type annotations:  ", fields_type_annotations());
3824   {
3825     bool have_pv = false;
3826     // previous versions are linked together through the InstanceKlass
3827     for (InstanceKlass* pv_node = previous_versions();
3828          pv_node != nullptr;
3829          pv_node = pv_node->previous_versions()) {
3830       if (!have_pv)
3831         st->print(BULLET"previous version:  ");
3832       have_pv = true;
3833       pv_node->constants()->print_value_on(st);
3834     }
3835     if (have_pv) st->cr();
3836   }
3837 
3838   print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3839   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3840   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3841   print_on_maybe_null(st, BULLET"record components:     ", record_components());
3842   st->print(BULLET"permitted subclasses:     "); permitted_subclasses()->print_value_on(st);     st->cr();
3843   if (java_mirror() != nullptr) {
3844     st->print(BULLET"java mirror:       ");
3845     java_mirror()->print_value_on(st);
3846     st->cr();
3847   } else {
3848     st->print_cr(BULLET"java mirror:       null");
3849   }
3850   st->print(BULLET"vtable length      %d  (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3851   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3852   st->print(BULLET"itable length      %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3853   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3854   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3855 
3856   FieldPrinter print_static_field(st);
3857   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3858   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3859   FieldPrinter print_nonstatic_field(st);
3860   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3861   ik->print_nonstatic_fields(&print_nonstatic_field);
3862 
3863   st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3864   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3865   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3866   while (map < end_map) {
3867     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3868     map++;
3869   }
3870   st->cr();
3871 
3872   if (fieldinfo_search_table() != nullptr) {
3873     st->print_cr(BULLET"---- field info search table:");
3874     FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
3875   }
3876 }
3877 
3878 void InstanceKlass::print_value_on(outputStream* st) const {
3879   assert(is_klass(), "must be klass");
3880   if (Verbose || WizardMode)  print_class_flags(st);
3881   name()->print_value_on(st);
3882 }
3883 
3884 void FieldPrinter::do_field(fieldDescriptor* fd) {
3885   _st->print(BULLET);
3886    if (_obj == nullptr) {
3887      fd->print_on(_st);
3888      _st->cr();
3889    } else {
3890      fd->print_on_for(_st, _obj);
3891      _st->cr();
3892    }
3893 }
3894 
3895 
3896 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3897   Klass::oop_print_on(obj, st);
3898 
3899   if (this == vmClasses::String_klass()) {
3900     typeArrayOop value  = java_lang_String::value(obj);
3901     juint        length = java_lang_String::length(obj);
3902     if (value != nullptr &&
3903         value->is_typeArray() &&
3904         length <= (juint) value->length()) {
3905       st->print(BULLET"string: ");
3906       java_lang_String::print(obj, st);
3907       st->cr();
3908     }
3909   }
3910 
3911   st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3912   FieldPrinter print_field(st, obj);
3913   print_nonstatic_fields(&print_field);
3914 
3915   if (this == vmClasses::Class_klass()) {
3916     st->print(BULLET"signature: ");
3917     java_lang_Class::print_signature(obj, st);
3918     st->cr();
3919     Klass* real_klass = java_lang_Class::as_Klass(obj);
3920     if (real_klass != nullptr && real_klass->is_instance_klass()) {
3921       st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3922       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3923     }
3924   } else if (this == vmClasses::MethodType_klass()) {
3925     st->print(BULLET"signature: ");
3926     java_lang_invoke_MethodType::print_signature(obj, st);
3927     st->cr();
3928   }
3929 }
3930 
3931 #ifndef PRODUCT
3932 
3933 bool InstanceKlass::verify_itable_index(int i) {
3934   int method_count = klassItable::method_count_for_interface(this);
3935   assert(i >= 0 && i < method_count, "index out of bounds");
3936   return true;
3937 }
3938 
3939 #endif //PRODUCT
3940 
3941 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3942   st->print("a ");
3943   name()->print_value_on(st);
3944   obj->print_address_on(st);
3945   if (this == vmClasses::String_klass()
3946       && java_lang_String::value(obj) != nullptr) {
3947     ResourceMark rm;
3948     int len = java_lang_String::length(obj);
3949     int plen = (len < 24 ? len : 12);
3950     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3951     st->print(" = \"%s\"", str);
3952     if (len > plen)
3953       st->print("...[%d]", len);
3954   } else if (this == vmClasses::Class_klass()) {
3955     Klass* k = java_lang_Class::as_Klass(obj);
3956     st->print(" = ");
3957     if (k != nullptr) {
3958       k->print_value_on(st);
3959     } else {
3960       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3961       st->print("%s", tname ? tname : "type?");
3962     }
3963   } else if (this == vmClasses::MethodType_klass()) {
3964     st->print(" = ");
3965     java_lang_invoke_MethodType::print_signature(obj, st);
3966   } else if (java_lang_boxing_object::is_instance(obj)) {
3967     st->print(" = ");
3968     java_lang_boxing_object::print(obj, st);
3969   } else if (this == vmClasses::LambdaForm_klass()) {
3970     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3971     if (vmentry != nullptr) {
3972       st->print(" => ");
3973       vmentry->print_value_on(st);
3974     }
3975   } else if (this == vmClasses::MemberName_klass()) {
3976     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3977     if (vmtarget != nullptr) {
3978       st->print(" = ");
3979       vmtarget->print_value_on(st);
3980     } else {
3981       oop clazz = java_lang_invoke_MemberName::clazz(obj);
3982       oop name  = java_lang_invoke_MemberName::name(obj);
3983       if (clazz != nullptr) {
3984         clazz->print_value_on(st);
3985       } else {
3986         st->print("null");
3987       }
3988       st->print(".");
3989       if (name != nullptr) {
3990         name->print_value_on(st);
3991       } else {
3992         st->print("null");
3993       }
3994     }
3995   }
3996 }
3997 
3998 const char* InstanceKlass::internal_name() const {
3999   return external_name();
4000 }
4001 
4002 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
4003                                              const ModuleEntry* module_entry,
4004                                              const ClassFileStream* cfs) const {
4005 
4006   if (ClassListWriter::is_enabled()) {
4007     ClassListWriter::write(this, cfs);
4008   }
4009 
4010   print_class_load_helper(loader_data, module_entry, cfs);
4011   print_class_load_cause_logging();
4012 }
4013 
4014 void InstanceKlass::print_class_load_helper(ClassLoaderData* loader_data,
4015                                              const ModuleEntry* module_entry,
4016                                              const ClassFileStream* cfs) const {
4017 
4018   if (!log_is_enabled(Info, class, load)) {
4019     return;
4020   }
4021 
4022   ResourceMark rm;
4023   LogMessage(class, load) msg;
4024   stringStream info_stream;
4025 
4026   // Name and class hierarchy info
4027   info_stream.print("%s", external_name());
4028 
4029   // Source
4030   if (cfs != nullptr) {
4031     if (cfs->source() != nullptr) {
4032       const char* module_name = (module_entry->name() == nullptr) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
4033       if (module_name != nullptr) {
4034         // When the boot loader created the stream, it didn't know the module name
4035         // yet. Let's format it now.
4036         if (cfs->from_boot_loader_modules_image()) {
4037           info_stream.print(" source: jrt:/%s", module_name);
4038         } else {
4039           info_stream.print(" source: %s", cfs->source());
4040         }
4041       } else {
4042         info_stream.print(" source: %s", cfs->source());
4043       }
4044     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
4045       Thread* current = Thread::current();
4046       Klass* caller = current->is_Java_thread() ?
4047         JavaThread::cast(current)->security_get_caller_class(1):
4048         nullptr;
4049       // caller can be null, for example, during a JVMTI VM_Init hook
4050       if (caller != nullptr) {
4051         info_stream.print(" source: instance of %s", caller->external_name());
4052       } else {
4053         // source is unknown
4054       }
4055     } else {
4056       oop class_loader = loader_data->class_loader();
4057       info_stream.print(" source: %s", class_loader->klass()->external_name());
4058     }
4059   } else {
4060     assert(this->in_aot_cache(), "must be");
4061     if (AOTMetaspace::in_aot_cache_dynamic_region((void*)this)) {
4062       info_stream.print(" source: shared objects file (top)");
4063     } else {
4064       info_stream.print(" source: shared objects file");
4065     }
4066   }
4067 
4068   msg.info("%s", info_stream.as_string());
4069 
4070   if (log_is_enabled(Debug, class, load)) {
4071     stringStream debug_stream;
4072 
4073     // Class hierarchy info
4074     debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
4075                        p2i(this),  p2i(super()));
4076 
4077     // Interfaces
4078     if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
4079       debug_stream.print(" interfaces:");
4080       int length = local_interfaces()->length();
4081       for (int i = 0; i < length; i++) {
4082         debug_stream.print(" " PTR_FORMAT,
4083                            p2i(local_interfaces()->at(i)));
4084       }
4085     }
4086 
4087     // Class loader
4088     debug_stream.print(" loader: [");
4089     loader_data->print_value_on(&debug_stream);
4090     debug_stream.print("]");
4091 
4092     // Classfile checksum
4093     if (cfs) {
4094       debug_stream.print(" bytes: %d checksum: %08x",
4095                          cfs->length(),
4096                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
4097                          cfs->length()));
4098     }
4099 
4100     msg.debug("%s", debug_stream.as_string());
4101   }
4102 }
4103 
4104 void InstanceKlass::print_class_load_cause_logging() const {
4105   bool log_cause_native = log_is_enabled(Info, class, load, cause, native);
4106   if (log_cause_native || log_is_enabled(Info, class, load, cause)) {
4107     JavaThread* current = JavaThread::current();
4108     ResourceMark rm(current);
4109     const char* name = external_name();
4110 
4111     if (LogClassLoadingCauseFor == nullptr ||
4112         (strcmp("*", LogClassLoadingCauseFor) != 0 &&
4113          strstr(name, LogClassLoadingCauseFor) == nullptr)) {
4114         return;
4115     }
4116 
4117     // Log Java stack first
4118     {
4119       LogMessage(class, load, cause) msg;
4120       NonInterleavingLogStream info_stream{LogLevelType::Info, msg};
4121 
4122       info_stream.print_cr("Java stack when loading %s:", name);
4123       current->print_stack_on(&info_stream);
4124     }
4125 
4126     // Log native stack second
4127     if (log_cause_native) {
4128       // Log to string first so that lines can be indented
4129       stringStream stack_stream;
4130       char buf[O_BUFLEN];
4131       address lastpc = nullptr;
4132       NativeStackPrinter nsp(current);
4133       nsp.print_stack(&stack_stream, buf, sizeof(buf), lastpc,
4134                       true /* print_source_info */, -1 /* max stack */);
4135 
4136       LogMessage(class, load, cause, native) msg;
4137       NonInterleavingLogStream info_stream{LogLevelType::Info, msg};
4138       info_stream.print_cr("Native stack when loading %s:", name);
4139 
4140       // Print each native stack line to the log
4141       int size = (int) stack_stream.size();
4142       char* stack = stack_stream.as_string();
4143       char* stack_end = stack + size;
4144       char* line_start = stack;
4145       for (char* p = stack; p < stack_end; p++) {
4146         if (*p == '\n') {
4147           *p = '\0';
4148           info_stream.print_cr("\t%s", line_start);
4149           line_start = p + 1;
4150         }
4151       }
4152       if (line_start < stack_end) {
4153         info_stream.print_cr("\t%s", line_start);
4154       }
4155     }
4156   }
4157 }
4158 
4159 // Verification
4160 
4161 class VerifyFieldClosure: public BasicOopIterateClosure {
4162  protected:
4163   template <class T> void do_oop_work(T* p) {
4164     oop obj = RawAccess<>::oop_load(p);
4165     if (!oopDesc::is_oop_or_null(obj)) {
4166       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
4167       Universe::print_on(tty);
4168       guarantee(false, "boom");
4169     }
4170   }
4171  public:
4172   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
4173   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
4174 };
4175 
4176 void InstanceKlass::verify_on(outputStream* st) {
4177 #ifndef PRODUCT
4178   // Avoid redundant verifies, this really should be in product.
4179   if (_verify_count == Universe::verify_count()) return;
4180   _verify_count = Universe::verify_count();
4181 #endif
4182 
4183   // Verify Klass
4184   Klass::verify_on(st);
4185 
4186   // Verify that klass is present in ClassLoaderData
4187   guarantee(class_loader_data()->contains_klass(this),
4188             "this class isn't found in class loader data");
4189 
4190   // Verify vtables
4191   if (is_linked()) {
4192     // $$$ This used to be done only for m/s collections.  Doing it
4193     // always seemed a valid generalization.  (DLD -- 6/00)
4194     vtable().verify(st);
4195   }
4196 
4197   // Verify first subklass
4198   if (subklass() != nullptr) {
4199     guarantee(subklass()->is_klass(), "should be klass");
4200   }
4201 
4202   // Verify siblings
4203   Klass* super = this->super();
4204   Klass* sib = next_sibling();
4205   if (sib != nullptr) {
4206     if (sib == this) {
4207       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
4208     }
4209 
4210     guarantee(sib->is_klass(), "should be klass");
4211     guarantee(sib->super() == super, "siblings should have same superklass");
4212   }
4213 
4214   // Verify local interfaces
4215   if (local_interfaces()) {
4216     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
4217     for (int j = 0; j < local_interfaces->length(); j++) {
4218       InstanceKlass* e = local_interfaces->at(j);
4219       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
4220     }
4221   }
4222 
4223   // Verify transitive interfaces
4224   if (transitive_interfaces() != nullptr) {
4225     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
4226     for (int j = 0; j < transitive_interfaces->length(); j++) {
4227       InstanceKlass* e = transitive_interfaces->at(j);
4228       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
4229     }
4230   }
4231 
4232   // Verify methods
4233   if (methods() != nullptr) {
4234     Array<Method*>* methods = this->methods();
4235     for (int j = 0; j < methods->length(); j++) {
4236       guarantee(methods->at(j)->is_method(), "non-method in methods array");
4237     }
4238     for (int j = 0; j < methods->length() - 1; j++) {
4239       Method* m1 = methods->at(j);
4240       Method* m2 = methods->at(j + 1);
4241       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
4242     }
4243   }
4244 
4245   // Verify method ordering
4246   if (method_ordering() != nullptr) {
4247     Array<int>* method_ordering = this->method_ordering();
4248     int length = method_ordering->length();
4249     if (JvmtiExport::can_maintain_original_method_order() ||
4250         ((CDSConfig::is_using_archive() || CDSConfig::is_dumping_archive()) && length != 0)) {
4251       guarantee(length == methods()->length(), "invalid method ordering length");
4252       jlong sum = 0;
4253       for (int j = 0; j < length; j++) {
4254         int original_index = method_ordering->at(j);
4255         guarantee(original_index >= 0, "invalid method ordering index");
4256         guarantee(original_index < length, "invalid method ordering index");
4257         sum += original_index;
4258       }
4259       // Verify sum of indices 0,1,...,length-1
4260       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
4261     } else {
4262       guarantee(length == 0, "invalid method ordering length");
4263     }
4264   }
4265 
4266   // Verify default methods
4267   if (default_methods() != nullptr) {
4268     Array<Method*>* methods = this->default_methods();
4269     for (int j = 0; j < methods->length(); j++) {
4270       guarantee(methods->at(j)->is_method(), "non-method in methods array");
4271     }
4272     for (int j = 0; j < methods->length() - 1; j++) {
4273       Method* m1 = methods->at(j);
4274       Method* m2 = methods->at(j + 1);
4275       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
4276     }
4277   }
4278 
4279   // Verify JNI static field identifiers
4280   if (jni_ids() != nullptr) {
4281     jni_ids()->verify(this);
4282   }
4283 
4284   // Verify other fields
4285   if (constants() != nullptr) {
4286     guarantee(constants()->is_constantPool(), "should be constant pool");
4287   }
4288 }
4289 
4290 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
4291   Klass::oop_verify_on(obj, st);
4292   VerifyFieldClosure blk;
4293   obj->oop_iterate(&blk);
4294 }
4295 
4296 // JNIid class for jfieldIDs only
4297 // Note to reviewers:
4298 // These JNI functions are just moved over to column 1 and not changed
4299 // in the compressed oops workspace.
4300 JNIid::JNIid(InstanceKlass* holder, int offset, JNIid* next) {
4301   _holder = holder;
4302   _offset = offset;
4303   _next = next;
4304   DEBUG_ONLY(_is_static_field_id = false;)
4305 }
4306 
4307 JNIid* JNIid::find(int offset) {
4308   JNIid* current = this;
4309   while (current != nullptr) {
4310     if (current->offset() == offset) return current;
4311     current = current->next();
4312   }
4313   return nullptr;
4314 }
4315 
4316 void JNIid::deallocate(JNIid* current) {
4317   while (current != nullptr) {
4318     JNIid* next = current->next();
4319     delete current;
4320     current = next;
4321   }
4322 }
4323 
4324 void JNIid::verify(InstanceKlass* holder) {
4325   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
4326   int end_field_offset;
4327   end_field_offset = first_field_offset + (holder->static_field_size() * wordSize);
4328 
4329   JNIid* current = this;
4330   while (current != nullptr) {
4331     guarantee(current->holder() == holder, "Invalid klass in JNIid");
4332 #ifdef ASSERT
4333     int o = current->offset();
4334     if (current->is_static_field_id()) {
4335       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
4336     }
4337 #endif
4338     current = current->next();
4339   }
4340 }
4341 
4342 void InstanceKlass::set_init_state(ClassState state) {
4343 #ifdef ASSERT
4344   bool good_state = in_aot_cache() ? (_init_state <= state)
4345                                                : (_init_state < state);
4346   assert(good_state || state == allocated, "illegal state transition");
4347 #endif
4348   assert(_init_thread == nullptr, "should be cleared before state change");
4349   AtomicAccess::release_store(&_init_state, state);
4350 }
4351 
4352 #if INCLUDE_JVMTI
4353 
4354 // RedefineClasses() support for previous versions
4355 
4356 // Globally, there is at least one previous version of a class to walk
4357 // during class unloading, which is saved because old methods in the class
4358 // are still running.   Otherwise the previous version list is cleaned up.
4359 bool InstanceKlass::_should_clean_previous_versions = false;
4360 
4361 // Returns true if there are previous versions of a class for class
4362 // unloading only. Also resets the flag to false. purge_previous_version
4363 // will set the flag to true if there are any left, i.e., if there's any
4364 // work to do for next time. This is to avoid the expensive code cache
4365 // walk in CLDG::clean_deallocate_lists().
4366 bool InstanceKlass::should_clean_previous_versions_and_reset() {
4367   bool ret = _should_clean_previous_versions;
4368   log_trace(redefine, class, iklass, purge)("Class unloading: should_clean_previous_versions = %s",
4369      ret ? "true" : "false");
4370   _should_clean_previous_versions = false;
4371   return ret;
4372 }
4373 
4374 // This nulls out the jmethodID for all obsolete methods in the previous version of the 'klass'.
4375 // These obsolete methods only exist in the previous version and we're about to delete the memory for them.
4376 // The jmethodID for these are deallocated when we unload the class, so this doesn't remove them from the table.
4377 void InstanceKlass::clear_obsolete_jmethod_ids(InstanceKlass* klass) {
4378   Array<Method*>* method_refs = klass->methods();
4379   for (int k = 0; k < method_refs->length(); k++) {
4380     Method* method = method_refs->at(k);
4381     // Only need to clear obsolete methods.
4382     if (method != nullptr && method->is_obsolete()) {
4383       method->clear_jmethod_id();
4384     }
4385   }
4386 }
4387 
4388 // Purge previous versions before adding new previous versions of the class and
4389 // during class unloading.
4390 void InstanceKlass::purge_previous_version_list() {
4391   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
4392   assert(has_been_redefined(), "Should only be called for main class");
4393 
4394   // Quick exit.
4395   if (previous_versions() == nullptr) {
4396     return;
4397   }
4398 
4399   // This klass has previous versions so see what we can cleanup
4400   // while it is safe to do so.
4401 
4402   int deleted_count = 0;    // leave debugging breadcrumbs
4403   int live_count = 0;
4404   ClassLoaderData* loader_data = class_loader_data();
4405   assert(loader_data != nullptr, "should never be null");
4406 
4407   ResourceMark rm;
4408   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
4409 
4410   // previous versions are linked together through the InstanceKlass
4411   InstanceKlass* pv_node = previous_versions();
4412   InstanceKlass* last = this;
4413   int version = 0;
4414 
4415   // check the previous versions list
4416   for (; pv_node != nullptr; ) {
4417 
4418     ConstantPool* pvcp = pv_node->constants();
4419     assert(pvcp != nullptr, "cp ref was unexpectedly cleared");
4420 
4421     if (!pvcp->on_stack()) {
4422       // If the constant pool isn't on stack, none of the methods
4423       // are executing.  Unlink this previous_version.
4424       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
4425       // so will be deallocated during the next phase of class unloading.
4426       log_trace(redefine, class, iklass, purge)
4427         ("previous version " PTR_FORMAT " is dead.", p2i(pv_node));
4428       // Unlink from previous version list.
4429       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
4430       InstanceKlass* next = pv_node->previous_versions();
4431       clear_obsolete_jmethod_ids(pv_node); // jmethodID maintenance for the unloaded class
4432       pv_node->link_previous_versions(nullptr);   // point next to null
4433       last->link_previous_versions(next);
4434       // Delete this node directly. Nothing is referring to it and we don't
4435       // want it to increase the counter for metadata to delete in CLDG.
4436       MetadataFactory::free_metadata(loader_data, pv_node);
4437       pv_node = next;
4438       deleted_count++;
4439       version++;
4440       continue;
4441     } else {
4442       assert(pvcp->pool_holder() != nullptr, "Constant pool with no holder");
4443       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
4444       live_count++;
4445       if (pvcp->in_aot_cache()) {
4446         // Shared previous versions can never be removed so no cleaning is needed.
4447         log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is shared", p2i(pv_node));
4448       } else {
4449         // Previous version alive, set that clean is needed for next time.
4450         _should_clean_previous_versions = true;
4451         log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is alive", p2i(pv_node));
4452       }
4453     }
4454 
4455     // next previous version
4456     last = pv_node;
4457     pv_node = pv_node->previous_versions();
4458     version++;
4459   }
4460   log_trace(redefine, class, iklass, purge)
4461     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
4462 }
4463 
4464 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
4465                                                 int emcp_method_count) {
4466   int obsolete_method_count = old_methods->length() - emcp_method_count;
4467 
4468   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
4469       _previous_versions != nullptr) {
4470     // We have a mix of obsolete and EMCP methods so we have to
4471     // clear out any matching EMCP method entries the hard way.
4472     int local_count = 0;
4473     for (int i = 0; i < old_methods->length(); i++) {
4474       Method* old_method = old_methods->at(i);
4475       if (old_method->is_obsolete()) {
4476         // only obsolete methods are interesting
4477         Symbol* m_name = old_method->name();
4478         Symbol* m_signature = old_method->signature();
4479 
4480         // previous versions are linked together through the InstanceKlass
4481         int j = 0;
4482         for (InstanceKlass* prev_version = _previous_versions;
4483              prev_version != nullptr;
4484              prev_version = prev_version->previous_versions(), j++) {
4485 
4486           Array<Method*>* method_refs = prev_version->methods();
4487           for (int k = 0; k < method_refs->length(); k++) {
4488             Method* method = method_refs->at(k);
4489 
4490             if (!method->is_obsolete() &&
4491                 method->name() == m_name &&
4492                 method->signature() == m_signature) {
4493               // The current RedefineClasses() call has made all EMCP
4494               // versions of this method obsolete so mark it as obsolete
4495               log_trace(redefine, class, iklass, add)
4496                 ("%s(%s): flush obsolete method @%d in version @%d",
4497                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
4498 
4499               method->set_is_obsolete();
4500               break;
4501             }
4502           }
4503 
4504           // The previous loop may not find a matching EMCP method, but
4505           // that doesn't mean that we can optimize and not go any
4506           // further back in the PreviousVersion generations. The EMCP
4507           // method for this generation could have already been made obsolete,
4508           // but there still may be an older EMCP method that has not
4509           // been made obsolete.
4510         }
4511 
4512         if (++local_count >= obsolete_method_count) {
4513           // no more obsolete methods so bail out now
4514           break;
4515         }
4516       }
4517     }
4518   }
4519 }
4520 
4521 // Save the scratch_class as the previous version if any of the methods are running.
4522 // The previous_versions are used to set breakpoints in EMCP methods and they are
4523 // also used to clean MethodData links to redefined methods that are no longer running.
4524 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4525                                          int emcp_method_count) {
4526   assert(Thread::current()->is_VM_thread(),
4527          "only VMThread can add previous versions");
4528 
4529   ResourceMark rm;
4530   log_trace(redefine, class, iklass, add)
4531     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4532 
4533   // Clean out old previous versions for this class
4534   purge_previous_version_list();
4535 
4536   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
4537   // a previous redefinition may be made obsolete by this redefinition.
4538   Array<Method*>* old_methods = scratch_class->methods();
4539   mark_newly_obsolete_methods(old_methods, emcp_method_count);
4540 
4541   // If the constant pool for this previous version of the class
4542   // is not marked as being on the stack, then none of the methods
4543   // in this previous version of the class are on the stack so
4544   // we don't need to add this as a previous version.
4545   ConstantPool* cp_ref = scratch_class->constants();
4546   if (!cp_ref->on_stack()) {
4547     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4548     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4549     return;
4550   }
4551 
4552   // Add previous version if any methods are still running or if this is
4553   // a shared class which should never be removed.
4554   assert(scratch_class->previous_versions() == nullptr, "shouldn't have a previous version");
4555   scratch_class->link_previous_versions(previous_versions());
4556   link_previous_versions(scratch_class);
4557   if (cp_ref->in_aot_cache()) {
4558     log_trace(redefine, class, iklass, add) ("scratch class added; class is shared");
4559   } else {
4560     //  We only set clean_previous_versions flag for processing during class
4561     // unloading for non-shared classes.
4562     _should_clean_previous_versions = true;
4563     log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4564   }
4565 } // end add_previous_version()
4566 
4567 #endif // INCLUDE_JVMTI
4568 
4569 Method* InstanceKlass::method_with_idnum(int idnum) const {
4570   Method* m = nullptr;
4571   if (idnum < methods()->length()) {
4572     m = methods()->at(idnum);
4573   }
4574   if (m == nullptr || m->method_idnum() != idnum) {
4575     for (int index = 0; index < methods()->length(); ++index) {
4576       m = methods()->at(index);
4577       if (m->method_idnum() == idnum) {
4578         return m;
4579       }
4580     }
4581     // None found, return null for the caller to handle.
4582     return nullptr;
4583   }
4584   return m;
4585 }
4586 
4587 
4588 Method* InstanceKlass::method_with_orig_idnum(int idnum) const {
4589   if (idnum >= methods()->length()) {
4590     return nullptr;
4591   }
4592   Method* m = methods()->at(idnum);
4593   if (m != nullptr && m->orig_method_idnum() == idnum) {
4594     return m;
4595   }
4596   // Obsolete method idnum does not match the original idnum
4597   for (int index = 0; index < methods()->length(); ++index) {
4598     m = methods()->at(index);
4599     if (m->orig_method_idnum() == idnum) {
4600       return m;
4601     }
4602   }
4603   // None found, return null for the caller to handle.
4604   return nullptr;
4605 }
4606 
4607 
4608 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) const {
4609   const InstanceKlass* holder = get_klass_version(version);
4610   if (holder == nullptr) {
4611     return nullptr; // The version of klass is gone, no method is found
4612   }
4613   return holder->method_with_orig_idnum(idnum);
4614 }
4615 
4616 #if INCLUDE_JVMTI
4617 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4618   return _cached_class_file;
4619 }
4620 
4621 jint InstanceKlass::get_cached_class_file_len() {
4622   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4623 }
4624 
4625 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4626   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4627 }
4628 #endif
4629 
4630 // Make a step iterating over the class hierarchy under the root class.
4631 // Skips subclasses if requested.
4632 void ClassHierarchyIterator::next() {
4633   assert(_current != nullptr, "required");
4634   if (_visit_subclasses && _current->subklass() != nullptr) {
4635     _current = _current->subklass();
4636     return; // visit next subclass
4637   }
4638   _visit_subclasses = true; // reset
4639   while (_current->next_sibling() == nullptr && _current != _root) {
4640     _current = _current->java_super(); // backtrack; no more sibling subclasses left
4641   }
4642   if (_current == _root) {
4643     // Iteration is over (back at root after backtracking). Invalidate the iterator.
4644     _current = nullptr;
4645     return;
4646   }
4647   _current = _current->next_sibling();
4648   return; // visit next sibling subclass
4649 }