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