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