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