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