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