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