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