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