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