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