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