1 /*
   2  * Copyright (c) 1997, 2026, 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 #ifndef SHARE_OOPS_INSTANCEKLASS_HPP
  26 #define SHARE_OOPS_INSTANCEKLASS_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "memory/referenceType.hpp"
  30 #include "oops/annotations.hpp"
  31 #include "oops/constMethod.hpp"
  32 #include "oops/fieldInfo.hpp"
  33 #include "oops/instanceKlassFlags.hpp"
  34 #include "oops/instanceOop.hpp"
  35 #include "runtime/handles.hpp"
  36 #include "runtime/javaThread.hpp"
  37 #include "utilities/accessFlags.hpp"
  38 #include "utilities/align.hpp"
  39 #include "utilities/growableArray.hpp"
  40 #include "utilities/macros.hpp"
  41 #if INCLUDE_JFR
  42 #include "jfr/support/jfrKlassExtension.hpp"
  43 #endif
  44 
  45 class ConstantPool;
  46 class DeoptimizationScope;
  47 class klassItable;
  48 class RecordComponent;
  49 
  50 // An InstanceKlass is the VM level representation of a Java class.
  51 // It contains all information needed for at class at execution runtime.
  52 
  53 //  InstanceKlass embedded field layout (after declared fields):
  54 //    [EMBEDDED Java vtable             ] size in words = vtable_len
  55 //    [EMBEDDED nonstatic oop-map blocks] size in words = nonstatic_oop_map_size
  56 //      The embedded nonstatic oop-map blocks are short pairs (offset, length)
  57 //      indicating where oops are located in instances of this klass.
  58 //    [EMBEDDED implementor of the interface] only exist for interface
  59 
  60 
  61 // forward declaration for class -- see below for definition
  62 #if INCLUDE_JVMTI
  63 class BreakpointInfo;
  64 #endif
  65 class ClassFileParser;
  66 class ClassFileStream;
  67 class KlassDepChange;
  68 class DependencyContext;
  69 class fieldDescriptor;
  70 class JNIid;
  71 class JvmtiCachedClassFieldMap;
  72 class nmethodBucket;
  73 class OopMapCache;
  74 class InterpreterOopMap;
  75 class PackageEntry;
  76 class ModuleEntry;
  77 
  78 // This is used in iterators below.
  79 class FieldClosure: public StackObj {
  80 public:
  81   virtual void do_field(fieldDescriptor* fd) = 0;
  82 };
  83 
  84 // Print fields.
  85 // If "obj" argument to constructor is null, prints static fields, otherwise prints non-static fields.
  86 class FieldPrinter: public FieldClosure {
  87    oop _obj;
  88    outputStream* _st;
  89  public:
  90    FieldPrinter(outputStream* st, oop obj = nullptr) : _obj(obj), _st(st) {}
  91    void do_field(fieldDescriptor* fd);
  92 };
  93 
  94 // Describes where oops are located in instances of this klass.
  95 class OopMapBlock {
  96  public:
  97   // Byte offset of the first oop mapped by this block.
  98   int offset() const          { return _offset; }
  99   void set_offset(int offset) { _offset = offset; }
 100 
 101   // Number of oops in this block.
 102   uint count() const         { return _count; }
 103   void set_count(uint count) { _count = count; }
 104 
 105   void increment_count(int diff) { _count += diff; }
 106 
 107   int offset_span() const { return _count * heapOopSize; }
 108 
 109   int end_offset() const {
 110     return offset() + offset_span();
 111   }
 112 
 113   bool is_contiguous(int another_offset) const {
 114     return another_offset == end_offset();
 115   }
 116 
 117   // sizeof(OopMapBlock) in words.
 118   static int size_in_words() {
 119     return align_up((int)sizeof(OopMapBlock), wordSize) >>
 120       LogBytesPerWord;
 121   }
 122 
 123   static int compare_offset(const OopMapBlock* a, const OopMapBlock* b) {
 124     return a->offset() - b->offset();
 125   }
 126 
 127  private:
 128   int  _offset;
 129   uint _count;
 130 };
 131 
 132 struct JvmtiCachedClassFileData;
 133 
 134 class InstanceKlass: public Klass {
 135   friend class VMStructs;
 136   friend class ClassFileParser;
 137   friend class CompileReplay;
 138 
 139  public:
 140   static const KlassKind Kind = InstanceKlassKind;
 141 
 142  protected:
 143   InstanceKlass(const ClassFileParser& parser, KlassKind kind = Kind, ReferenceType reference_type = REF_NONE);
 144 
 145  public:
 146   InstanceKlass();
 147 
 148   // See "The Java Virtual Machine Specification" section 2.16.2-5 for a detailed description
 149   // of the class loading & initialization procedure, and the use of the states.
 150   enum ClassState : u1 {
 151     allocated,                          // allocated (but not yet linked)
 152     loaded,                             // loaded and inserted in class hierarchy (but not linked yet)
 153     linked,                             // successfully linked/verified (but not initialized yet)
 154     being_initialized,                  // currently running class initializer
 155     fully_initialized,                  // initialized (successful final state)
 156     initialization_error                // error happened during initialization
 157   };
 158 
 159  private:
 160   static InstanceKlass* allocate_instance_klass(const ClassFileParser& parser, TRAPS);
 161 
 162  protected:
 163   // If you add a new field that points to any metaspace object, you
 164   // must add this field to InstanceKlass::metaspace_pointers_do().
 165 
 166   // Annotations for this class
 167   Annotations*    _annotations;
 168   // Package this class is defined in
 169   PackageEntry*   _package_entry;
 170   // Array classes holding elements of this class.
 171   ObjArrayKlass* volatile _array_klasses;
 172   // Constant pool for this class.
 173   ConstantPool* _constants;
 174   // The InnerClasses attribute and EnclosingMethod attribute. The
 175   // _inner_classes is an array of shorts. If the class has InnerClasses
 176   // attribute, then the _inner_classes array begins with 4-tuples of shorts
 177   // [inner_class_info_index, outer_class_info_index,
 178   // inner_name_index, inner_class_access_flags] for the InnerClasses
 179   // attribute. If the EnclosingMethod attribute exists, it occupies the
 180   // last two shorts [class_index, method_index] of the array. If only
 181   // the InnerClasses attribute exists, the _inner_classes array length is
 182   // number_of_inner_classes * 4. If the class has both InnerClasses
 183   // and EnclosingMethod attributes the _inner_classes array length is
 184   // number_of_inner_classes * 4 + enclosing_method_attribute_size.
 185   Array<jushort>* _inner_classes;
 186 
 187   // The NestMembers attribute. An array of shorts, where each is a
 188   // class info index for the class that is a nest member. This data
 189   // has not been validated.
 190   Array<jushort>* _nest_members;
 191 
 192   // Resolved nest-host klass: either true nest-host or self if we are not
 193   // nested, or an error occurred resolving or validating the nominated
 194   // nest-host. Can also be set directly by JDK API's that establish nest
 195   // relationships.
 196   // By always being set it makes nest-member access checks simpler.
 197   InstanceKlass* _nest_host;
 198 
 199   // The PermittedSubclasses attribute. An array of shorts, where each is a
 200   // class info index for the class that is a permitted subclass.
 201   Array<jushort>* _permitted_subclasses;
 202 
 203   // The contents of the Record attribute.
 204   Array<RecordComponent*>* _record_components;
 205 
 206   // the source debug extension for this klass, null if not specified.
 207   // Specified as UTF-8 string without terminating zero byte in the classfile,
 208   // it is stored in the instanceklass as a null-terminated UTF-8 string
 209   const char*     _source_debug_extension;
 210 
 211   // Number of heapOopSize words used by non-static fields in this klass
 212   // (including inherited fields but after header_size()).
 213   int             _nonstatic_field_size;
 214   int             _static_field_size;       // number words used by static fields (oop and non-oop) in this klass
 215   int             _nonstatic_oop_map_size;  // size in words of nonstatic oop map blocks
 216   int             _itable_len;              // length of Java itable (in words)
 217 
 218   // The NestHost attribute. The class info index for the class
 219   // that is the nest-host of this class. This data has not been validated.
 220   u2              _nest_host_index;
 221   u2              _this_class_index;        // constant pool entry
 222   u2              _static_oop_field_count;  // number of static oop fields in this klass
 223 
 224   volatile u2     _idnum_allocated_count;   // JNI/JVMTI: increments with the addition of methods, old ids don't change
 225 
 226   // Class states are defined as ClassState (see above).
 227   // Place the _init_state here to utilize the unused 2-byte after
 228   // _idnum_allocated_count.
 229   volatile ClassState _init_state;          // state of class
 230 
 231   u1                 _reference_type;                // reference type
 232 
 233   AccessFlags        _access_flags;    // Access flags. The class/interface distinction is stored here.
 234 
 235   // State is set either at parse time or while executing, atomically to not disturb other state
 236   InstanceKlassFlags _misc_flags;
 237 
 238   JavaThread* volatile _init_thread;        // Pointer to current thread doing initialization (to handle recursive initialization)
 239 
 240   OopMapCache*    volatile _oop_map_cache;   // OopMapCache for all methods in the klass (allocated lazily)
 241   JNIid*          _jni_ids;                  // First JNI identifier for static fields in this class
 242   jmethodID* volatile _methods_jmethod_ids;  // jmethodIDs corresponding to method_idnum, or null if none
 243   nmethodBucket*  volatile _dep_context;     // packed DependencyContext structure
 244   uint64_t        volatile _dep_context_last_cleaned;
 245   nmethod*        _osr_nmethods_head;    // Head of list of on-stack replacement nmethods for this class
 246 #if INCLUDE_JVMTI
 247   BreakpointInfo* _breakpoints;          // bpt lists, managed by Method*
 248   // Linked instanceKlasses of previous versions
 249   InstanceKlass* _previous_versions;
 250   // JVMTI fields can be moved to their own structure - see 6315920
 251   // JVMTI: cached class file, before retransformable agent modified it in CFLH
 252   JvmtiCachedClassFileData* _cached_class_file;
 253 #endif
 254 
 255 #if INCLUDE_JVMTI
 256   JvmtiCachedClassFieldMap* _jvmti_cached_class_field_map;  // JVMTI: used during heap iteration
 257 #endif
 258 
 259   NOT_PRODUCT(int _verify_count;)  // to avoid redundant verifies
 260   NOT_PRODUCT(volatile int _shared_class_load_count;) // ensure a shared class is loaded only once
 261 
 262   // Method array.
 263   Array<Method*>* _methods;
 264   // Default Method Array, concrete methods inherited from interfaces
 265   Array<Method*>* _default_methods;
 266   // Interfaces (InstanceKlass*s) this class declares locally to implement.
 267   Array<InstanceKlass*>* _local_interfaces;
 268   // Interfaces (InstanceKlass*s) this class implements transitively.
 269   Array<InstanceKlass*>* _transitive_interfaces;
 270   // Int array containing the original order of method in the class file (for JVMTI).
 271   Array<int>*     _method_ordering;
 272   // Int array containing the vtable_indices for default_methods
 273   // offset matches _default_methods offset
 274   Array<int>*     _default_vtable_indices;
 275 
 276   // Fields information is stored in an UNSIGNED5 encoded stream (see fieldInfo.hpp)
 277   Array<u1>*          _fieldinfo_stream;
 278   Array<u1>*          _fieldinfo_search_table;
 279   Array<FieldStatus>* _fields_status;
 280 
 281   // embedded Java vtable follows here
 282   // embedded Java itables follows here
 283   // embedded static fields follows here
 284   // embedded nonstatic oop-map blocks follows here
 285   // embedded implementor of this interface follows here
 286   //   The embedded implementor only exists if the current klass is an
 287   //   interface. The possible values of the implementor fall into following
 288   //   three cases:
 289   //     null: no implementor.
 290   //     A Klass* that's not itself: one implementor.
 291   //     Itself: more than one implementors.
 292   //
 293 
 294   friend class SystemDictionary;
 295 
 296   static bool _disable_method_binary_search;
 297 
 298   // Controls finalizer registration
 299   static bool _finalization_enabled;
 300 
 301  public:
 302 
 303   // Queries finalization state
 304   static bool is_finalization_enabled() { return _finalization_enabled; }
 305 
 306   // Sets finalization state
 307   static void set_finalization_enabled(bool val) { _finalization_enabled = val; }
 308 
 309   // Access flags
 310   AccessFlags access_flags() const         { return _access_flags;  }
 311   void set_access_flags(AccessFlags flags) { _access_flags = flags; }
 312 
 313   bool is_public() const                { return _access_flags.is_public(); }
 314   bool is_final() const                 { return _access_flags.is_final(); }
 315   bool is_interface() const override    { return _access_flags.is_interface(); }
 316   bool is_abstract() const override     { return _access_flags.is_abstract(); }
 317   bool is_super() const                 { return _access_flags.is_super(); }
 318   bool is_synthetic() const             { return _access_flags.is_synthetic(); }
 319   void set_is_synthetic()               { _access_flags.set_is_synthetic(); }
 320 
 321   static ByteSize access_flags_offset() { return byte_offset_of(InstanceKlass, _access_flags); }
 322 
 323   void set_is_cloneable();
 324 
 325   // Quick checks for the loader that defined this class (without switching on this->class_loader())
 326   bool defined_by_boot_loader() const      { return _misc_flags.defined_by_boot_loader(); }
 327   bool defined_by_platform_loader() const  { return _misc_flags.defined_by_platform_loader(); }
 328   bool defined_by_app_loader() const       { return _misc_flags.defined_by_app_loader(); }
 329   bool defined_by_other_loaders() const    { return _misc_flags.defined_by_other_loaders(); }
 330   void set_class_loader_type()             { _misc_flags.set_class_loader_type(_class_loader_data); }
 331 
 332   bool shared_loading_failed() const { return _misc_flags.shared_loading_failed(); }
 333 
 334   void set_shared_loading_failed() { _misc_flags.set_shared_loading_failed(true); }
 335 
 336   bool has_nonstatic_fields() const        { return _misc_flags.has_nonstatic_fields(); }
 337   void set_has_nonstatic_fields(bool b)    { _misc_flags.set_has_nonstatic_fields(b); }
 338 
 339   bool has_localvariable_table() const     { return _misc_flags.has_localvariable_table(); }
 340   void set_has_localvariable_table(bool b) { _misc_flags.set_has_localvariable_table(b); }
 341 
 342   bool fail_over_verified() const { return _misc_flags.fail_over_verified(); }
 343   void set_fail_over_verified() { _misc_flags.set_fail_over_verified(true); }
 344 
 345   // field sizes
 346   int nonstatic_field_size() const         { return _nonstatic_field_size; }
 347   void set_nonstatic_field_size(int size)  { _nonstatic_field_size = size; }
 348 
 349   int static_field_size() const            { return _static_field_size; }
 350   void set_static_field_size(int size)     { _static_field_size = size; }
 351 
 352   int static_oop_field_count() const       { return (int)_static_oop_field_count; }
 353   void set_static_oop_field_count(u2 size) { _static_oop_field_count = size; }
 354 
 355   bool trust_final_fields()                { return _misc_flags.trust_final_fields(); }
 356   void set_trust_final_fields(bool value)  { _misc_flags.set_trust_final_fields(value); }
 357 
 358   // Java itable
 359   int  itable_length() const               { return _itable_len; }
 360   void set_itable_length(int len)          { _itable_len = len; }
 361 
 362   // array klasses
 363   ObjArrayKlass* array_klasses() const     { return _array_klasses; }
 364   inline ObjArrayKlass* array_klasses_acquire() const; // load with acquire semantics
 365   inline void release_set_array_klasses(ObjArrayKlass* k); // store with release semantics
 366   void set_array_klasses(ObjArrayKlass* k) { _array_klasses = k; }
 367 
 368   // methods
 369   Array<Method*>* methods() const          { return _methods; }
 370   void set_methods(Array<Method*>* a)      { _methods = a; }
 371   Method* method_with_idnum(int idnum) const;
 372   Method* method_with_orig_idnum(int idnum) const;
 373   Method* method_with_orig_idnum(int idnum, int version) const;
 374 
 375   // method ordering
 376   Array<int>* method_ordering() const     { return _method_ordering; }
 377   void set_method_ordering(Array<int>* m) { _method_ordering = m; }
 378   void copy_method_ordering(const intArray* m, TRAPS);
 379 
 380   // default_methods
 381   Array<Method*>* default_methods() const  { return _default_methods; }
 382   void set_default_methods(Array<Method*>* a) { _default_methods = a; }
 383 
 384   // default method vtable_indices
 385   Array<int>* default_vtable_indices() const { return _default_vtable_indices; }
 386   void set_default_vtable_indices(Array<int>* v) { _default_vtable_indices = v; }
 387   Array<int>* create_new_default_vtable_indices(int len, TRAPS);
 388 
 389   // interfaces
 390   Array<InstanceKlass*>* local_interfaces() const          { return _local_interfaces; }
 391   void set_local_interfaces(Array<InstanceKlass*>* a)      {
 392     guarantee(_local_interfaces == nullptr || a == nullptr, "Just checking");
 393     _local_interfaces = a; }
 394 
 395   Array<InstanceKlass*>* transitive_interfaces() const     { return _transitive_interfaces; }
 396   void set_transitive_interfaces(Array<InstanceKlass*>* a) {
 397     guarantee(_transitive_interfaces == nullptr || a == nullptr, "Just checking");
 398     _transitive_interfaces = a;
 399   }
 400 
 401  private:
 402   friend class fieldDescriptor;
 403   FieldInfo field(int index) const;
 404 
 405  public:
 406   int     field_offset      (int index) const { return field(index).offset(); }
 407   int     field_access_flags(int index) const { return field(index).access_flags().as_field_flags(); }
 408   FieldInfo::FieldFlags field_flags(int index) const { return field(index).field_flags(); }
 409   FieldStatus field_status(int index)   const { return fields_status()->at(index); }
 410   inline Symbol* field_name        (int index) const;
 411   inline Symbol* field_signature   (int index) const;
 412 
 413   // Number of Java declared fields
 414   int java_fields_count() const;
 415   int total_fields_count() const;
 416 
 417   Array<u1>* fieldinfo_stream() const { return _fieldinfo_stream; }
 418   void set_fieldinfo_stream(Array<u1>* fis) { _fieldinfo_stream = fis; }
 419 
 420   Array<u1>* fieldinfo_search_table() const { return _fieldinfo_search_table; }
 421   void set_fieldinfo_search_table(Array<u1>* table) { _fieldinfo_search_table = table; }
 422 
 423   Array<FieldStatus>* fields_status() const {return _fields_status; }
 424   void set_fields_status(Array<FieldStatus>* array) { _fields_status = array; }
 425 
 426   // inner classes
 427   Array<u2>* inner_classes() const       { return _inner_classes; }
 428   void set_inner_classes(Array<u2>* f)   { _inner_classes = f; }
 429 
 430   // nest members
 431   Array<u2>* nest_members() const     { return _nest_members; }
 432   void set_nest_members(Array<u2>* m) { _nest_members = m; }
 433 
 434   // nest-host index
 435   jushort nest_host_index() const { return _nest_host_index; }
 436   void set_nest_host_index(u2 i)  { _nest_host_index = i; }
 437   // dynamic nest member support
 438   void set_nest_host(InstanceKlass* host);
 439 
 440   // record components
 441   Array<RecordComponent*>* record_components() const { return _record_components; }
 442   void set_record_components(Array<RecordComponent*>* record_components) {
 443     _record_components = record_components;
 444   }
 445   bool is_record() const;
 446 
 447   // test for enum class (or possibly an anonymous subclass within a sealed enum)
 448   bool is_enum_subclass() const;
 449 
 450   // permitted subclasses
 451   Array<u2>* permitted_subclasses() const     { return _permitted_subclasses; }
 452   void set_permitted_subclasses(Array<u2>* s) { _permitted_subclasses = s; }
 453 
 454 private:
 455   // Called to verify that k is a member of this nest - does not look at k's nest-host,
 456   // nor does it resolve any CP entries or load any classes.
 457   bool has_nest_member(JavaThread* current, InstanceKlass* k) const;
 458 
 459 public:
 460   // Call this only if you know that the nest host has been initialized.
 461   InstanceKlass* nest_host_not_null() {
 462     assert(_nest_host != nullptr, "must be");
 463     return _nest_host;
 464   }
 465   InstanceKlass* nest_host_or_null() {
 466     return _nest_host;
 467   }
 468   // Used to construct informative IllegalAccessError messages at a higher level,
 469   // if there was an issue resolving or validating the nest host.
 470   // Returns null if there was no error.
 471   const char* nest_host_error();
 472   // Returns nest-host class, resolving and validating it if needed.
 473   // Returns null if resolution is not possible from the calling context.
 474   InstanceKlass* nest_host(TRAPS);
 475   // Check if this klass is a nestmate of k - resolves this nest-host and k's
 476   bool has_nestmate_access_to(InstanceKlass* k, TRAPS);
 477 
 478   // Called to verify that k is a permitted subclass of this class.
 479   // The incoming stringStream is used for logging, and for the caller to create
 480   // a detailed exception message on failure.
 481   bool has_as_permitted_subclass(const InstanceKlass* k, stringStream& ss) const;
 482 
 483   enum InnerClassAttributeOffset {
 484     // From http://mirror.eng/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc10.html#18814
 485     inner_class_inner_class_info_offset = 0,
 486     inner_class_outer_class_info_offset = 1,
 487     inner_class_inner_name_offset = 2,
 488     inner_class_access_flags_offset = 3,
 489     inner_class_next_offset = 4
 490   };
 491 
 492   enum EnclosingMethodAttributeOffset {
 493     enclosing_method_class_index_offset = 0,
 494     enclosing_method_method_index_offset = 1,
 495     enclosing_method_attribute_size = 2
 496   };
 497 
 498   // package
 499   PackageEntry* package() const override { return _package_entry; }
 500   ModuleEntry* module() const override;
 501   bool in_javabase_module() const;
 502   bool in_unnamed_package() const   { return (_package_entry == nullptr); }
 503   void set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS);
 504   // If the package for the InstanceKlass is in the boot loader's package entry
 505   // table then sets the classpath_index field so that
 506   // get_system_package() will know to return a non-null value for the
 507   // package's location.  And, so that the package will be added to the list of
 508   // packages returned by get_system_packages().
 509   // For packages whose classes are loaded from the boot loader class path, the
 510   // classpath_index indicates which entry on the boot loader class path.
 511   void set_classpath_index(s2 path_index);
 512   bool is_same_class_package(const Klass* class2) const;
 513   bool is_same_class_package(oop other_class_loader, const Symbol* other_class_name) const;
 514 
 515   // find an enclosing class
 516   InstanceKlass* compute_enclosing_class(bool* inner_is_member, TRAPS) const;
 517 
 518   // Find InnerClasses attribute and return outer_class_info_index & inner_name_index.
 519   bool find_inner_classes_attr(int* ooff, int* noff, TRAPS) const;
 520 
 521  private:
 522   // Check prohibited package ("java/" only loadable by boot or platform loaders)
 523   static void check_prohibited_package(Symbol* class_name,
 524                                        ClassLoaderData* loader_data,
 525                                        TRAPS);
 526 
 527   JavaThread* init_thread()  { return AtomicAccess::load(&_init_thread); }
 528   const char* init_thread_name() {
 529     return init_thread()->name_raw();
 530   }
 531 
 532  public:
 533   // initialization state
 534   bool is_loaded() const                   { return init_state() >= loaded; }
 535   bool is_linked() const                   { return init_state() >= linked; }
 536   bool is_initialized() const              { return init_state() == fully_initialized; }
 537   bool is_not_initialized() const          { return init_state() <  being_initialized; }
 538   bool is_being_initialized() const        { return init_state() == being_initialized; }
 539   bool is_in_error_state() const           { return init_state() == initialization_error; }
 540   bool is_reentrant_initialization(Thread *thread)  { return thread == _init_thread; }
 541   ClassState  init_state() const           { return AtomicAccess::load_acquire(&_init_state); }
 542   const char* init_state_name() const;
 543   bool is_rewritten() const                { return _misc_flags.rewritten(); }
 544 
 545   // is this a sealed class
 546   bool is_sealed() const;
 547 
 548   // defineClass specified verification
 549   bool should_verify_class() const         { return _misc_flags.should_verify_class(); }
 550   void set_should_verify_class(bool value) { _misc_flags.set_should_verify_class(value); }
 551 
 552   // marking
 553   bool is_marked_dependent() const         { return _misc_flags.is_marked_dependent(); }
 554   void set_is_marked_dependent(bool value) { _misc_flags.set_is_marked_dependent(value); }
 555 
 556   // initialization (virtuals from Klass)
 557   bool should_be_initialized() const override;  // means that initialize should be called
 558   void initialize_with_aot_initialized_mirror(bool early_init, TRAPS);
 559   void assert_no_clinit_will_run_for_aot_initialized_class() const NOT_DEBUG_RETURN;
 560   void initialize(TRAPS) override;
 561   void initialize_preemptable(TRAPS) override;
 562   void link_class(TRAPS);
 563   bool link_class_or_fail(TRAPS); // returns false on failure
 564   void rewrite_class(TRAPS);
 565   void link_methods(TRAPS);
 566   Method* class_initializer() const;
 567   bool interface_needs_clinit_execution_as_super(bool also_check_supers=true) const;
 568 
 569   // reference type
 570   ReferenceType reference_type() const     { return (ReferenceType)_reference_type; }
 571 
 572   // this class cp index
 573   u2 this_class_index() const             { return _this_class_index; }
 574   void set_this_class_index(u2 index)     { _this_class_index = index; }
 575 
 576   static ByteSize reference_type_offset() { return byte_offset_of(InstanceKlass, _reference_type); }
 577 
 578   // find local field, returns true if found
 579   bool find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
 580   // find field in direct superinterfaces, returns the interface in which the field is defined
 581   Klass* find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
 582   // find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
 583   Klass* find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const override;
 584   // find instance or static fields according to JVM spec 5.4.3.2, returns the klass in which the field is defined
 585   Klass* find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const;
 586 
 587   // find a non-static or static field given its offset within the class.
 588   bool contains_field_offset(int offset);
 589 
 590   bool find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const;
 591   bool find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const;
 592 
 593  private:
 594   inline static int quick_search(const Array<Method*>* methods, const Symbol* name);
 595 
 596  public:
 597   static void disable_method_binary_search() {
 598     _disable_method_binary_search = true;
 599   }
 600 
 601   // find a local method (returns null if not found)
 602   Method* find_method(const Symbol* name, const Symbol* signature) const;
 603   static Method* find_method(const Array<Method*>* methods,
 604                              const Symbol* name,
 605                              const Symbol* signature);
 606 
 607   // find a local method, but skip static methods
 608   Method* find_instance_method(const Symbol* name, const Symbol* signature,
 609                                PrivateLookupMode private_mode) const;
 610   static Method* find_instance_method(const Array<Method*>* methods,
 611                                       const Symbol* name,
 612                                       const Symbol* signature,
 613                                       PrivateLookupMode private_mode);
 614 
 615   // find a local method (returns null if not found)
 616   Method* find_local_method(const Symbol* name,
 617                             const Symbol* signature,
 618                             OverpassLookupMode overpass_mode,
 619                             StaticLookupMode static_mode,
 620                             PrivateLookupMode private_mode) const;
 621 
 622   // find a local method from given methods array (returns null if not found)
 623   static Method* find_local_method(const Array<Method*>* methods,
 624                                    const Symbol* name,
 625                                    const Symbol* signature,
 626                                    OverpassLookupMode overpass_mode,
 627                                    StaticLookupMode static_mode,
 628                                    PrivateLookupMode private_mode);
 629 
 630   // find a local method index in methods or default_methods (returns -1 if not found)
 631   static int find_method_index(const Array<Method*>* methods,
 632                                const Symbol* name,
 633                                const Symbol* signature,
 634                                OverpassLookupMode overpass_mode,
 635                                StaticLookupMode static_mode,
 636                                PrivateLookupMode private_mode);
 637 
 638   // lookup operation (returns null if not found)
 639   Method* uncached_lookup_method(const Symbol* name,
 640                                  const Symbol* signature,
 641                                  OverpassLookupMode overpass_mode,
 642                                  PrivateLookupMode private_mode = PrivateLookupMode::find) const override;
 643 
 644   // lookup a method in all the interfaces that this class implements
 645   // (returns null if not found)
 646   Method* lookup_method_in_all_interfaces(Symbol* name, Symbol* signature, DefaultsLookupMode defaults_mode) const;
 647 
 648   // lookup a method in local defaults then in all interfaces
 649   // (returns null if not found)
 650   Method* lookup_method_in_ordered_interfaces(Symbol* name, Symbol* signature) const;
 651 
 652   // Find method indices by name.  If a method with the specified name is
 653   // found the index to the first method is returned, and 'end' is filled in
 654   // with the index of first non-name-matching method.  If no method is found
 655   // -1 is returned.
 656   int find_method_by_name(const Symbol* name, int* end) const;
 657   static int find_method_by_name(const Array<Method*>* methods,
 658                                  const Symbol* name, int* end);
 659 
 660   // constant pool
 661   ConstantPool* constants() const        { return _constants; }
 662   void set_constants(ConstantPool* c)    { _constants = c; }
 663 
 664   // protection domain
 665   oop protection_domain() const override;
 666 
 667   // signers
 668   objArrayOop signers() const;
 669 
 670   bool is_contended() const                { return _misc_flags.is_contended(); }
 671   void set_is_contended(bool value)        { _misc_flags.set_is_contended(value); }
 672 
 673   // source file name
 674   Symbol* source_file_name() const;
 675   u2 source_file_name_index() const;
 676   void set_source_file_name_index(u2 sourcefile_index);
 677 
 678   // minor and major version numbers of class file
 679   u2 minor_version() const;
 680   void set_minor_version(u2 minor_version);
 681   u2 major_version() const;
 682   void set_major_version(u2 major_version);
 683 
 684   // source debug extension
 685   const char* source_debug_extension() const { return _source_debug_extension; }
 686   void set_source_debug_extension(const char* array, int length);
 687 
 688   // nonstatic oop-map blocks
 689   static int nonstatic_oop_map_size(unsigned int oop_map_count) {
 690     return oop_map_count * OopMapBlock::size_in_words();
 691   }
 692   unsigned int nonstatic_oop_map_count() const {
 693     return _nonstatic_oop_map_size / OopMapBlock::size_in_words();
 694   }
 695   int nonstatic_oop_map_size() const { return _nonstatic_oop_map_size; }
 696   void set_nonstatic_oop_map_size(int words) {
 697     _nonstatic_oop_map_size = words;
 698   }
 699 
 700   bool has_contended_annotations() const { return _misc_flags.has_contended_annotations(); }
 701   void set_has_contended_annotations(bool value)  { _misc_flags.set_has_contended_annotations(value); }
 702 
 703 #if INCLUDE_JVMTI
 704   // Redefinition locking.  Class can only be redefined by one thread at a time.
 705   bool is_being_redefined() const          { return _misc_flags.is_being_redefined(); }
 706   void set_is_being_redefined(bool value)  { _misc_flags.set_is_being_redefined(value); }
 707 
 708   // RedefineClasses() support for previous versions:
 709   void add_previous_version(InstanceKlass* ik, int emcp_method_count);
 710   void purge_previous_version_list();
 711 
 712   InstanceKlass* previous_versions() const { return _previous_versions; }
 713 #else
 714   InstanceKlass* previous_versions() const { return nullptr; }
 715 #endif
 716 
 717   const InstanceKlass* get_klass_version(int version) const;
 718 
 719   bool has_been_redefined() const { return _misc_flags.has_been_redefined(); }
 720   void set_has_been_redefined() { _misc_flags.set_has_been_redefined(true); }
 721 
 722   bool is_scratch_class() const { return _misc_flags.is_scratch_class(); }
 723   void set_is_scratch_class() { _misc_flags.set_is_scratch_class(true); }
 724 
 725   bool has_resolved_methods() const { return _misc_flags.has_resolved_methods(); }
 726   void set_has_resolved_methods()   { _misc_flags.set_has_resolved_methods(true); }
 727   void set_has_resolved_methods(bool value)   { _misc_flags.set_has_resolved_methods(value); }
 728 
 729 public:
 730 #if INCLUDE_JVMTI
 731 
 732   void init_previous_versions() {
 733     _previous_versions = nullptr;
 734   }
 735 
 736  private:
 737   static bool  _should_clean_previous_versions;
 738  public:
 739   static void purge_previous_versions(InstanceKlass* ik) {
 740     if (ik->has_been_redefined()) {
 741       ik->purge_previous_version_list();
 742     }
 743   }
 744 
 745   static bool should_clean_previous_versions_and_reset();
 746   static bool should_clean_previous_versions() { return _should_clean_previous_versions; }
 747 
 748   // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation
 749   void set_cached_class_file(JvmtiCachedClassFileData *data) {
 750     _cached_class_file = data;
 751   }
 752   JvmtiCachedClassFileData * get_cached_class_file();
 753   jint get_cached_class_file_len();
 754   unsigned char * get_cached_class_file_bytes();
 755 
 756   // JVMTI: Support for caching of field indices, types, and offsets
 757   void set_jvmti_cached_class_field_map(JvmtiCachedClassFieldMap* descriptor) {
 758     _jvmti_cached_class_field_map = descriptor;
 759   }
 760   JvmtiCachedClassFieldMap* jvmti_cached_class_field_map() const {
 761     return _jvmti_cached_class_field_map;
 762   }
 763 #else // INCLUDE_JVMTI
 764 
 765   static void purge_previous_versions(InstanceKlass* ik) { return; };
 766   static bool should_clean_previous_versions_and_reset() { return false; }
 767 
 768   void set_cached_class_file(JvmtiCachedClassFileData *data) {
 769     assert(data == nullptr, "unexpected call with JVMTI disabled");
 770   }
 771   JvmtiCachedClassFileData * get_cached_class_file() { return (JvmtiCachedClassFileData *)nullptr; }
 772 
 773 #endif // INCLUDE_JVMTI
 774 
 775   bool has_nonstatic_concrete_methods() const { return _misc_flags.has_nonstatic_concrete_methods(); }
 776   void set_has_nonstatic_concrete_methods(bool b) { _misc_flags.set_has_nonstatic_concrete_methods(b); }
 777 
 778   bool declares_nonstatic_concrete_methods() const { return _misc_flags.declares_nonstatic_concrete_methods(); }
 779   void set_declares_nonstatic_concrete_methods(bool b) { _misc_flags.set_declares_nonstatic_concrete_methods(b); }
 780 
 781   bool has_miranda_methods () const     { return _misc_flags.has_miranda_methods(); }
 782   void set_has_miranda_methods()        { _misc_flags.set_has_miranda_methods(true); }
 783   bool has_final_method() const         { return _misc_flags.has_final_method(); }
 784   void set_has_final_method()           { _misc_flags.set_has_final_method(true); }
 785 
 786   // for adding methods, ConstMethod::UNSET_IDNUM means no more ids available
 787   inline u2 next_method_idnum();
 788   void set_initial_method_idnum(u2 value)             { _idnum_allocated_count = value; }
 789 
 790   // generics support
 791   Symbol* generic_signature() const;
 792   u2 generic_signature_index() const;
 793   void set_generic_signature_index(u2 sig_index);
 794 
 795   u2 enclosing_method_data(int offset) const;
 796   u2 enclosing_method_class_index() const {
 797     return enclosing_method_data(enclosing_method_class_index_offset);
 798   }
 799   u2 enclosing_method_method_index() {
 800     return enclosing_method_data(enclosing_method_method_index_offset);
 801   }
 802   void set_enclosing_method_indices(u2 class_index,
 803                                     u2 method_index);
 804 
 805   // jmethodID support
 806   jmethodID get_jmethod_id(Method* method);
 807   void make_methods_jmethod_ids();
 808   jmethodID jmethod_id_or_null(Method* method);
 809   void update_methods_jmethod_cache();
 810 
 811   // annotations support
 812   Annotations* annotations() const          { return _annotations; }
 813   void set_annotations(Annotations* anno)   { _annotations = anno; }
 814 
 815   AnnotationArray* class_annotations() const {
 816     return (_annotations != nullptr) ? _annotations->class_annotations() : nullptr;
 817   }
 818   Array<AnnotationArray*>* fields_annotations() const {
 819     return (_annotations != nullptr) ? _annotations->fields_annotations() : nullptr;
 820   }
 821   AnnotationArray* class_type_annotations() const {
 822     return (_annotations != nullptr) ? _annotations->class_type_annotations() : nullptr;
 823   }
 824   Array<AnnotationArray*>* fields_type_annotations() const {
 825     return (_annotations != nullptr) ? _annotations->fields_type_annotations() : nullptr;
 826   }
 827   // allocation
 828   instanceOop allocate_instance(TRAPS);
 829   static instanceOop allocate_instance(oop cls, TRAPS);
 830 
 831   // additional member function to return a handle
 832   instanceHandle allocate_instance_handle(TRAPS);
 833 
 834   // Helper function
 835   static instanceOop register_finalizer(instanceOop i, TRAPS);
 836 
 837   // Check whether reflection/jni/jvm code is allowed to instantiate this class;
 838   // if not, throw either an Error or an Exception.
 839   void check_valid_for_instantiation(bool throwError, TRAPS) override;
 840 
 841   // initialization
 842   void call_class_initializer(TRAPS);
 843   void set_initialization_state_and_notify(ClassState state, TRAPS);
 844 
 845   // OopMapCache support
 846   OopMapCache* oop_map_cache()               { return _oop_map_cache; }
 847   void set_oop_map_cache(OopMapCache *cache) { _oop_map_cache = cache; }
 848   void mask_for(const methodHandle& method, int bci, InterpreterOopMap* entry);
 849 
 850   // JNI identifier support (for static fields - for jni performance)
 851   JNIid* jni_ids()                               { return _jni_ids; }
 852   void set_jni_ids(JNIid* ids)                   { _jni_ids = ids; }
 853   JNIid* jni_id_for(int offset);
 854 
 855  public:
 856   // maintenance of deoptimization dependencies
 857   inline DependencyContext dependencies();
 858   void mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes);
 859   void add_dependent_nmethod(nmethod* nm);
 860   void clean_dependency_context();
 861   // Setup link to hierarchy and deoptimize
 862   void add_to_hierarchy(JavaThread* current);
 863 
 864   // On-stack replacement support
 865   nmethod* osr_nmethods_head() const         { return _osr_nmethods_head; };
 866   void set_osr_nmethods_head(nmethod* h)     { _osr_nmethods_head = h; };
 867   void add_osr_nmethod(nmethod* n);
 868   bool remove_osr_nmethod(nmethod* n);
 869   int mark_osr_nmethods(DeoptimizationScope* deopt_scope, const Method* m);
 870   nmethod* lookup_osr_nmethod(const Method* m, int bci, int level, bool match_level) const;
 871 
 872 #if INCLUDE_JVMTI
 873   // Breakpoint support (see methods on Method* for details)
 874   BreakpointInfo* breakpoints() const       { return _breakpoints; };
 875   void set_breakpoints(BreakpointInfo* bps) { _breakpoints = bps; };
 876 #endif
 877 
 878   // support for stub routines
 879   static ByteSize init_state_offset()  { return byte_offset_of(InstanceKlass, _init_state); }
 880   JFR_ONLY(DEFINE_KLASS_TRACE_ID_OFFSET;)
 881   static ByteSize init_thread_offset() { return byte_offset_of(InstanceKlass, _init_thread); }
 882 
 883   // subclass/subinterface checks
 884   bool implements_interface(Klass* k) const;
 885   bool is_same_or_direct_interface(Klass* k) const;
 886 
 887 #ifdef ASSERT
 888   // check whether this class or one of its superclasses was redefined
 889   bool has_redefined_this_or_super() const;
 890 #endif
 891 
 892   // Access to the implementor of an interface.
 893   InstanceKlass* implementor() const;
 894   void set_implementor(InstanceKlass* ik);
 895   int  nof_implementors() const;
 896   void add_implementor(InstanceKlass* ik);  // ik is a new class that implements this interface
 897   void init_implementor();           // initialize
 898 
 899  private:
 900   // link this class into the implementors list of every interface it implements
 901   void process_interfaces();
 902 
 903  public:
 904   // virtual operations from Klass
 905   GrowableArray<Klass*>* compute_secondary_supers(int num_extra_slots,
 906                                                   Array<InstanceKlass*>* transitive_interfaces) override;
 907   bool can_be_primary_super_slow() const override;
 908   size_t oop_size(oop obj) const override { return size_helper(); }
 909   // slow because it's a virtual call and used for verifying the layout_helper.
 910   // Using the layout_helper bits, we can call is_instance_klass without a virtual call.
 911   DEBUG_ONLY(bool is_instance_klass_slow() const override { return true; })
 912 
 913   // Iterators
 914   void do_local_static_fields(FieldClosure* cl);
 915   void do_nonstatic_fields(FieldClosure* cl); // including inherited fields
 916   void do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle, TRAPS);
 917   void print_nonstatic_fields(FieldClosure* cl); // including inherited and injected fields
 918 
 919   void methods_do(void f(Method* method));
 920 
 921   static InstanceKlass* cast(Klass* k) {
 922     return const_cast<InstanceKlass*>(cast(const_cast<const Klass*>(k)));
 923   }
 924 
 925   static const InstanceKlass* cast(const Klass* k) {
 926     assert(k != nullptr, "k should not be null");
 927     assert(k->is_instance_klass(), "cast to InstanceKlass");
 928     return static_cast<const InstanceKlass*>(k);
 929   }
 930 
 931   // This hides Klass::super(). The _super of an InstanceKlass is
 932   // always an InstanceKlass (or nullptr)
 933   InstanceKlass* super() const {
 934     return (Klass::super() == nullptr) ? nullptr : InstanceKlass::cast(Klass::super());
 935   }
 936 
 937   InstanceKlass* java_super() const override {
 938     return InstanceKlass::super();
 939   }
 940 
 941   // Sizing (in words)
 942   static int header_size()            { return sizeof(InstanceKlass)/wordSize; }
 943 
 944   static int size(int vtable_length, int itable_length,
 945                   int nonstatic_oop_map_size,
 946                   bool is_interface) {
 947     return align_metadata_size(header_size() +
 948            vtable_length +
 949            itable_length +
 950            nonstatic_oop_map_size +
 951            (is_interface ? (int)sizeof(Klass*)/wordSize : 0));
 952   }
 953 
 954   int size() const override           { return size(vtable_length(),
 955                                                     itable_length(),
 956                                                     nonstatic_oop_map_size(),
 957                                                     is_interface());
 958   }
 959 
 960 
 961   inline intptr_t* start_of_itable() const;
 962   inline intptr_t* end_of_itable() const;
 963   inline oop static_field_base_raw();
 964 
 965   inline OopMapBlock* start_of_nonstatic_oop_maps() const;
 966   inline Klass** end_of_nonstatic_oop_maps() const;
 967 
 968   inline InstanceKlass* volatile* adr_implementor() const;
 969 
 970   // Use this to return the size of an instance in heap words:
 971   int size_helper() const {
 972     return layout_helper_to_size_helper(layout_helper());
 973   }
 974 
 975   // This bit is initialized in classFileParser.cpp.
 976   // It is false under any of the following conditions:
 977   //  - the class is abstract (including any interface)
 978   //  - the class size is larger than FastAllocateSizeLimit
 979   //  - the class is java/lang/Class, which cannot be allocated directly
 980   bool can_be_fastpath_allocated() const {
 981     return !layout_helper_needs_slow_path(layout_helper());
 982   }
 983 
 984   // Java itable
 985   klassItable itable() const;        // return klassItable wrapper
 986   Method* method_at_itable(InstanceKlass* holder, int index, TRAPS);
 987   Method* method_at_itable_or_null(InstanceKlass* holder, int index, bool& itable_entry_found);
 988   int vtable_index_of_interface_method(Method* method);
 989 
 990 #if INCLUDE_JVMTI
 991   void adjust_default_methods(bool* trace_name_printed);
 992 #endif // INCLUDE_JVMTI
 993 
 994   void clean_weak_instanceklass_links();
 995  private:
 996   void clean_implementors_list();
 997   void clean_method_data();
 998 
 999  public:
1000   // Explicit metaspace deallocation of fields
1001   // For RedefineClasses and class file parsing errors, we need to deallocate
1002   // instanceKlasses and the metadata they point to.
1003   void deallocate_contents(ClassLoaderData* loader_data);
1004   static void deallocate_methods(ClassLoaderData* loader_data,
1005                                  Array<Method*>* methods);
1006   void static deallocate_interfaces(ClassLoaderData* loader_data,
1007                                     const InstanceKlass* super_klass,
1008                                     Array<InstanceKlass*>* local_interfaces,
1009                                     Array<InstanceKlass*>* transitive_interfaces);
1010   void static deallocate_record_components(ClassLoaderData* loader_data,
1011                                            Array<RecordComponent*>* record_component);
1012 
1013   bool on_stack() const override;
1014 
1015   // callbacks for actions during class unloading
1016   static void unload_class(InstanceKlass* ik);
1017 
1018   void release_C_heap_structures(bool release_sub_metadata = true) override;
1019 
1020   // Naming
1021   const char* signature_name() const override;
1022 
1023   // Oop fields (and metadata) iterators
1024   //
1025   // The InstanceKlass iterators also visits the Object's klass.
1026 
1027   // Forward iteration
1028  public:
1029   // Iterate over all oop fields in the oop maps.
1030   template <typename T, class OopClosureType>
1031   inline void oop_oop_iterate_oop_maps(oop obj, OopClosureType* closure);
1032 
1033   // Iterate over all oop fields and metadata.
1034   template <typename T, class OopClosureType>
1035   inline void oop_oop_iterate(oop obj, OopClosureType* closure);
1036 
1037   // Iterate over all oop fields in one oop map.
1038   template <typename T, class OopClosureType>
1039   inline void oop_oop_iterate_oop_map(OopMapBlock* map, oop obj, OopClosureType* closure);
1040 
1041 
1042   // Reverse iteration
1043   // Iterate over all oop fields and metadata.
1044   template <typename T, class OopClosureType>
1045   inline void oop_oop_iterate_reverse(oop obj, OopClosureType* closure);
1046 
1047  private:
1048   // Iterate over all oop fields in the oop maps.
1049   template <typename T, class OopClosureType>
1050   inline void oop_oop_iterate_oop_maps_reverse(oop obj, OopClosureType* closure);
1051 
1052   // Iterate over all oop fields in one oop map.
1053   template <typename T, class OopClosureType>
1054   inline void oop_oop_iterate_oop_map_reverse(OopMapBlock* map, oop obj, OopClosureType* closure);
1055 
1056 
1057   // Bounded range iteration
1058  public:
1059   // Iterate over all oop fields in the oop maps.
1060   template <typename T, class OopClosureType>
1061   inline void oop_oop_iterate_oop_maps_bounded(oop obj, OopClosureType* closure, MemRegion mr);
1062 
1063   // Iterate over all oop fields and metadata.
1064   template <typename T, class OopClosureType>
1065   inline void oop_oop_iterate_bounded(oop obj, OopClosureType* closure, MemRegion mr);
1066 
1067  private:
1068   // Iterate over all oop fields in one oop map.
1069   template <typename T, class OopClosureType>
1070   inline void oop_oop_iterate_oop_map_bounded(OopMapBlock* map, oop obj, OopClosureType* closure, MemRegion mr);
1071 
1072 
1073  public:
1074   u2 idnum_allocated_count() const      { return _idnum_allocated_count; }
1075 
1076 private:
1077   // initialization state
1078   void set_init_state(ClassState state);
1079   void set_rewritten()                  { _misc_flags.set_rewritten(true); }
1080   void set_init_thread(JavaThread *thread)  {
1081     assert((thread == JavaThread::current() && _init_thread == nullptr) ||
1082            (thread == nullptr && _init_thread == JavaThread::current()), "Only one thread is allowed to own initialization");
1083     AtomicAccess::store(&_init_thread, thread);
1084   }
1085 
1086   jmethodID* methods_jmethod_ids_acquire() const;
1087   void release_set_methods_jmethod_ids(jmethodID* jmeths);
1088   // This nulls out obsolete jmethodIDs for all methods in 'klass'.
1089   static void clear_obsolete_jmethod_ids(InstanceKlass* klass);
1090   jmethodID update_jmethod_id(jmethodID* jmeths, Method* method, int idnum);
1091 
1092 public:
1093   // Lock for (1) initialization; (2) access to the ConstantPool of this class.
1094   // Must be one per class and it has to be a VM internal object so java code
1095   // cannot lock it (like the mirror).
1096   // It has to be an object not a Mutex because it's held through java calls.
1097   oop init_lock() const;
1098 
1099   // Returns the array class for the n'th dimension
1100   ArrayKlass* array_klass(int n, TRAPS) override;
1101   ArrayKlass* array_klass_or_null(int n) override;
1102 
1103   // Returns the array class with this class as element type
1104   ArrayKlass* array_klass(TRAPS) override;
1105   ArrayKlass* array_klass_or_null() override;
1106 
1107   static void clean_initialization_error_table();
1108 private:
1109   void fence_and_clear_init_lock();
1110 
1111   bool link_class_impl                           (TRAPS);
1112   bool verify_code                               (TRAPS);
1113   void initialize_impl                           (TRAPS);
1114   void initialize_super_interfaces               (TRAPS);
1115 
1116   void add_initialization_error(JavaThread* current, Handle exception);
1117   oop get_initialization_error(JavaThread* current);
1118 
1119   // find a local method (returns null if not found)
1120   Method* find_method_impl(const Symbol* name,
1121                            const Symbol* signature,
1122                            OverpassLookupMode overpass_mode,
1123                            StaticLookupMode static_mode,
1124                            PrivateLookupMode private_mode) const;
1125 
1126   static Method* find_method_impl(const Array<Method*>* methods,
1127                                   const Symbol* name,
1128                                   const Symbol* signature,
1129                                   OverpassLookupMode overpass_mode,
1130                                   StaticLookupMode static_mode,
1131                                   PrivateLookupMode private_mode);
1132 
1133 #if INCLUDE_JVMTI
1134   // RedefineClasses support
1135   void link_previous_versions(InstanceKlass* pv) { _previous_versions = pv; }
1136   void mark_newly_obsolete_methods(Array<Method*>* old_methods, int emcp_method_count);
1137 #endif
1138 public:
1139 
1140 #if INCLUDE_CDS
1141   // CDS support - remove and restore oops from metadata. Oops are not shared.
1142   void remove_unshareable_info() override;
1143   void remove_unshareable_flags();
1144   void remove_java_mirror() override;
1145   void restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, PackageEntry* pkg_entry, TRAPS);
1146   void init_shared_package_entry();
1147   bool can_be_verified_at_dumptime() const;
1148   void compute_has_loops_flag_for_methods();
1149 #endif
1150   bool     has_init_deps_processed() const { return _misc_flags.has_init_deps_processed(); }
1151   void set_has_init_deps_processed() {
1152     assert(is_initialized(), "");
1153     assert(!has_init_deps_processed(), "already set"); // one-off action
1154     _misc_flags.set_has_init_deps_processed(true);
1155   }
1156 
1157   u2 compute_modifier_flags() const override;
1158 
1159 public:
1160   // JVMTI support
1161   jint jvmti_class_status() const override;
1162 
1163   void metaspace_pointers_do(MetaspaceClosure* iter) override;
1164 
1165  public:
1166   // Printing
1167   void print_on(outputStream* st) const override;
1168   void print_value_on(outputStream* st) const override;
1169   void print_class_flags(outputStream* st) const;
1170 
1171   void oop_print_value_on(oop obj, outputStream* st) override;
1172 
1173   void oop_print_on      (oop obj, outputStream* st) override;
1174 
1175 #ifndef PRODUCT
1176   void print_dependent_nmethods(bool verbose = false);
1177   bool is_dependent_nmethod(nmethod* nm);
1178   bool verify_itable_index(int index);
1179 #endif
1180 
1181   const char* internal_name() const override;
1182 
1183   // Verification
1184   void verify_on(outputStream* st) override;
1185 
1186   void oop_verify_on(oop obj, outputStream* st) override;
1187 
1188   // Logging
1189   void print_class_load_logging(ClassLoaderData* loader_data,
1190                                 const ModuleEntry* module_entry,
1191                                 const ClassFileStream* cfs) const;
1192  private:
1193   void print_class_load_cause_logging() const;
1194   void print_class_load_helper(ClassLoaderData* loader_data,
1195                                const ModuleEntry* module_entry,
1196                                const ClassFileStream* cfs) const;
1197 };
1198 
1199 // for adding methods
1200 // UNSET_IDNUM return means no more ids available
1201 inline u2 InstanceKlass::next_method_idnum() {
1202   if (_idnum_allocated_count == ConstMethod::MAX_IDNUM) {
1203     return ConstMethod::UNSET_IDNUM; // no more ids available
1204   } else {
1205     return _idnum_allocated_count++;
1206   }
1207 }
1208 
1209 class PrintClassClosure : public KlassClosure {
1210 private:
1211   outputStream* _st;
1212   bool _verbose;
1213 public:
1214   PrintClassClosure(outputStream* st, bool verbose);
1215 
1216   void do_klass(Klass* k);
1217 };
1218 
1219 /* JNIid class for jfieldIDs only */
1220 class JNIid: public CHeapObj<mtClass> {
1221   friend class VMStructs;
1222  private:
1223   InstanceKlass*     _holder;
1224   JNIid*             _next;
1225   int                _offset;
1226 #ifdef ASSERT
1227   bool               _is_static_field_id;
1228 #endif
1229 
1230  public:
1231   // Accessors
1232   InstanceKlass* holder() const   { return _holder; }
1233   int offset() const              { return _offset; }
1234   JNIid* next()                   { return _next; }
1235   // Constructor
1236   JNIid(InstanceKlass* holder, int offset, JNIid* next);
1237   // Identifier lookup
1238   JNIid* find(int offset);
1239 
1240   bool find_local_field(fieldDescriptor* fd) {
1241     return InstanceKlass::cast(holder())->find_local_field_from_offset(offset(), true, fd);
1242   }
1243 
1244   static void deallocate(JNIid* id);
1245   // Debugging
1246 #ifdef ASSERT
1247   bool is_static_field_id() const { return _is_static_field_id; }
1248   void set_is_static_field_id()   { _is_static_field_id = true; }
1249 #endif
1250   void verify(InstanceKlass* holder);
1251 };
1252 
1253 // An iterator that's used to access the inner classes indices in the
1254 // InstanceKlass::_inner_classes array.
1255 class InnerClassesIterator : public StackObj {
1256  private:
1257   Array<jushort>* _inner_classes;
1258   int _length;
1259   int _idx;
1260  public:
1261 
1262   InnerClassesIterator(const InstanceKlass* k) {
1263     _inner_classes = k->inner_classes();
1264     if (k->inner_classes() != nullptr) {
1265       _length = _inner_classes->length();
1266       // The inner class array's length should be the multiple of
1267       // inner_class_next_offset if it only contains the InnerClasses
1268       // attribute data, or it should be
1269       // n*inner_class_next_offset+enclosing_method_attribute_size
1270       // if it also contains the EnclosingMethod data.
1271       assert((_length % InstanceKlass::inner_class_next_offset == 0 ||
1272               _length % InstanceKlass::inner_class_next_offset == InstanceKlass::enclosing_method_attribute_size),
1273              "just checking");
1274       // Remove the enclosing_method portion if exists.
1275       if (_length % InstanceKlass::inner_class_next_offset == InstanceKlass::enclosing_method_attribute_size) {
1276         _length -= InstanceKlass::enclosing_method_attribute_size;
1277       }
1278     } else {
1279       _length = 0;
1280     }
1281     _idx = 0;
1282   }
1283 
1284   int length() const {
1285     return _length;
1286   }
1287 
1288   void next() {
1289     _idx += InstanceKlass::inner_class_next_offset;
1290   }
1291 
1292   bool done() const {
1293     return (_idx >= _length);
1294   }
1295 
1296   u2 inner_class_info_index() const {
1297     return _inner_classes->at(
1298                _idx + InstanceKlass::inner_class_inner_class_info_offset);
1299   }
1300 
1301   void set_inner_class_info_index(u2 index) {
1302     _inner_classes->at_put(
1303                _idx + InstanceKlass::inner_class_inner_class_info_offset, index);
1304   }
1305 
1306   u2 outer_class_info_index() const {
1307     return _inner_classes->at(
1308                _idx + InstanceKlass::inner_class_outer_class_info_offset);
1309   }
1310 
1311   void set_outer_class_info_index(u2 index) {
1312     _inner_classes->at_put(
1313                _idx + InstanceKlass::inner_class_outer_class_info_offset, index);
1314   }
1315 
1316   u2 inner_name_index() const {
1317     return _inner_classes->at(
1318                _idx + InstanceKlass::inner_class_inner_name_offset);
1319   }
1320 
1321   void set_inner_name_index(u2 index) {
1322     _inner_classes->at_put(
1323                _idx + InstanceKlass::inner_class_inner_name_offset, index);
1324   }
1325 
1326   u2 inner_access_flags() const {
1327     return _inner_classes->at(
1328                _idx + InstanceKlass::inner_class_access_flags_offset);
1329   }
1330 };
1331 
1332 // Iterator over class hierarchy under a particular class. Implements depth-first pre-order traversal.
1333 // Usage:
1334 //  for (ClassHierarchyIterator iter(root_klass); !iter.done(); iter.next()) {
1335 //    Klass* k = iter.klass();
1336 //    ...
1337 //  }
1338 class ClassHierarchyIterator : public StackObj {
1339  private:
1340   InstanceKlass* _root;
1341   Klass*         _current;
1342   bool           _visit_subclasses;
1343 
1344  public:
1345   ClassHierarchyIterator(InstanceKlass* root) : _root(root), _current(root), _visit_subclasses(true) {
1346     assert(_root == _current, "required"); // initial state
1347   }
1348 
1349   bool done() {
1350     return (_current == nullptr);
1351   }
1352 
1353   // Make a step iterating over the class hierarchy under the root class.
1354   // Skips subclasses if requested.
1355   void next();
1356 
1357   Klass* klass() {
1358     assert(!done(), "sanity");
1359     return _current;
1360   }
1361 
1362   // Skip subclasses of the current class.
1363   void skip_subclasses() {
1364     _visit_subclasses = false;
1365   }
1366 };
1367 
1368 #endif // SHARE_OOPS_INSTANCEKLASS_HPP