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