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