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