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