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