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