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