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