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