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