src/share/vm/oops/instanceKlass.cpp

Tue, 08 Aug 2017 15:57:29 +0800

author
aoqi
date
Tue, 08 Aug 2017 15:57:29 +0800
changeset 6876
710a3c8b516e
parent 6718
bd4d69d9cb7d
parent 423
6cfa41b33dfb
child 7535
7ae4e26cb1e0
permissions
-rw-r--r--

merge

     1 /*
     2  * Copyright (c) 1997, 2014, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/javaClasses.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "classfile/verifier.hpp"
    29 #include "classfile/vmSymbols.hpp"
    30 #include "compiler/compileBroker.hpp"
    31 #include "gc_implementation/shared/markSweep.inline.hpp"
    32 #include "gc_interface/collectedHeap.inline.hpp"
    33 #include "interpreter/oopMapCache.hpp"
    34 #include "interpreter/rewriter.hpp"
    35 #include "jvmtifiles/jvmti.h"
    36 #include "memory/genOopClosures.inline.hpp"
    37 #include "memory/heapInspection.hpp"
    38 #include "memory/metadataFactory.hpp"
    39 #include "memory/oopFactory.hpp"
    40 #include "oops/fieldStreams.hpp"
    41 #include "oops/instanceClassLoaderKlass.hpp"
    42 #include "oops/instanceKlass.hpp"
    43 #include "oops/instanceMirrorKlass.hpp"
    44 #include "oops/instanceOop.hpp"
    45 #include "oops/klass.inline.hpp"
    46 #include "oops/method.hpp"
    47 #include "oops/oop.inline.hpp"
    48 #include "oops/symbol.hpp"
    49 #include "prims/jvmtiExport.hpp"
    50 #include "prims/jvmtiRedefineClassesTrace.hpp"
    51 #include "prims/jvmtiRedefineClasses.hpp"
    52 #include "prims/methodComparator.hpp"
    53 #include "runtime/fieldDescriptor.hpp"
    54 #include "runtime/handles.inline.hpp"
    55 #include "runtime/javaCalls.hpp"
    56 #include "runtime/mutexLocker.hpp"
    57 #include "runtime/thread.inline.hpp"
    58 #include "services/classLoadingService.hpp"
    59 #include "services/threadService.hpp"
    60 #include "utilities/dtrace.hpp"
    61 #include "utilities/macros.hpp"
    62 #if INCLUDE_ALL_GCS
    63 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    64 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    65 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    66 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    67 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
    68 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    69 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    70 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    71 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    72 #include "oops/oop.pcgc.inline.hpp"
    73 #endif // INCLUDE_ALL_GCS
    74 #ifdef COMPILER1
    75 #include "c1/c1_Compiler.hpp"
    76 #endif
    78 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    80 #ifdef DTRACE_ENABLED
    82 #ifndef USDT2
    84 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    85   char*, intptr_t, oop, intptr_t);
    86 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    87   char*, intptr_t, oop, intptr_t, int);
    88 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    89   char*, intptr_t, oop, intptr_t, int);
    90 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    91   char*, intptr_t, oop, intptr_t, int);
    92 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    93   char*, intptr_t, oop, intptr_t, int);
    94 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    95   char*, intptr_t, oop, intptr_t, int);
    96 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
    97   char*, intptr_t, oop, intptr_t, int);
    98 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
    99   char*, intptr_t, oop, intptr_t, int);
   101 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   102   {                                                              \
   103     char* data = NULL;                                           \
   104     int len = 0;                                                 \
   105     Symbol* name = (clss)->name();                               \
   106     if (name != NULL) {                                          \
   107       data = (char*)name->bytes();                               \
   108       len = name->utf8_length();                                 \
   109     }                                                            \
   110     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   111       data, len, (void *)(clss)->class_loader(), thread_type);           \
   112   }
   114 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   115   {                                                              \
   116     char* data = NULL;                                           \
   117     int len = 0;                                                 \
   118     Symbol* name = (clss)->name();                               \
   119     if (name != NULL) {                                          \
   120       data = (char*)name->bytes();                               \
   121       len = name->utf8_length();                                 \
   122     }                                                            \
   123     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   124       data, len, (void *)(clss)->class_loader(), thread_type, wait);     \
   125   }
   126 #else /* USDT2 */
   128 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   129 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   130 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   131 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   132 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   133 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   134 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   135 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   136 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   137   {                                                              \
   138     char* data = NULL;                                           \
   139     int len = 0;                                                 \
   140     Symbol* name = (clss)->name();                               \
   141     if (name != NULL) {                                          \
   142       data = (char*)name->bytes();                               \
   143       len = name->utf8_length();                                 \
   144     }                                                            \
   145     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   146       data, len, (clss)->class_loader(), thread_type);           \
   147   }
   149 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   150   {                                                              \
   151     char* data = NULL;                                           \
   152     int len = 0;                                                 \
   153     Symbol* name = (clss)->name();                               \
   154     if (name != NULL) {                                          \
   155       data = (char*)name->bytes();                               \
   156       len = name->utf8_length();                                 \
   157     }                                                            \
   158     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   159       data, len, (clss)->class_loader(), thread_type, wait);     \
   160   }
   161 #endif /* USDT2 */
   163 #else //  ndef DTRACE_ENABLED
   165 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   166 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   168 #endif //  ndef DTRACE_ENABLED
   170 volatile int InstanceKlass::_total_instanceKlass_count = 0;
   172 InstanceKlass* InstanceKlass::allocate_instance_klass(
   173                                               ClassLoaderData* loader_data,
   174                                               int vtable_len,
   175                                               int itable_len,
   176                                               int static_field_size,
   177                                               int nonstatic_oop_map_size,
   178                                               ReferenceType rt,
   179                                               AccessFlags access_flags,
   180                                               Symbol* name,
   181                                               Klass* super_klass,
   182                                               bool is_anonymous,
   183                                               TRAPS) {
   185   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   186                                  access_flags.is_interface(), is_anonymous);
   188   // Allocation
   189   InstanceKlass* ik;
   190   if (rt == REF_NONE) {
   191     if (name == vmSymbols::java_lang_Class()) {
   192       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   193         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   194         access_flags, is_anonymous);
   195     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   196           (SystemDictionary::ClassLoader_klass_loaded() &&
   197           super_klass != NULL &&
   198           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   199       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   200         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   201         access_flags, is_anonymous);
   202     } else {
   203       // normal class
   204       ik = new (loader_data, size, THREAD) InstanceKlass(
   205         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   206         access_flags, is_anonymous);
   207     }
   208   } else {
   209     // reference klass
   210     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   211         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   212         access_flags, is_anonymous);
   213   }
   215   // Check for pending exception before adding to the loader data and incrementing
   216   // class count.  Can get OOM here.
   217   if (HAS_PENDING_EXCEPTION) {
   218     return NULL;
   219   }
   221   // Add all classes to our internal class loader list here,
   222   // including classes in the bootstrap (NULL) class loader.
   223   loader_data->add_class(ik);
   225   Atomic::inc(&_total_instanceKlass_count);
   226   return ik;
   227 }
   230 // copy method ordering from resource area to Metaspace
   231 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
   232   if (m != NULL) {
   233     // allocate a new array and copy contents (memcpy?)
   234     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
   235     for (int i = 0; i < m->length(); i++) {
   236       _method_ordering->at_put(i, m->at(i));
   237     }
   238   } else {
   239     _method_ordering = Universe::the_empty_int_array();
   240   }
   241 }
   243 // create a new array of vtable_indices for default methods
   244 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
   245   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
   246   assert(default_vtable_indices() == NULL, "only create once");
   247   set_default_vtable_indices(vtable_indices);
   248   return vtable_indices;
   249 }
   251 InstanceKlass::InstanceKlass(int vtable_len,
   252                              int itable_len,
   253                              int static_field_size,
   254                              int nonstatic_oop_map_size,
   255                              ReferenceType rt,
   256                              AccessFlags access_flags,
   257                              bool is_anonymous) {
   258   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   260   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   261                                    access_flags.is_interface(), is_anonymous);
   263   set_vtable_length(vtable_len);
   264   set_itable_length(itable_len);
   265   set_static_field_size(static_field_size);
   266   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   267   set_access_flags(access_flags);
   268   _misc_flags = 0;  // initialize to zero
   269   set_is_anonymous(is_anonymous);
   270   assert(size() == iksize, "wrong size for object");
   272   set_array_klasses(NULL);
   273   set_methods(NULL);
   274   set_method_ordering(NULL);
   275   set_default_methods(NULL);
   276   set_default_vtable_indices(NULL);
   277   set_local_interfaces(NULL);
   278   set_transitive_interfaces(NULL);
   279   init_implementor();
   280   set_fields(NULL, 0);
   281   set_constants(NULL);
   282   set_class_loader_data(NULL);
   283   set_source_file_name_index(0);
   284   set_source_debug_extension(NULL, 0);
   285   set_array_name(NULL);
   286   set_inner_classes(NULL);
   287   set_static_oop_field_count(0);
   288   set_nonstatic_field_size(0);
   289   set_is_marked_dependent(false);
   290   set_init_state(InstanceKlass::allocated);
   291   set_init_thread(NULL);
   292   set_reference_type(rt);
   293   set_oop_map_cache(NULL);
   294   set_jni_ids(NULL);
   295   set_osr_nmethods_head(NULL);
   296   set_breakpoints(NULL);
   297   init_previous_versions();
   298   set_generic_signature_index(0);
   299   release_set_methods_jmethod_ids(NULL);
   300   set_annotations(NULL);
   301   set_jvmti_cached_class_field_map(NULL);
   302   set_initial_method_idnum(0);
   303   _dependencies = NULL;
   304   set_jvmti_cached_class_field_map(NULL);
   305   set_cached_class_file(NULL);
   306   set_initial_method_idnum(0);
   307   set_minor_version(0);
   308   set_major_version(0);
   309   NOT_PRODUCT(_verify_count = 0;)
   311   // initialize the non-header words to zero
   312   intptr_t* p = (intptr_t*)this;
   313   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
   314     p[index] = NULL_WORD;
   315   }
   317   // Set temporary value until parseClassFile updates it with the real instance
   318   // size.
   319   set_layout_helper(Klass::instance_layout_helper(0, true));
   320 }
   323 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
   324                                        Array<Method*>* methods) {
   325   if (methods != NULL && methods != Universe::the_empty_method_array() &&
   326       !methods->is_shared()) {
   327     for (int i = 0; i < methods->length(); i++) {
   328       Method* method = methods->at(i);
   329       if (method == NULL) continue;  // maybe null if error processing
   330       // Only want to delete methods that are not executing for RedefineClasses.
   331       // The previous version will point to them so they're not totally dangling
   332       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   333       MetadataFactory::free_metadata(loader_data, method);
   334     }
   335     MetadataFactory::free_array<Method*>(loader_data, methods);
   336   }
   337 }
   339 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
   340                                           Klass* super_klass,
   341                                           Array<Klass*>* local_interfaces,
   342                                           Array<Klass*>* transitive_interfaces) {
   343   // Only deallocate transitive interfaces if not empty, same as super class
   344   // or same as local interfaces.  See code in parseClassFile.
   345   Array<Klass*>* ti = transitive_interfaces;
   346   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
   347     // check that the interfaces don't come from super class
   348     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
   349                     InstanceKlass::cast(super_klass)->transitive_interfaces();
   350     if (ti != sti && ti != NULL && !ti->is_shared()) {
   351       MetadataFactory::free_array<Klass*>(loader_data, ti);
   352     }
   353   }
   355   // local interfaces can be empty
   356   if (local_interfaces != Universe::the_empty_klass_array() &&
   357       local_interfaces != NULL && !local_interfaces->is_shared()) {
   358     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
   359   }
   360 }
   362 // This function deallocates the metadata and C heap pointers that the
   363 // InstanceKlass points to.
   364 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   366   // Orphan the mirror first, CMS thinks it's still live.
   367   if (java_mirror() != NULL) {
   368     java_lang_Class::set_klass(java_mirror(), NULL);
   369   }
   371   // Need to take this class off the class loader data list.
   372   loader_data->remove_class(this);
   374   // The array_klass for this class is created later, after error handling.
   375   // For class redefinition, we keep the original class so this scratch class
   376   // doesn't have an array class.  Either way, assert that there is nothing
   377   // to deallocate.
   378   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   380   // Release C heap allocated data that this might point to, which includes
   381   // reference counting symbol names.
   382   release_C_heap_structures();
   384   deallocate_methods(loader_data, methods());
   385   set_methods(NULL);
   387   if (method_ordering() != NULL &&
   388       method_ordering() != Universe::the_empty_int_array() &&
   389       !method_ordering()->is_shared()) {
   390     MetadataFactory::free_array<int>(loader_data, method_ordering());
   391   }
   392   set_method_ordering(NULL);
   394   // default methods can be empty
   395   if (default_methods() != NULL &&
   396       default_methods() != Universe::the_empty_method_array() &&
   397       !default_methods()->is_shared()) {
   398     MetadataFactory::free_array<Method*>(loader_data, default_methods());
   399   }
   400   // Do NOT deallocate the default methods, they are owned by superinterfaces.
   401   set_default_methods(NULL);
   403   // default methods vtable indices can be empty
   404   if (default_vtable_indices() != NULL &&
   405       !default_vtable_indices()->is_shared()) {
   406     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
   407   }
   408   set_default_vtable_indices(NULL);
   411   // This array is in Klass, but remove it with the InstanceKlass since
   412   // this place would be the only caller and it can share memory with transitive
   413   // interfaces.
   414   if (secondary_supers() != NULL &&
   415       secondary_supers() != Universe::the_empty_klass_array() &&
   416       secondary_supers() != transitive_interfaces() &&
   417       !secondary_supers()->is_shared()) {
   418     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   419   }
   420   set_secondary_supers(NULL);
   422   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
   423   set_transitive_interfaces(NULL);
   424   set_local_interfaces(NULL);
   426   if (fields() != NULL && !fields()->is_shared()) {
   427     MetadataFactory::free_array<jushort>(loader_data, fields());
   428   }
   429   set_fields(NULL, 0);
   431   // If a method from a redefined class is using this constant pool, don't
   432   // delete it, yet.  The new class's previous version will point to this.
   433   if (constants() != NULL) {
   434     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   435     if (!constants()->is_shared()) {
   436       MetadataFactory::free_metadata(loader_data, constants());
   437     }
   438     set_constants(NULL);
   439   }
   441   if (inner_classes() != NULL &&
   442       inner_classes() != Universe::the_empty_short_array() &&
   443       !inner_classes()->is_shared()) {
   444     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   445   }
   446   set_inner_classes(NULL);
   448   // We should deallocate the Annotations instance if it's not in shared spaces.
   449   if (annotations() != NULL && !annotations()->is_shared()) {
   450     MetadataFactory::free_metadata(loader_data, annotations());
   451   }
   452   set_annotations(NULL);
   453 }
   455 bool InstanceKlass::should_be_initialized() const {
   456   return !is_initialized();
   457 }
   459 klassVtable* InstanceKlass::vtable() const {
   460   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   461 }
   463 klassItable* InstanceKlass::itable() const {
   464   return new klassItable(instanceKlassHandle(this));
   465 }
   467 void InstanceKlass::eager_initialize(Thread *thread) {
   468   if (!EagerInitialization) return;
   470   if (this->is_not_initialized()) {
   471     // abort if the the class has a class initializer
   472     if (this->class_initializer() != NULL) return;
   474     // abort if it is java.lang.Object (initialization is handled in genesis)
   475     Klass* super = this->super();
   476     if (super == NULL) return;
   478     // abort if the super class should be initialized
   479     if (!InstanceKlass::cast(super)->is_initialized()) return;
   481     // call body to expose the this pointer
   482     instanceKlassHandle this_oop(thread, this);
   483     eager_initialize_impl(this_oop);
   484   }
   485 }
   487 // JVMTI spec thinks there are signers and protection domain in the
   488 // instanceKlass.  These accessors pretend these fields are there.
   489 // The hprof specification also thinks these fields are in InstanceKlass.
   490 oop InstanceKlass::protection_domain() const {
   491   // return the protection_domain from the mirror
   492   return java_lang_Class::protection_domain(java_mirror());
   493 }
   495 // To remove these from requires an incompatible change and CCC request.
   496 objArrayOop InstanceKlass::signers() const {
   497   // return the signers from the mirror
   498   return java_lang_Class::signers(java_mirror());
   499 }
   501 oop InstanceKlass::init_lock() const {
   502   // return the init lock from the mirror
   503   oop lock = java_lang_Class::init_lock(java_mirror());
   504   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   505          "only fully initialized state can have a null lock");
   506   return lock;
   507 }
   509 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   510 // threads to get this lock will see a null lock and will not lock.
   511 // That's okay because they all check for initialized state after getting
   512 // the lock and return.
   513 void InstanceKlass::fence_and_clear_init_lock() {
   514   // make sure previous stores are all done, notably the init_state.
   515   OrderAccess::storestore();
   516   java_lang_Class::set_init_lock(java_mirror(), NULL);
   517   assert(!is_not_initialized(), "class must be initialized now");
   518 }
   520 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   521   EXCEPTION_MARK;
   522   oop init_lock = this_oop->init_lock();
   523   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   525   // abort if someone beat us to the initialization
   526   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   528   ClassState old_state = this_oop->init_state();
   529   link_class_impl(this_oop, true, THREAD);
   530   if (HAS_PENDING_EXCEPTION) {
   531     CLEAR_PENDING_EXCEPTION;
   532     // Abort if linking the class throws an exception.
   534     // Use a test to avoid redundantly resetting the state if there's
   535     // no change.  Set_init_state() asserts that state changes make
   536     // progress, whereas here we might just be spinning in place.
   537     if( old_state != this_oop->_init_state )
   538       this_oop->set_init_state (old_state);
   539   } else {
   540     // linking successfull, mark class as initialized
   541     this_oop->set_init_state (fully_initialized);
   542     this_oop->fence_and_clear_init_lock();
   543     // trace
   544     if (TraceClassInitialization) {
   545       ResourceMark rm(THREAD);
   546       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   547     }
   548   }
   549 }
   552 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   553 // process. The step comments refers to the procedure described in that section.
   554 // Note: implementation moved to static method to expose the this pointer.
   555 void InstanceKlass::initialize(TRAPS) {
   556   if (this->should_be_initialized()) {
   557     HandleMark hm(THREAD);
   558     instanceKlassHandle this_oop(THREAD, this);
   559     initialize_impl(this_oop, CHECK);
   560     // Note: at this point the class may be initialized
   561     //       OR it may be in the state of being initialized
   562     //       in case of recursive initialization!
   563   } else {
   564     assert(is_initialized(), "sanity check");
   565   }
   566 }
   569 bool InstanceKlass::verify_code(
   570     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   571   // 1) Verify the bytecodes
   572   Verifier::Mode mode =
   573     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   574   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   575 }
   578 // Used exclusively by the shared spaces dump mechanism to prevent
   579 // classes mapped into the shared regions in new VMs from appearing linked.
   581 void InstanceKlass::unlink_class() {
   582   assert(is_linked(), "must be linked");
   583   _init_state = loaded;
   584 }
   586 void InstanceKlass::link_class(TRAPS) {
   587   assert(is_loaded(), "must be loaded");
   588   if (!is_linked()) {
   589     HandleMark hm(THREAD);
   590     instanceKlassHandle this_oop(THREAD, this);
   591     link_class_impl(this_oop, true, CHECK);
   592   }
   593 }
   595 // Called to verify that a class can link during initialization, without
   596 // throwing a VerifyError.
   597 bool InstanceKlass::link_class_or_fail(TRAPS) {
   598   assert(is_loaded(), "must be loaded");
   599   if (!is_linked()) {
   600     HandleMark hm(THREAD);
   601     instanceKlassHandle this_oop(THREAD, this);
   602     link_class_impl(this_oop, false, CHECK_false);
   603   }
   604   return is_linked();
   605 }
   607 bool InstanceKlass::link_class_impl(
   608     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   609   // check for error state
   610   if (this_oop->is_in_error_state()) {
   611     ResourceMark rm(THREAD);
   612     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   613                this_oop->external_name(), false);
   614   }
   615   // return if already verified
   616   if (this_oop->is_linked()) {
   617     return true;
   618   }
   620   // Timing
   621   // timer handles recursion
   622   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   623   JavaThread* jt = (JavaThread*)THREAD;
   625   // link super class before linking this class
   626   instanceKlassHandle super(THREAD, this_oop->super());
   627   if (super.not_null()) {
   628     if (super->is_interface()) {  // check if super class is an interface
   629       ResourceMark rm(THREAD);
   630       Exceptions::fthrow(
   631         THREAD_AND_LOCATION,
   632         vmSymbols::java_lang_IncompatibleClassChangeError(),
   633         "class %s has interface %s as super class",
   634         this_oop->external_name(),
   635         super->external_name()
   636       );
   637       return false;
   638     }
   640     link_class_impl(super, throw_verifyerror, CHECK_false);
   641   }
   643   // link all interfaces implemented by this class before linking this class
   644   Array<Klass*>* interfaces = this_oop->local_interfaces();
   645   int num_interfaces = interfaces->length();
   646   for (int index = 0; index < num_interfaces; index++) {
   647     HandleMark hm(THREAD);
   648     instanceKlassHandle ih(THREAD, interfaces->at(index));
   649     link_class_impl(ih, throw_verifyerror, CHECK_false);
   650   }
   652   // in case the class is linked in the process of linking its superclasses
   653   if (this_oop->is_linked()) {
   654     return true;
   655   }
   657   // trace only the link time for this klass that includes
   658   // the verification time
   659   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   660                              ClassLoader::perf_class_link_selftime(),
   661                              ClassLoader::perf_classes_linked(),
   662                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   663                              jt->get_thread_stat()->perf_timers_addr(),
   664                              PerfClassTraceTime::CLASS_LINK);
   666   // verification & rewriting
   667   {
   668     oop init_lock = this_oop->init_lock();
   669     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   670     // rewritten will have been set if loader constraint error found
   671     // on an earlier link attempt
   672     // don't verify or rewrite if already rewritten
   674     if (!this_oop->is_linked()) {
   675       if (!this_oop->is_rewritten()) {
   676         {
   677           // Timer includes any side effects of class verification (resolution,
   678           // etc), but not recursive entry into verify_code().
   679           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   680                                    ClassLoader::perf_class_verify_selftime(),
   681                                    ClassLoader::perf_classes_verified(),
   682                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   683                                    jt->get_thread_stat()->perf_timers_addr(),
   684                                    PerfClassTraceTime::CLASS_VERIFY);
   685           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   686           if (!verify_ok) {
   687             return false;
   688           }
   689         }
   691         // Just in case a side-effect of verify linked this class already
   692         // (which can sometimes happen since the verifier loads classes
   693         // using custom class loaders, which are free to initialize things)
   694         if (this_oop->is_linked()) {
   695           return true;
   696         }
   698         // also sets rewritten
   699         this_oop->rewrite_class(CHECK_false);
   700       }
   702       // relocate jsrs and link methods after they are all rewritten
   703       this_oop->link_methods(CHECK_false);
   705       // Initialize the vtable and interface table after
   706       // methods have been rewritten since rewrite may
   707       // fabricate new Method*s.
   708       // also does loader constraint checking
   709       if (!this_oop()->is_shared()) {
   710         ResourceMark rm(THREAD);
   711         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   712         this_oop->itable()->initialize_itable(true, CHECK_false);
   713       }
   714 #ifdef ASSERT
   715       else {
   716         ResourceMark rm(THREAD);
   717         this_oop->vtable()->verify(tty, true);
   718         // In case itable verification is ever added.
   719         // this_oop->itable()->verify(tty, true);
   720       }
   721 #endif
   722       this_oop->set_init_state(linked);
   723       if (JvmtiExport::should_post_class_prepare()) {
   724         Thread *thread = THREAD;
   725         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   726         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   727       }
   728     }
   729   }
   730   return true;
   731 }
   734 // Rewrite the byte codes of all of the methods of a class.
   735 // The rewriter must be called exactly once. Rewriting must happen after
   736 // verification but before the first method of the class is executed.
   737 void InstanceKlass::rewrite_class(TRAPS) {
   738   assert(is_loaded(), "must be loaded");
   739   instanceKlassHandle this_oop(THREAD, this);
   740   if (this_oop->is_rewritten()) {
   741     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   742     return;
   743   }
   744   Rewriter::rewrite(this_oop, CHECK);
   745   this_oop->set_rewritten();
   746 }
   748 // Now relocate and link method entry points after class is rewritten.
   749 // This is outside is_rewritten flag. In case of an exception, it can be
   750 // executed more than once.
   751 void InstanceKlass::link_methods(TRAPS) {
   752   int len = methods()->length();
   753   for (int i = len-1; i >= 0; i--) {
   754     methodHandle m(THREAD, methods()->at(i));
   756     // Set up method entry points for compiler and interpreter    .
   757     m->link_method(m, CHECK);
   759     // This is for JVMTI and unrelated to relocator but the last thing we do
   760 #ifdef ASSERT
   761     if (StressMethodComparator) {
   762       ResourceMark rm(THREAD);
   763       static int nmc = 0;
   764       for (int j = i; j >= 0 && j >= i-4; j--) {
   765         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   766         bool z = MethodComparator::methods_EMCP(m(),
   767                    methods()->at(j));
   768         if (j == i && !z) {
   769           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   770           assert(z, "method must compare equal to itself");
   771         }
   772       }
   773     }
   774 #endif //ASSERT
   775   }
   776 }
   779 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   780   // Make sure klass is linked (verified) before initialization
   781   // A class could already be verified, since it has been reflected upon.
   782   this_oop->link_class(CHECK);
   784   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   786   bool wait = false;
   788   // refer to the JVM book page 47 for description of steps
   789   // Step 1
   790   {
   791     oop init_lock = this_oop->init_lock();
   792     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   794     Thread *self = THREAD; // it's passed the current thread
   796     // Step 2
   797     // If we were to use wait() instead of waitInterruptibly() then
   798     // we might end up throwing IE from link/symbol resolution sites
   799     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   800     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   801         wait = true;
   802       ol.waitUninterruptibly(CHECK);
   803     }
   805     // Step 3
   806     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   807       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   808       return;
   809     }
   811     // Step 4
   812     if (this_oop->is_initialized()) {
   813       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   814       return;
   815     }
   817     // Step 5
   818     if (this_oop->is_in_error_state()) {
   819       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   820       ResourceMark rm(THREAD);
   821       const char* desc = "Could not initialize class ";
   822       const char* className = this_oop->external_name();
   823       size_t msglen = strlen(desc) + strlen(className) + 1;
   824       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   825       if (NULL == message) {
   826         // Out of memory: can't create detailed error message
   827         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   828       } else {
   829         jio_snprintf(message, msglen, "%s%s", desc, className);
   830         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   831       }
   832     }
   834     // Step 6
   835     this_oop->set_init_state(being_initialized);
   836     this_oop->set_init_thread(self);
   837   }
   839   // Step 7
   840   Klass* super_klass = this_oop->super();
   841   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   842     super_klass->initialize(THREAD);
   844     if (HAS_PENDING_EXCEPTION) {
   845       Handle e(THREAD, PENDING_EXCEPTION);
   846       CLEAR_PENDING_EXCEPTION;
   847       {
   848         EXCEPTION_MARK;
   849         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   850         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   851       }
   852       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   853       THROW_OOP(e());
   854     }
   855   }
   857   if (this_oop->has_default_methods()) {
   858     // Step 7.5: initialize any interfaces which have default methods
   859     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   860       Klass* iface = this_oop->local_interfaces()->at(i);
   861       InstanceKlass* ik = InstanceKlass::cast(iface);
   862       if (ik->has_default_methods() && ik->should_be_initialized()) {
   863         ik->initialize(THREAD);
   865         if (HAS_PENDING_EXCEPTION) {
   866           Handle e(THREAD, PENDING_EXCEPTION);
   867           CLEAR_PENDING_EXCEPTION;
   868           {
   869             EXCEPTION_MARK;
   870             // Locks object, set state, and notify all waiting threads
   871             this_oop->set_initialization_state_and_notify(
   872                 initialization_error, THREAD);
   874             // ignore any exception thrown, superclass initialization error is
   875             // thrown below
   876             CLEAR_PENDING_EXCEPTION;
   877           }
   878           DTRACE_CLASSINIT_PROBE_WAIT(
   879               super__failed, InstanceKlass::cast(this_oop()), -1, wait);
   880           THROW_OOP(e());
   881         }
   882       }
   883     }
   884   }
   886   // Step 8
   887   {
   888     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   889     JavaThread* jt = (JavaThread*)THREAD;
   890     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   891     // Timer includes any side effects of class initialization (resolution,
   892     // etc), but not recursive entry into call_class_initializer().
   893     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   894                              ClassLoader::perf_class_init_selftime(),
   895                              ClassLoader::perf_classes_inited(),
   896                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   897                              jt->get_thread_stat()->perf_timers_addr(),
   898                              PerfClassTraceTime::CLASS_CLINIT);
   899     this_oop->call_class_initializer(THREAD);
   900   }
   902   // Step 9
   903   if (!HAS_PENDING_EXCEPTION) {
   904     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   905     { ResourceMark rm(THREAD);
   906       debug_only(this_oop->vtable()->verify(tty, true);)
   907     }
   908   }
   909   else {
   910     // Step 10 and 11
   911     Handle e(THREAD, PENDING_EXCEPTION);
   912     CLEAR_PENDING_EXCEPTION;
   913     {
   914       EXCEPTION_MARK;
   915       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   916       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   917     }
   918     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   919     if (e->is_a(SystemDictionary::Error_klass())) {
   920       THROW_OOP(e());
   921     } else {
   922       JavaCallArguments args(e);
   923       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   924                 vmSymbols::throwable_void_signature(),
   925                 &args);
   926     }
   927   }
   928   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   929 }
   932 // Note: implementation moved to static method to expose the this pointer.
   933 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   934   instanceKlassHandle kh(THREAD, this);
   935   set_initialization_state_and_notify_impl(kh, state, CHECK);
   936 }
   938 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   939   oop init_lock = this_oop->init_lock();
   940   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   941   this_oop->set_init_state(state);
   942   this_oop->fence_and_clear_init_lock();
   943   ol.notify_all(CHECK);
   944 }
   946 // The embedded _implementor field can only record one implementor.
   947 // When there are more than one implementors, the _implementor field
   948 // is set to the interface Klass* itself. Following are the possible
   949 // values for the _implementor field:
   950 //   NULL                  - no implementor
   951 //   implementor Klass*    - one implementor
   952 //   self                  - more than one implementor
   953 //
   954 // The _implementor field only exists for interfaces.
   955 void InstanceKlass::add_implementor(Klass* k) {
   956   assert(Compile_lock->owned_by_self(), "");
   957   assert(is_interface(), "not interface");
   958   // Filter out my subinterfaces.
   959   // (Note: Interfaces are never on the subklass list.)
   960   if (InstanceKlass::cast(k)->is_interface()) return;
   962   // Filter out subclasses whose supers already implement me.
   963   // (Note: CHA must walk subclasses of direct implementors
   964   // in order to locate indirect implementors.)
   965   Klass* sk = InstanceKlass::cast(k)->super();
   966   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   967     // We only need to check one immediate superclass, since the
   968     // implements_interface query looks at transitive_interfaces.
   969     // Any supers of the super have the same (or fewer) transitive_interfaces.
   970     return;
   972   Klass* ik = implementor();
   973   if (ik == NULL) {
   974     set_implementor(k);
   975   } else if (ik != this) {
   976     // There is already an implementor. Use itself as an indicator of
   977     // more than one implementors.
   978     set_implementor(this);
   979   }
   981   // The implementor also implements the transitive_interfaces
   982   for (int index = 0; index < local_interfaces()->length(); index++) {
   983     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
   984   }
   985 }
   987 void InstanceKlass::init_implementor() {
   988   if (is_interface()) {
   989     set_implementor(NULL);
   990   }
   991 }
   994 void InstanceKlass::process_interfaces(Thread *thread) {
   995   // link this class into the implementors list of every interface it implements
   996   Klass* this_as_klass_oop = this;
   997   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
   998     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
   999     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
  1000     assert(interf->is_interface(), "expected interface");
  1001     interf->add_implementor(this_as_klass_oop);
  1005 bool InstanceKlass::can_be_primary_super_slow() const {
  1006   if (is_interface())
  1007     return false;
  1008   else
  1009     return Klass::can_be_primary_super_slow();
  1012 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
  1013   // The secondaries are the implemented interfaces.
  1014   InstanceKlass* ik = InstanceKlass::cast(this);
  1015   Array<Klass*>* interfaces = ik->transitive_interfaces();
  1016   int num_secondaries = num_extra_slots + interfaces->length();
  1017   if (num_secondaries == 0) {
  1018     // Must share this for correct bootstrapping!
  1019     set_secondary_supers(Universe::the_empty_klass_array());
  1020     return NULL;
  1021   } else if (num_extra_slots == 0) {
  1022     // The secondary super list is exactly the same as the transitive interfaces.
  1023     // Redefine classes has to be careful not to delete this!
  1024     set_secondary_supers(interfaces);
  1025     return NULL;
  1026   } else {
  1027     // Copy transitive interfaces to a temporary growable array to be constructed
  1028     // into the secondary super list with extra slots.
  1029     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
  1030     for (int i = 0; i < interfaces->length(); i++) {
  1031       secondaries->push(interfaces->at(i));
  1033     return secondaries;
  1037 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
  1038   if (k->is_interface()) {
  1039     return implements_interface(k);
  1040   } else {
  1041     return Klass::compute_is_subtype_of(k);
  1045 bool InstanceKlass::implements_interface(Klass* k) const {
  1046   if (this == k) return true;
  1047   assert(k->is_interface(), "should be an interface class");
  1048   for (int i = 0; i < transitive_interfaces()->length(); i++) {
  1049     if (transitive_interfaces()->at(i) == k) {
  1050       return true;
  1053   return false;
  1056 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
  1057   // Verify direct super interface
  1058   if (this == k) return true;
  1059   assert(k->is_interface(), "should be an interface class");
  1060   for (int i = 0; i < local_interfaces()->length(); i++) {
  1061     if (local_interfaces()->at(i) == k) {
  1062       return true;
  1065   return false;
  1068 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
  1069   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  1070   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
  1071     report_java_out_of_memory("Requested array size exceeds VM limit");
  1072     JvmtiExport::post_array_size_exhausted();
  1073     THROW_OOP_0(Universe::out_of_memory_error_array_size());
  1075   int size = objArrayOopDesc::object_size(length);
  1076   Klass* ak = array_klass(n, CHECK_NULL);
  1077   KlassHandle h_ak (THREAD, ak);
  1078   objArrayOop o =
  1079     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  1080   return o;
  1083 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
  1084   if (TraceFinalizerRegistration) {
  1085     tty->print("Registered ");
  1086     i->print_value_on(tty);
  1087     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  1089   instanceHandle h_i(THREAD, i);
  1090   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  1091   JavaValue result(T_VOID);
  1092   JavaCallArguments args(h_i);
  1093   methodHandle mh (THREAD, Universe::finalizer_register_method());
  1094   JavaCalls::call(&result, mh, &args, CHECK_NULL);
  1095   return h_i();
  1098 instanceOop InstanceKlass::allocate_instance(TRAPS) {
  1099   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  1100   int size = size_helper();  // Query before forming handle.
  1102   KlassHandle h_k(THREAD, this);
  1104   instanceOop i;
  1106   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1107   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1108     i = register_finalizer(i, CHECK_NULL);
  1110   return i;
  1113 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1114   if (is_interface() || is_abstract()) {
  1115     ResourceMark rm(THREAD);
  1116     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1117               : vmSymbols::java_lang_InstantiationException(), external_name());
  1119   if (this == SystemDictionary::Class_klass()) {
  1120     ResourceMark rm(THREAD);
  1121     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1122               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1126 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1127   instanceKlassHandle this_oop(THREAD, this);
  1128   return array_klass_impl(this_oop, or_null, n, THREAD);
  1131 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1132   if (this_oop->array_klasses() == NULL) {
  1133     if (or_null) return NULL;
  1135     ResourceMark rm;
  1136     JavaThread *jt = (JavaThread *)THREAD;
  1138       // Atomic creation of array_klasses
  1139       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1140       MutexLocker ma(MultiArray_lock, THREAD);
  1142       // Check if update has already taken place
  1143       if (this_oop->array_klasses() == NULL) {
  1144         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1145         this_oop->set_array_klasses(k);
  1149   // _this will always be set at this point
  1150   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1151   if (or_null) {
  1152     return oak->array_klass_or_null(n);
  1154   return oak->array_klass(n, CHECK_NULL);
  1157 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1158   return array_klass_impl(or_null, 1, THREAD);
  1161 void InstanceKlass::call_class_initializer(TRAPS) {
  1162   instanceKlassHandle ik (THREAD, this);
  1163   call_class_initializer_impl(ik, THREAD);
  1166 static int call_class_initializer_impl_counter = 0;   // for debugging
  1168 Method* InstanceKlass::class_initializer() {
  1169   Method* clinit = find_method(
  1170       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1171   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1172     return clinit;
  1174   return NULL;
  1177 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1178   if (ReplayCompiles &&
  1179       (ReplaySuppressInitializers == 1 ||
  1180        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1181     // Hide the existence of the initializer for the purpose of replaying the compile
  1182     return;
  1185   methodHandle h_method(THREAD, this_oop->class_initializer());
  1186   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1187   if (TraceClassInitialization) {
  1188     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1189     this_oop->name()->print_value();
  1190     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1192   if (h_method() != NULL) {
  1193     JavaCallArguments args; // No arguments
  1194     JavaValue result(T_VOID);
  1195     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1200 void InstanceKlass::mask_for(methodHandle method, int bci,
  1201   InterpreterOopMap* entry_for) {
  1202   // Dirty read, then double-check under a lock.
  1203   if (_oop_map_cache == NULL) {
  1204     // Otherwise, allocate a new one.
  1205     MutexLocker x(OopMapCacheAlloc_lock);
  1206     // First time use. Allocate a cache in C heap
  1207     if (_oop_map_cache == NULL) {
  1208       // Release stores from OopMapCache constructor before assignment
  1209       // to _oop_map_cache. C++ compilers on ppc do not emit the
  1210       // required memory barrier only because of the volatile
  1211       // qualifier of _oop_map_cache.
  1212       OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
  1215   // _oop_map_cache is constant after init; lookup below does is own locking.
  1216   _oop_map_cache->lookup(method, bci, entry_for);
  1220 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1221   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1222     Symbol* f_name = fs.name();
  1223     Symbol* f_sig  = fs.signature();
  1224     if (f_name == name && f_sig == sig) {
  1225       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1226       return true;
  1229   return false;
  1233 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1234   const int n = local_interfaces()->length();
  1235   for (int i = 0; i < n; i++) {
  1236     Klass* intf1 = local_interfaces()->at(i);
  1237     assert(intf1->is_interface(), "just checking type");
  1238     // search for field in current interface
  1239     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1240       assert(fd->is_static(), "interface field must be static");
  1241       return intf1;
  1243     // search for field in direct superinterfaces
  1244     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1245     if (intf2 != NULL) return intf2;
  1247   // otherwise field lookup fails
  1248   return NULL;
  1252 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1253   // search order according to newest JVM spec (5.4.3.2, p.167).
  1254   // 1) search for field in current klass
  1255   if (find_local_field(name, sig, fd)) {
  1256     return const_cast<InstanceKlass*>(this);
  1258   // 2) search for field recursively in direct superinterfaces
  1259   { Klass* intf = find_interface_field(name, sig, fd);
  1260     if (intf != NULL) return intf;
  1262   // 3) apply field lookup recursively if superclass exists
  1263   { Klass* supr = super();
  1264     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1266   // 4) otherwise field lookup fails
  1267   return NULL;
  1271 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1272   // search order according to newest JVM spec (5.4.3.2, p.167).
  1273   // 1) search for field in current klass
  1274   if (find_local_field(name, sig, fd)) {
  1275     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1277   // 2) search for field recursively in direct superinterfaces
  1278   if (is_static) {
  1279     Klass* intf = find_interface_field(name, sig, fd);
  1280     if (intf != NULL) return intf;
  1282   // 3) apply field lookup recursively if superclass exists
  1283   { Klass* supr = super();
  1284     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1286   // 4) otherwise field lookup fails
  1287   return NULL;
  1291 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1292   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1293     if (fs.offset() == offset) {
  1294       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1295       if (fd->is_static() == is_static) return true;
  1298   return false;
  1302 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1303   Klass* klass = const_cast<InstanceKlass*>(this);
  1304   while (klass != NULL) {
  1305     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1306       return true;
  1308     klass = klass->super();
  1310   return false;
  1314 void InstanceKlass::methods_do(void f(Method* method)) {
  1315   int len = methods()->length();
  1316   for (int index = 0; index < len; index++) {
  1317     Method* m = methods()->at(index);
  1318     assert(m->is_method(), "must be method");
  1319     f(m);
  1324 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1325   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1326     if (fs.access_flags().is_static()) {
  1327       fieldDescriptor& fd = fs.field_descriptor();
  1328       cl->do_field(&fd);
  1334 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
  1335   instanceKlassHandle h_this(THREAD, this);
  1336   do_local_static_fields_impl(h_this, f, mirror, CHECK);
  1340 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
  1341                              void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {
  1342   for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
  1343     if (fs.access_flags().is_static()) {
  1344       fieldDescriptor& fd = fs.field_descriptor();
  1345       f(&fd, mirror, CHECK);
  1351 static int compare_fields_by_offset(int* a, int* b) {
  1352   return a[0] - b[0];
  1355 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1356   InstanceKlass* super = superklass();
  1357   if (super != NULL) {
  1358     super->do_nonstatic_fields(cl);
  1360   fieldDescriptor fd;
  1361   int length = java_fields_count();
  1362   // In DebugInfo nonstatic fields are sorted by offset.
  1363   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1364   int j = 0;
  1365   for (int i = 0; i < length; i += 1) {
  1366     fd.reinitialize(this, i);
  1367     if (!fd.is_static()) {
  1368       fields_sorted[j + 0] = fd.offset();
  1369       fields_sorted[j + 1] = i;
  1370       j += 2;
  1373   if (j > 0) {
  1374     length = j;
  1375     // _sort_Fn is defined in growableArray.hpp.
  1376     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1377     for (int i = 0; i < length; i += 2) {
  1378       fd.reinitialize(this, fields_sorted[i + 1]);
  1379       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1380       cl->do_field(&fd);
  1383   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1387 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1388   if (array_klasses() != NULL)
  1389     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1392 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1393   if (array_klasses() != NULL)
  1394     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1397 #ifdef ASSERT
  1398 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1399   int len = methods->length();
  1400   for (int index = 0; index < len; index++) {
  1401     Method* m = methods->at(index);
  1402     assert(m->is_method(), "must be method");
  1403     if (m->signature() == signature && m->name() == name) {
  1404        return index;
  1407   return -1;
  1409 #endif
  1411 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1412   int len = methods->length();
  1413   // methods are sorted, so do binary search
  1414   int l = 0;
  1415   int h = len - 1;
  1416   while (l <= h) {
  1417     int mid = (l + h) >> 1;
  1418     Method* m = methods->at(mid);
  1419     assert(m->is_method(), "must be method");
  1420     int res = m->name()->fast_compare(name);
  1421     if (res == 0) {
  1422       return mid;
  1423     } else if (res < 0) {
  1424       l = mid + 1;
  1425     } else {
  1426       h = mid - 1;
  1429   return -1;
  1432 // find_method looks up the name/signature in the local methods array
  1433 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1434   return find_method_impl(name, signature, false);
  1437 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
  1438   return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass);
  1441 // find_instance_method looks up the name/signature in the local methods array
  1442 // and skips over static methods
  1443 Method* InstanceKlass::find_instance_method(
  1444     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1445   Method* meth = InstanceKlass::find_method(methods, name, signature);
  1446   if (meth != NULL && meth->is_static()) {
  1447       meth = NULL;
  1449   return meth;
  1452 // find_method looks up the name/signature in the local methods array
  1453 Method* InstanceKlass::find_method(
  1454     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1455   return InstanceKlass::find_method_impl(methods, name, signature, false);
  1458 Method* InstanceKlass::find_method_impl(
  1459     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
  1460   int hit = find_method_index(methods, name, signature, skipping_overpass);
  1461   return hit >= 0 ? methods->at(hit): NULL;
  1464 // Used directly for default_methods to find the index into the
  1465 // default_vtable_indices, and indirectly by find_method
  1466 // find_method_index looks in the local methods array to return the index
  1467 // of the matching name/signature. If, overpass methods are being ignored,
  1468 // the search continues to find a potential non-overpass match.  This capability
  1469 // is important during method resolution to prefer a static method, for example,
  1470 // over an overpass method.
  1471 int InstanceKlass::find_method_index(
  1472     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
  1473   int hit = binary_search(methods, name);
  1474   if (hit != -1) {
  1475     Method* m = methods->at(hit);
  1476     // Do linear search to find matching signature.  First, quick check
  1477     // for common case, ignoring overpasses if requested.
  1478     if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return hit;
  1480     // search downwards through overloaded methods
  1481     int i;
  1482     for (i = hit - 1; i >= 0; --i) {
  1483         Method* m = methods->at(i);
  1484         assert(m->is_method(), "must be method");
  1485         if (m->name() != name) break;
  1486         if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
  1488     // search upwards
  1489     for (i = hit + 1; i < methods->length(); ++i) {
  1490         Method* m = methods->at(i);
  1491         assert(m->is_method(), "must be method");
  1492         if (m->name() != name) break;
  1493         if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
  1495     // not found
  1496 #ifdef ASSERT
  1497     int index = skipping_overpass ? -1 : linear_search(methods, name, signature);
  1498     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1499 #endif
  1501   return -1;
  1503 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1504   return find_method_by_name(methods(), name, end);
  1507 int InstanceKlass::find_method_by_name(
  1508     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1509   assert(end_ptr != NULL, "just checking");
  1510   int start = binary_search(methods, name);
  1511   int end = start + 1;
  1512   if (start != -1) {
  1513     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1514     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1515     *end_ptr = end;
  1516     return start;
  1518   return -1;
  1521 // uncached_lookup_method searches both the local class methods array and all
  1522 // superclasses methods arrays, skipping any overpass methods in superclasses.
  1523 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
  1524   MethodLookupMode lookup_mode = mode;
  1525   Klass* klass = const_cast<InstanceKlass*>(this);
  1526   while (klass != NULL) {
  1527     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
  1528     if (method != NULL) {
  1529       return method;
  1531     klass = InstanceKlass::cast(klass)->super();
  1532     lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
  1534   return NULL;
  1537 // lookup a method in the default methods list then in all transitive interfaces
  1538 // Do NOT return private or static methods
  1539 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
  1540                                                          Symbol* signature) const {
  1541   Method* m = NULL;
  1542   if (default_methods() != NULL) {
  1543     m = find_method(default_methods(), name, signature);
  1545   // Look up interfaces
  1546   if (m == NULL) {
  1547     m = lookup_method_in_all_interfaces(name, signature, normal);
  1549   return m;
  1552 // lookup a method in all the interfaces that this class implements
  1553 // Do NOT return private or static methods, new in JDK8 which are not externally visible
  1554 // They should only be found in the initial InterfaceMethodRef
  1555 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1556                                                        Symbol* signature,
  1557                                                        MethodLookupMode mode) const {
  1558   Array<Klass*>* all_ifs = transitive_interfaces();
  1559   int num_ifs = all_ifs->length();
  1560   InstanceKlass *ik = NULL;
  1561   for (int i = 0; i < num_ifs; i++) {
  1562     ik = InstanceKlass::cast(all_ifs->at(i));
  1563     Method* m = ik->lookup_method(name, signature);
  1564     if (m != NULL && m->is_public() && !m->is_static() &&
  1565         ((mode != skip_defaults) || !m->is_default_method())) {
  1566       return m;
  1569   return NULL;
  1572 /* jni_id_for_impl for jfieldIds only */
  1573 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1574   MutexLocker ml(JfieldIdCreation_lock);
  1575   // Retry lookup after we got the lock
  1576   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1577   if (probe == NULL) {
  1578     // Slow case, allocate new static field identifier
  1579     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1580     this_oop->set_jni_ids(probe);
  1582   return probe;
  1586 /* jni_id_for for jfieldIds only */
  1587 JNIid* InstanceKlass::jni_id_for(int offset) {
  1588   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1589   if (probe == NULL) {
  1590     probe = jni_id_for_impl(this, offset);
  1592   return probe;
  1595 u2 InstanceKlass::enclosing_method_data(int offset) {
  1596   Array<jushort>* inner_class_list = inner_classes();
  1597   if (inner_class_list == NULL) {
  1598     return 0;
  1600   int length = inner_class_list->length();
  1601   if (length % inner_class_next_offset == 0) {
  1602     return 0;
  1603   } else {
  1604     int index = length - enclosing_method_attribute_size;
  1605     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1606     return inner_class_list->at(index + offset);
  1610 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1611                                                  u2 method_index) {
  1612   Array<jushort>* inner_class_list = inner_classes();
  1613   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1614   int length = inner_class_list->length();
  1615   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1616     int index = length - enclosing_method_attribute_size;
  1617     inner_class_list->at_put(
  1618       index + enclosing_method_class_index_offset, class_index);
  1619     inner_class_list->at_put(
  1620       index + enclosing_method_method_index_offset, method_index);
  1624 // Lookup or create a jmethodID.
  1625 // This code is called by the VMThread and JavaThreads so the
  1626 // locking has to be done very carefully to avoid deadlocks
  1627 // and/or other cache consistency problems.
  1628 //
  1629 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1630   size_t idnum = (size_t)method_h->method_idnum();
  1631   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1632   size_t length = 0;
  1633   jmethodID id = NULL;
  1635   // We use a double-check locking idiom here because this cache is
  1636   // performance sensitive. In the normal system, this cache only
  1637   // transitions from NULL to non-NULL which is safe because we use
  1638   // release_set_methods_jmethod_ids() to advertise the new cache.
  1639   // A partially constructed cache should never be seen by a racing
  1640   // thread. We also use release_store_ptr() to save a new jmethodID
  1641   // in the cache so a partially constructed jmethodID should never be
  1642   // seen either. Cache reads of existing jmethodIDs proceed without a
  1643   // lock, but cache writes of a new jmethodID requires uniqueness and
  1644   // creation of the cache itself requires no leaks so a lock is
  1645   // generally acquired in those two cases.
  1646   //
  1647   // If the RedefineClasses() API has been used, then this cache can
  1648   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1649   // Cache creation requires no leaks and we require safety between all
  1650   // cache accesses and freeing of the old cache so a lock is generally
  1651   // acquired when the RedefineClasses() API has been used.
  1653   if (jmeths != NULL) {
  1654     // the cache already exists
  1655     if (!ik_h->idnum_can_increment()) {
  1656       // the cache can't grow so we can just get the current values
  1657       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1658     } else {
  1659       // cache can grow so we have to be more careful
  1660       if (Threads::number_of_threads() == 0 ||
  1661           SafepointSynchronize::is_at_safepoint()) {
  1662         // we're single threaded or at a safepoint - no locking needed
  1663         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1664       } else {
  1665         MutexLocker ml(JmethodIdCreation_lock);
  1666         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1670   // implied else:
  1671   // we need to allocate a cache so default length and id values are good
  1673   if (jmeths == NULL ||   // no cache yet
  1674       length <= idnum ||  // cache is too short
  1675       id == NULL) {       // cache doesn't contain entry
  1677     // This function can be called by the VMThread so we have to do all
  1678     // things that might block on a safepoint before grabbing the lock.
  1679     // Otherwise, we can deadlock with the VMThread or have a cache
  1680     // consistency issue. These vars keep track of what we might have
  1681     // to free after the lock is dropped.
  1682     jmethodID  to_dealloc_id     = NULL;
  1683     jmethodID* to_dealloc_jmeths = NULL;
  1685     // may not allocate new_jmeths or use it if we allocate it
  1686     jmethodID* new_jmeths = NULL;
  1687     if (length <= idnum) {
  1688       // allocate a new cache that might be used
  1689       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1690       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1691       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1692       // cache size is stored in element[0], other elements offset by one
  1693       new_jmeths[0] = (jmethodID)size;
  1696     // allocate a new jmethodID that might be used
  1697     jmethodID new_id = NULL;
  1698     if (method_h->is_old() && !method_h->is_obsolete()) {
  1699       // The method passed in is old (but not obsolete), we need to use the current version
  1700       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1701       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1702       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1703     } else {
  1704       // It is the current version of the method or an obsolete method,
  1705       // use the version passed in
  1706       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1709     if (Threads::number_of_threads() == 0 ||
  1710         SafepointSynchronize::is_at_safepoint()) {
  1711       // we're single threaded or at a safepoint - no locking needed
  1712       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1713                                           &to_dealloc_id, &to_dealloc_jmeths);
  1714     } else {
  1715       MutexLocker ml(JmethodIdCreation_lock);
  1716       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1717                                           &to_dealloc_id, &to_dealloc_jmeths);
  1720     // The lock has been dropped so we can free resources.
  1721     // Free up either the old cache or the new cache if we allocated one.
  1722     if (to_dealloc_jmeths != NULL) {
  1723       FreeHeap(to_dealloc_jmeths);
  1725     // free up the new ID since it wasn't needed
  1726     if (to_dealloc_id != NULL) {
  1727       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1730   return id;
  1734 // Common code to fetch the jmethodID from the cache or update the
  1735 // cache with the new jmethodID. This function should never do anything
  1736 // that causes the caller to go to a safepoint or we can deadlock with
  1737 // the VMThread or have cache consistency issues.
  1738 //
  1739 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1740             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1741             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1742             jmethodID** to_dealloc_jmeths_p) {
  1743   assert(new_id != NULL, "sanity check");
  1744   assert(to_dealloc_id_p != NULL, "sanity check");
  1745   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1746   assert(Threads::number_of_threads() == 0 ||
  1747          SafepointSynchronize::is_at_safepoint() ||
  1748          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1750   // reacquire the cache - we are locked, single threaded or at a safepoint
  1751   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1752   jmethodID  id     = NULL;
  1753   size_t     length = 0;
  1755   if (jmeths == NULL ||                         // no cache yet
  1756       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1757     if (jmeths != NULL) {
  1758       // copy any existing entries from the old cache
  1759       for (size_t index = 0; index < length; index++) {
  1760         new_jmeths[index+1] = jmeths[index+1];
  1762       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1764     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1765   } else {
  1766     // fetch jmethodID (if any) from the existing cache
  1767     id = jmeths[idnum+1];
  1768     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1770   if (id == NULL) {
  1771     // No matching jmethodID in the existing cache or we have a new
  1772     // cache or we just grew the cache. This cache write is done here
  1773     // by the first thread to win the foot race because a jmethodID
  1774     // needs to be unique once it is generally available.
  1775     id = new_id;
  1777     // The jmethodID cache can be read while unlocked so we have to
  1778     // make sure the new jmethodID is complete before installing it
  1779     // in the cache.
  1780     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1781   } else {
  1782     *to_dealloc_id_p = new_id; // save new id for later delete
  1784   return id;
  1788 // Common code to get the jmethodID cache length and the jmethodID
  1789 // value at index idnum if there is one.
  1790 //
  1791 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1792        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1793   assert(cache != NULL, "sanity check");
  1794   assert(length_p != NULL, "sanity check");
  1795   assert(id_p != NULL, "sanity check");
  1797   // cache size is stored in element[0], other elements offset by one
  1798   *length_p = (size_t)cache[0];
  1799   if (*length_p <= idnum) {  // cache is too short
  1800     *id_p = NULL;
  1801   } else {
  1802     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1807 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1808 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1809   size_t idnum = (size_t)method->method_idnum();
  1810   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1811   size_t length;                                // length assigned as debugging crumb
  1812   jmethodID id = NULL;
  1813   if (jmeths != NULL &&                         // If there is a cache
  1814       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1815     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1817   return id;
  1821 //
  1822 // Walk the list of dependent nmethods searching for nmethods which
  1823 // are dependent on the changes that were passed in and mark them for
  1824 // deoptimization.  Returns the number of nmethods found.
  1825 //
  1826 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1827   assert_locked_or_safepoint(CodeCache_lock);
  1828   int found = 0;
  1829   nmethodBucket* b = _dependencies;
  1830   while (b != NULL) {
  1831     nmethod* nm = b->get_nmethod();
  1832     // since dependencies aren't removed until an nmethod becomes a zombie,
  1833     // the dependency list may contain nmethods which aren't alive.
  1834     if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1835       if (TraceDependencies) {
  1836         ResourceMark rm;
  1837         tty->print_cr("Marked for deoptimization");
  1838         tty->print_cr("  context = %s", this->external_name());
  1839         changes.print();
  1840         nm->print();
  1841         nm->print_dependencies();
  1843       nm->mark_for_deoptimization();
  1844       found++;
  1846     b = b->next();
  1848   return found;
  1852 //
  1853 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1854 // It's possible that an nmethod has multiple dependencies on this klass
  1855 // so a count is kept for each bucket to guarantee that creation and
  1856 // deletion of dependencies is consistent.
  1857 //
  1858 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1859   assert_locked_or_safepoint(CodeCache_lock);
  1860   nmethodBucket* b = _dependencies;
  1861   nmethodBucket* last = NULL;
  1862   while (b != NULL) {
  1863     if (nm == b->get_nmethod()) {
  1864       b->increment();
  1865       return;
  1867     b = b->next();
  1869   _dependencies = new nmethodBucket(nm, _dependencies);
  1873 //
  1874 // Decrement count of the nmethod in the dependency list and remove
  1875 // the bucket competely when the count goes to 0.  This method must
  1876 // find a corresponding bucket otherwise there's a bug in the
  1877 // recording of dependecies.
  1878 //
  1879 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1880   assert_locked_or_safepoint(CodeCache_lock);
  1881   nmethodBucket* b = _dependencies;
  1882   nmethodBucket* last = NULL;
  1883   while (b != NULL) {
  1884     if (nm == b->get_nmethod()) {
  1885       if (b->decrement() == 0) {
  1886         if (last == NULL) {
  1887           _dependencies = b->next();
  1888         } else {
  1889           last->set_next(b->next());
  1891         delete b;
  1893       return;
  1895     last = b;
  1896     b = b->next();
  1898 #ifdef ASSERT
  1899   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1900   nm->print();
  1901 #endif // ASSERT
  1902   ShouldNotReachHere();
  1906 #ifndef PRODUCT
  1907 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1908   nmethodBucket* b = _dependencies;
  1909   int idx = 0;
  1910   while (b != NULL) {
  1911     nmethod* nm = b->get_nmethod();
  1912     tty->print("[%d] count=%d { ", idx++, b->count());
  1913     if (!verbose) {
  1914       nm->print_on(tty, "nmethod");
  1915       tty->print_cr(" } ");
  1916     } else {
  1917       nm->print();
  1918       nm->print_dependencies();
  1919       tty->print_cr("--- } ");
  1921     b = b->next();
  1926 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  1927   nmethodBucket* b = _dependencies;
  1928   while (b != NULL) {
  1929     if (nm == b->get_nmethod()) {
  1930       return true;
  1932     b = b->next();
  1934   return false;
  1936 #endif //PRODUCT
  1939 // Garbage collection
  1941 #ifdef ASSERT
  1942 template <class T> void assert_is_in(T *p) {
  1943   T heap_oop = oopDesc::load_heap_oop(p);
  1944   if (!oopDesc::is_null(heap_oop)) {
  1945     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1946     assert(Universe::heap()->is_in(o), "should be in heap");
  1949 template <class T> void assert_is_in_closed_subset(T *p) {
  1950   T heap_oop = oopDesc::load_heap_oop(p);
  1951   if (!oopDesc::is_null(heap_oop)) {
  1952     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1953     assert(Universe::heap()->is_in_closed_subset(o),
  1954            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  1957 template <class T> void assert_is_in_reserved(T *p) {
  1958   T heap_oop = oopDesc::load_heap_oop(p);
  1959   if (!oopDesc::is_null(heap_oop)) {
  1960     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1961     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  1964 template <class T> void assert_nothing(T *p) {}
  1966 #else
  1967 template <class T> void assert_is_in(T *p) {}
  1968 template <class T> void assert_is_in_closed_subset(T *p) {}
  1969 template <class T> void assert_is_in_reserved(T *p) {}
  1970 template <class T> void assert_nothing(T *p) {}
  1971 #endif // ASSERT
  1973 //
  1974 // Macros that iterate over areas of oops which are specialized on type of
  1975 // oop pointer either narrow or wide, depending on UseCompressedOops
  1976 //
  1977 // Parameters are:
  1978 //   T         - type of oop to point to (either oop or narrowOop)
  1979 //   start_p   - starting pointer for region to iterate over
  1980 //   count     - number of oops or narrowOops to iterate over
  1981 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  1982 //               makes it more efficient to put in a macro rather than making
  1983 //               it a template function)
  1984 //   assert_fn - assert function which is template function because performance
  1985 //               doesn't matter when enabled.
  1986 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  1987   T, start_p, count, do_oop,                \
  1988   assert_fn)                                \
  1989 {                                           \
  1990   T* p         = (T*)(start_p);             \
  1991   T* const end = p + (count);               \
  1992   while (p < end) {                         \
  1993     (assert_fn)(p);                         \
  1994     do_oop;                                 \
  1995     ++p;                                    \
  1996   }                                         \
  1999 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  2000   T, start_p, count, do_oop,                \
  2001   assert_fn)                                \
  2002 {                                           \
  2003   T* const start = (T*)(start_p);           \
  2004   T*       p     = start + (count);         \
  2005   while (start < p) {                       \
  2006     --p;                                    \
  2007     (assert_fn)(p);                         \
  2008     do_oop;                                 \
  2009   }                                         \
  2012 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  2013   T, start_p, count, low, high,             \
  2014   do_oop, assert_fn)                        \
  2015 {                                           \
  2016   T* const l = (T*)(low);                   \
  2017   T* const h = (T*)(high);                  \
  2018   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  2019          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  2020          "bounded region must be properly aligned"); \
  2021   T* p       = (T*)(start_p);               \
  2022   T* end     = p + (count);                 \
  2023   if (p < l) p = l;                         \
  2024   if (end > h) end = h;                     \
  2025   while (p < end) {                         \
  2026     (assert_fn)(p);                         \
  2027     do_oop;                                 \
  2028     ++p;                                    \
  2029   }                                         \
  2033 // The following macros call specialized macros, passing either oop or
  2034 // narrowOop as the specialization type.  These test the UseCompressedOops
  2035 // flag.
  2036 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  2037 {                                                                        \
  2038   /* Compute oopmap block range. The common case                         \
  2039      is nonstatic_oop_map_size == 1. */                                  \
  2040   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2041   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2042   if (UseCompressedOops) {                                               \
  2043     while (map < end_map) {                                              \
  2044       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  2045         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2046         do_oop, assert_fn)                                               \
  2047       ++map;                                                             \
  2048     }                                                                    \
  2049   } else {                                                               \
  2050     while (map < end_map) {                                              \
  2051       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  2052         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2053         do_oop, assert_fn)                                               \
  2054       ++map;                                                             \
  2055     }                                                                    \
  2056   }                                                                      \
  2059 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  2060 {                                                                        \
  2061   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  2062   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  2063   if (UseCompressedOops) {                                               \
  2064     while (start_map < map) {                                            \
  2065       --map;                                                             \
  2066       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  2067         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2068         do_oop, assert_fn)                                               \
  2069     }                                                                    \
  2070   } else {                                                               \
  2071     while (start_map < map) {                                            \
  2072       --map;                                                             \
  2073       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  2074         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2075         do_oop, assert_fn)                                               \
  2076     }                                                                    \
  2077   }                                                                      \
  2080 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  2081                                               assert_fn)                 \
  2082 {                                                                        \
  2083   /* Compute oopmap block range. The common case is                      \
  2084      nonstatic_oop_map_size == 1, so we accept the                       \
  2085      usually non-existent extra overhead of examining                    \
  2086      all the maps. */                                                    \
  2087   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2088   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2089   if (UseCompressedOops) {                                               \
  2090     while (map < end_map) {                                              \
  2091       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  2092         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2093         low, high,                                                       \
  2094         do_oop, assert_fn)                                               \
  2095       ++map;                                                             \
  2096     }                                                                    \
  2097   } else {                                                               \
  2098     while (map < end_map) {                                              \
  2099       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2100         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2101         low, high,                                                       \
  2102         do_oop, assert_fn)                                               \
  2103       ++map;                                                             \
  2104     }                                                                    \
  2105   }                                                                      \
  2108 void InstanceKlass::oop_follow_contents(oop obj) {
  2109   assert(obj != NULL, "can't follow the content of NULL object");
  2110   MarkSweep::follow_klass(obj->klass());
  2111   InstanceKlass_OOP_MAP_ITERATE( \
  2112     obj, \
  2113     MarkSweep::mark_and_push(p), \
  2114     assert_is_in_closed_subset)
  2117 #if INCLUDE_ALL_GCS
  2118 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2119                                         oop obj) {
  2120   assert(obj != NULL, "can't follow the content of NULL object");
  2121   PSParallelCompact::follow_klass(cm, obj->klass());
  2122   // Only mark the header and let the scan of the meta-data mark
  2123   // everything else.
  2124   InstanceKlass_OOP_MAP_ITERATE( \
  2125     obj, \
  2126     PSParallelCompact::mark_and_push(cm, p), \
  2127     assert_is_in)
  2129 #endif // INCLUDE_ALL_GCS
  2131 // closure's do_metadata() method dictates whether the given closure should be
  2132 // applied to the klass ptr in the object header.
  2134 #define if_do_metadata_checked(closure, nv_suffix)                    \
  2135   /* Make sure the non-virtual and the virtual versions match. */     \
  2136   assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
  2137       "Inconsistency in do_metadata");                                \
  2138   if (closure->do_metadata##nv_suffix())
  2140 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2142 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2143   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2144   /* header */                                                          \
  2145   if_do_metadata_checked(closure, nv_suffix) {                          \
  2146     closure->do_klass##nv_suffix(obj->klass());                         \
  2147   }                                                                     \
  2148   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2149     obj,                                                                \
  2150     SpecializationStats::                                               \
  2151       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2152     (closure)->do_oop##nv_suffix(p),                                    \
  2153     assert_is_in_closed_subset)                                         \
  2154   return size_helper();                                                 \
  2157 #if INCLUDE_ALL_GCS
  2158 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2160 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2161                                               OopClosureType* closure) {        \
  2162   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2163   /* header */                                                                  \
  2164   if_do_metadata_checked(closure, nv_suffix) {                                  \
  2165     closure->do_klass##nv_suffix(obj->klass());                                 \
  2166   }                                                                             \
  2167   /* instance variables */                                                      \
  2168   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2169     obj,                                                                        \
  2170     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2171     (closure)->do_oop##nv_suffix(p),                                            \
  2172     assert_is_in_closed_subset)                                                 \
  2173    return size_helper();                                                        \
  2175 #endif // INCLUDE_ALL_GCS
  2177 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2179 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2180                                                   OopClosureType* closure, \
  2181                                                   MemRegion mr) {          \
  2182   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2183   if_do_metadata_checked(closure, nv_suffix) {                           \
  2184     if (mr.contains(obj)) {                                              \
  2185       closure->do_klass##nv_suffix(obj->klass());                        \
  2186     }                                                                    \
  2187   }                                                                      \
  2188   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2189     obj, mr.start(), mr.end(),                                           \
  2190     (closure)->do_oop##nv_suffix(p),                                     \
  2191     assert_is_in_closed_subset)                                          \
  2192   return size_helper();                                                  \
  2195 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2196 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2197 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2198 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2199 #if INCLUDE_ALL_GCS
  2200 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2201 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2202 #endif // INCLUDE_ALL_GCS
  2204 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2205   int size = size_helper();
  2206   InstanceKlass_OOP_MAP_ITERATE( \
  2207     obj, \
  2208     MarkSweep::adjust_pointer(p), \
  2209     assert_is_in)
  2210   return size;
  2213 #if INCLUDE_ALL_GCS
  2214 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2215   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2216     obj, \
  2217     if (PSScavenge::should_scavenge(p)) { \
  2218       pm->claim_or_forward_depth(p); \
  2219     }, \
  2220     assert_nothing )
  2223 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2224   int size = size_helper();
  2225   InstanceKlass_OOP_MAP_ITERATE( \
  2226     obj, \
  2227     PSParallelCompact::adjust_pointer(p), \
  2228     assert_is_in)
  2229   return size;
  2232 #endif // INCLUDE_ALL_GCS
  2234 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2235   assert(is_loader_alive(is_alive), "this klass should be live");
  2236   if (is_interface()) {
  2237     if (ClassUnloading) {
  2238       Klass* impl = implementor();
  2239       if (impl != NULL) {
  2240         if (!impl->is_loader_alive(is_alive)) {
  2241           // remove this guy
  2242           Klass** klass = adr_implementor();
  2243           assert(klass != NULL, "null klass");
  2244           if (klass != NULL) {
  2245             *klass = NULL;
  2253 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2254   for (int m = 0; m < methods()->length(); m++) {
  2255     MethodData* mdo = methods()->at(m)->method_data();
  2256     if (mdo != NULL) {
  2257       mdo->clean_method_data(is_alive);
  2263 static void remove_unshareable_in_class(Klass* k) {
  2264   // remove klass's unshareable info
  2265   k->remove_unshareable_info();
  2268 void InstanceKlass::remove_unshareable_info() {
  2269   Klass::remove_unshareable_info();
  2270   // Unlink the class
  2271   if (is_linked()) {
  2272     unlink_class();
  2274   init_implementor();
  2276   constants()->remove_unshareable_info();
  2278   for (int i = 0; i < methods()->length(); i++) {
  2279     Method* m = methods()->at(i);
  2280     m->remove_unshareable_info();
  2283   // do array classes also.
  2284   array_klasses_do(remove_unshareable_in_class);
  2287 void restore_unshareable_in_class(Klass* k, TRAPS) {
  2288   k->restore_unshareable_info(CHECK);
  2291 void InstanceKlass::restore_unshareable_info(TRAPS) {
  2292   Klass::restore_unshareable_info(CHECK);
  2293   instanceKlassHandle ik(THREAD, this);
  2295   Array<Method*>* methods = ik->methods();
  2296   int num_methods = methods->length();
  2297   for (int index2 = 0; index2 < num_methods; ++index2) {
  2298     methodHandle m(THREAD, methods->at(index2));
  2299     m->restore_unshareable_info(CHECK);
  2301   if (JvmtiExport::has_redefined_a_class()) {
  2302     // Reinitialize vtable because RedefineClasses may have changed some
  2303     // entries in this vtable for super classes so the CDS vtable might
  2304     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2305     // vtables in the shared system dictionary, only the main one.
  2306     // It also redefines the itable too so fix that too.
  2307     ResourceMark rm(THREAD);
  2308     ik->vtable()->initialize_vtable(false, CHECK);
  2309     ik->itable()->initialize_itable(false, CHECK);
  2312   // restore constant pool resolved references
  2313   ik->constants()->restore_unshareable_info(CHECK);
  2315   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2318 static void clear_all_breakpoints(Method* m) {
  2319   m->clear_all_breakpoints();
  2323 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
  2324   // notify the debugger
  2325   if (JvmtiExport::should_post_class_unload()) {
  2326     JvmtiExport::post_class_unload(ik);
  2329   // notify ClassLoadingService of class unload
  2330   ClassLoadingService::notify_class_unloaded(ik);
  2333 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
  2334   // Clean up C heap
  2335   ik->release_C_heap_structures();
  2336   ik->constants()->release_C_heap_structures();
  2339 void InstanceKlass::release_C_heap_structures() {
  2341   // Can't release the constant pool here because the constant pool can be
  2342   // deallocated separately from the InstanceKlass for default methods and
  2343   // redefine classes.
  2345   // Deallocate oop map cache
  2346   if (_oop_map_cache != NULL) {
  2347     delete _oop_map_cache;
  2348     _oop_map_cache = NULL;
  2351   // Deallocate JNI identifiers for jfieldIDs
  2352   JNIid::deallocate(jni_ids());
  2353   set_jni_ids(NULL);
  2355   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2356   if (jmeths != (jmethodID*)NULL) {
  2357     release_set_methods_jmethod_ids(NULL);
  2358     FreeHeap(jmeths);
  2361   // Deallocate MemberNameTable
  2363     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
  2364     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
  2365     MemberNameTable* mnt = member_names();
  2366     if (mnt != NULL) {
  2367       delete mnt;
  2368       set_member_names(NULL);
  2372   // release dependencies
  2373   nmethodBucket* b = _dependencies;
  2374   _dependencies = NULL;
  2375   while (b != NULL) {
  2376     nmethodBucket* next = b->next();
  2377     delete b;
  2378     b = next;
  2381   // Deallocate breakpoint records
  2382   if (breakpoints() != 0x0) {
  2383     methods_do(clear_all_breakpoints);
  2384     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2387   // deallocate information about previous versions
  2388   if (_previous_versions != NULL) {
  2389     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2390       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2391       delete pv_node;
  2393     delete _previous_versions;
  2394     _previous_versions = NULL;
  2397   // deallocate the cached class file
  2398   if (_cached_class_file != NULL) {
  2399     os::free(_cached_class_file, mtClass);
  2400     _cached_class_file = NULL;
  2403   // Decrement symbol reference counts associated with the unloaded class.
  2404   if (_name != NULL) _name->decrement_refcount();
  2405   // unreference array name derived from this class name (arrays of an unloaded
  2406   // class can't be referenced anymore).
  2407   if (_array_name != NULL)  _array_name->decrement_refcount();
  2408   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2410   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2411   Atomic::dec(&_total_instanceKlass_count);
  2414 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2415   if (array == NULL) {
  2416     _source_debug_extension = NULL;
  2417   } else {
  2418     // Adding one to the attribute length in order to store a null terminator
  2419     // character could cause an overflow because the attribute length is
  2420     // already coded with an u4 in the classfile, but in practice, it's
  2421     // unlikely to happen.
  2422     assert((length+1) > length, "Overflow checking");
  2423     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2424     for (int i = 0; i < length; i++) {
  2425       sde[i] = array[i];
  2427     sde[length] = '\0';
  2428     _source_debug_extension = sde;
  2432 address InstanceKlass::static_field_addr(int offset) {
  2433   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
  2437 const char* InstanceKlass::signature_name() const {
  2438   int hash_len = 0;
  2439   char hash_buf[40];
  2441   // If this is an anonymous class, append a hash to make the name unique
  2442   if (is_anonymous()) {
  2443     assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
  2444     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
  2445     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
  2446     hash_len = (int)strlen(hash_buf);
  2449   // Get the internal name as a c string
  2450   const char* src = (const char*) (name()->as_C_string());
  2451   const int src_length = (int)strlen(src);
  2453   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
  2455   // Add L as type indicator
  2456   int dest_index = 0;
  2457   dest[dest_index++] = 'L';
  2459   // Add the actual class name
  2460   for (int src_index = 0; src_index < src_length; ) {
  2461     dest[dest_index++] = src[src_index++];
  2464   // If we have a hash, append it
  2465   for (int hash_index = 0; hash_index < hash_len; ) {
  2466     dest[dest_index++] = hash_buf[hash_index++];
  2469   // Add the semicolon and the NULL
  2470   dest[dest_index++] = ';';
  2471   dest[dest_index] = '\0';
  2472   return dest;
  2475 // different verisons of is_same_class_package
  2476 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2477   Klass* class1 = this;
  2478   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2479   Symbol* classname1 = class1->name();
  2481   if (class2->oop_is_objArray()) {
  2482     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2484   oop classloader2;
  2485   if (class2->oop_is_instance()) {
  2486     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2487   } else {
  2488     assert(class2->oop_is_typeArray(), "should be type array");
  2489     classloader2 = NULL;
  2491   Symbol* classname2 = class2->name();
  2493   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2494                                               classloader2, classname2);
  2497 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2498   Klass* class1 = this;
  2499   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2500   Symbol* classname1 = class1->name();
  2502   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2503                                               classloader2, classname2);
  2506 // return true if two classes are in the same package, classloader
  2507 // and classname information is enough to determine a class's package
  2508 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2509                                           oop class_loader2, Symbol* class_name2) {
  2510   if (class_loader1 != class_loader2) {
  2511     return false;
  2512   } else if (class_name1 == class_name2) {
  2513     return true;                // skip painful bytewise comparison
  2514   } else {
  2515     ResourceMark rm;
  2517     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2518     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2519     // Otherwise, we just compare jbyte values between the strings.
  2520     const jbyte *name1 = class_name1->base();
  2521     const jbyte *name2 = class_name2->base();
  2523     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2524     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2526     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2527       // One of the two doesn't have a package.  Only return true
  2528       // if the other one also doesn't have a package.
  2529       return last_slash1 == last_slash2;
  2530     } else {
  2531       // Skip over '['s
  2532       if (*name1 == '[') {
  2533         do {
  2534           name1++;
  2535         } while (*name1 == '[');
  2536         if (*name1 != 'L') {
  2537           // Something is terribly wrong.  Shouldn't be here.
  2538           return false;
  2541       if (*name2 == '[') {
  2542         do {
  2543           name2++;
  2544         } while (*name2 == '[');
  2545         if (*name2 != 'L') {
  2546           // Something is terribly wrong.  Shouldn't be here.
  2547           return false;
  2551       // Check that package part is identical
  2552       int length1 = last_slash1 - name1;
  2553       int length2 = last_slash2 - name2;
  2555       return UTF8::equal(name1, length1, name2, length2);
  2560 // Returns true iff super_method can be overridden by a method in targetclassname
  2561 // See JSL 3rd edition 8.4.6.1
  2562 // Assumes name-signature match
  2563 // "this" is InstanceKlass of super_method which must exist
  2564 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2565 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2566    // Private methods can not be overridden
  2567    if (super_method->is_private()) {
  2568      return false;
  2570    // If super method is accessible, then override
  2571    if ((super_method->is_protected()) ||
  2572        (super_method->is_public())) {
  2573      return true;
  2575    // Package-private methods are not inherited outside of package
  2576    assert(super_method->is_package_private(), "must be package private");
  2577    return(is_same_class_package(targetclassloader(), targetclassname));
  2580 /* defined for now in jvm.cpp, for historical reasons *--
  2581 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2582                                                      Symbol*& simple_name_result, TRAPS) {
  2583   ...
  2585 */
  2587 // tell if two classes have the same enclosing class (at package level)
  2588 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2589                                                 Klass* class2_oop, TRAPS) {
  2590   if (class2_oop == class1())                       return true;
  2591   if (!class2_oop->oop_is_instance())  return false;
  2592   instanceKlassHandle class2(THREAD, class2_oop);
  2594   // must be in same package before we try anything else
  2595   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2596     return false;
  2598   // As long as there is an outer1.getEnclosingClass,
  2599   // shift the search outward.
  2600   instanceKlassHandle outer1 = class1;
  2601   for (;;) {
  2602     // As we walk along, look for equalities between outer1 and class2.
  2603     // Eventually, the walks will terminate as outer1 stops
  2604     // at the top-level class around the original class.
  2605     bool ignore_inner_is_member;
  2606     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2607                                                     CHECK_false);
  2608     if (next == NULL)  break;
  2609     if (next == class2())  return true;
  2610     outer1 = instanceKlassHandle(THREAD, next);
  2613   // Now do the same for class2.
  2614   instanceKlassHandle outer2 = class2;
  2615   for (;;) {
  2616     bool ignore_inner_is_member;
  2617     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2618                                                     CHECK_false);
  2619     if (next == NULL)  break;
  2620     // Might as well check the new outer against all available values.
  2621     if (next == class1())  return true;
  2622     if (next == outer1())  return true;
  2623     outer2 = instanceKlassHandle(THREAD, next);
  2626   // If by this point we have not found an equality between the
  2627   // two classes, we know they are in separate package members.
  2628   return false;
  2632 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2633   jint access = access_flags().as_int();
  2635   // But check if it happens to be member class.
  2636   instanceKlassHandle ik(THREAD, this);
  2637   InnerClassesIterator iter(ik);
  2638   for (; !iter.done(); iter.next()) {
  2639     int ioff = iter.inner_class_info_index();
  2640     // Inner class attribute can be zero, skip it.
  2641     // Strange but true:  JVM spec. allows null inner class refs.
  2642     if (ioff == 0) continue;
  2644     // only look at classes that are already loaded
  2645     // since we are looking for the flags for our self.
  2646     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2647     if ((ik->name() == inner_name)) {
  2648       // This is really a member class.
  2649       access = iter.inner_access_flags();
  2650       break;
  2653   // Remember to strip ACC_SUPER bit
  2654   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2657 jint InstanceKlass::jvmti_class_status() const {
  2658   jint result = 0;
  2660   if (is_linked()) {
  2661     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2664   if (is_initialized()) {
  2665     assert(is_linked(), "Class status is not consistent");
  2666     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2668   if (is_in_error_state()) {
  2669     result |= JVMTI_CLASS_STATUS_ERROR;
  2671   return result;
  2674 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2675   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2676   int method_table_offset_in_words = ioe->offset()/wordSize;
  2677   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2678                        / itableOffsetEntry::size();
  2680   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2681     // If the interface isn't implemented by the receiver class,
  2682     // the VM should throw IncompatibleClassChangeError.
  2683     if (cnt >= nof_interfaces) {
  2684       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2687     Klass* ik = ioe->interface_klass();
  2688     if (ik == holder) break;
  2691   itableMethodEntry* ime = ioe->first_method_entry(this);
  2692   Method* m = ime[index].method();
  2693   if (m == NULL) {
  2694     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2696   return m;
  2700 #if INCLUDE_JVMTI
  2701 // update default_methods for redefineclasses for methods that are
  2702 // not yet in the vtable due to concurrent subclass define and superinterface
  2703 // redefinition
  2704 // Note: those in the vtable, should have been updated via adjust_method_entries
  2705 void InstanceKlass::adjust_default_methods(Method** old_methods, Method** new_methods,
  2706                                            int methods_length, bool* trace_name_printed) {
  2707   // search the default_methods for uses of either obsolete or EMCP methods
  2708   if (default_methods() != NULL) {
  2709     for (int j = 0; j < methods_length; j++) {
  2710       Method* old_method = old_methods[j];
  2711       Method* new_method = new_methods[j];
  2713       for (int index = 0; index < default_methods()->length(); index ++) {
  2714         if (default_methods()->at(index) == old_method) {
  2715           default_methods()->at_put(index, new_method);
  2716           if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
  2717             if (!(*trace_name_printed)) {
  2718               // RC_TRACE_MESG macro has an embedded ResourceMark
  2719               RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
  2720                              external_name(),
  2721                              old_method->method_holder()->external_name()));
  2722               *trace_name_printed = true;
  2724             RC_TRACE(0x00100000, ("default method update: %s(%s) ",
  2725                                   new_method->name()->as_C_string(),
  2726                                   new_method->signature()->as_C_string()));
  2733 #endif // INCLUDE_JVMTI
  2735 // On-stack replacement stuff
  2736 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2737   // only one compilation can be active
  2738   NEEDS_CLEANUP
  2739   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2740   OsrList_lock->lock_without_safepoint_check();
  2741   assert(n->is_osr_method(), "wrong kind of nmethod");
  2742   n->set_osr_link(osr_nmethods_head());
  2743   set_osr_nmethods_head(n);
  2744   // Raise the highest osr level if necessary
  2745   if (TieredCompilation) {
  2746     Method* m = n->method();
  2747     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2749   // Remember to unlock again
  2750   OsrList_lock->unlock();
  2752   // Get rid of the osr methods for the same bci that have lower levels.
  2753   if (TieredCompilation) {
  2754     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2755       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2756       if (inv != NULL && inv->is_in_use()) {
  2757         inv->make_not_entrant();
  2764 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2765   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2766   OsrList_lock->lock_without_safepoint_check();
  2767   assert(n->is_osr_method(), "wrong kind of nmethod");
  2768   nmethod* last = NULL;
  2769   nmethod* cur  = osr_nmethods_head();
  2770   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2771   Method* m = n->method();
  2772   // Search for match
  2773   while(cur != NULL && cur != n) {
  2774     if (TieredCompilation && m == cur->method()) {
  2775       // Find max level before n
  2776       max_level = MAX2(max_level, cur->comp_level());
  2778     last = cur;
  2779     cur = cur->osr_link();
  2781   nmethod* next = NULL;
  2782   if (cur == n) {
  2783     next = cur->osr_link();
  2784     if (last == NULL) {
  2785       // Remove first element
  2786       set_osr_nmethods_head(next);
  2787     } else {
  2788       last->set_osr_link(next);
  2791   n->set_osr_link(NULL);
  2792   if (TieredCompilation) {
  2793     cur = next;
  2794     while (cur != NULL) {
  2795       // Find max level after n
  2796       if (m == cur->method()) {
  2797         max_level = MAX2(max_level, cur->comp_level());
  2799       cur = cur->osr_link();
  2801     m->set_highest_osr_comp_level(max_level);
  2803   // Remember to unlock again
  2804   OsrList_lock->unlock();
  2807 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
  2808   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2809   OsrList_lock->lock_without_safepoint_check();
  2810   nmethod* osr = osr_nmethods_head();
  2811   nmethod* best = NULL;
  2812   while (osr != NULL) {
  2813     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2814     // There can be a time when a c1 osr method exists but we are waiting
  2815     // for a c2 version. When c2 completes its osr nmethod we will trash
  2816     // the c1 version and only be able to find the c2 version. However
  2817     // while we overflow in the c1 code at back branches we don't want to
  2818     // try and switch to the same code as we are already running
  2820     if (osr->method() == m &&
  2821         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2822       if (match_level) {
  2823         if (osr->comp_level() == comp_level) {
  2824           // Found a match - return it.
  2825           OsrList_lock->unlock();
  2826           return osr;
  2828       } else {
  2829         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2830           if (osr->comp_level() == CompLevel_highest_tier) {
  2831             // Found the best possible - return it.
  2832             OsrList_lock->unlock();
  2833             return osr;
  2835           best = osr;
  2839     osr = osr->osr_link();
  2841   OsrList_lock->unlock();
  2842   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2843     return best;
  2845   return NULL;
  2848 void InstanceKlass::add_member_name(int index, Handle mem_name) {
  2849   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  2850   MutexLocker ml(MemberNameTable_lock);
  2851   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  2852   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2854   if (_member_names == NULL) {
  2855     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
  2857   _member_names->add_member_name(index, mem_name_wref);
  2860 oop InstanceKlass::get_member_name(int index) {
  2861   MutexLocker ml(MemberNameTable_lock);
  2862   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  2863   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2865   if (_member_names == NULL) {
  2866     return NULL;
  2868   oop mem_name =_member_names->get_member_name(index);
  2869   return mem_name;
  2872 // -----------------------------------------------------------------------------------------------------
  2873 // Printing
  2875 #ifndef PRODUCT
  2877 #define BULLET  " - "
  2879 static const char* state_names[] = {
  2880   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  2881 };
  2883 static void print_vtable(intptr_t* start, int len, outputStream* st) {
  2884   for (int i = 0; i < len; i++) {
  2885     intptr_t e = start[i];
  2886     st->print("%d : " INTPTR_FORMAT, i, e);
  2887     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
  2888       st->print(" ");
  2889       ((Metadata*)e)->print_value_on(st);
  2891     st->cr();
  2895 void InstanceKlass::print_on(outputStream* st) const {
  2896   assert(is_klass(), "must be klass");
  2897   Klass::print_on(st);
  2899   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  2900   st->print(BULLET"klass size:        %d", size());                               st->cr();
  2901   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  2902   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
  2903   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  2904   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  2905   st->print(BULLET"sub:               ");
  2906   Klass* sub = subklass();
  2907   int n;
  2908   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  2909     if (n < MaxSubklassPrintSize) {
  2910       sub->print_value_on(st);
  2911       st->print("   ");
  2914   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  2915   st->cr();
  2917   if (is_interface()) {
  2918     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  2919     if (nof_implementors() == 1) {
  2920       st->print_cr(BULLET"implementor:    ");
  2921       st->print("   ");
  2922       implementor()->print_value_on(st);
  2923       st->cr();
  2927   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  2928   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  2929   if (Verbose || WizardMode) {
  2930     Array<Method*>* method_array = methods();
  2931     for (int i = 0; i < method_array->length(); i++) {
  2932       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  2935   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
  2936   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
  2937   if (Verbose && default_methods() != NULL) {
  2938     Array<Method*>* method_array = default_methods();
  2939     for (int i = 0; i < method_array->length(); i++) {
  2940       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  2943   if (default_vtable_indices() != NULL) {
  2944     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
  2946   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  2947   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  2948   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  2949   if (class_loader_data() != NULL) {
  2950     st->print(BULLET"class loader data:  ");
  2951     class_loader_data()->print_value_on(st);
  2952     st->cr();
  2954   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  2955   if (source_file_name() != NULL) {
  2956     st->print(BULLET"source file:       ");
  2957     source_file_name()->print_value_on(st);
  2958     st->cr();
  2960   if (source_debug_extension() != NULL) {
  2961     st->print(BULLET"source debug extension:       ");
  2962     st->print("%s", source_debug_extension());
  2963     st->cr();
  2965   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  2966   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  2967   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  2968   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  2970     bool have_pv = false;
  2971     PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  2972     for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  2973          pv_node != NULL; pv_node = pvw.next_previous_version()) {
  2974       if (!have_pv)
  2975         st->print(BULLET"previous version:  ");
  2976       have_pv = true;
  2977       pv_node->prev_constant_pool()->print_value_on(st);
  2979     if (have_pv) st->cr();
  2980   } // pvw is cleaned up
  2982   if (generic_signature() != NULL) {
  2983     st->print(BULLET"generic signature: ");
  2984     generic_signature()->print_value_on(st);
  2985     st->cr();
  2987   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  2988   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  2989   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  2990   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
  2991   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  2992   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
  2993   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  2994   FieldPrinter print_static_field(st);
  2995   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  2996   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  2997   FieldPrinter print_nonstatic_field(st);
  2998   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  3000   st->print(BULLET"non-static oop maps: ");
  3001   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  3002   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  3003   while (map < end_map) {
  3004     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  3005     map++;
  3007   st->cr();
  3010 #endif //PRODUCT
  3012 void InstanceKlass::print_value_on(outputStream* st) const {
  3013   assert(is_klass(), "must be klass");
  3014   if (Verbose || WizardMode)  access_flags().print_on(st);
  3015   name()->print_value_on(st);
  3018 #ifndef PRODUCT
  3020 void FieldPrinter::do_field(fieldDescriptor* fd) {
  3021   _st->print(BULLET);
  3022    if (_obj == NULL) {
  3023      fd->print_on(_st);
  3024      _st->cr();
  3025    } else {
  3026      fd->print_on_for(_st, _obj);
  3027      _st->cr();
  3032 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  3033   Klass::oop_print_on(obj, st);
  3035   if (this == SystemDictionary::String_klass()) {
  3036     typeArrayOop value  = java_lang_String::value(obj);
  3037     juint        offset = java_lang_String::offset(obj);
  3038     juint        length = java_lang_String::length(obj);
  3039     if (value != NULL &&
  3040         value->is_typeArray() &&
  3041         offset          <= (juint) value->length() &&
  3042         offset + length <= (juint) value->length()) {
  3043       st->print(BULLET"string: ");
  3044       Handle h_obj(obj);
  3045       java_lang_String::print(h_obj, st);
  3046       st->cr();
  3047       if (!WizardMode)  return;  // that is enough
  3051   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  3052   FieldPrinter print_field(st, obj);
  3053   do_nonstatic_fields(&print_field);
  3055   if (this == SystemDictionary::Class_klass()) {
  3056     st->print(BULLET"signature: ");
  3057     java_lang_Class::print_signature(obj, st);
  3058     st->cr();
  3059     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  3060     st->print(BULLET"fake entry for mirror: ");
  3061     mirrored_klass->print_value_on_maybe_null(st);
  3062     st->cr();
  3063     Klass* array_klass = java_lang_Class::array_klass(obj);
  3064     st->print(BULLET"fake entry for array: ");
  3065     array_klass->print_value_on_maybe_null(st);
  3066     st->cr();
  3067     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  3068     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  3069     Klass* real_klass = java_lang_Class::as_Klass(obj);
  3070     if (real_klass != NULL && real_klass->oop_is_instance()) {
  3071       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  3073   } else if (this == SystemDictionary::MethodType_klass()) {
  3074     st->print(BULLET"signature: ");
  3075     java_lang_invoke_MethodType::print_signature(obj, st);
  3076     st->cr();
  3080 #endif //PRODUCT
  3082 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  3083   st->print("a ");
  3084   name()->print_value_on(st);
  3085   obj->print_address_on(st);
  3086   if (this == SystemDictionary::String_klass()
  3087       && java_lang_String::value(obj) != NULL) {
  3088     ResourceMark rm;
  3089     int len = java_lang_String::length(obj);
  3090     int plen = (len < 24 ? len : 12);
  3091     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  3092     st->print(" = \"%s\"", str);
  3093     if (len > plen)
  3094       st->print("...[%d]", len);
  3095   } else if (this == SystemDictionary::Class_klass()) {
  3096     Klass* k = java_lang_Class::as_Klass(obj);
  3097     st->print(" = ");
  3098     if (k != NULL) {
  3099       k->print_value_on(st);
  3100     } else {
  3101       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  3102       st->print("%s", tname ? tname : "type?");
  3104   } else if (this == SystemDictionary::MethodType_klass()) {
  3105     st->print(" = ");
  3106     java_lang_invoke_MethodType::print_signature(obj, st);
  3107   } else if (java_lang_boxing_object::is_instance(obj)) {
  3108     st->print(" = ");
  3109     java_lang_boxing_object::print(obj, st);
  3110   } else if (this == SystemDictionary::LambdaForm_klass()) {
  3111     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  3112     if (vmentry != NULL) {
  3113       st->print(" => ");
  3114       vmentry->print_value_on(st);
  3116   } else if (this == SystemDictionary::MemberName_klass()) {
  3117     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  3118     if (vmtarget != NULL) {
  3119       st->print(" = ");
  3120       vmtarget->print_value_on(st);
  3121     } else {
  3122       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  3123       st->print(".");
  3124       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  3129 const char* InstanceKlass::internal_name() const {
  3130   return external_name();
  3133 #if INCLUDE_SERVICES
  3134 // Size Statistics
  3135 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  3136   Klass::collect_statistics(sz);
  3138   sz->_inst_size  = HeapWordSize * size_helper();
  3139   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  3140   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  3141   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  3142         ((is_interface() || is_anonymous()) ?
  3143          align_object_offset(nonstatic_oop_map_size()) :
  3144          nonstatic_oop_map_size());
  3146   int n = 0;
  3147   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  3148   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  3149   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  3150   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  3151   n += (sz->_fields_bytes                = sz->count_array(fields()));
  3152   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  3153   sz->_ro_bytes += n;
  3155   const ConstantPool* cp = constants();
  3156   if (cp) {
  3157     cp->collect_statistics(sz);
  3160   const Annotations* anno = annotations();
  3161   if (anno) {
  3162     anno->collect_statistics(sz);
  3165   const Array<Method*>* methods_array = methods();
  3166   if (methods()) {
  3167     for (int i = 0; i < methods_array->length(); i++) {
  3168       Method* method = methods_array->at(i);
  3169       if (method) {
  3170         sz->_method_count ++;
  3171         method->collect_statistics(sz);
  3176 #endif // INCLUDE_SERVICES
  3178 // Verification
  3180 class VerifyFieldClosure: public OopClosure {
  3181  protected:
  3182   template <class T> void do_oop_work(T* p) {
  3183     oop obj = oopDesc::load_decode_heap_oop(p);
  3184     if (!obj->is_oop_or_null()) {
  3185       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  3186       Universe::print();
  3187       guarantee(false, "boom");
  3190  public:
  3191   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  3192   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  3193 };
  3195 void InstanceKlass::verify_on(outputStream* st) {
  3196 #ifndef PRODUCT
  3197   // Avoid redundant verifies, this really should be in product.
  3198   if (_verify_count == Universe::verify_count()) return;
  3199   _verify_count = Universe::verify_count();
  3200 #endif
  3202   // Verify Klass
  3203   Klass::verify_on(st);
  3205   // Verify that klass is present in ClassLoaderData
  3206   guarantee(class_loader_data()->contains_klass(this),
  3207             "this class isn't found in class loader data");
  3209   // Verify vtables
  3210   if (is_linked()) {
  3211     ResourceMark rm;
  3212     // $$$ This used to be done only for m/s collections.  Doing it
  3213     // always seemed a valid generalization.  (DLD -- 6/00)
  3214     vtable()->verify(st);
  3217   // Verify first subklass
  3218   if (subklass_oop() != NULL) {
  3219     guarantee(subklass_oop()->is_klass(), "should be klass");
  3222   // Verify siblings
  3223   Klass* super = this->super();
  3224   Klass* sib = next_sibling();
  3225   if (sib != NULL) {
  3226     if (sib == this) {
  3227       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3230     guarantee(sib->is_klass(), "should be klass");
  3231     guarantee(sib->super() == super, "siblings should have same superklass");
  3234   // Verify implementor fields
  3235   Klass* im = implementor();
  3236   if (im != NULL) {
  3237     guarantee(is_interface(), "only interfaces should have implementor set");
  3238     guarantee(im->is_klass(), "should be klass");
  3239     guarantee(!im->is_interface() || im == this,
  3240       "implementors cannot be interfaces");
  3243   // Verify local interfaces
  3244   if (local_interfaces()) {
  3245     Array<Klass*>* local_interfaces = this->local_interfaces();
  3246     for (int j = 0; j < local_interfaces->length(); j++) {
  3247       Klass* e = local_interfaces->at(j);
  3248       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3252   // Verify transitive interfaces
  3253   if (transitive_interfaces() != NULL) {
  3254     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3255     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3256       Klass* e = transitive_interfaces->at(j);
  3257       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3261   // Verify methods
  3262   if (methods() != NULL) {
  3263     Array<Method*>* methods = this->methods();
  3264     for (int j = 0; j < methods->length(); j++) {
  3265       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3267     for (int j = 0; j < methods->length() - 1; j++) {
  3268       Method* m1 = methods->at(j);
  3269       Method* m2 = methods->at(j + 1);
  3270       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3274   // Verify method ordering
  3275   if (method_ordering() != NULL) {
  3276     Array<int>* method_ordering = this->method_ordering();
  3277     int length = method_ordering->length();
  3278     if (JvmtiExport::can_maintain_original_method_order() ||
  3279         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
  3280       guarantee(length == methods()->length(), "invalid method ordering length");
  3281       jlong sum = 0;
  3282       for (int j = 0; j < length; j++) {
  3283         int original_index = method_ordering->at(j);
  3284         guarantee(original_index >= 0, "invalid method ordering index");
  3285         guarantee(original_index < length, "invalid method ordering index");
  3286         sum += original_index;
  3288       // Verify sum of indices 0,1,...,length-1
  3289       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3290     } else {
  3291       guarantee(length == 0, "invalid method ordering length");
  3295   // Verify default methods
  3296   if (default_methods() != NULL) {
  3297     Array<Method*>* methods = this->default_methods();
  3298     for (int j = 0; j < methods->length(); j++) {
  3299       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3301     for (int j = 0; j < methods->length() - 1; j++) {
  3302       Method* m1 = methods->at(j);
  3303       Method* m2 = methods->at(j + 1);
  3304       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3308   // Verify JNI static field identifiers
  3309   if (jni_ids() != NULL) {
  3310     jni_ids()->verify(this);
  3313   // Verify other fields
  3314   if (array_klasses() != NULL) {
  3315     guarantee(array_klasses()->is_klass(), "should be klass");
  3317   if (constants() != NULL) {
  3318     guarantee(constants()->is_constantPool(), "should be constant pool");
  3320   const Klass* host = host_klass();
  3321   if (host != NULL) {
  3322     guarantee(host->is_klass(), "should be klass");
  3326 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3327   Klass::oop_verify_on(obj, st);
  3328   VerifyFieldClosure blk;
  3329   obj->oop_iterate_no_header(&blk);
  3333 // JNIid class for jfieldIDs only
  3334 // Note to reviewers:
  3335 // These JNI functions are just moved over to column 1 and not changed
  3336 // in the compressed oops workspace.
  3337 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3338   _holder = holder;
  3339   _offset = offset;
  3340   _next = next;
  3341   debug_only(_is_static_field_id = false;)
  3345 JNIid* JNIid::find(int offset) {
  3346   JNIid* current = this;
  3347   while (current != NULL) {
  3348     if (current->offset() == offset) return current;
  3349     current = current->next();
  3351   return NULL;
  3354 void JNIid::deallocate(JNIid* current) {
  3355   while (current != NULL) {
  3356     JNIid* next = current->next();
  3357     delete current;
  3358     current = next;
  3363 void JNIid::verify(Klass* holder) {
  3364   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3365   int end_field_offset;
  3366   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3368   JNIid* current = this;
  3369   while (current != NULL) {
  3370     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3371 #ifdef ASSERT
  3372     int o = current->offset();
  3373     if (current->is_static_field_id()) {
  3374       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3376 #endif
  3377     current = current->next();
  3382 #ifdef ASSERT
  3383 void InstanceKlass::set_init_state(ClassState state) {
  3384   bool good_state = is_shared() ? (_init_state <= state)
  3385                                                : (_init_state < state);
  3386   assert(good_state || state == allocated, "illegal state transition");
  3387   _init_state = (u1)state;
  3389 #endif
  3392 // RedefineClasses() support for previous versions:
  3394 // Purge previous versions
  3395 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3396   if (ik->previous_versions() != NULL) {
  3397     // This klass has previous versions so see what we can cleanup
  3398     // while it is safe to do so.
  3400     int deleted_count = 0;    // leave debugging breadcrumbs
  3401     int live_count = 0;
  3402     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3403                        ClassLoaderData::the_null_class_loader_data() :
  3404                        ik->class_loader_data();
  3406     // RC_TRACE macro has an embedded ResourceMark
  3407     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3408       ik->external_name(), ik->previous_versions()->length()));
  3410     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3411       // check the previous versions array
  3412       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3413       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3414       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3416       ConstantPool* pvcp = cp_ref;
  3417       if (!pvcp->on_stack()) {
  3418         // If the constant pool isn't on stack, none of the methods
  3419         // are executing.  Delete all the methods, the constant pool and
  3420         // and this previous version node.
  3421         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3422         if (method_refs != NULL) {
  3423           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3424             Method* method = method_refs->at(j);
  3425             assert(method != NULL, "method ref was unexpectedly cleared");
  3426             method_refs->remove_at(j);
  3427             // method will be freed with associated class.
  3430         // Remove the constant pool
  3431         delete pv_node;
  3432         // Since we are traversing the array backwards, we don't have to
  3433         // do anything special with the index.
  3434         ik->previous_versions()->remove_at(i);
  3435         deleted_count++;
  3436         continue;
  3437       } else {
  3438         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3439         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3440         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3441         live_count++;
  3444       // At least one method is live in this previous version, clean out
  3445       // the others or mark them as obsolete.
  3446       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3447       if (method_refs != NULL) {
  3448         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3449           method_refs->length()));
  3450         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3451           Method* method = method_refs->at(j);
  3452           assert(method != NULL, "method ref was unexpectedly cleared");
  3454           // Remove the emcp method if it's not executing
  3455           // If it's been made obsolete by a redefinition of a non-emcp
  3456           // method, mark it as obsolete but leave it to clean up later.
  3457           if (!method->on_stack()) {
  3458             method_refs->remove_at(j);
  3459           } else if (emcp_method_count == 0) {
  3460             method->set_is_obsolete();
  3461           } else {
  3462             // RC_TRACE macro has an embedded ResourceMark
  3463             RC_TRACE(0x00000200,
  3464               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3465               method->name()->as_C_string(),
  3466               method->signature()->as_C_string(), j, i));
  3471     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3472     RC_TRACE(0x00000200,
  3473       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3474       deleted_count));
  3478 // External interface for use during class unloading.
  3479 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3480   // Call with >0 emcp methods since they are not currently being redefined.
  3481   purge_previous_versions_internal(ik, 1);
  3485 // Potentially add an information node that contains pointers to the
  3486 // interesting parts of the previous version of the_class.
  3487 // This is also where we clean out any unused references.
  3488 // Note that while we delete nodes from the _previous_versions
  3489 // array, we never delete the array itself until the klass is
  3490 // unloaded. The has_been_redefined() query depends on that fact.
  3491 //
  3492 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3493        BitMap* emcp_methods, int emcp_method_count) {
  3494   assert(Thread::current()->is_VM_thread(),
  3495          "only VMThread can add previous versions");
  3497   if (_previous_versions == NULL) {
  3498     // This is the first previous version so make some space.
  3499     // Start with 2 elements under the assumption that the class
  3500     // won't be redefined much.
  3501     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3502                             GrowableArray<PreviousVersionNode *>(2, true);
  3505   ConstantPool* cp_ref = ikh->constants();
  3507   // RC_TRACE macro has an embedded ResourceMark
  3508   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3509                         "on_stack=%d",
  3510     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3511     cp_ref->on_stack()));
  3513   // If the constant pool for this previous version of the class
  3514   // is not marked as being on the stack, then none of the methods
  3515   // in this previous version of the class are on the stack so
  3516   // we don't need to create a new PreviousVersionNode. However,
  3517   // we still need to examine older previous versions below.
  3518   Array<Method*>* old_methods = ikh->methods();
  3520   if (cp_ref->on_stack()) {
  3521     PreviousVersionNode * pv_node = NULL;
  3522     if (emcp_method_count == 0) {
  3523       // non-shared ConstantPool gets a reference
  3524       pv_node = new PreviousVersionNode(cp_ref, NULL);
  3525       RC_TRACE(0x00000400,
  3526           ("add: all methods are obsolete; flushing any EMCP refs"));
  3527     } else {
  3528       int local_count = 0;
  3529       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3530           GrowableArray<Method*>(emcp_method_count, true);
  3531       for (int i = 0; i < old_methods->length(); i++) {
  3532         if (emcp_methods->at(i)) {
  3533             // this old method is EMCP. Save it only if it's on the stack
  3534             Method* old_method = old_methods->at(i);
  3535             if (old_method->on_stack()) {
  3536               method_refs->append(old_method);
  3538           if (++local_count >= emcp_method_count) {
  3539             // no more EMCP methods so bail out now
  3540             break;
  3544       // non-shared ConstantPool gets a reference
  3545       pv_node = new PreviousVersionNode(cp_ref, method_refs);
  3547     // append new previous version.
  3548     _previous_versions->append(pv_node);
  3551   // Since the caller is the VMThread and we are at a safepoint, this
  3552   // is a good time to clear out unused references.
  3554   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3555     _previous_versions->length()));
  3557   // Purge previous versions not executing on the stack
  3558   purge_previous_versions_internal(this, emcp_method_count);
  3560   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3562   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3563       _previous_versions->length() > 0) {
  3564     // We have a mix of obsolete and EMCP methods so we have to
  3565     // clear out any matching EMCP method entries the hard way.
  3566     int local_count = 0;
  3567     for (int i = 0; i < old_methods->length(); i++) {
  3568       if (!emcp_methods->at(i)) {
  3569         // only obsolete methods are interesting
  3570         Method* old_method = old_methods->at(i);
  3571         Symbol* m_name = old_method->name();
  3572         Symbol* m_signature = old_method->signature();
  3574         // we might not have added the last entry
  3575         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3576           // check the previous versions array for non executing obsolete methods
  3577           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3579           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3580           if (method_refs == NULL) {
  3581             // We have run into a PreviousVersion generation where
  3582             // all methods were made obsolete during that generation's
  3583             // RedefineClasses() operation. At the time of that
  3584             // operation, all EMCP methods were flushed so we don't
  3585             // have to go back any further.
  3586             //
  3587             // A NULL method_refs is different than an empty method_refs.
  3588             // We cannot infer any optimizations about older generations
  3589             // from an empty method_refs for the current generation.
  3590             break;
  3593           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3594             Method* method = method_refs->at(k);
  3596             if (!method->is_obsolete() &&
  3597                 method->name() == m_name &&
  3598                 method->signature() == m_signature) {
  3599               // The current RedefineClasses() call has made all EMCP
  3600               // versions of this method obsolete so mark it as obsolete
  3601               // and remove the reference.
  3602               RC_TRACE(0x00000400,
  3603                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3604                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3606               method->set_is_obsolete();
  3607               // Leave obsolete methods on the previous version list to
  3608               // clean up later.
  3609               break;
  3613           // The previous loop may not find a matching EMCP method, but
  3614           // that doesn't mean that we can optimize and not go any
  3615           // further back in the PreviousVersion generations. The EMCP
  3616           // method for this generation could have already been deleted,
  3617           // but there still may be an older EMCP method that has not
  3618           // been deleted.
  3621         if (++local_count >= obsolete_method_count) {
  3622           // no more obsolete methods so bail out now
  3623           break;
  3628 } // end add_previous_version()
  3631 // Determine if InstanceKlass has a previous version.
  3632 bool InstanceKlass::has_previous_version() const {
  3633   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3634 } // end has_previous_version()
  3637 Method* InstanceKlass::method_with_idnum(int idnum) {
  3638   Method* m = NULL;
  3639   if (idnum < methods()->length()) {
  3640     m = methods()->at(idnum);
  3642   if (m == NULL || m->method_idnum() != idnum) {
  3643     for (int index = 0; index < methods()->length(); ++index) {
  3644       m = methods()->at(index);
  3645       if (m->method_idnum() == idnum) {
  3646         return m;
  3649     // None found, return null for the caller to handle.
  3650     return NULL;
  3652   return m;
  3655 jint InstanceKlass::get_cached_class_file_len() {
  3656   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
  3659 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
  3660   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
  3664 // Construct a PreviousVersionNode entry for the array hung off
  3665 // the InstanceKlass.
  3666 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3667   GrowableArray<Method*>* prev_EMCP_methods) {
  3669   _prev_constant_pool = prev_constant_pool;
  3670   _prev_EMCP_methods = prev_EMCP_methods;
  3674 // Destroy a PreviousVersionNode
  3675 PreviousVersionNode::~PreviousVersionNode() {
  3676   if (_prev_constant_pool != NULL) {
  3677     _prev_constant_pool = NULL;
  3680   if (_prev_EMCP_methods != NULL) {
  3681     delete _prev_EMCP_methods;
  3685 // Construct a helper for walking the previous versions array
  3686 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
  3687   _thread = thread;
  3688   _previous_versions = ik->previous_versions();
  3689   _current_index = 0;
  3690   _current_p = NULL;
  3691   _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
  3695 // Return the interesting information for the next previous version
  3696 // of the klass. Returns NULL if there are no more previous versions.
  3697 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
  3698   if (_previous_versions == NULL) {
  3699     // no previous versions so nothing to return
  3700     return NULL;
  3703   _current_p = NULL;  // reset to NULL
  3704   _current_constant_pool_handle = NULL;
  3706   int length = _previous_versions->length();
  3708   while (_current_index < length) {
  3709     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3711     // Save a handle to the constant pool for this previous version,
  3712     // which keeps all the methods from being deallocated.
  3713     _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
  3714     _current_p = pv_node;
  3715     return pv_node;
  3718   return NULL;
  3719 } // end next_previous_version()

mercurial