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