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