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