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