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