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