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