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