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