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