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