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