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