1 /*
   2  * Copyright (c) 1997, 2019, 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 "classfile/classLoaderData.hpp"
  29 #include "code/vmreg.hpp"
  30 #include "memory/referenceType.hpp"
  31 #include "oops/annotations.hpp"
  32 #include "oops/constMethod.hpp"
  33 #include "oops/fieldInfo.hpp"
  34 #include "oops/instanceOop.hpp"
  35 #include "oops/klassVtable.hpp"
  36 #include "runtime/handles.hpp"
  37 #include "runtime/os.hpp"
  38 #include "utilities/accessFlags.hpp"
  39 #include "utilities/align.hpp"
  40 #include "utilities/macros.hpp"
  41 #if INCLUDE_JFR
  42 #include "jfr/support/jfrKlassExtension.hpp"
  43 #endif
  44 
  45 
  46 // An InstanceKlass is the VM level representation of a Java class.
  47 // It contains all information needed for at class at execution runtime.
  48 
  49 //  InstanceKlass embedded field layout (after declared fields):
  50 //    [EMBEDDED Java vtable             ] size in words = vtable_len
  51 //    [EMBEDDED nonstatic oop-map blocks] size in words = nonstatic_oop_map_size
  52 //      The embedded nonstatic oop-map blocks are short pairs (offset, length)
  53 //      indicating where oops are located in instances of this klass.
  54 //    [EMBEDDED implementor of the interface] only exist for interface
  55 //    [EMBEDDED unsafe_anonymous_host klass] only exist for an unsafe anonymous class (JSR 292 enabled)
  56 //    [EMBEDDED fingerprint       ] only if should_store_fingerprint()==true
  57 //    [EMBEDDED ValueKlassFixedBlock] only if is a ValueKlass instance
  58 
  59 
  60 // forward declaration for class -- see below for definition
  61 #if INCLUDE_JVMTI
  62 class BreakpointInfo;
  63 #endif
  64 class ClassFileParser;
  65 class ClassFileStream;
  66 class KlassDepChange;
  67 class DependencyContext;
  68 class fieldDescriptor;
  69 class jniIdMapBase;
  70 class JNIid;
  71 class JvmtiCachedClassFieldMap;
  72 class nmethodBucket;
  73 class OopMapCache;
  74 class BufferedValueTypeBlob;
  75 class InterpreterOopMap;
  76 class PackageEntry;
  77 class ModuleEntry;
  78 
  79 // This is used in iterators below.
  80 class FieldClosure: public StackObj {
  81 public:
  82   virtual void do_field(fieldDescriptor* fd) = 0;
  83 };
  84 
  85 #ifndef PRODUCT
  86 // Print fields.
  87 // If "obj" argument to constructor is NULL, prints static fields, otherwise prints non-static fields.
  88 class FieldPrinter: public FieldClosure {
  89    oop _obj;
  90    outputStream* _st;
  91  public:
  92    FieldPrinter(outputStream* st, oop obj = NULL) : _obj(obj), _st(st) {}
  93    void do_field(fieldDescriptor* fd);
  94 };
  95 #endif  // !PRODUCT
  96 
  97 // Describes where oops are located in instances of this klass.
  98 class OopMapBlock {
  99  public:
 100   // Byte offset of the first oop mapped by this block.
 101   int offset() const          { return _offset; }
 102   void set_offset(int offset) { _offset = offset; }
 103 
 104   // Number of oops in this block.
 105   uint count() const         { return _count; }
 106   void set_count(uint count) { _count = count; }
 107 
 108   void increment_count(int diff)     { _count += diff; }
 109 
 110   int offset_span() const { return _count * heapOopSize; }
 111 
 112   int end_offset() const {
 113     return offset() + offset_span();
 114   }
 115 
 116   bool is_contiguous(int another_offset) const {
 117     return another_offset == end_offset();
 118   }
 119 
 120   // sizeof(OopMapBlock) in words.
 121   static const int size_in_words() {
 122     return align_up((int)sizeof(OopMapBlock), wordSize) >>
 123       LogBytesPerWord;
 124   }
 125 
 126   static int compare_offset(const OopMapBlock* a, const OopMapBlock* b) {
 127     return a->offset() - b->offset();
 128   }
 129 
 130  private:
 131   int  _offset;
 132   uint _count;
 133 };
 134 
 135 struct JvmtiCachedClassFileData;
 136 
 137 class SigEntry;
 138 
 139 class ValueKlassFixedBlock {
 140   Array<SigEntry>** _extended_sig;
 141   Array<VMRegPair>** _return_regs;
 142   address* _pack_handler;
 143   address* _unpack_handler;
 144   int* _default_value_offset;
 145   Klass** _value_array_klass;
 146   int _alignment;
 147   int _first_field_offset;
 148   int _exact_size_in_bytes;
 149 
 150   friend class ValueKlass;
 151 };
 152 
 153 class ValueTypes {
 154 public:
 155   u2 _class_info_index;
 156   Symbol* _class_name;
 157 };
 158 
 159 class InstanceKlass: public Klass {
 160   friend class VMStructs;
 161   friend class JVMCIVMStructs;
 162   friend class ClassFileParser;
 163   friend class CompileReplay;
 164 
 165  public:
 166   static const KlassID ID = InstanceKlassID;
 167 
 168  protected:
 169   InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id = ID);
 170 
 171  public:
 172   InstanceKlass() { assert(DumpSharedSpaces || UseSharedSpaces, "only for CDS"); }
 173 
 174   // See "The Java Virtual Machine Specification" section 2.16.2-5 for a detailed description
 175   // of the class loading & initialization procedure, and the use of the states.
 176   enum ClassState {
 177     allocated,                          // allocated (but not yet linked)
 178     loaded,                             // loaded and inserted in class hierarchy (but not linked yet)
 179     linked,                             // successfully linked/verified (but not initialized yet)
 180     being_initialized,                  // currently running class initializer
 181     fully_initialized,                  // initialized (successful final state)
 182     initialization_error                // error happened during initialization
 183   };
 184 
 185  private:
 186   static InstanceKlass* allocate_instance_klass(const ClassFileParser& parser, TRAPS);
 187 
 188  protected:
 189   // If you add a new field that points to any metaspace object, you
 190   // must add this field to InstanceKlass::metaspace_pointers_do().
 191 
 192   // Annotations for this class
 193   Annotations*    _annotations;
 194   // Package this class is defined in
 195   PackageEntry*   _package_entry;
 196   // Array classes holding elements of this class.
 197   Klass* volatile _array_klasses;
 198   // Constant pool for this class.
 199   ConstantPool* _constants;
 200   // The InnerClasses attribute and EnclosingMethod attribute. The
 201   // _inner_classes is an array of shorts. If the class has InnerClasses
 202   // attribute, then the _inner_classes array begins with 4-tuples of shorts
 203   // [inner_class_info_index, outer_class_info_index,
 204   // inner_name_index, inner_class_access_flags] for the InnerClasses
 205   // attribute. If the EnclosingMethod attribute exists, it occupies the
 206   // last two shorts [class_index, method_index] of the array. If only
 207   // the InnerClasses attribute exists, the _inner_classes array length is
 208   // number_of_inner_classes * 4. If the class has both InnerClasses
 209   // and EnclosingMethod attributes the _inner_classes array length is
 210   // number_of_inner_classes * 4 + enclosing_method_attribute_size.
 211   Array<jushort>* _inner_classes;
 212 
 213   // The NestMembers attribute. An array of shorts, where each is a
 214   // class info index for the class that is a nest member. This data
 215   // has not been validated.
 216   Array<jushort>* _nest_members;
 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   jushort _nest_host_index;
 221 
 222   // Resolved nest-host klass: either true nest-host or self if we are not nested.
 223   // By always being set it makes nest-member access checks simpler.
 224   InstanceKlass* _nest_host;
 225 
 226   Array<ValueTypes>* _value_types;
 227 
 228   // the source debug extension for this klass, NULL if not specified.
 229   // Specified as UTF-8 string without terminating zero byte in the classfile,
 230   // it is stored in the instanceklass as a NULL-terminated UTF-8 string
 231   const char*     _source_debug_extension;
 232   // Array name derived from this class which needs unreferencing
 233   // if this class is unloaded.
 234   Symbol*         _array_name;
 235 
 236   // Number of heapOopSize words used by non-static fields in this klass
 237   // (including inherited fields but after header_size()).
 238   int             _nonstatic_field_size;
 239   int             _static_field_size;    // number words used by static fields (oop and non-oop) in this klass
 240   // Constant pool index to the utf8 entry of the Generic signature,
 241   // or 0 if none.
 242   u2              _generic_signature_index;
 243   // Constant pool index to the utf8 entry for the name of source file
 244   // containing this klass, 0 if not specified.
 245   u2              _source_file_name_index;
 246   u2              _static_oop_field_count;// number of static oop fields in this klass
 247   u2              _java_fields_count;    // The number of declared Java fields
 248   int             _nonstatic_oop_map_size;// size in words of nonstatic oop map blocks
 249 
 250   int             _itable_len;           // length of Java itable (in words)
 251   // _is_marked_dependent can be set concurrently, thus cannot be part of the
 252   // _misc_flags.
 253   bool            _is_marked_dependent;  // used for marking during flushing and deoptimization
 254 
 255  public:
 256   enum {
 257     _extra_is_being_redefined   = 1 << 0, // used for locking redefinition
 258     _extra_has_resolved_methods = 1 << 1, // resolved methods table entries added for this class
 259     _extra_has_value_fields     = 1 << 2, // has value fields and related embedded section is not empty
 260     _extra_is_bufferable        = 1 << 3  // value can be buffered out side of the Java heap
 261   };
 262 
 263  protected:
 264   u1              _extra_flags;
 265 
 266   // The low three bits of _misc_flags contains the kind field.
 267   // This can be used to quickly discriminate among the five kinds of
 268   // InstanceKlass.
 269 
 270   static const unsigned _misc_kind_field_size = 3;
 271   static const unsigned _misc_kind_field_pos  = 0;
 272   static const unsigned _misc_kind_field_mask = (1u << _misc_kind_field_size) - 1u;
 273 
 274   static const unsigned _misc_kind_other        = 0; // concrete InstanceKlass
 275   static const unsigned _misc_kind_reference    = 1; // InstanceRefKlass
 276   static const unsigned _misc_kind_class_loader = 2; // InstanceClassLoaderKlass
 277   static const unsigned _misc_kind_mirror       = 3; // InstanceMirrorKlass
 278   static const unsigned _misc_kind_value_type   = 4; // ValueKlass
 279 
 280   // Start after _misc_kind field.
 281   enum {
 282     _misc_rewritten                           = 1 << 3,  // methods rewritten.
 283     _misc_has_nonstatic_fields                = 1 << 4,  // for sizing with UseCompressedOops
 284     _misc_should_verify_class                 = 1 << 5,  // allow caching of preverification
 285     _misc_is_unsafe_anonymous                 = 1 << 6,  // has embedded _unsafe_anonymous_host field
 286     _misc_is_contended                        = 1 << 7,  // marked with contended annotation
 287     _misc_has_nonstatic_concrete_methods      = 1 << 8,  // class/superclass/implemented interfaces has non-static, concrete methods
 288     _misc_declares_nonstatic_concrete_methods = 1 << 9,  // directly declares non-static, concrete methods
 289     _misc_has_been_redefined                  = 1 << 10,  // class has been redefined
 290     _misc_has_passed_fingerprint_check        = 1 << 11, // when this class was loaded, the fingerprint computed from its
 291                                                          // code source was found to be matching the value recorded by AOT.
 292     _misc_is_scratch_class                    = 1 << 12, // class is the redefined scratch class
 293     _misc_is_shared_boot_class                = 1 << 13, // defining class loader is boot class loader
 294     _misc_is_shared_platform_class            = 1 << 14, // defining class loader is platform class loader
 295     _misc_is_shared_app_class                 = 1 << 15  // defining class loader is app class loader
 296     // u2 _misc_flags full (see _extra_flags)
 297   };
 298   u2 loader_type_bits() {
 299     return _misc_is_shared_boot_class|_misc_is_shared_platform_class|_misc_is_shared_app_class;
 300   }
 301   u2              _misc_flags;
 302   u2              _minor_version;        // minor version number of class file
 303   u2              _major_version;        // major version number of class file
 304   Thread*         _init_thread;          // Pointer to current thread doing initialization (to handle recursive initialization)
 305   OopMapCache*    volatile _oop_map_cache;   // OopMapCache for all methods in the klass (allocated lazily)
 306   JNIid*          _jni_ids;              // First JNI identifier for static fields in this class
 307   jmethodID*      volatile _methods_jmethod_ids;  // jmethodIDs corresponding to method_idnum, or NULL if none
 308   nmethodBucket*  volatile _dep_context;          // packed DependencyContext structure
 309   uint64_t        volatile _dep_context_last_cleaned;
 310   nmethod*        _osr_nmethods_head;    // Head of list of on-stack replacement nmethods for this class
 311 #if INCLUDE_JVMTI
 312   BreakpointInfo* _breakpoints;          // bpt lists, managed by Method*
 313   // Linked instanceKlasses of previous versions
 314   InstanceKlass* _previous_versions;
 315   // JVMTI fields can be moved to their own structure - see 6315920
 316   // JVMTI: cached class file, before retransformable agent modified it in CFLH
 317   JvmtiCachedClassFileData* _cached_class_file;
 318 #endif
 319 
 320   volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
 321 
 322   // Class states are defined as ClassState (see above).
 323   // Place the _init_state here to utilize the unused 2-byte after
 324   // _idnum_allocated_count.
 325   u1              _init_state;                    // state of class
 326   u1              _reference_type;                // reference type
 327 
 328   u2              _this_class_index;              // constant pool entry
 329 #if INCLUDE_JVMTI
 330   JvmtiCachedClassFieldMap* _jvmti_cached_class_field_map;  // JVMTI: used during heap iteration
 331 #endif
 332 
 333   NOT_PRODUCT(int _verify_count;)  // to avoid redundant verifies
 334 
 335   // Method array.
 336   Array<Method*>* _methods;
 337   // Default Method Array, concrete methods inherited from interfaces
 338   Array<Method*>* _default_methods;
 339   // Interfaces (InstanceKlass*s) this class declares locally to implement.
 340   Array<InstanceKlass*>* _local_interfaces;
 341   // Interfaces (InstanceKlass*s) this class implements transitively.
 342   Array<InstanceKlass*>* _transitive_interfaces;
 343   // Int array containing the original order of method in the class file (for JVMTI).
 344   Array<int>*     _method_ordering;
 345   // Int array containing the vtable_indices for default_methods
 346   // offset matches _default_methods offset
 347   Array<int>*     _default_vtable_indices;
 348 
 349   // Instance and static variable information, starts with 6-tuples of shorts
 350   // [access, name index, sig index, initval index, low_offset, high_offset]
 351   // for all fields, followed by the generic signature data at the end of
 352   // the array. Only fields with generic signature attributes have the generic
 353   // signature data set in the array. The fields array looks like following:
 354   //
 355   // f1: [access, name index, sig index, initial value index, low_offset, high_offset]
 356   // f2: [access, name index, sig index, initial value index, low_offset, high_offset]
 357   //      ...
 358   // fn: [access, name index, sig index, initial value index, low_offset, high_offset]
 359   //     [generic signature index]
 360   //     [generic signature index]
 361   //     ...
 362   Array<u2>*      _fields;
 363 
 364   const ValueKlassFixedBlock* _adr_valueklass_fixed_block;
 365 
 366   // embedded Java vtable follows here
 367   // embedded Java itables follows here
 368   // embedded static fields follows here
 369   // embedded nonstatic oop-map blocks follows here
 370   // embedded implementor of this interface follows here
 371   //   The embedded implementor only exists if the current klass is an
 372   //   iterface. The possible values of the implementor fall into following
 373   //   three cases:
 374   //     NULL: no implementor.
 375   //     A Klass* that's not itself: one implementor.
 376   //     Itself: more than one implementors.
 377   // embedded unsafe_anonymous_host klass follows here
 378   //   The embedded host klass only exists in an unsafe anonymous class for
 379   //   dynamic language support (JSR 292 enabled). The host class grants
 380   //   its access privileges to this class also. The host class is either
 381   //   named, or a previously loaded unsafe anonymous class. A non-anonymous class
 382   //   or an anonymous class loaded through normal classloading does not
 383   //   have this embedded field.
 384   //
 385 
 386   friend class SystemDictionary;
 387 
 388  public:
 389   u2 loader_type() {
 390     return _misc_flags & loader_type_bits();
 391   }
 392 
 393   bool is_shared_boot_class() const {
 394     return (_misc_flags & _misc_is_shared_boot_class) != 0;
 395   }
 396   bool is_shared_platform_class() const {
 397     return (_misc_flags & _misc_is_shared_platform_class) != 0;
 398   }
 399   bool is_shared_app_class() const {
 400     return (_misc_flags & _misc_is_shared_app_class) != 0;
 401   }
 402 
 403   void clear_class_loader_type() {
 404     _misc_flags &= ~loader_type_bits();
 405   }
 406 
 407   void set_class_loader_type(s2 loader_type);
 408 
 409   bool has_nonstatic_fields() const        {
 410     return (_misc_flags & _misc_has_nonstatic_fields) != 0;
 411   }
 412   void set_has_nonstatic_fields(bool b)    {
 413     if (b) {
 414       _misc_flags |= _misc_has_nonstatic_fields;
 415     } else {
 416       _misc_flags &= ~_misc_has_nonstatic_fields;
 417     }
 418   }
 419 
 420   bool has_value_fields() const          {
 421     return (_extra_flags & _extra_has_value_fields) != 0;
 422   }
 423   void set_has_value_fields()  {
 424     _extra_flags |= _extra_has_value_fields;
 425   }
 426 
 427   // field sizes
 428   int nonstatic_field_size() const         { return _nonstatic_field_size; }
 429   void set_nonstatic_field_size(int size)  { _nonstatic_field_size = size; }
 430 
 431   int static_field_size() const            { return _static_field_size; }
 432   void set_static_field_size(int size)     { _static_field_size = size; }
 433 
 434   int static_oop_field_count() const       { return (int)_static_oop_field_count; }
 435   void set_static_oop_field_count(u2 size) { _static_oop_field_count = size; }
 436 
 437   // Java itable
 438   int  itable_length() const               { return _itable_len; }
 439   void set_itable_length(int len)          { _itable_len = len; }
 440 
 441   // array klasses
 442   Klass* array_klasses() const             { return _array_klasses; }
 443   inline Klass* array_klasses_acquire() const; // load with acquire semantics
 444   void set_array_klasses(Klass* k)         { _array_klasses = k; }
 445   inline void release_set_array_klasses(Klass* k); // store with release semantics
 446 
 447   // methods
 448   Array<Method*>* methods() const          { return _methods; }
 449   void set_methods(Array<Method*>* a)      { _methods = a; }
 450   Method* method_with_idnum(int idnum);
 451   Method* method_with_orig_idnum(int idnum);
 452   Method* method_with_orig_idnum(int idnum, int version);
 453 
 454   // method ordering
 455   Array<int>* method_ordering() const     { return _method_ordering; }
 456   void set_method_ordering(Array<int>* m) { _method_ordering = m; }
 457   void copy_method_ordering(const intArray* m, TRAPS);
 458 
 459   // default_methods
 460   Array<Method*>* default_methods() const  { return _default_methods; }
 461   void set_default_methods(Array<Method*>* a) { _default_methods = a; }
 462 
 463   // default method vtable_indices
 464   Array<int>* default_vtable_indices() const { return _default_vtable_indices; }
 465   void set_default_vtable_indices(Array<int>* v) { _default_vtable_indices = v; }
 466   Array<int>* create_new_default_vtable_indices(int len, TRAPS);
 467 
 468   // interfaces
 469   Array<InstanceKlass*>* local_interfaces() const          { return _local_interfaces; }
 470   void set_local_interfaces(Array<InstanceKlass*>* a)      {
 471     guarantee(_local_interfaces == NULL || a == NULL, "Just checking");
 472     _local_interfaces = a; }
 473 
 474   Array<InstanceKlass*>* transitive_interfaces() const     { return _transitive_interfaces; }
 475   void set_transitive_interfaces(Array<InstanceKlass*>* a) {
 476     guarantee(_transitive_interfaces == NULL || a == NULL, "Just checking");
 477     _transitive_interfaces = a;
 478   }
 479 
 480  private:
 481   friend class fieldDescriptor;
 482   FieldInfo* field(int index) const { return FieldInfo::from_field_array(_fields, index); }
 483 
 484  public:
 485   int     field_offset      (int index) const { return field(index)->offset(); }
 486   int     field_access_flags(int index) const { return field(index)->access_flags(); }
 487   Symbol* field_name        (int index) const { return field(index)->name(constants()); }
 488   Symbol* field_signature   (int index) const { return field(index)->signature(constants()); }
 489   bool    field_is_flattened(int index) const { return field(index)->is_flattened(); }
 490 
 491   // Number of Java declared fields
 492   int java_fields_count() const           { return (int)_java_fields_count; }
 493 
 494   Array<u2>* fields() const            { return _fields; }
 495   void set_fields(Array<u2>* f, u2 java_fields_count) {
 496     guarantee(_fields == NULL || f == NULL, "Just checking");
 497     _fields = f;
 498     _java_fields_count = java_fields_count;
 499   }
 500 
 501   // inner classes
 502   Array<u2>* inner_classes() const       { return _inner_classes; }
 503   void set_inner_classes(Array<u2>* f)   { _inner_classes = f; }
 504 
 505   // nest members
 506   Array<u2>* nest_members() const     { return _nest_members; }
 507   void set_nest_members(Array<u2>* m) { _nest_members = m; }
 508 
 509   // nest-host index
 510   jushort nest_host_index() const { return _nest_host_index; }
 511   void set_nest_host_index(u2 i)  { _nest_host_index = i; }
 512 
 513 private:
 514   // Called to verify that k is a member of this nest - does not look at k's nest-host
 515   bool has_nest_member(InstanceKlass* k, TRAPS) const;
 516 public:
 517   // Returns nest-host class, resolving and validating it if needed
 518   // Returns NULL if an exception occurs during loading, or validation fails
 519   InstanceKlass* nest_host(Symbol* validationException, TRAPS);
 520   // Check if this klass is a nestmate of k - resolves this nest-host and k's
 521   bool has_nestmate_access_to(InstanceKlass* k, TRAPS);
 522 
 523   enum InnerClassAttributeOffset {
 524     // From http://mirror.eng/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc10.html#18814
 525     inner_class_inner_class_info_offset = 0,
 526     inner_class_outer_class_info_offset = 1,
 527     inner_class_inner_name_offset = 2,
 528     inner_class_access_flags_offset = 3,
 529     inner_class_next_offset = 4
 530   };
 531 
 532   enum EnclosingMethodAttributeOffset {
 533     enclosing_method_class_index_offset = 0,
 534     enclosing_method_method_index_offset = 1,
 535     enclosing_method_attribute_size = 2
 536   };
 537 
 538   // method override check
 539   bool is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS);
 540 
 541   // package
 542   PackageEntry* package() const     { return _package_entry; }
 543   ModuleEntry* module() const;
 544   bool in_unnamed_package() const   { return (_package_entry == NULL); }
 545   void set_package(PackageEntry* p) { _package_entry = p; }
 546   void set_package(ClassLoaderData* loader_data, TRAPS);
 547   bool is_same_class_package(const Klass* class2) const;
 548   bool is_same_class_package(oop other_class_loader, const Symbol* other_class_name) const;
 549 
 550   // find an enclosing class
 551   InstanceKlass* compute_enclosing_class(bool* inner_is_member, TRAPS) const;
 552 
 553   // Find InnerClasses attribute and return outer_class_info_index & inner_name_index.
 554   bool find_inner_classes_attr(int* ooff, int* noff, TRAPS) const;
 555 
 556  private:
 557   // Check prohibited package ("java/" only loadable by boot or platform loaders)
 558   static void check_prohibited_package(Symbol* class_name,
 559                                        ClassLoaderData* loader_data,
 560                                        TRAPS);
 561  public:
 562   // initialization state
 563   bool is_loaded() const                   { return _init_state >= loaded; }
 564   bool is_linked() const                   { return _init_state >= linked; }
 565   bool is_initialized() const              { return _init_state == fully_initialized; }
 566   bool is_not_initialized() const          { return _init_state <  being_initialized; }
 567   bool is_being_initialized() const        { return _init_state == being_initialized; }
 568   bool is_in_error_state() const           { return _init_state == initialization_error; }
 569   bool is_reentrant_initialization(Thread *thread)  { return thread == _init_thread; }
 570   ClassState  init_state()                 { return (ClassState)_init_state; }
 571   bool is_rewritten() const                { return (_misc_flags & _misc_rewritten) != 0; }
 572 
 573   // defineClass specified verification
 574   bool should_verify_class() const         {
 575     return (_misc_flags & _misc_should_verify_class) != 0;
 576   }
 577   void set_should_verify_class(bool value) {
 578     if (value) {
 579       _misc_flags |= _misc_should_verify_class;
 580     } else {
 581       _misc_flags &= ~_misc_should_verify_class;
 582     }
 583   }
 584 
 585   // marking
 586   bool is_marked_dependent() const         { return _is_marked_dependent; }
 587   void set_is_marked_dependent(bool value) { _is_marked_dependent = value; }
 588 
 589   static ByteSize extra_flags_offset() { return in_ByteSize(offset_of(InstanceKlass, _extra_flags)); }
 590 
 591   // initialization (virtuals from Klass)
 592   bool should_be_initialized() const;  // means that initialize should be called
 593   void initialize(TRAPS);
 594   void link_class(TRAPS);
 595   bool link_class_or_fail(TRAPS); // returns false on failure
 596   void rewrite_class(TRAPS);
 597   void link_methods(TRAPS);
 598   Method* class_initializer() const;
 599 
 600   // set the class to initialized if no static initializer is present
 601   void eager_initialize(Thread *thread);
 602 
 603   // reference type
 604   ReferenceType reference_type() const     { return (ReferenceType)_reference_type; }
 605   void set_reference_type(ReferenceType t) {
 606     assert(t == (u1)t, "overflow");
 607     _reference_type = (u1)t;
 608   }
 609 
 610   // this class cp index
 611   u2 this_class_index() const             { return _this_class_index; }
 612   void set_this_class_index(u2 index)     { _this_class_index = index; }
 613 
 614   static ByteSize reference_type_offset() { return in_ByteSize(offset_of(InstanceKlass, _reference_type)); }
 615 
 616   // find local field, returns true if found
 617   bool find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
 618   // find field in direct superinterfaces, returns the interface in which the field is defined
 619   Klass* find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
 620   // find field according to JVM spec 5.4.3.2, returns the klass in which the field is defined
 621   Klass* find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const;
 622   // find instance or static fields according to JVM spec 5.4.3.2, returns the klass in which the field is defined
 623   Klass* find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const;
 624 
 625   // find a non-static or static field given its offset within the class.
 626   bool contains_field_offset(int offset) {
 627     return instanceOopDesc::contains_field_offset(offset, nonstatic_field_size(), is_value());
 628   }
 629 
 630   bool find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const;
 631   bool find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const;
 632 
 633   // find a local method (returns NULL if not found)
 634   Method* find_method(const Symbol* name, const Symbol* signature) const;
 635   static Method* find_method(const Array<Method*>* methods,
 636                              const Symbol* name,
 637                              const Symbol* signature);
 638 
 639   // find a local method, but skip static methods
 640   Method* find_instance_method(const Symbol* name, const Symbol* signature,
 641                                PrivateLookupMode private_mode = find_private) const;
 642   static Method* find_instance_method(const Array<Method*>* methods,
 643                                       const Symbol* name,
 644                                       const Symbol* signature,
 645                                       PrivateLookupMode private_mode = find_private);
 646 
 647   // find a local method (returns NULL if not found)
 648   Method* find_local_method(const Symbol* name,
 649                             const Symbol* signature,
 650                             OverpassLookupMode overpass_mode,
 651                             StaticLookupMode static_mode,
 652                             PrivateLookupMode private_mode) const;
 653 
 654   // find a local method from given methods array (returns NULL if not found)
 655   static Method* find_local_method(const Array<Method*>* methods,
 656                                    const Symbol* name,
 657                                    const Symbol* signature,
 658                                    OverpassLookupMode overpass_mode,
 659                                    StaticLookupMode static_mode,
 660                                    PrivateLookupMode private_mode);
 661 
 662   // find a local method index in methods or default_methods (returns -1 if not found)
 663   static int find_method_index(const Array<Method*>* methods,
 664                                const Symbol* name,
 665                                const Symbol* signature,
 666                                OverpassLookupMode overpass_mode,
 667                                StaticLookupMode static_mode,
 668                                PrivateLookupMode private_mode);
 669 
 670   // lookup operation (returns NULL if not found)
 671   Method* uncached_lookup_method(const Symbol* name,
 672                                  const Symbol* signature,
 673                                  OverpassLookupMode overpass_mode,
 674                                  PrivateLookupMode private_mode = find_private) const;
 675 
 676   // lookup a method in all the interfaces that this class implements
 677   // (returns NULL if not found)
 678   Method* lookup_method_in_all_interfaces(Symbol* name, Symbol* signature, DefaultsLookupMode defaults_mode) const;
 679 
 680   // lookup a method in local defaults then in all interfaces
 681   // (returns NULL if not found)
 682   Method* lookup_method_in_ordered_interfaces(Symbol* name, Symbol* signature) const;
 683 
 684   // Find method indices by name.  If a method with the specified name is
 685   // found the index to the first method is returned, and 'end' is filled in
 686   // with the index of first non-name-matching method.  If no method is found
 687   // -1 is returned.
 688   int find_method_by_name(const Symbol* name, int* end) const;
 689   static int find_method_by_name(const Array<Method*>* methods,
 690                                  const Symbol* name, int* end);
 691 
 692   // constant pool
 693   ConstantPool* constants() const        { return _constants; }
 694   void set_constants(ConstantPool* c)    { _constants = c; }
 695 
 696   // protection domain
 697   oop protection_domain() const;
 698 
 699   // signers
 700   objArrayOop signers() const;
 701 
 702   // host class
 703   InstanceKlass* unsafe_anonymous_host() const {
 704     InstanceKlass** hk = adr_unsafe_anonymous_host();
 705     if (hk == NULL) {
 706       assert(!is_unsafe_anonymous(), "Unsafe anonymous classes have host klasses");
 707       return NULL;
 708     } else {
 709       assert(*hk != NULL, "host klass should always be set if the address is not null");
 710       assert(is_unsafe_anonymous(), "Only unsafe anonymous classes have host klasses");
 711       return *hk;
 712     }
 713   }
 714   void set_unsafe_anonymous_host(const InstanceKlass* host) {
 715     assert(is_unsafe_anonymous(), "not unsafe anonymous");
 716     const InstanceKlass** addr = (const InstanceKlass **)adr_unsafe_anonymous_host();
 717     assert(addr != NULL, "no reversed space");
 718     if (addr != NULL) {
 719       *addr = host;
 720     }
 721   }
 722   bool is_unsafe_anonymous() const                {
 723     return (_misc_flags & _misc_is_unsafe_anonymous) != 0;
 724   }
 725   void set_is_unsafe_anonymous(bool value)        {
 726     if (value) {
 727       _misc_flags |= _misc_is_unsafe_anonymous;
 728     } else {
 729       _misc_flags &= ~_misc_is_unsafe_anonymous;
 730     }
 731   }
 732 
 733   bool is_contended() const                {
 734     return (_misc_flags & _misc_is_contended) != 0;
 735   }
 736   void set_is_contended(bool value)        {
 737     if (value) {
 738       _misc_flags |= _misc_is_contended;
 739     } else {
 740       _misc_flags &= ~_misc_is_contended;
 741     }
 742   }
 743 
 744   // source file name
 745   Symbol* source_file_name() const               {
 746     return (_source_file_name_index == 0) ?
 747       (Symbol*)NULL : _constants->symbol_at(_source_file_name_index);
 748   }
 749   u2 source_file_name_index() const              {
 750     return _source_file_name_index;
 751   }
 752   void set_source_file_name_index(u2 sourcefile_index) {
 753     _source_file_name_index = sourcefile_index;
 754   }
 755 
 756   // minor and major version numbers of class file
 757   u2 minor_version() const                 { return _minor_version; }
 758   void set_minor_version(u2 minor_version) { _minor_version = minor_version; }
 759   u2 major_version() const                 { return _major_version; }
 760   void set_major_version(u2 major_version) { _major_version = major_version; }
 761 
 762   // source debug extension
 763   const char* source_debug_extension() const { return _source_debug_extension; }
 764   void set_source_debug_extension(const char* array, int length);
 765 
 766   // symbol unloading support (refcount already added)
 767   Symbol* array_name()                     { return _array_name; }
 768   void set_array_name(Symbol* name)        { assert(_array_name == NULL  || name == NULL, "name already created"); _array_name = name; }
 769 
 770   // nonstatic oop-map blocks
 771   static int nonstatic_oop_map_size(unsigned int oop_map_count) {
 772     return oop_map_count * OopMapBlock::size_in_words();
 773   }
 774   unsigned int nonstatic_oop_map_count() const {
 775     return _nonstatic_oop_map_size / OopMapBlock::size_in_words();
 776   }
 777   int nonstatic_oop_map_size() const { return _nonstatic_oop_map_size; }
 778   void set_nonstatic_oop_map_size(int words) {
 779     _nonstatic_oop_map_size = words;
 780   }
 781 
 782 #if INCLUDE_JVMTI
 783   // Redefinition locking.  Class can only be redefined by one thread at a time.
 784   bool is_being_redefined() const          {
 785     return (_extra_flags & _extra_is_being_redefined);
 786   }
 787   void set_is_being_redefined(bool value)  {
 788     if (value) {
 789       _extra_flags |= _extra_is_being_redefined;
 790     } else {
 791       _extra_flags &= ~_extra_is_being_redefined;
 792     }
 793   }
 794 
 795   // RedefineClasses() support for previous versions:
 796   void add_previous_version(InstanceKlass* ik, int emcp_method_count);
 797   void purge_previous_version_list();
 798 
 799   InstanceKlass* previous_versions() const { return _previous_versions; }
 800 #else
 801   InstanceKlass* previous_versions() const { return NULL; }
 802 #endif
 803 
 804   InstanceKlass* get_klass_version(int version) {
 805     for (InstanceKlass* ik = this; ik != NULL; ik = ik->previous_versions()) {
 806       if (ik->constants()->version() == version) {
 807         return ik;
 808       }
 809     }
 810     return NULL;
 811   }
 812 
 813   bool has_been_redefined() const {
 814     return (_misc_flags & _misc_has_been_redefined) != 0;
 815   }
 816   void set_has_been_redefined() {
 817     _misc_flags |= _misc_has_been_redefined;
 818   }
 819 
 820   bool has_passed_fingerprint_check() const {
 821     return (_misc_flags & _misc_has_passed_fingerprint_check) != 0;
 822   }
 823   void set_has_passed_fingerprint_check(bool b) {
 824     if (b) {
 825       _misc_flags |= _misc_has_passed_fingerprint_check;
 826     } else {
 827       _misc_flags &= ~_misc_has_passed_fingerprint_check;
 828     }
 829   }
 830   bool supers_have_passed_fingerprint_checks();
 831 
 832   static bool should_store_fingerprint(bool is_unsafe_anonymous);
 833   bool should_store_fingerprint() const { return should_store_fingerprint(is_unsafe_anonymous()); }
 834   bool has_stored_fingerprint() const;
 835   uint64_t get_stored_fingerprint() const;
 836   void store_fingerprint(uint64_t fingerprint);
 837 
 838   bool is_scratch_class() const {
 839     return (_misc_flags & _misc_is_scratch_class) != 0;
 840   }
 841 
 842   void set_is_scratch_class() {
 843     _misc_flags |= _misc_is_scratch_class;
 844   }
 845 
 846   bool has_resolved_methods() const {
 847     return (_extra_flags & _extra_has_resolved_methods) != 0;
 848   }
 849 
 850   void set_has_resolved_methods() {
 851     _extra_flags |= _extra_has_resolved_methods;
 852   }
 853 private:
 854 
 855   void set_kind(unsigned kind) {
 856     assert(kind <= _misc_kind_field_mask, "Invalid InstanceKlass kind");
 857     unsigned fmask = _misc_kind_field_mask << _misc_kind_field_pos;
 858     unsigned flags = _misc_flags & ~fmask;
 859     _misc_flags = (flags | (kind << _misc_kind_field_pos));
 860   }
 861 
 862   bool is_kind(unsigned desired) const {
 863     unsigned kind = (_misc_flags >> _misc_kind_field_pos) & _misc_kind_field_mask;
 864     return kind == desired;
 865   }
 866 
 867 public:
 868 
 869   // Other is anything that is not one of the more specialized kinds of InstanceKlass.
 870   bool is_other_instance_klass() const        { return is_kind(_misc_kind_other); }
 871   bool is_reference_instance_klass() const    { return is_kind(_misc_kind_reference); }
 872   bool is_mirror_instance_klass() const       { return is_kind(_misc_kind_mirror); }
 873   bool is_class_loader_instance_klass() const { return is_kind(_misc_kind_class_loader); }
 874   bool is_value_type_klass()            const { return is_kind(_misc_kind_value_type); }
 875 
 876 #if INCLUDE_JVMTI
 877 
 878   void init_previous_versions() {
 879     _previous_versions = NULL;
 880   }
 881 
 882  private:
 883   static bool  _has_previous_versions;
 884  public:
 885   static void purge_previous_versions(InstanceKlass* ik) {
 886     if (ik->has_been_redefined()) {
 887       ik->purge_previous_version_list();
 888     }
 889   }
 890 
 891   static bool has_previous_versions_and_reset();
 892   static bool has_previous_versions() { return _has_previous_versions; }
 893 
 894   // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation
 895   void set_cached_class_file(JvmtiCachedClassFileData *data) {
 896     _cached_class_file = data;
 897   }
 898   JvmtiCachedClassFileData * get_cached_class_file();
 899   jint get_cached_class_file_len();
 900   unsigned char * get_cached_class_file_bytes();
 901 
 902   // JVMTI: Support for caching of field indices, types, and offsets
 903   void set_jvmti_cached_class_field_map(JvmtiCachedClassFieldMap* descriptor) {
 904     _jvmti_cached_class_field_map = descriptor;
 905   }
 906   JvmtiCachedClassFieldMap* jvmti_cached_class_field_map() const {
 907     return _jvmti_cached_class_field_map;
 908   }
 909 #else // INCLUDE_JVMTI
 910 
 911   static void purge_previous_versions(InstanceKlass* ik) { return; };
 912   static bool has_previous_versions_and_reset() { return false; }
 913 
 914   void set_cached_class_file(JvmtiCachedClassFileData *data) {
 915     assert(data == NULL, "unexpected call with JVMTI disabled");
 916   }
 917   JvmtiCachedClassFileData * get_cached_class_file() { return (JvmtiCachedClassFileData *)NULL; }
 918 
 919 #endif // INCLUDE_JVMTI
 920 
 921   bool has_nonstatic_concrete_methods() const {
 922     return (_misc_flags & _misc_has_nonstatic_concrete_methods) != 0;
 923   }
 924   void set_has_nonstatic_concrete_methods(bool b) {
 925     if (b) {
 926       _misc_flags |= _misc_has_nonstatic_concrete_methods;
 927     } else {
 928       _misc_flags &= ~_misc_has_nonstatic_concrete_methods;
 929     }
 930   }
 931 
 932   bool declares_nonstatic_concrete_methods() const {
 933     return (_misc_flags & _misc_declares_nonstatic_concrete_methods) != 0;
 934   }
 935   void set_declares_nonstatic_concrete_methods(bool b) {
 936     if (b) {
 937       _misc_flags |= _misc_declares_nonstatic_concrete_methods;
 938     } else {
 939       _misc_flags &= ~_misc_declares_nonstatic_concrete_methods;
 940     }
 941   }
 942 
 943   // for adding methods, ConstMethod::UNSET_IDNUM means no more ids available
 944   inline u2 next_method_idnum();
 945   void set_initial_method_idnum(u2 value)             { _idnum_allocated_count = value; }
 946 
 947   // generics support
 948   Symbol* generic_signature() const                   {
 949     return (_generic_signature_index == 0) ?
 950       (Symbol*)NULL : _constants->symbol_at(_generic_signature_index);
 951   }
 952   u2 generic_signature_index() const                  {
 953     return _generic_signature_index;
 954   }
 955   void set_generic_signature_index(u2 sig_index)      {
 956     _generic_signature_index = sig_index;
 957   }
 958 
 959   u2 enclosing_method_data(int offset) const;
 960   u2 enclosing_method_class_index() const {
 961     return enclosing_method_data(enclosing_method_class_index_offset);
 962   }
 963   u2 enclosing_method_method_index() {
 964     return enclosing_method_data(enclosing_method_method_index_offset);
 965   }
 966   void set_enclosing_method_indices(u2 class_index,
 967                                     u2 method_index);
 968 
 969   // jmethodID support
 970   jmethodID get_jmethod_id(const methodHandle& method_h);
 971   jmethodID get_jmethod_id_fetch_or_update(size_t idnum,
 972                      jmethodID new_id, jmethodID* new_jmeths,
 973                      jmethodID* to_dealloc_id_p,
 974                      jmethodID** to_dealloc_jmeths_p);
 975   static void get_jmethod_id_length_value(jmethodID* cache, size_t idnum,
 976                 size_t *length_p, jmethodID* id_p);
 977   void ensure_space_for_methodids(int start_offset = 0);
 978   jmethodID jmethod_id_or_null(Method* method);
 979 
 980   // annotations support
 981   Annotations* annotations() const          { return _annotations; }
 982   void set_annotations(Annotations* anno)   { _annotations = anno; }
 983 
 984   AnnotationArray* class_annotations() const {
 985     return (_annotations != NULL) ? _annotations->class_annotations() : NULL;
 986   }
 987   Array<AnnotationArray*>* fields_annotations() const {
 988     return (_annotations != NULL) ? _annotations->fields_annotations() : NULL;
 989   }
 990   AnnotationArray* class_type_annotations() const {
 991     return (_annotations != NULL) ? _annotations->class_type_annotations() : NULL;
 992   }
 993   Array<AnnotationArray*>* fields_type_annotations() const {
 994     return (_annotations != NULL) ? _annotations->fields_type_annotations() : NULL;
 995   }
 996   // allocation
 997   instanceOop allocate_instance(TRAPS);
 998 
 999   // additional member function to return a handle
1000   instanceHandle allocate_instance_handle(TRAPS);
1001 
1002   objArrayOop allocate_objArray(int n, int length, TRAPS);
1003   // Helper function
1004   static instanceOop register_finalizer(instanceOop i, TRAPS);
1005 
1006   // Check whether reflection/jni/jvm code is allowed to instantiate this class;
1007   // if not, throw either an Error or an Exception.
1008   virtual void check_valid_for_instantiation(bool throwError, TRAPS);
1009 
1010   // initialization
1011   void call_class_initializer(TRAPS);
1012   void set_initialization_state_and_notify(ClassState state, TRAPS);
1013 
1014   // OopMapCache support
1015   OopMapCache* oop_map_cache()               { return _oop_map_cache; }
1016   void set_oop_map_cache(OopMapCache *cache) { _oop_map_cache = cache; }
1017   void mask_for(const methodHandle& method, int bci, InterpreterOopMap* entry);
1018 
1019   // JNI identifier support (for static fields - for jni performance)
1020   JNIid* jni_ids()                               { return _jni_ids; }
1021   void set_jni_ids(JNIid* ids)                   { _jni_ids = ids; }
1022   JNIid* jni_id_for(int offset);
1023 
1024   // maintenance of deoptimization dependencies
1025   inline DependencyContext dependencies();
1026   int  mark_dependent_nmethods(KlassDepChange& changes);
1027   void add_dependent_nmethod(nmethod* nm);
1028   void remove_dependent_nmethod(nmethod* nm);
1029   void clean_dependency_context();
1030 
1031   // On-stack replacement support
1032   nmethod* osr_nmethods_head() const         { return _osr_nmethods_head; };
1033   void set_osr_nmethods_head(nmethod* h)     { _osr_nmethods_head = h; };
1034   void add_osr_nmethod(nmethod* n);
1035   bool remove_osr_nmethod(nmethod* n);
1036   int mark_osr_nmethods(const Method* m);
1037   nmethod* lookup_osr_nmethod(const Method* m, int bci, int level, bool match_level) const;
1038 
1039 #if INCLUDE_JVMTI
1040   // Breakpoint support (see methods on Method* for details)
1041   BreakpointInfo* breakpoints() const       { return _breakpoints; };
1042   void set_breakpoints(BreakpointInfo* bps) { _breakpoints = bps; };
1043 #endif
1044 
1045   // support for stub routines
1046   static ByteSize init_state_offset()  { return in_ByteSize(offset_of(InstanceKlass, _init_state)); }
1047   JFR_ONLY(DEFINE_KLASS_TRACE_ID_OFFSET;)
1048   static ByteSize init_thread_offset() { return in_ByteSize(offset_of(InstanceKlass, _init_thread)); }
1049 
1050   static ByteSize adr_valueklass_fixed_block_offset() { return in_ByteSize(offset_of(InstanceKlass, _adr_valueklass_fixed_block)); }
1051 
1052   // subclass/subinterface checks
1053   bool implements_interface(Klass* k) const;
1054   bool is_same_or_direct_interface(Klass* k) const;
1055 
1056 #ifdef ASSERT
1057   // check whether this class or one of its superclasses was redefined
1058   bool has_redefined_this_or_super() const;
1059 #endif
1060 
1061   // Access to the implementor of an interface.
1062   Klass* implementor() const;
1063   void set_implementor(Klass* k);
1064   int  nof_implementors() const;
1065   void add_implementor(Klass* k);  // k is a new class that implements this interface
1066   void init_implementor();           // initialize
1067 
1068   // link this class into the implementors list of every interface it implements
1069   void process_interfaces(Thread *thread);
1070 
1071   // virtual operations from Klass
1072   bool is_leaf_class() const               { return _subklass == NULL; }
1073   GrowableArray<Klass*>* compute_secondary_supers(int num_extra_slots,
1074                                                   Array<InstanceKlass*>* transitive_interfaces);
1075   bool can_be_primary_super_slow() const;
1076   int oop_size(oop obj)  const             { return size_helper(); }
1077   // slow because it's a virtual call and used for verifying the layout_helper.
1078   // Using the layout_helper bits, we can call is_instance_klass without a virtual call.
1079   DEBUG_ONLY(bool is_instance_klass_slow() const      { return true; })
1080 
1081   // Iterators
1082   void do_local_static_fields(FieldClosure* cl);
1083   void do_nonstatic_fields(FieldClosure* cl); // including inherited fields
1084   void do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle, TRAPS);
1085 
1086   void methods_do(void f(Method* method));
1087   virtual void array_klasses_do(void f(Klass* k));
1088 
1089   static InstanceKlass* cast(Klass* k) {
1090     return const_cast<InstanceKlass*>(cast(const_cast<const Klass*>(k)));
1091   }
1092 
1093   static const InstanceKlass* cast(const Klass* k) {
1094     assert(k != NULL, "k should not be null");
1095     assert(k->is_instance_klass(), "cast to InstanceKlass");
1096     return static_cast<const InstanceKlass*>(k);
1097   }
1098 
1099   virtual InstanceKlass* java_super() const {
1100     return (super() == NULL) ? NULL : cast(super());
1101   }
1102 
1103   // Sizing (in words)
1104   static int header_size()            { return sizeof(InstanceKlass)/wordSize; }
1105 
1106   static int size(int vtable_length, int itable_length,
1107                   int nonstatic_oop_map_size,
1108                   bool is_interface, bool is_unsafe_anonymous, bool has_stored_fingerprint,
1109                   int java_fields, bool is_value_type) {
1110     return align_metadata_size(header_size() +
1111            vtable_length +
1112            itable_length +
1113            nonstatic_oop_map_size +
1114            (is_interface ? (int)sizeof(Klass*)/wordSize : 0) +
1115            (is_unsafe_anonymous ? (int)sizeof(Klass*)/wordSize : 0) +
1116            (has_stored_fingerprint ? (int)sizeof(uint64_t*)/wordSize : 0) +
1117            (java_fields * (int)sizeof(Klass*)/wordSize) +
1118            (is_value_type ? (int)sizeof(ValueKlassFixedBlock) : 0));
1119   }
1120   int size() const                    { return size(vtable_length(),
1121                                                itable_length(),
1122                                                nonstatic_oop_map_size(),
1123                                                is_interface(),
1124                                                is_unsafe_anonymous(),
1125                                                has_stored_fingerprint(),
1126                                                has_value_fields() ? java_fields_count() : 0,
1127                                                is_value());
1128   }
1129 #if INCLUDE_SERVICES
1130   virtual void collect_statistics(KlassSizeStats *sz) const;
1131 #endif
1132 
1133   intptr_t* start_of_itable()   const { return (intptr_t*)start_of_vtable() + vtable_length(); }
1134   intptr_t* end_of_itable()     const { return start_of_itable() + itable_length(); }
1135 
1136   int  itable_offset_in_words() const { return start_of_itable() - (intptr_t*)this; }
1137 
1138   oop static_field_base_raw() { return java_mirror(); }
1139 
1140   bool bounds_check(address addr, bool edge_ok = false, intptr_t size_in_bytes = -1) const PRODUCT_RETURN0;
1141 
1142   OopMapBlock* start_of_nonstatic_oop_maps() const {
1143     return (OopMapBlock*)(start_of_itable() + itable_length());
1144   }
1145 
1146   Klass** end_of_nonstatic_oop_maps() const {
1147     return (Klass**)(start_of_nonstatic_oop_maps() +
1148                      nonstatic_oop_map_count());
1149   }
1150 
1151   Klass* volatile* adr_implementor() const {
1152     if (is_interface()) {
1153       return (Klass* volatile*)end_of_nonstatic_oop_maps();
1154     } else {
1155       return NULL;
1156     }
1157   };
1158 
1159   InstanceKlass** adr_unsafe_anonymous_host() const {
1160     if (is_unsafe_anonymous()) {
1161       InstanceKlass** adr_impl = (InstanceKlass**)adr_implementor();
1162       if (adr_impl != NULL) {
1163         return adr_impl + 1;
1164       } else {
1165         return (InstanceKlass **)end_of_nonstatic_oop_maps();
1166       }
1167     } else {
1168       return NULL;
1169     }
1170   }
1171 
1172   address adr_fingerprint() const {
1173     if (has_stored_fingerprint()) {
1174       InstanceKlass** adr_host = adr_unsafe_anonymous_host();
1175       if (adr_host != NULL) {
1176         return (address)(adr_host + 1);
1177       }
1178 
1179       Klass* volatile* adr_impl = adr_implementor();
1180       if (adr_impl != NULL) {
1181         return (address)(adr_impl + 1);
1182       }
1183 
1184       return (address)end_of_nonstatic_oop_maps();
1185     } else {
1186       return NULL;
1187     }
1188   }
1189 
1190   address adr_value_fields_klasses() const {
1191     if (has_value_fields()) {
1192       address adr_fing = adr_fingerprint();
1193       if (adr_fing != NULL) {
1194         return adr_fingerprint() + sizeof(u8);
1195       }
1196 
1197       InstanceKlass** adr_host = adr_unsafe_anonymous_host();
1198       if (adr_host != NULL) {
1199         return (address)(adr_host + 1);
1200       }
1201 
1202       Klass* volatile* adr_impl = adr_implementor();
1203       if (adr_impl != NULL) {
1204         return (address)(adr_impl + 1);
1205       }
1206 
1207       return (address)end_of_nonstatic_oop_maps();
1208     } else {
1209       return NULL;
1210     }
1211   }
1212 
1213   Klass* get_value_field_klass(int idx) const {
1214     assert(has_value_fields(), "Sanity checking");
1215     Klass* k = ((Klass**)adr_value_fields_klasses())[idx];
1216     assert(k != NULL, "Should always be set before being read");
1217     assert(k->is_value(), "Must be a value type");
1218     return k;
1219   }
1220 
1221   Klass* get_value_field_klass_or_null(int idx) const {
1222     assert(has_value_fields(), "Sanity checking");
1223     Klass* k = ((Klass**)adr_value_fields_klasses())[idx];
1224     assert(k == NULL || k->is_value(), "Must be a value type");
1225     return k;
1226   }
1227 
1228   void set_value_field_klass(int idx, Klass* k) {
1229     assert(has_value_fields(), "Sanity checking");
1230     assert(k != NULL, "Should not be set to NULL");
1231     assert(((Klass**)adr_value_fields_klasses())[idx] == NULL, "Should not be set twice");
1232     ((Klass**)adr_value_fields_klasses())[idx] = k;
1233   }
1234 
1235   // Use this to return the size of an instance in heap words:
1236   virtual int size_helper() const {
1237     return layout_helper_to_size_helper(layout_helper());
1238   }
1239 
1240   // This bit is initialized in classFileParser.cpp.
1241   // It is false under any of the following conditions:
1242   //  - the class is abstract (including any interface)
1243   //  - the class has a finalizer (if !RegisterFinalizersAtInit)
1244   //  - the class size is larger than FastAllocateSizeLimit
1245   //  - the class is java/lang/Class, which cannot be allocated directly
1246   bool can_be_fastpath_allocated() const {
1247     return !layout_helper_needs_slow_path(layout_helper());
1248   }
1249 
1250   // Java itable
1251   klassItable itable() const;        // return klassItable wrapper
1252   Method* method_at_itable(Klass* holder, int index, TRAPS);
1253 
1254 #if INCLUDE_JVMTI
1255   void adjust_default_methods(bool* trace_name_printed);
1256 #endif // INCLUDE_JVMTI
1257 
1258   void clean_weak_instanceklass_links();
1259  private:
1260   void clean_implementors_list();
1261   void clean_method_data();
1262 
1263  public:
1264   // Explicit metaspace deallocation of fields
1265   // For RedefineClasses and class file parsing errors, we need to deallocate
1266   // instanceKlasses and the metadata they point to.
1267   void deallocate_contents(ClassLoaderData* loader_data);
1268   static void deallocate_methods(ClassLoaderData* loader_data,
1269                                  Array<Method*>* methods);
1270   void static deallocate_interfaces(ClassLoaderData* loader_data,
1271                                     const Klass* super_klass,
1272                                     Array<InstanceKlass*>* local_interfaces,
1273                                     Array<InstanceKlass*>* transitive_interfaces);
1274 
1275   // The constant pool is on stack if any of the methods are executing or
1276   // referenced by handles.
1277   bool on_stack() const { return _constants->on_stack(); }
1278 
1279   // callbacks for actions during class unloading
1280   static void unload_class(InstanceKlass* ik);
1281   static void release_C_heap_structures(InstanceKlass* ik);
1282 
1283   // Naming
1284   const char* signature_name() const;
1285   const char* signature_name_of(char c) const;
1286   static Symbol* package_from_name(const Symbol* name, TRAPS);
1287 
1288   // Oop fields (and metadata) iterators
1289   //
1290   // The InstanceKlass iterators also visits the Object's klass.
1291 
1292   // Forward iteration
1293  public:
1294   // Iterate over all oop fields in the oop maps.
1295   template <typename T, class OopClosureType>
1296   inline void oop_oop_iterate_oop_maps(oop obj, OopClosureType* closure);
1297 
1298   // Iterate over all oop fields and metadata.
1299   template <typename T, class OopClosureType>
1300   inline void oop_oop_iterate(oop obj, OopClosureType* closure);
1301 
1302   // Iterate over all oop fields in one oop map.
1303   template <typename T, class OopClosureType>
1304   inline void oop_oop_iterate_oop_map(OopMapBlock* map, oop obj, OopClosureType* closure);
1305 
1306 
1307   // Reverse iteration
1308   // Iterate over all oop fields and metadata.
1309   template <typename T, class OopClosureType>
1310   inline void oop_oop_iterate_reverse(oop obj, OopClosureType* closure);
1311 
1312  private:
1313   // Iterate over all oop fields in the oop maps.
1314   template <typename T, class OopClosureType>
1315   inline void oop_oop_iterate_oop_maps_reverse(oop obj, OopClosureType* closure);
1316 
1317   // Iterate over all oop fields in one oop map.
1318   template <typename T, class OopClosureType>
1319   inline void oop_oop_iterate_oop_map_reverse(OopMapBlock* map, oop obj, OopClosureType* closure);
1320 
1321 
1322   // Bounded range iteration
1323  public:
1324   // Iterate over all oop fields in the oop maps.
1325   template <typename T, class OopClosureType>
1326   inline void oop_oop_iterate_oop_maps_bounded(oop obj, OopClosureType* closure, MemRegion mr);
1327 
1328   // Iterate over all oop fields and metadata.
1329   template <typename T, class OopClosureType>
1330   inline void oop_oop_iterate_bounded(oop obj, OopClosureType* closure, MemRegion mr);
1331 
1332  private:
1333   // Iterate over all oop fields in one oop map.
1334   template <typename T, class OopClosureType>
1335   inline void oop_oop_iterate_oop_map_bounded(OopMapBlock* map, oop obj, OopClosureType* closure, MemRegion mr);
1336 
1337 
1338  public:
1339   u2 idnum_allocated_count() const      { return _idnum_allocated_count; }
1340 
1341 public:
1342   void set_in_error_state() {
1343     assert(DumpSharedSpaces, "only call this when dumping archive");
1344     _init_state = initialization_error;
1345   }
1346   bool check_sharing_error_state();
1347 
1348 private:
1349   // initialization state
1350   void set_init_state(ClassState state);
1351   void set_rewritten()                  { _misc_flags |= _misc_rewritten; }
1352   void set_init_thread(Thread *thread)  { _init_thread = thread; }
1353 
1354   // The RedefineClasses() API can cause new method idnums to be needed
1355   // which will cause the caches to grow. Safety requires different
1356   // cache management logic if the caches can grow instead of just
1357   // going from NULL to non-NULL.
1358   bool idnum_can_increment() const      { return has_been_redefined(); }
1359   inline jmethodID* methods_jmethod_ids_acquire() const;
1360   inline void release_set_methods_jmethod_ids(jmethodID* jmeths);
1361 
1362   // Lock during initialization
1363 public:
1364   // Lock for (1) initialization; (2) access to the ConstantPool of this class.
1365   // Must be one per class and it has to be a VM internal object so java code
1366   // cannot lock it (like the mirror).
1367   // It has to be an object not a Mutex because it's held through java calls.
1368   oop init_lock() const;
1369 private:
1370   void fence_and_clear_init_lock();
1371 
1372   bool link_class_impl                           (TRAPS);
1373   bool verify_code                               (TRAPS);
1374   void initialize_impl                           (TRAPS);
1375   void initialize_super_interfaces               (TRAPS);
1376   void eager_initialize_impl                     ();
1377   /* jni_id_for_impl for jfieldID only */
1378   JNIid* jni_id_for_impl                         (int offset);
1379 protected:
1380   // Returns the array class for the n'th dimension
1381   virtual Klass* array_klass_impl(ArrayStorageProperties storage_props, bool or_null, int n, TRAPS);
1382 
1383   // Returns the array class with this class as element type
1384   virtual Klass* array_klass_impl(ArrayStorageProperties storage_props, bool or_null, TRAPS);
1385 
1386 private:
1387 
1388   // find a local method (returns NULL if not found)
1389   Method* find_method_impl(const Symbol* name,
1390                            const Symbol* signature,
1391                            OverpassLookupMode overpass_mode,
1392                            StaticLookupMode static_mode,
1393                            PrivateLookupMode private_mode) const;
1394 
1395   static Method* find_method_impl(const Array<Method*>* methods,
1396                                   const Symbol* name,
1397                                   const Symbol* signature,
1398                                   OverpassLookupMode overpass_mode,
1399                                   StaticLookupMode static_mode,
1400                                   PrivateLookupMode private_mode);
1401 
1402   // Free CHeap allocated fields.
1403   void release_C_heap_structures();
1404 
1405 #if INCLUDE_JVMTI
1406   // RedefineClasses support
1407   void link_previous_versions(InstanceKlass* pv) { _previous_versions = pv; }
1408   void mark_newly_obsolete_methods(Array<Method*>* old_methods, int emcp_method_count);
1409 #endif
1410 public:
1411   // CDS support - remove and restore oops from metadata. Oops are not shared.
1412   virtual void remove_unshareable_info();
1413   virtual void remove_java_mirror();
1414   virtual void restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS);
1415 
1416   // jvm support
1417   jint compute_modifier_flags(TRAPS) const;
1418 
1419 public:
1420   // JVMTI support
1421   jint jvmti_class_status() const;
1422 
1423   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
1424 
1425  public:
1426   // Printing
1427 #ifndef PRODUCT
1428   void print_on(outputStream* st) const;
1429 #endif
1430   void print_value_on(outputStream* st) const;
1431 
1432   void oop_print_value_on(oop obj, outputStream* st);
1433 
1434 #ifndef PRODUCT
1435   void oop_print_on      (oop obj, outputStream* st);
1436 
1437   void print_dependent_nmethods(bool verbose = false);
1438   bool is_dependent_nmethod(nmethod* nm);
1439   bool verify_itable_index(int index);
1440 #endif
1441 
1442   const char* internal_name() const;
1443 
1444   // Verification
1445   void verify_on(outputStream* st);
1446 
1447   void oop_verify_on(oop obj, outputStream* st);
1448 
1449   // Logging
1450   void print_class_load_logging(ClassLoaderData* loader_data,
1451                                 const char* module_name,
1452                                 const ClassFileStream* cfs) const;
1453 };
1454 
1455 // for adding methods
1456 // UNSET_IDNUM return means no more ids available
1457 inline u2 InstanceKlass::next_method_idnum() {
1458   if (_idnum_allocated_count == ConstMethod::MAX_IDNUM) {
1459     return ConstMethod::UNSET_IDNUM; // no more ids available
1460   } else {
1461     return _idnum_allocated_count++;
1462   }
1463 }
1464 
1465 
1466 /* JNIid class for jfieldIDs only */
1467 class JNIid: public CHeapObj<mtClass> {
1468   friend class VMStructs;
1469  private:
1470   Klass*             _holder;
1471   JNIid*             _next;
1472   int                _offset;
1473 #ifdef ASSERT
1474   bool               _is_static_field_id;
1475 #endif
1476 
1477  public:
1478   // Accessors
1479   Klass* holder() const           { return _holder; }
1480   int offset() const              { return _offset; }
1481   JNIid* next()                   { return _next; }
1482   // Constructor
1483   JNIid(Klass* holder, int offset, JNIid* next);
1484   // Identifier lookup
1485   JNIid* find(int offset);
1486 
1487   bool find_local_field(fieldDescriptor* fd) {
1488     return InstanceKlass::cast(holder())->find_local_field_from_offset(offset(), true, fd);
1489   }
1490 
1491   static void deallocate(JNIid* id);
1492   // Debugging
1493 #ifdef ASSERT
1494   bool is_static_field_id() const { return _is_static_field_id; }
1495   void set_is_static_field_id()   { _is_static_field_id = true; }
1496 #endif
1497   void verify(Klass* holder);
1498 };
1499 
1500 // An iterator that's used to access the inner classes indices in the
1501 // InstanceKlass::_inner_classes array.
1502 class InnerClassesIterator : public StackObj {
1503  private:
1504   Array<jushort>* _inner_classes;
1505   int _length;
1506   int _idx;
1507  public:
1508 
1509   InnerClassesIterator(const InstanceKlass* k) {
1510     _inner_classes = k->inner_classes();
1511     if (k->inner_classes() != NULL) {
1512       _length = _inner_classes->length();
1513       // The inner class array's length should be the multiple of
1514       // inner_class_next_offset if it only contains the InnerClasses
1515       // attribute data, or it should be
1516       // n*inner_class_next_offset+enclosing_method_attribute_size
1517       // if it also contains the EnclosingMethod data.
1518       assert((_length % InstanceKlass::inner_class_next_offset == 0 ||
1519               _length % InstanceKlass::inner_class_next_offset == InstanceKlass::enclosing_method_attribute_size),
1520              "just checking");
1521       // Remove the enclosing_method portion if exists.
1522       if (_length % InstanceKlass::inner_class_next_offset == InstanceKlass::enclosing_method_attribute_size) {
1523         _length -= InstanceKlass::enclosing_method_attribute_size;
1524       }
1525     } else {
1526       _length = 0;
1527     }
1528     _idx = 0;
1529   }
1530 
1531   int length() const {
1532     return _length;
1533   }
1534 
1535   void next() {
1536     _idx += InstanceKlass::inner_class_next_offset;
1537   }
1538 
1539   bool done() const {
1540     return (_idx >= _length);
1541   }
1542 
1543   u2 inner_class_info_index() const {
1544     return _inner_classes->at(
1545                _idx + InstanceKlass::inner_class_inner_class_info_offset);
1546   }
1547 
1548   void set_inner_class_info_index(u2 index) {
1549     _inner_classes->at_put(
1550                _idx + InstanceKlass::inner_class_inner_class_info_offset, index);
1551   }
1552 
1553   u2 outer_class_info_index() const {
1554     return _inner_classes->at(
1555                _idx + InstanceKlass::inner_class_outer_class_info_offset);
1556   }
1557 
1558   void set_outer_class_info_index(u2 index) {
1559     _inner_classes->at_put(
1560                _idx + InstanceKlass::inner_class_outer_class_info_offset, index);
1561   }
1562 
1563   u2 inner_name_index() const {
1564     return _inner_classes->at(
1565                _idx + InstanceKlass::inner_class_inner_name_offset);
1566   }
1567 
1568   void set_inner_name_index(u2 index) {
1569     _inner_classes->at_put(
1570                _idx + InstanceKlass::inner_class_inner_name_offset, index);
1571   }
1572 
1573   u2 inner_access_flags() const {
1574     return _inner_classes->at(
1575                _idx + InstanceKlass::inner_class_access_flags_offset);
1576   }
1577 };
1578 
1579 #endif // SHARE_OOPS_INSTANCEKLASS_HPP