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