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