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