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