src/share/vm/oops/instanceKlass.cpp

Fri, 08 Mar 2013 17:49:52 -0800

author
dcubed
date
Fri, 08 Mar 2013 17:49:52 -0800
changeset 4714
35ef86296a5d
parent 4712
3efdfd6ddbf2
parent 4693
872b3feace55
child 4719
c8b31b461e1a
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 1997, 2013, 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/methodComparator.hpp"
    52 #include "runtime/fieldDescriptor.hpp"
    53 #include "runtime/handles.inline.hpp"
    54 #include "runtime/javaCalls.hpp"
    55 #include "runtime/mutexLocker.hpp"
    56 #include "runtime/thread.inline.hpp"
    57 #include "services/threadService.hpp"
    58 #include "utilities/dtrace.hpp"
    59 #include "utilities/macros.hpp"
    60 #if INCLUDE_ALL_GCS
    61 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    62 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    63 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    64 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    65 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
    66 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    67 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    68 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    69 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    70 #include "oops/oop.pcgc.inline.hpp"
    71 #endif // INCLUDE_ALL_GCS
    72 #ifdef COMPILER1
    73 #include "c1/c1_Compiler.hpp"
    74 #endif
    76 #ifdef DTRACE_ENABLED
    78 #ifndef USDT2
    80 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    81   char*, intptr_t, oop, intptr_t);
    82 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    83   char*, intptr_t, oop, intptr_t, int);
    84 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    85   char*, intptr_t, oop, intptr_t, int);
    86 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    87   char*, intptr_t, oop, intptr_t, int);
    88 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    89   char*, intptr_t, oop, intptr_t, int);
    90 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    91   char*, intptr_t, oop, intptr_t, int);
    92 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
    93   char*, intptr_t, oop, intptr_t, int);
    94 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
    95   char*, intptr_t, oop, intptr_t, int);
    97 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
    98   {                                                              \
    99     char* data = NULL;                                           \
   100     int len = 0;                                                 \
   101     Symbol* name = (clss)->name();                               \
   102     if (name != NULL) {                                          \
   103       data = (char*)name->bytes();                               \
   104       len = name->utf8_length();                                 \
   105     }                                                            \
   106     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   107       data, len, (clss)->class_loader(), thread_type);           \
   108   }
   110 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   111   {                                                              \
   112     char* data = NULL;                                           \
   113     int len = 0;                                                 \
   114     Symbol* name = (clss)->name();                               \
   115     if (name != NULL) {                                          \
   116       data = (char*)name->bytes();                               \
   117       len = name->utf8_length();                                 \
   118     }                                                            \
   119     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   120       data, len, (clss)->class_loader(), thread_type, wait);     \
   121   }
   122 #else /* USDT2 */
   124 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   125 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   126 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   127 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   128 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   129 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   130 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   131 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   132 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   133   {                                                              \
   134     char* data = NULL;                                           \
   135     int len = 0;                                                 \
   136     Symbol* name = (clss)->name();                               \
   137     if (name != NULL) {                                          \
   138       data = (char*)name->bytes();                               \
   139       len = name->utf8_length();                                 \
   140     }                                                            \
   141     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   142       data, len, (clss)->class_loader(), thread_type);           \
   143   }
   145 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   146   {                                                              \
   147     char* data = NULL;                                           \
   148     int len = 0;                                                 \
   149     Symbol* name = (clss)->name();                               \
   150     if (name != NULL) {                                          \
   151       data = (char*)name->bytes();                               \
   152       len = name->utf8_length();                                 \
   153     }                                                            \
   154     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   155       data, len, (clss)->class_loader(), thread_type, wait);     \
   156   }
   157 #endif /* USDT2 */
   159 #else //  ndef DTRACE_ENABLED
   161 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   162 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   164 #endif //  ndef DTRACE_ENABLED
   166 volatile int InstanceKlass::_total_instanceKlass_count = 0;
   168 Klass* InstanceKlass::allocate_instance_klass(ClassLoaderData* loader_data,
   169                                               int vtable_len,
   170                                               int itable_len,
   171                                               int static_field_size,
   172                                               int nonstatic_oop_map_size,
   173                                               ReferenceType rt,
   174                                               AccessFlags access_flags,
   175                                               Symbol* name,
   176                                               Klass* super_klass,
   177                                               bool is_anonymous,
   178                                               TRAPS) {
   180   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   181                                  access_flags.is_interface(), is_anonymous);
   183   // Allocation
   184   InstanceKlass* ik;
   185   if (rt == REF_NONE) {
   186     if (name == vmSymbols::java_lang_Class()) {
   187       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   188         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   189         access_flags, is_anonymous);
   190     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   191           (SystemDictionary::ClassLoader_klass_loaded() &&
   192           super_klass != NULL &&
   193           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   194       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   195         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   196         access_flags, is_anonymous);
   197     } else {
   198       // normal class
   199       ik = new (loader_data, size, THREAD) InstanceKlass(
   200         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   201         access_flags, is_anonymous);
   202     }
   203   } else {
   204     // reference klass
   205     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   206         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   207         access_flags, is_anonymous);
   208   }
   210   Atomic::inc(&_total_instanceKlass_count);
   211   return ik;
   212 }
   214 InstanceKlass::InstanceKlass(int vtable_len,
   215                              int itable_len,
   216                              int static_field_size,
   217                              int nonstatic_oop_map_size,
   218                              ReferenceType rt,
   219                              AccessFlags access_flags,
   220                              bool is_anonymous) {
   221   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   223   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   224                                    access_flags.is_interface(), is_anonymous);
   226   // The sizes of these these three variables are used for determining the
   227   // size of the instanceKlassOop. It is critical that these are set to the right
   228   // sizes before the first GC, i.e., when we allocate the mirror.
   229   set_vtable_length(vtable_len);
   230   set_itable_length(itable_len);
   231   set_static_field_size(static_field_size);
   232   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   233   set_access_flags(access_flags);
   234   _misc_flags = 0;  // initialize to zero
   235   set_is_anonymous(is_anonymous);
   236   assert(size() == iksize, "wrong size for object");
   238   set_array_klasses(NULL);
   239   set_methods(NULL);
   240   set_method_ordering(NULL);
   241   set_local_interfaces(NULL);
   242   set_transitive_interfaces(NULL);
   243   init_implementor();
   244   set_fields(NULL, 0);
   245   set_constants(NULL);
   246   set_class_loader_data(NULL);
   247   set_protection_domain(NULL);
   248   set_signers(NULL);
   249   set_source_file_name(NULL);
   250   set_source_debug_extension(NULL, 0);
   251   set_array_name(NULL);
   252   set_inner_classes(NULL);
   253   set_static_oop_field_count(0);
   254   set_nonstatic_field_size(0);
   255   set_is_marked_dependent(false);
   256   set_init_state(InstanceKlass::allocated);
   257   set_init_thread(NULL);
   258   set_init_lock(NULL);
   259   set_reference_type(rt);
   260   set_oop_map_cache(NULL);
   261   set_jni_ids(NULL);
   262   set_osr_nmethods_head(NULL);
   263   set_breakpoints(NULL);
   264   init_previous_versions();
   265   set_generic_signature(NULL);
   266   release_set_methods_jmethod_ids(NULL);
   267   release_set_methods_cached_itable_indices(NULL);
   268   set_annotations(NULL);
   269   set_jvmti_cached_class_field_map(NULL);
   270   set_initial_method_idnum(0);
   271   _dependencies = NULL;
   272   set_jvmti_cached_class_field_map(NULL);
   273   set_cached_class_file(NULL, 0);
   274   set_initial_method_idnum(0);
   275   set_minor_version(0);
   276   set_major_version(0);
   277   NOT_PRODUCT(_verify_count = 0;)
   279   // initialize the non-header words to zero
   280   intptr_t* p = (intptr_t*)this;
   281   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
   282     p[index] = NULL_WORD;
   283   }
   285   // Set temporary value until parseClassFile updates it with the real instance
   286   // size.
   287   set_layout_helper(Klass::instance_layout_helper(0, true));
   288 }
   291 // This function deallocates the metadata and C heap pointers that the
   292 // InstanceKlass points to.
   293 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   295   // Orphan the mirror first, CMS thinks it's still live.
   296   java_lang_Class::set_klass(java_mirror(), NULL);
   298   // Need to take this class off the class loader data list.
   299   loader_data->remove_class(this);
   301   // The array_klass for this class is created later, after error handling.
   302   // For class redefinition, we keep the original class so this scratch class
   303   // doesn't have an array class.  Either way, assert that there is nothing
   304   // to deallocate.
   305   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   307   // Release C heap allocated data that this might point to, which includes
   308   // reference counting symbol names.
   309   release_C_heap_structures();
   311   Array<Method*>* ms = methods();
   312   if (ms != Universe::the_empty_method_array()) {
   313     for (int i = 0; i <= methods()->length() -1 ; i++) {
   314       Method* method = methods()->at(i);
   315       // Only want to delete methods that are not executing for RedefineClasses.
   316       // The previous version will point to them so they're not totally dangling
   317       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   318       MetadataFactory::free_metadata(loader_data, method);
   319     }
   320     MetadataFactory::free_array<Method*>(loader_data, methods());
   321   }
   322   set_methods(NULL);
   324   if (method_ordering() != Universe::the_empty_int_array()) {
   325     MetadataFactory::free_array<int>(loader_data, method_ordering());
   326   }
   327   set_method_ordering(NULL);
   329   // This array is in Klass, but remove it with the InstanceKlass since
   330   // this place would be the only caller and it can share memory with transitive
   331   // interfaces.
   332   if (secondary_supers() != Universe::the_empty_klass_array() &&
   333       secondary_supers() != transitive_interfaces()) {
   334     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   335   }
   336   set_secondary_supers(NULL);
   338   // Only deallocate transitive interfaces if not empty, same as super class
   339   // or same as local interfaces.   See code in parseClassFile.
   340   Array<Klass*>* ti = transitive_interfaces();
   341   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces()) {
   342     // check that the interfaces don't come from super class
   343     Array<Klass*>* sti = (super() == NULL) ? NULL :
   344        InstanceKlass::cast(super())->transitive_interfaces();
   345     if (ti != sti) {
   346       MetadataFactory::free_array<Klass*>(loader_data, ti);
   347     }
   348   }
   349   set_transitive_interfaces(NULL);
   351   // local interfaces can be empty
   352   Array<Klass*>* li = local_interfaces();
   353   if (li != Universe::the_empty_klass_array()) {
   354     MetadataFactory::free_array<Klass*>(loader_data, li);
   355   }
   356   set_local_interfaces(NULL);
   358   MetadataFactory::free_array<jushort>(loader_data, fields());
   359   set_fields(NULL, 0);
   361   // If a method from a redefined class is using this constant pool, don't
   362   // delete it, yet.  The new class's previous version will point to this.
   363   assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   364   MetadataFactory::free_metadata(loader_data, constants());
   365   set_constants(NULL);
   367   if (inner_classes() != Universe::the_empty_short_array()) {
   368     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   369   }
   370   set_inner_classes(NULL);
   372   // Null out Java heap objects, although these won't be walked to keep
   373   // alive once this InstanceKlass is deallocated.
   374   set_protection_domain(NULL);
   375   set_signers(NULL);
   376   set_init_lock(NULL);
   378   // We should deallocate the Annotations instance
   379   MetadataFactory::free_metadata(loader_data, annotations());
   380   set_annotations(NULL);
   381 }
   383 volatile oop InstanceKlass::init_lock() const {
   384   volatile oop lock = _init_lock;  // read once
   385   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   386          "only fully initialized state can have a null lock");
   387   return lock;
   388 }
   390 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   391 // threads to get this lock will see a null lock and will not lock.
   392 // That's okay because they all check for initialized state after getting
   393 // the lock and return.
   394 void InstanceKlass::fence_and_clear_init_lock() {
   395   // make sure previous stores are all done, notably the init_state.
   396   OrderAccess::storestore();
   397   klass_oop_store(&_init_lock, NULL);
   398   assert(!is_not_initialized(), "class must be initialized now");
   399 }
   402 bool InstanceKlass::should_be_initialized() const {
   403   return !is_initialized();
   404 }
   406 klassVtable* InstanceKlass::vtable() const {
   407   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   408 }
   410 klassItable* InstanceKlass::itable() const {
   411   return new klassItable(instanceKlassHandle(this));
   412 }
   414 void InstanceKlass::eager_initialize(Thread *thread) {
   415   if (!EagerInitialization) return;
   417   if (this->is_not_initialized()) {
   418     // abort if the the class has a class initializer
   419     if (this->class_initializer() != NULL) return;
   421     // abort if it is java.lang.Object (initialization is handled in genesis)
   422     Klass* super = this->super();
   423     if (super == NULL) return;
   425     // abort if the super class should be initialized
   426     if (!InstanceKlass::cast(super)->is_initialized()) return;
   428     // call body to expose the this pointer
   429     instanceKlassHandle this_oop(thread, this);
   430     eager_initialize_impl(this_oop);
   431   }
   432 }
   435 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   436   EXCEPTION_MARK;
   437   volatile oop init_lock = this_oop->init_lock();
   438   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   440   // abort if someone beat us to the initialization
   441   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   443   ClassState old_state = this_oop->init_state();
   444   link_class_impl(this_oop, true, THREAD);
   445   if (HAS_PENDING_EXCEPTION) {
   446     CLEAR_PENDING_EXCEPTION;
   447     // Abort if linking the class throws an exception.
   449     // Use a test to avoid redundantly resetting the state if there's
   450     // no change.  Set_init_state() asserts that state changes make
   451     // progress, whereas here we might just be spinning in place.
   452     if( old_state != this_oop->_init_state )
   453       this_oop->set_init_state (old_state);
   454   } else {
   455     // linking successfull, mark class as initialized
   456     this_oop->set_init_state (fully_initialized);
   457     this_oop->fence_and_clear_init_lock();
   458     // trace
   459     if (TraceClassInitialization) {
   460       ResourceMark rm(THREAD);
   461       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   462     }
   463   }
   464 }
   467 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   468 // process. The step comments refers to the procedure described in that section.
   469 // Note: implementation moved to static method to expose the this pointer.
   470 void InstanceKlass::initialize(TRAPS) {
   471   if (this->should_be_initialized()) {
   472     HandleMark hm(THREAD);
   473     instanceKlassHandle this_oop(THREAD, this);
   474     initialize_impl(this_oop, CHECK);
   475     // Note: at this point the class may be initialized
   476     //       OR it may be in the state of being initialized
   477     //       in case of recursive initialization!
   478   } else {
   479     assert(is_initialized(), "sanity check");
   480   }
   481 }
   484 bool InstanceKlass::verify_code(
   485     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   486   // 1) Verify the bytecodes
   487   Verifier::Mode mode =
   488     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   489   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   490 }
   493 // Used exclusively by the shared spaces dump mechanism to prevent
   494 // classes mapped into the shared regions in new VMs from appearing linked.
   496 void InstanceKlass::unlink_class() {
   497   assert(is_linked(), "must be linked");
   498   _init_state = loaded;
   499 }
   501 void InstanceKlass::link_class(TRAPS) {
   502   assert(is_loaded(), "must be loaded");
   503   if (!is_linked()) {
   504     HandleMark hm(THREAD);
   505     instanceKlassHandle this_oop(THREAD, this);
   506     link_class_impl(this_oop, true, CHECK);
   507   }
   508 }
   510 // Called to verify that a class can link during initialization, without
   511 // throwing a VerifyError.
   512 bool InstanceKlass::link_class_or_fail(TRAPS) {
   513   assert(is_loaded(), "must be loaded");
   514   if (!is_linked()) {
   515     HandleMark hm(THREAD);
   516     instanceKlassHandle this_oop(THREAD, this);
   517     link_class_impl(this_oop, false, CHECK_false);
   518   }
   519   return is_linked();
   520 }
   522 bool InstanceKlass::link_class_impl(
   523     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   524   // check for error state
   525   if (this_oop->is_in_error_state()) {
   526     ResourceMark rm(THREAD);
   527     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   528                this_oop->external_name(), false);
   529   }
   530   // return if already verified
   531   if (this_oop->is_linked()) {
   532     return true;
   533   }
   535   // Timing
   536   // timer handles recursion
   537   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   538   JavaThread* jt = (JavaThread*)THREAD;
   540   // link super class before linking this class
   541   instanceKlassHandle super(THREAD, this_oop->super());
   542   if (super.not_null()) {
   543     if (super->is_interface()) {  // check if super class is an interface
   544       ResourceMark rm(THREAD);
   545       Exceptions::fthrow(
   546         THREAD_AND_LOCATION,
   547         vmSymbols::java_lang_IncompatibleClassChangeError(),
   548         "class %s has interface %s as super class",
   549         this_oop->external_name(),
   550         super->external_name()
   551       );
   552       return false;
   553     }
   555     link_class_impl(super, throw_verifyerror, CHECK_false);
   556   }
   558   // link all interfaces implemented by this class before linking this class
   559   Array<Klass*>* interfaces = this_oop->local_interfaces();
   560   int num_interfaces = interfaces->length();
   561   for (int index = 0; index < num_interfaces; index++) {
   562     HandleMark hm(THREAD);
   563     instanceKlassHandle ih(THREAD, interfaces->at(index));
   564     link_class_impl(ih, throw_verifyerror, CHECK_false);
   565   }
   567   // in case the class is linked in the process of linking its superclasses
   568   if (this_oop->is_linked()) {
   569     return true;
   570   }
   572   // trace only the link time for this klass that includes
   573   // the verification time
   574   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   575                              ClassLoader::perf_class_link_selftime(),
   576                              ClassLoader::perf_classes_linked(),
   577                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   578                              jt->get_thread_stat()->perf_timers_addr(),
   579                              PerfClassTraceTime::CLASS_LINK);
   581   // verification & rewriting
   582   {
   583     volatile oop init_lock = this_oop->init_lock();
   584     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   585     // rewritten will have been set if loader constraint error found
   586     // on an earlier link attempt
   587     // don't verify or rewrite if already rewritten
   589     if (!this_oop->is_linked()) {
   590       if (!this_oop->is_rewritten()) {
   591         {
   592           // Timer includes any side effects of class verification (resolution,
   593           // etc), but not recursive entry into verify_code().
   594           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   595                                    ClassLoader::perf_class_verify_selftime(),
   596                                    ClassLoader::perf_classes_verified(),
   597                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   598                                    jt->get_thread_stat()->perf_timers_addr(),
   599                                    PerfClassTraceTime::CLASS_VERIFY);
   600           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   601           if (!verify_ok) {
   602             return false;
   603           }
   604         }
   606         // Just in case a side-effect of verify linked this class already
   607         // (which can sometimes happen since the verifier loads classes
   608         // using custom class loaders, which are free to initialize things)
   609         if (this_oop->is_linked()) {
   610           return true;
   611         }
   613         // also sets rewritten
   614         this_oop->rewrite_class(CHECK_false);
   615       }
   617       // relocate jsrs and link methods after they are all rewritten
   618       this_oop->link_methods(CHECK_false);
   620       // Initialize the vtable and interface table after
   621       // methods have been rewritten since rewrite may
   622       // fabricate new Method*s.
   623       // also does loader constraint checking
   624       if (!this_oop()->is_shared()) {
   625         ResourceMark rm(THREAD);
   626         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   627         this_oop->itable()->initialize_itable(true, CHECK_false);
   628       }
   629 #ifdef ASSERT
   630       else {
   631         ResourceMark rm(THREAD);
   632         this_oop->vtable()->verify(tty, true);
   633         // In case itable verification is ever added.
   634         // this_oop->itable()->verify(tty, true);
   635       }
   636 #endif
   637       this_oop->set_init_state(linked);
   638       if (JvmtiExport::should_post_class_prepare()) {
   639         Thread *thread = THREAD;
   640         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   641         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   642       }
   643     }
   644   }
   645   return true;
   646 }
   649 // Rewrite the byte codes of all of the methods of a class.
   650 // The rewriter must be called exactly once. Rewriting must happen after
   651 // verification but before the first method of the class is executed.
   652 void InstanceKlass::rewrite_class(TRAPS) {
   653   assert(is_loaded(), "must be loaded");
   654   instanceKlassHandle this_oop(THREAD, this);
   655   if (this_oop->is_rewritten()) {
   656     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   657     return;
   658   }
   659   Rewriter::rewrite(this_oop, CHECK);
   660   this_oop->set_rewritten();
   661 }
   663 // Now relocate and link method entry points after class is rewritten.
   664 // This is outside is_rewritten flag. In case of an exception, it can be
   665 // executed more than once.
   666 void InstanceKlass::link_methods(TRAPS) {
   667   int len = methods()->length();
   668   for (int i = len-1; i >= 0; i--) {
   669     methodHandle m(THREAD, methods()->at(i));
   671     // Set up method entry points for compiler and interpreter    .
   672     m->link_method(m, CHECK);
   674     // This is for JVMTI and unrelated to relocator but the last thing we do
   675 #ifdef ASSERT
   676     if (StressMethodComparator) {
   677       ResourceMark rm(THREAD);
   678       static int nmc = 0;
   679       for (int j = i; j >= 0 && j >= i-4; j--) {
   680         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   681         bool z = MethodComparator::methods_EMCP(m(),
   682                    methods()->at(j));
   683         if (j == i && !z) {
   684           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   685           assert(z, "method must compare equal to itself");
   686         }
   687       }
   688     }
   689 #endif //ASSERT
   690   }
   691 }
   694 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   695   // Make sure klass is linked (verified) before initialization
   696   // A class could already be verified, since it has been reflected upon.
   697   this_oop->link_class(CHECK);
   699   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   701   bool wait = false;
   703   // refer to the JVM book page 47 for description of steps
   704   // Step 1
   705   {
   706     volatile oop init_lock = this_oop->init_lock();
   707     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   709     Thread *self = THREAD; // it's passed the current thread
   711     // Step 2
   712     // If we were to use wait() instead of waitInterruptibly() then
   713     // we might end up throwing IE from link/symbol resolution sites
   714     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   715     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   716         wait = true;
   717       ol.waitUninterruptibly(CHECK);
   718     }
   720     // Step 3
   721     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   722       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   723       return;
   724     }
   726     // Step 4
   727     if (this_oop->is_initialized()) {
   728       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   729       return;
   730     }
   732     // Step 5
   733     if (this_oop->is_in_error_state()) {
   734       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   735       ResourceMark rm(THREAD);
   736       const char* desc = "Could not initialize class ";
   737       const char* className = this_oop->external_name();
   738       size_t msglen = strlen(desc) + strlen(className) + 1;
   739       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   740       if (NULL == message) {
   741         // Out of memory: can't create detailed error message
   742         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   743       } else {
   744         jio_snprintf(message, msglen, "%s%s", desc, className);
   745         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   746       }
   747     }
   749     // Step 6
   750     this_oop->set_init_state(being_initialized);
   751     this_oop->set_init_thread(self);
   752   }
   754   // Step 7
   755   Klass* super_klass = this_oop->super();
   756   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   757     super_klass->initialize(THREAD);
   759     if (HAS_PENDING_EXCEPTION) {
   760       Handle e(THREAD, PENDING_EXCEPTION);
   761       CLEAR_PENDING_EXCEPTION;
   762       {
   763         EXCEPTION_MARK;
   764         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   765         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   766       }
   767       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   768       THROW_OOP(e());
   769     }
   770   }
   772   if (this_oop->has_default_methods()) {
   773     // Step 7.5: initialize any interfaces which have default methods
   774     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   775       Klass* iface = this_oop->local_interfaces()->at(i);
   776       InstanceKlass* ik = InstanceKlass::cast(iface);
   777       if (ik->has_default_methods() && ik->should_be_initialized()) {
   778         ik->initialize(THREAD);
   780         if (HAS_PENDING_EXCEPTION) {
   781           Handle e(THREAD, PENDING_EXCEPTION);
   782           CLEAR_PENDING_EXCEPTION;
   783           {
   784             EXCEPTION_MARK;
   785             // Locks object, set state, and notify all waiting threads
   786             this_oop->set_initialization_state_and_notify(
   787                 initialization_error, THREAD);
   789             // ignore any exception thrown, superclass initialization error is
   790             // thrown below
   791             CLEAR_PENDING_EXCEPTION;
   792           }
   793           DTRACE_CLASSINIT_PROBE_WAIT(
   794               super__failed, InstanceKlass::cast(this_oop()), -1, wait);
   795           THROW_OOP(e());
   796         }
   797       }
   798     }
   799   }
   801   // Step 8
   802   {
   803     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   804     JavaThread* jt = (JavaThread*)THREAD;
   805     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   806     // Timer includes any side effects of class initialization (resolution,
   807     // etc), but not recursive entry into call_class_initializer().
   808     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   809                              ClassLoader::perf_class_init_selftime(),
   810                              ClassLoader::perf_classes_inited(),
   811                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   812                              jt->get_thread_stat()->perf_timers_addr(),
   813                              PerfClassTraceTime::CLASS_CLINIT);
   814     this_oop->call_class_initializer(THREAD);
   815   }
   817   // Step 9
   818   if (!HAS_PENDING_EXCEPTION) {
   819     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   820     { ResourceMark rm(THREAD);
   821       debug_only(this_oop->vtable()->verify(tty, true);)
   822     }
   823   }
   824   else {
   825     // Step 10 and 11
   826     Handle e(THREAD, PENDING_EXCEPTION);
   827     CLEAR_PENDING_EXCEPTION;
   828     {
   829       EXCEPTION_MARK;
   830       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   831       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   832     }
   833     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   834     if (e->is_a(SystemDictionary::Error_klass())) {
   835       THROW_OOP(e());
   836     } else {
   837       JavaCallArguments args(e);
   838       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   839                 vmSymbols::throwable_void_signature(),
   840                 &args);
   841     }
   842   }
   843   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   844 }
   847 // Note: implementation moved to static method to expose the this pointer.
   848 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   849   instanceKlassHandle kh(THREAD, this);
   850   set_initialization_state_and_notify_impl(kh, state, CHECK);
   851 }
   853 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   854   volatile oop init_lock = this_oop->init_lock();
   855   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   856   this_oop->set_init_state(state);
   857   this_oop->fence_and_clear_init_lock();
   858   ol.notify_all(CHECK);
   859 }
   861 // The embedded _implementor field can only record one implementor.
   862 // When there are more than one implementors, the _implementor field
   863 // is set to the interface Klass* itself. Following are the possible
   864 // values for the _implementor field:
   865 //   NULL                  - no implementor
   866 //   implementor Klass*    - one implementor
   867 //   self                  - more than one implementor
   868 //
   869 // The _implementor field only exists for interfaces.
   870 void InstanceKlass::add_implementor(Klass* k) {
   871   assert(Compile_lock->owned_by_self(), "");
   872   assert(is_interface(), "not interface");
   873   // Filter out my subinterfaces.
   874   // (Note: Interfaces are never on the subklass list.)
   875   if (InstanceKlass::cast(k)->is_interface()) return;
   877   // Filter out subclasses whose supers already implement me.
   878   // (Note: CHA must walk subclasses of direct implementors
   879   // in order to locate indirect implementors.)
   880   Klass* sk = InstanceKlass::cast(k)->super();
   881   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   882     // We only need to check one immediate superclass, since the
   883     // implements_interface query looks at transitive_interfaces.
   884     // Any supers of the super have the same (or fewer) transitive_interfaces.
   885     return;
   887   Klass* ik = implementor();
   888   if (ik == NULL) {
   889     set_implementor(k);
   890   } else if (ik != this) {
   891     // There is already an implementor. Use itself as an indicator of
   892     // more than one implementors.
   893     set_implementor(this);
   894   }
   896   // The implementor also implements the transitive_interfaces
   897   for (int index = 0; index < local_interfaces()->length(); index++) {
   898     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
   899   }
   900 }
   902 void InstanceKlass::init_implementor() {
   903   if (is_interface()) {
   904     set_implementor(NULL);
   905   }
   906 }
   909 void InstanceKlass::process_interfaces(Thread *thread) {
   910   // link this class into the implementors list of every interface it implements
   911   Klass* this_as_klass_oop = this;
   912   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
   913     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
   914     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
   915     assert(interf->is_interface(), "expected interface");
   916     interf->add_implementor(this_as_klass_oop);
   917   }
   918 }
   920 bool InstanceKlass::can_be_primary_super_slow() const {
   921   if (is_interface())
   922     return false;
   923   else
   924     return Klass::can_be_primary_super_slow();
   925 }
   927 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
   928   // The secondaries are the implemented interfaces.
   929   InstanceKlass* ik = InstanceKlass::cast(this);
   930   Array<Klass*>* interfaces = ik->transitive_interfaces();
   931   int num_secondaries = num_extra_slots + interfaces->length();
   932   if (num_secondaries == 0) {
   933     // Must share this for correct bootstrapping!
   934     set_secondary_supers(Universe::the_empty_klass_array());
   935     return NULL;
   936   } else if (num_extra_slots == 0) {
   937     // The secondary super list is exactly the same as the transitive interfaces.
   938     // Redefine classes has to be careful not to delete this!
   939     set_secondary_supers(interfaces);
   940     return NULL;
   941   } else {
   942     // Copy transitive interfaces to a temporary growable array to be constructed
   943     // into the secondary super list with extra slots.
   944     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
   945     for (int i = 0; i < interfaces->length(); i++) {
   946       secondaries->push(interfaces->at(i));
   947     }
   948     return secondaries;
   949   }
   950 }
   952 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
   953   if (k->is_interface()) {
   954     return implements_interface(k);
   955   } else {
   956     return Klass::compute_is_subtype_of(k);
   957   }
   958 }
   960 bool InstanceKlass::implements_interface(Klass* k) const {
   961   if (this == k) return true;
   962   assert(k->is_interface(), "should be an interface class");
   963   for (int i = 0; i < transitive_interfaces()->length(); i++) {
   964     if (transitive_interfaces()->at(i) == k) {
   965       return true;
   966     }
   967   }
   968   return false;
   969 }
   971 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
   972   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
   973   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
   974     report_java_out_of_memory("Requested array size exceeds VM limit");
   975     JvmtiExport::post_array_size_exhausted();
   976     THROW_OOP_0(Universe::out_of_memory_error_array_size());
   977   }
   978   int size = objArrayOopDesc::object_size(length);
   979   Klass* ak = array_klass(n, CHECK_NULL);
   980   KlassHandle h_ak (THREAD, ak);
   981   objArrayOop o =
   982     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
   983   return o;
   984 }
   986 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
   987   if (TraceFinalizerRegistration) {
   988     tty->print("Registered ");
   989     i->print_value_on(tty);
   990     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
   991   }
   992   instanceHandle h_i(THREAD, i);
   993   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
   994   JavaValue result(T_VOID);
   995   JavaCallArguments args(h_i);
   996   methodHandle mh (THREAD, Universe::finalizer_register_method());
   997   JavaCalls::call(&result, mh, &args, CHECK_NULL);
   998   return h_i();
   999 }
  1001 instanceOop InstanceKlass::allocate_instance(TRAPS) {
  1002   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  1003   int size = size_helper();  // Query before forming handle.
  1005   KlassHandle h_k(THREAD, this);
  1007   instanceOop i;
  1009   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1010   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1011     i = register_finalizer(i, CHECK_NULL);
  1013   return i;
  1016 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1017   if (is_interface() || is_abstract()) {
  1018     ResourceMark rm(THREAD);
  1019     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1020               : vmSymbols::java_lang_InstantiationException(), external_name());
  1022   if (this == SystemDictionary::Class_klass()) {
  1023     ResourceMark rm(THREAD);
  1024     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1025               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1029 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1030   instanceKlassHandle this_oop(THREAD, this);
  1031   return array_klass_impl(this_oop, or_null, n, THREAD);
  1034 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1035   if (this_oop->array_klasses() == NULL) {
  1036     if (or_null) return NULL;
  1038     ResourceMark rm;
  1039     JavaThread *jt = (JavaThread *)THREAD;
  1041       // Atomic creation of array_klasses
  1042       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1043       MutexLocker ma(MultiArray_lock, THREAD);
  1045       // Check if update has already taken place
  1046       if (this_oop->array_klasses() == NULL) {
  1047         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1048         this_oop->set_array_klasses(k);
  1052   // _this will always be set at this point
  1053   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1054   if (or_null) {
  1055     return oak->array_klass_or_null(n);
  1057   return oak->array_klass(n, CHECK_NULL);
  1060 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1061   return array_klass_impl(or_null, 1, THREAD);
  1064 void InstanceKlass::call_class_initializer(TRAPS) {
  1065   instanceKlassHandle ik (THREAD, this);
  1066   call_class_initializer_impl(ik, THREAD);
  1069 static int call_class_initializer_impl_counter = 0;   // for debugging
  1071 Method* InstanceKlass::class_initializer() {
  1072   Method* clinit = find_method(
  1073       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1074   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1075     return clinit;
  1077   return NULL;
  1080 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1081   if (ReplayCompiles &&
  1082       (ReplaySuppressInitializers == 1 ||
  1083        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1084     // Hide the existence of the initializer for the purpose of replaying the compile
  1085     return;
  1088   methodHandle h_method(THREAD, this_oop->class_initializer());
  1089   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1090   if (TraceClassInitialization) {
  1091     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1092     this_oop->name()->print_value();
  1093     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1095   if (h_method() != NULL) {
  1096     JavaCallArguments args; // No arguments
  1097     JavaValue result(T_VOID);
  1098     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1103 void InstanceKlass::mask_for(methodHandle method, int bci,
  1104   InterpreterOopMap* entry_for) {
  1105   // Dirty read, then double-check under a lock.
  1106   if (_oop_map_cache == NULL) {
  1107     // Otherwise, allocate a new one.
  1108     MutexLocker x(OopMapCacheAlloc_lock);
  1109     // First time use. Allocate a cache in C heap
  1110     if (_oop_map_cache == NULL) {
  1111       _oop_map_cache = new OopMapCache();
  1114   // _oop_map_cache is constant after init; lookup below does is own locking.
  1115   _oop_map_cache->lookup(method, bci, entry_for);
  1119 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1120   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1121     Symbol* f_name = fs.name();
  1122     Symbol* f_sig  = fs.signature();
  1123     if (f_name == name && f_sig == sig) {
  1124       fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
  1125       return true;
  1128   return false;
  1132 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1133   const int n = local_interfaces()->length();
  1134   for (int i = 0; i < n; i++) {
  1135     Klass* intf1 = local_interfaces()->at(i);
  1136     assert(intf1->is_interface(), "just checking type");
  1137     // search for field in current interface
  1138     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1139       assert(fd->is_static(), "interface field must be static");
  1140       return intf1;
  1142     // search for field in direct superinterfaces
  1143     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1144     if (intf2 != NULL) return intf2;
  1146   // otherwise field lookup fails
  1147   return NULL;
  1151 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1152   // search order according to newest JVM spec (5.4.3.2, p.167).
  1153   // 1) search for field in current klass
  1154   if (find_local_field(name, sig, fd)) {
  1155     return const_cast<InstanceKlass*>(this);
  1157   // 2) search for field recursively in direct superinterfaces
  1158   { Klass* intf = find_interface_field(name, sig, fd);
  1159     if (intf != NULL) return intf;
  1161   // 3) apply field lookup recursively if superclass exists
  1162   { Klass* supr = super();
  1163     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1165   // 4) otherwise field lookup fails
  1166   return NULL;
  1170 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1171   // search order according to newest JVM spec (5.4.3.2, p.167).
  1172   // 1) search for field in current klass
  1173   if (find_local_field(name, sig, fd)) {
  1174     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1176   // 2) search for field recursively in direct superinterfaces
  1177   if (is_static) {
  1178     Klass* intf = find_interface_field(name, sig, fd);
  1179     if (intf != NULL) return intf;
  1181   // 3) apply field lookup recursively if superclass exists
  1182   { Klass* supr = super();
  1183     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1185   // 4) otherwise field lookup fails
  1186   return NULL;
  1190 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1191   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1192     if (fs.offset() == offset) {
  1193       fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
  1194       if (fd->is_static() == is_static) return true;
  1197   return false;
  1201 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1202   Klass* klass = const_cast<InstanceKlass*>(this);
  1203   while (klass != NULL) {
  1204     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1205       return true;
  1207     klass = klass->super();
  1209   return false;
  1213 void InstanceKlass::methods_do(void f(Method* method)) {
  1214   int len = methods()->length();
  1215   for (int index = 0; index < len; index++) {
  1216     Method* m = methods()->at(index);
  1217     assert(m->is_method(), "must be method");
  1218     f(m);
  1223 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1224   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1225     if (fs.access_flags().is_static()) {
  1226       fieldDescriptor fd;
  1227       fd.initialize(this, fs.index());
  1228       cl->do_field(&fd);
  1234 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
  1235   instanceKlassHandle h_this(THREAD, this);
  1236   do_local_static_fields_impl(h_this, f, CHECK);
  1240 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
  1241   for (JavaFieldStream fs(this_oop()); !fs.done(); fs.next()) {
  1242     if (fs.access_flags().is_static()) {
  1243       fieldDescriptor fd;
  1244       fd.initialize(this_oop(), fs.index());
  1245       f(&fd, CHECK);
  1251 static int compare_fields_by_offset(int* a, int* b) {
  1252   return a[0] - b[0];
  1255 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1256   InstanceKlass* super = superklass();
  1257   if (super != NULL) {
  1258     super->do_nonstatic_fields(cl);
  1260   fieldDescriptor fd;
  1261   int length = java_fields_count();
  1262   // In DebugInfo nonstatic fields are sorted by offset.
  1263   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1264   int j = 0;
  1265   for (int i = 0; i < length; i += 1) {
  1266     fd.initialize(this, i);
  1267     if (!fd.is_static()) {
  1268       fields_sorted[j + 0] = fd.offset();
  1269       fields_sorted[j + 1] = i;
  1270       j += 2;
  1273   if (j > 0) {
  1274     length = j;
  1275     // _sort_Fn is defined in growableArray.hpp.
  1276     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1277     for (int i = 0; i < length; i += 2) {
  1278       fd.initialize(this, fields_sorted[i + 1]);
  1279       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1280       cl->do_field(&fd);
  1283   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1287 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1288   if (array_klasses() != NULL)
  1289     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1292 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1293   if (array_klasses() != NULL)
  1294     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1298 void InstanceKlass::with_array_klasses_do(void f(Klass* k)) {
  1299   f(this);
  1300   array_klasses_do(f);
  1303 #ifdef ASSERT
  1304 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1305   int len = methods->length();
  1306   for (int index = 0; index < len; index++) {
  1307     Method* m = methods->at(index);
  1308     assert(m->is_method(), "must be method");
  1309     if (m->signature() == signature && m->name() == name) {
  1310        return index;
  1313   return -1;
  1315 #endif
  1317 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1318   int len = methods->length();
  1319   // methods are sorted, so do binary search
  1320   int l = 0;
  1321   int h = len - 1;
  1322   while (l <= h) {
  1323     int mid = (l + h) >> 1;
  1324     Method* m = methods->at(mid);
  1325     assert(m->is_method(), "must be method");
  1326     int res = m->name()->fast_compare(name);
  1327     if (res == 0) {
  1328       return mid;
  1329     } else if (res < 0) {
  1330       l = mid + 1;
  1331     } else {
  1332       h = mid - 1;
  1335   return -1;
  1338 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1339   return InstanceKlass::find_method(methods(), name, signature);
  1342 Method* InstanceKlass::find_method(
  1343     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1344   int hit = binary_search(methods, name);
  1345   if (hit != -1) {
  1346     Method* m = methods->at(hit);
  1347     // Do linear search to find matching signature.  First, quick check
  1348     // for common case
  1349     if (m->signature() == signature) return m;
  1350     // search downwards through overloaded methods
  1351     int i;
  1352     for (i = hit - 1; i >= 0; --i) {
  1353         Method* m = methods->at(i);
  1354         assert(m->is_method(), "must be method");
  1355         if (m->name() != name) break;
  1356         if (m->signature() == signature) return m;
  1358     // search upwards
  1359     for (i = hit + 1; i < methods->length(); ++i) {
  1360         Method* m = methods->at(i);
  1361         assert(m->is_method(), "must be method");
  1362         if (m->name() != name) break;
  1363         if (m->signature() == signature) return m;
  1365     // not found
  1366 #ifdef ASSERT
  1367     int index = linear_search(methods, name, signature);
  1368     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1369 #endif
  1371   return NULL;
  1374 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1375   return find_method_by_name(methods(), name, end);
  1378 int InstanceKlass::find_method_by_name(
  1379     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1380   assert(end_ptr != NULL, "just checking");
  1381   int start = binary_search(methods, name);
  1382   int end = start + 1;
  1383   if (start != -1) {
  1384     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1385     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1386     *end_ptr = end;
  1387     return start;
  1389   return -1;
  1392 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
  1393   Klass* klass = const_cast<InstanceKlass*>(this);
  1394   while (klass != NULL) {
  1395     Method* method = InstanceKlass::cast(klass)->find_method(name, signature);
  1396     if (method != NULL) return method;
  1397     klass = InstanceKlass::cast(klass)->super();
  1399   return NULL;
  1402 // lookup a method in all the interfaces that this class implements
  1403 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1404                                                          Symbol* signature) const {
  1405   Array<Klass*>* all_ifs = transitive_interfaces();
  1406   int num_ifs = all_ifs->length();
  1407   InstanceKlass *ik = NULL;
  1408   for (int i = 0; i < num_ifs; i++) {
  1409     ik = InstanceKlass::cast(all_ifs->at(i));
  1410     Method* m = ik->lookup_method(name, signature);
  1411     if (m != NULL) {
  1412       return m;
  1415   return NULL;
  1418 /* jni_id_for_impl for jfieldIds only */
  1419 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1420   MutexLocker ml(JfieldIdCreation_lock);
  1421   // Retry lookup after we got the lock
  1422   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1423   if (probe == NULL) {
  1424     // Slow case, allocate new static field identifier
  1425     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1426     this_oop->set_jni_ids(probe);
  1428   return probe;
  1432 /* jni_id_for for jfieldIds only */
  1433 JNIid* InstanceKlass::jni_id_for(int offset) {
  1434   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1435   if (probe == NULL) {
  1436     probe = jni_id_for_impl(this, offset);
  1438   return probe;
  1441 u2 InstanceKlass::enclosing_method_data(int offset) {
  1442   Array<jushort>* inner_class_list = inner_classes();
  1443   if (inner_class_list == NULL) {
  1444     return 0;
  1446   int length = inner_class_list->length();
  1447   if (length % inner_class_next_offset == 0) {
  1448     return 0;
  1449   } else {
  1450     int index = length - enclosing_method_attribute_size;
  1451     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1452     return inner_class_list->at(index + offset);
  1456 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1457                                                  u2 method_index) {
  1458   Array<jushort>* inner_class_list = inner_classes();
  1459   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1460   int length = inner_class_list->length();
  1461   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1462     int index = length - enclosing_method_attribute_size;
  1463     inner_class_list->at_put(
  1464       index + enclosing_method_class_index_offset, class_index);
  1465     inner_class_list->at_put(
  1466       index + enclosing_method_method_index_offset, method_index);
  1470 // Lookup or create a jmethodID.
  1471 // This code is called by the VMThread and JavaThreads so the
  1472 // locking has to be done very carefully to avoid deadlocks
  1473 // and/or other cache consistency problems.
  1474 //
  1475 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1476   size_t idnum = (size_t)method_h->method_idnum();
  1477   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1478   size_t length = 0;
  1479   jmethodID id = NULL;
  1481   // We use a double-check locking idiom here because this cache is
  1482   // performance sensitive. In the normal system, this cache only
  1483   // transitions from NULL to non-NULL which is safe because we use
  1484   // release_set_methods_jmethod_ids() to advertise the new cache.
  1485   // A partially constructed cache should never be seen by a racing
  1486   // thread. We also use release_store_ptr() to save a new jmethodID
  1487   // in the cache so a partially constructed jmethodID should never be
  1488   // seen either. Cache reads of existing jmethodIDs proceed without a
  1489   // lock, but cache writes of a new jmethodID requires uniqueness and
  1490   // creation of the cache itself requires no leaks so a lock is
  1491   // generally acquired in those two cases.
  1492   //
  1493   // If the RedefineClasses() API has been used, then this cache can
  1494   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1495   // Cache creation requires no leaks and we require safety between all
  1496   // cache accesses and freeing of the old cache so a lock is generally
  1497   // acquired when the RedefineClasses() API has been used.
  1499   if (jmeths != NULL) {
  1500     // the cache already exists
  1501     if (!ik_h->idnum_can_increment()) {
  1502       // the cache can't grow so we can just get the current values
  1503       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1504     } else {
  1505       // cache can grow so we have to be more careful
  1506       if (Threads::number_of_threads() == 0 ||
  1507           SafepointSynchronize::is_at_safepoint()) {
  1508         // we're single threaded or at a safepoint - no locking needed
  1509         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1510       } else {
  1511         MutexLocker ml(JmethodIdCreation_lock);
  1512         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1516   // implied else:
  1517   // we need to allocate a cache so default length and id values are good
  1519   if (jmeths == NULL ||   // no cache yet
  1520       length <= idnum ||  // cache is too short
  1521       id == NULL) {       // cache doesn't contain entry
  1523     // This function can be called by the VMThread so we have to do all
  1524     // things that might block on a safepoint before grabbing the lock.
  1525     // Otherwise, we can deadlock with the VMThread or have a cache
  1526     // consistency issue. These vars keep track of what we might have
  1527     // to free after the lock is dropped.
  1528     jmethodID  to_dealloc_id     = NULL;
  1529     jmethodID* to_dealloc_jmeths = NULL;
  1531     // may not allocate new_jmeths or use it if we allocate it
  1532     jmethodID* new_jmeths = NULL;
  1533     if (length <= idnum) {
  1534       // allocate a new cache that might be used
  1535       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1536       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1537       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1538       // cache size is stored in element[0], other elements offset by one
  1539       new_jmeths[0] = (jmethodID)size;
  1542     // allocate a new jmethodID that might be used
  1543     jmethodID new_id = NULL;
  1544     if (method_h->is_old() && !method_h->is_obsolete()) {
  1545       // The method passed in is old (but not obsolete), we need to use the current version
  1546       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1547       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1548       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1549     } else {
  1550       // It is the current version of the method or an obsolete method,
  1551       // use the version passed in
  1552       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1555     if (Threads::number_of_threads() == 0 ||
  1556         SafepointSynchronize::is_at_safepoint()) {
  1557       // we're single threaded or at a safepoint - no locking needed
  1558       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1559                                           &to_dealloc_id, &to_dealloc_jmeths);
  1560     } else {
  1561       MutexLocker ml(JmethodIdCreation_lock);
  1562       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1563                                           &to_dealloc_id, &to_dealloc_jmeths);
  1566     // The lock has been dropped so we can free resources.
  1567     // Free up either the old cache or the new cache if we allocated one.
  1568     if (to_dealloc_jmeths != NULL) {
  1569       FreeHeap(to_dealloc_jmeths);
  1571     // free up the new ID since it wasn't needed
  1572     if (to_dealloc_id != NULL) {
  1573       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1576   return id;
  1580 // Common code to fetch the jmethodID from the cache or update the
  1581 // cache with the new jmethodID. This function should never do anything
  1582 // that causes the caller to go to a safepoint or we can deadlock with
  1583 // the VMThread or have cache consistency issues.
  1584 //
  1585 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1586             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1587             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1588             jmethodID** to_dealloc_jmeths_p) {
  1589   assert(new_id != NULL, "sanity check");
  1590   assert(to_dealloc_id_p != NULL, "sanity check");
  1591   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1592   assert(Threads::number_of_threads() == 0 ||
  1593          SafepointSynchronize::is_at_safepoint() ||
  1594          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1596   // reacquire the cache - we are locked, single threaded or at a safepoint
  1597   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1598   jmethodID  id     = NULL;
  1599   size_t     length = 0;
  1601   if (jmeths == NULL ||                         // no cache yet
  1602       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1603     if (jmeths != NULL) {
  1604       // copy any existing entries from the old cache
  1605       for (size_t index = 0; index < length; index++) {
  1606         new_jmeths[index+1] = jmeths[index+1];
  1608       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1610     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1611   } else {
  1612     // fetch jmethodID (if any) from the existing cache
  1613     id = jmeths[idnum+1];
  1614     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1616   if (id == NULL) {
  1617     // No matching jmethodID in the existing cache or we have a new
  1618     // cache or we just grew the cache. This cache write is done here
  1619     // by the first thread to win the foot race because a jmethodID
  1620     // needs to be unique once it is generally available.
  1621     id = new_id;
  1623     // The jmethodID cache can be read while unlocked so we have to
  1624     // make sure the new jmethodID is complete before installing it
  1625     // in the cache.
  1626     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1627   } else {
  1628     *to_dealloc_id_p = new_id; // save new id for later delete
  1630   return id;
  1634 // Common code to get the jmethodID cache length and the jmethodID
  1635 // value at index idnum if there is one.
  1636 //
  1637 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1638        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1639   assert(cache != NULL, "sanity check");
  1640   assert(length_p != NULL, "sanity check");
  1641   assert(id_p != NULL, "sanity check");
  1643   // cache size is stored in element[0], other elements offset by one
  1644   *length_p = (size_t)cache[0];
  1645   if (*length_p <= idnum) {  // cache is too short
  1646     *id_p = NULL;
  1647   } else {
  1648     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1653 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1654 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1655   size_t idnum = (size_t)method->method_idnum();
  1656   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1657   size_t length;                                // length assigned as debugging crumb
  1658   jmethodID id = NULL;
  1659   if (jmeths != NULL &&                         // If there is a cache
  1660       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1661     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1663   return id;
  1667 // Cache an itable index
  1668 void InstanceKlass::set_cached_itable_index(size_t idnum, int index) {
  1669   int* indices = methods_cached_itable_indices_acquire();
  1670   int* to_dealloc_indices = NULL;
  1672   // We use a double-check locking idiom here because this cache is
  1673   // performance sensitive. In the normal system, this cache only
  1674   // transitions from NULL to non-NULL which is safe because we use
  1675   // release_set_methods_cached_itable_indices() to advertise the
  1676   // new cache. A partially constructed cache should never be seen
  1677   // by a racing thread. Cache reads and writes proceed without a
  1678   // lock, but creation of the cache itself requires no leaks so a
  1679   // lock is generally acquired in that case.
  1680   //
  1681   // If the RedefineClasses() API has been used, then this cache can
  1682   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1683   // Cache creation requires no leaks and we require safety between all
  1684   // cache accesses and freeing of the old cache so a lock is generally
  1685   // acquired when the RedefineClasses() API has been used.
  1687   if (indices == NULL || idnum_can_increment()) {
  1688     // we need a cache or the cache can grow
  1689     MutexLocker ml(JNICachedItableIndex_lock);
  1690     // reacquire the cache to see if another thread already did the work
  1691     indices = methods_cached_itable_indices_acquire();
  1692     size_t length = 0;
  1693     // cache size is stored in element[0], other elements offset by one
  1694     if (indices == NULL || (length = (size_t)indices[0]) <= idnum) {
  1695       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
  1696       int* new_indices = NEW_C_HEAP_ARRAY(int, size+1, mtClass);
  1697       new_indices[0] = (int)size;
  1698       // copy any existing entries
  1699       size_t i;
  1700       for (i = 0; i < length; i++) {
  1701         new_indices[i+1] = indices[i+1];
  1703       // Set all the rest to -1
  1704       for (i = length; i < size; i++) {
  1705         new_indices[i+1] = -1;
  1707       if (indices != NULL) {
  1708         // We have an old cache to delete so save it for after we
  1709         // drop the lock.
  1710         to_dealloc_indices = indices;
  1712       release_set_methods_cached_itable_indices(indices = new_indices);
  1715     if (idnum_can_increment()) {
  1716       // this cache can grow so we have to write to it safely
  1717       indices[idnum+1] = index;
  1719   } else {
  1720     CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
  1723   if (!idnum_can_increment()) {
  1724     // The cache cannot grow and this JNI itable index value does not
  1725     // have to be unique like a jmethodID. If there is a race to set it,
  1726     // it doesn't matter.
  1727     indices[idnum+1] = index;
  1730   if (to_dealloc_indices != NULL) {
  1731     // we allocated a new cache so free the old one
  1732     FreeHeap(to_dealloc_indices);
  1737 // Retrieve a cached itable index
  1738 int InstanceKlass::cached_itable_index(size_t idnum) {
  1739   int* indices = methods_cached_itable_indices_acquire();
  1740   if (indices != NULL && ((size_t)indices[0]) > idnum) {
  1741      // indices exist and are long enough, retrieve possible cached
  1742     return indices[idnum+1];
  1744   return -1;
  1748 //
  1749 // Walk the list of dependent nmethods searching for nmethods which
  1750 // are dependent on the changes that were passed in and mark them for
  1751 // deoptimization.  Returns the number of nmethods found.
  1752 //
  1753 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1754   assert_locked_or_safepoint(CodeCache_lock);
  1755   int found = 0;
  1756   nmethodBucket* b = _dependencies;
  1757   while (b != NULL) {
  1758     nmethod* nm = b->get_nmethod();
  1759     // since dependencies aren't removed until an nmethod becomes a zombie,
  1760     // the dependency list may contain nmethods which aren't alive.
  1761     if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1762       if (TraceDependencies) {
  1763         ResourceMark rm;
  1764         tty->print_cr("Marked for deoptimization");
  1765         tty->print_cr("  context = %s", this->external_name());
  1766         changes.print();
  1767         nm->print();
  1768         nm->print_dependencies();
  1770       nm->mark_for_deoptimization();
  1771       found++;
  1773     b = b->next();
  1775   return found;
  1779 //
  1780 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1781 // It's possible that an nmethod has multiple dependencies on this klass
  1782 // so a count is kept for each bucket to guarantee that creation and
  1783 // deletion of dependencies is consistent.
  1784 //
  1785 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1786   assert_locked_or_safepoint(CodeCache_lock);
  1787   nmethodBucket* b = _dependencies;
  1788   nmethodBucket* last = NULL;
  1789   while (b != NULL) {
  1790     if (nm == b->get_nmethod()) {
  1791       b->increment();
  1792       return;
  1794     b = b->next();
  1796   _dependencies = new nmethodBucket(nm, _dependencies);
  1800 //
  1801 // Decrement count of the nmethod in the dependency list and remove
  1802 // the bucket competely when the count goes to 0.  This method must
  1803 // find a corresponding bucket otherwise there's a bug in the
  1804 // recording of dependecies.
  1805 //
  1806 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1807   assert_locked_or_safepoint(CodeCache_lock);
  1808   nmethodBucket* b = _dependencies;
  1809   nmethodBucket* last = NULL;
  1810   while (b != NULL) {
  1811     if (nm == b->get_nmethod()) {
  1812       if (b->decrement() == 0) {
  1813         if (last == NULL) {
  1814           _dependencies = b->next();
  1815         } else {
  1816           last->set_next(b->next());
  1818         delete b;
  1820       return;
  1822     last = b;
  1823     b = b->next();
  1825 #ifdef ASSERT
  1826   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1827   nm->print();
  1828 #endif // ASSERT
  1829   ShouldNotReachHere();
  1833 #ifndef PRODUCT
  1834 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1835   nmethodBucket* b = _dependencies;
  1836   int idx = 0;
  1837   while (b != NULL) {
  1838     nmethod* nm = b->get_nmethod();
  1839     tty->print("[%d] count=%d { ", idx++, b->count());
  1840     if (!verbose) {
  1841       nm->print_on(tty, "nmethod");
  1842       tty->print_cr(" } ");
  1843     } else {
  1844       nm->print();
  1845       nm->print_dependencies();
  1846       tty->print_cr("--- } ");
  1848     b = b->next();
  1853 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  1854   nmethodBucket* b = _dependencies;
  1855   while (b != NULL) {
  1856     if (nm == b->get_nmethod()) {
  1857       return true;
  1859     b = b->next();
  1861   return false;
  1863 #endif //PRODUCT
  1866 // Garbage collection
  1868 void InstanceKlass::oops_do(OopClosure* cl) {
  1869   Klass::oops_do(cl);
  1871   cl->do_oop(adr_protection_domain());
  1872   cl->do_oop(adr_signers());
  1873   cl->do_oop(adr_init_lock());
  1875   // Don't walk the arrays since they are walked from the ClassLoaderData objects.
  1878 #ifdef ASSERT
  1879 template <class T> void assert_is_in(T *p) {
  1880   T heap_oop = oopDesc::load_heap_oop(p);
  1881   if (!oopDesc::is_null(heap_oop)) {
  1882     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1883     assert(Universe::heap()->is_in(o), "should be in heap");
  1886 template <class T> void assert_is_in_closed_subset(T *p) {
  1887   T heap_oop = oopDesc::load_heap_oop(p);
  1888   if (!oopDesc::is_null(heap_oop)) {
  1889     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1890     assert(Universe::heap()->is_in_closed_subset(o),
  1891            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  1894 template <class T> void assert_is_in_reserved(T *p) {
  1895   T heap_oop = oopDesc::load_heap_oop(p);
  1896   if (!oopDesc::is_null(heap_oop)) {
  1897     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1898     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  1901 template <class T> void assert_nothing(T *p) {}
  1903 #else
  1904 template <class T> void assert_is_in(T *p) {}
  1905 template <class T> void assert_is_in_closed_subset(T *p) {}
  1906 template <class T> void assert_is_in_reserved(T *p) {}
  1907 template <class T> void assert_nothing(T *p) {}
  1908 #endif // ASSERT
  1910 //
  1911 // Macros that iterate over areas of oops which are specialized on type of
  1912 // oop pointer either narrow or wide, depending on UseCompressedOops
  1913 //
  1914 // Parameters are:
  1915 //   T         - type of oop to point to (either oop or narrowOop)
  1916 //   start_p   - starting pointer for region to iterate over
  1917 //   count     - number of oops or narrowOops to iterate over
  1918 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  1919 //               makes it more efficient to put in a macro rather than making
  1920 //               it a template function)
  1921 //   assert_fn - assert function which is template function because performance
  1922 //               doesn't matter when enabled.
  1923 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  1924   T, start_p, count, do_oop,                \
  1925   assert_fn)                                \
  1926 {                                           \
  1927   T* p         = (T*)(start_p);             \
  1928   T* const end = p + (count);               \
  1929   while (p < end) {                         \
  1930     (assert_fn)(p);                         \
  1931     do_oop;                                 \
  1932     ++p;                                    \
  1933   }                                         \
  1936 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  1937   T, start_p, count, do_oop,                \
  1938   assert_fn)                                \
  1939 {                                           \
  1940   T* const start = (T*)(start_p);           \
  1941   T*       p     = start + (count);         \
  1942   while (start < p) {                       \
  1943     --p;                                    \
  1944     (assert_fn)(p);                         \
  1945     do_oop;                                 \
  1946   }                                         \
  1949 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  1950   T, start_p, count, low, high,             \
  1951   do_oop, assert_fn)                        \
  1952 {                                           \
  1953   T* const l = (T*)(low);                   \
  1954   T* const h = (T*)(high);                  \
  1955   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  1956          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  1957          "bounded region must be properly aligned"); \
  1958   T* p       = (T*)(start_p);               \
  1959   T* end     = p + (count);                 \
  1960   if (p < l) p = l;                         \
  1961   if (end > h) end = h;                     \
  1962   while (p < end) {                         \
  1963     (assert_fn)(p);                         \
  1964     do_oop;                                 \
  1965     ++p;                                    \
  1966   }                                         \
  1970 // The following macros call specialized macros, passing either oop or
  1971 // narrowOop as the specialization type.  These test the UseCompressedOops
  1972 // flag.
  1973 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  1974 {                                                                        \
  1975   /* Compute oopmap block range. The common case                         \
  1976      is nonstatic_oop_map_size == 1. */                                  \
  1977   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  1978   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  1979   if (UseCompressedOops) {                                               \
  1980     while (map < end_map) {                                              \
  1981       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  1982         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1983         do_oop, assert_fn)                                               \
  1984       ++map;                                                             \
  1985     }                                                                    \
  1986   } else {                                                               \
  1987     while (map < end_map) {                                              \
  1988       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  1989         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1990         do_oop, assert_fn)                                               \
  1991       ++map;                                                             \
  1992     }                                                                    \
  1993   }                                                                      \
  1996 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  1997 {                                                                        \
  1998   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  1999   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  2000   if (UseCompressedOops) {                                               \
  2001     while (start_map < map) {                                            \
  2002       --map;                                                             \
  2003       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  2004         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2005         do_oop, assert_fn)                                               \
  2006     }                                                                    \
  2007   } else {                                                               \
  2008     while (start_map < map) {                                            \
  2009       --map;                                                             \
  2010       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  2011         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2012         do_oop, assert_fn)                                               \
  2013     }                                                                    \
  2014   }                                                                      \
  2017 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  2018                                               assert_fn)                 \
  2019 {                                                                        \
  2020   /* Compute oopmap block range. The common case is                      \
  2021      nonstatic_oop_map_size == 1, so we accept the                       \
  2022      usually non-existent extra overhead of examining                    \
  2023      all the maps. */                                                    \
  2024   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2025   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2026   if (UseCompressedOops) {                                               \
  2027     while (map < end_map) {                                              \
  2028       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  2029         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2030         low, high,                                                       \
  2031         do_oop, assert_fn)                                               \
  2032       ++map;                                                             \
  2033     }                                                                    \
  2034   } else {                                                               \
  2035     while (map < end_map) {                                              \
  2036       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2037         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2038         low, high,                                                       \
  2039         do_oop, assert_fn)                                               \
  2040       ++map;                                                             \
  2041     }                                                                    \
  2042   }                                                                      \
  2045 void InstanceKlass::oop_follow_contents(oop obj) {
  2046   assert(obj != NULL, "can't follow the content of NULL object");
  2047   MarkSweep::follow_klass(obj->klass());
  2048   InstanceKlass_OOP_MAP_ITERATE( \
  2049     obj, \
  2050     MarkSweep::mark_and_push(p), \
  2051     assert_is_in_closed_subset)
  2054 #if INCLUDE_ALL_GCS
  2055 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2056                                         oop obj) {
  2057   assert(obj != NULL, "can't follow the content of NULL object");
  2058   PSParallelCompact::follow_klass(cm, obj->klass());
  2059   // Only mark the header and let the scan of the meta-data mark
  2060   // everything else.
  2061   InstanceKlass_OOP_MAP_ITERATE( \
  2062     obj, \
  2063     PSParallelCompact::mark_and_push(cm, p), \
  2064     assert_is_in)
  2066 #endif // INCLUDE_ALL_GCS
  2068 // closure's do_metadata() method dictates whether the given closure should be
  2069 // applied to the klass ptr in the object header.
  2071 #define if_do_metadata_checked(closure, nv_suffix)                    \
  2072   /* Make sure the non-virtual and the virtual versions match. */     \
  2073   assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
  2074       "Inconsistency in do_metadata");                                \
  2075   if (closure->do_metadata##nv_suffix())
  2077 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2079 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2080   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2081   /* header */                                                          \
  2082   if_do_metadata_checked(closure, nv_suffix) {                          \
  2083     closure->do_klass##nv_suffix(obj->klass());                         \
  2084   }                                                                     \
  2085   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2086     obj,                                                                \
  2087     SpecializationStats::                                               \
  2088       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2089     (closure)->do_oop##nv_suffix(p),                                    \
  2090     assert_is_in_closed_subset)                                         \
  2091   return size_helper();                                                 \
  2094 #if INCLUDE_ALL_GCS
  2095 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2097 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2098                                               OopClosureType* closure) {        \
  2099   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2100   /* header */                                                                  \
  2101   if_do_metadata_checked(closure, nv_suffix) {                                  \
  2102     closure->do_klass##nv_suffix(obj->klass());                                 \
  2103   }                                                                             \
  2104   /* instance variables */                                                      \
  2105   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2106     obj,                                                                        \
  2107     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2108     (closure)->do_oop##nv_suffix(p),                                            \
  2109     assert_is_in_closed_subset)                                                 \
  2110    return size_helper();                                                        \
  2112 #endif // INCLUDE_ALL_GCS
  2114 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2116 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2117                                                   OopClosureType* closure, \
  2118                                                   MemRegion mr) {          \
  2119   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2120   if_do_metadata_checked(closure, nv_suffix) {                           \
  2121     if (mr.contains(obj)) {                                              \
  2122       closure->do_klass##nv_suffix(obj->klass());                        \
  2123     }                                                                    \
  2124   }                                                                      \
  2125   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2126     obj, mr.start(), mr.end(),                                           \
  2127     (closure)->do_oop##nv_suffix(p),                                     \
  2128     assert_is_in_closed_subset)                                          \
  2129   return size_helper();                                                  \
  2132 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2133 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2134 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2135 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2136 #if INCLUDE_ALL_GCS
  2137 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2138 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2139 #endif // INCLUDE_ALL_GCS
  2141 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2142   int size = size_helper();
  2143   InstanceKlass_OOP_MAP_ITERATE( \
  2144     obj, \
  2145     MarkSweep::adjust_pointer(p), \
  2146     assert_is_in)
  2147   MarkSweep::adjust_klass(obj->klass());
  2148   return size;
  2151 #if INCLUDE_ALL_GCS
  2152 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2153   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2154     obj, \
  2155     if (PSScavenge::should_scavenge(p)) { \
  2156       pm->claim_or_forward_depth(p); \
  2157     }, \
  2158     assert_nothing )
  2161 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2162   int size = size_helper();
  2163   InstanceKlass_OOP_MAP_ITERATE( \
  2164     obj, \
  2165     PSParallelCompact::adjust_pointer(p), \
  2166     assert_is_in)
  2167   obj->update_header(cm);
  2168   return size;
  2171 #endif // INCLUDE_ALL_GCS
  2173 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2174   assert(is_loader_alive(is_alive), "this klass should be live");
  2175   if (is_interface()) {
  2176     if (ClassUnloading) {
  2177       Klass* impl = implementor();
  2178       if (impl != NULL) {
  2179         if (!impl->is_loader_alive(is_alive)) {
  2180           // remove this guy
  2181           Klass** klass = adr_implementor();
  2182           assert(klass != NULL, "null klass");
  2183           if (klass != NULL) {
  2184             *klass = NULL;
  2192 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2193 #ifdef COMPILER2
  2194   // Currently only used by C2.
  2195   for (int m = 0; m < methods()->length(); m++) {
  2196     MethodData* mdo = methods()->at(m)->method_data();
  2197     if (mdo != NULL) {
  2198       for (ProfileData* data = mdo->first_data();
  2199            mdo->is_valid(data);
  2200            data = mdo->next_data(data)) {
  2201         data->clean_weak_klass_links(is_alive);
  2205 #else
  2206 #ifdef ASSERT
  2207   // Verify that we haven't started to use MDOs for C1.
  2208   for (int m = 0; m < methods()->length(); m++) {
  2209     MethodData* mdo = methods()->at(m)->method_data();
  2210     assert(mdo == NULL, "Didn't expect C1 to use MDOs");
  2212 #endif // ASSERT
  2213 #endif // !COMPILER2
  2217 static void remove_unshareable_in_class(Klass* k) {
  2218   // remove klass's unshareable info
  2219   k->remove_unshareable_info();
  2222 void InstanceKlass::remove_unshareable_info() {
  2223   Klass::remove_unshareable_info();
  2224   // Unlink the class
  2225   if (is_linked()) {
  2226     unlink_class();
  2228   init_implementor();
  2230   constants()->remove_unshareable_info();
  2232   for (int i = 0; i < methods()->length(); i++) {
  2233     Method* m = methods()->at(i);
  2234     m->remove_unshareable_info();
  2237   // Need to reinstate when reading back the class.
  2238   set_init_lock(NULL);
  2240   // do array classes also.
  2241   array_klasses_do(remove_unshareable_in_class);
  2244 void restore_unshareable_in_class(Klass* k, TRAPS) {
  2245   k->restore_unshareable_info(CHECK);
  2248 void InstanceKlass::restore_unshareable_info(TRAPS) {
  2249   Klass::restore_unshareable_info(CHECK);
  2250   instanceKlassHandle ik(THREAD, this);
  2252   Array<Method*>* methods = ik->methods();
  2253   int num_methods = methods->length();
  2254   for (int index2 = 0; index2 < num_methods; ++index2) {
  2255     methodHandle m(THREAD, methods->at(index2));
  2256     m()->link_method(m, CHECK);
  2257     // restore method's vtable by calling a virtual function
  2258     m->restore_vtable();
  2260   if (JvmtiExport::has_redefined_a_class()) {
  2261     // Reinitialize vtable because RedefineClasses may have changed some
  2262     // entries in this vtable for super classes so the CDS vtable might
  2263     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2264     // vtables in the shared system dictionary, only the main one.
  2265     // It also redefines the itable too so fix that too.
  2266     ResourceMark rm(THREAD);
  2267     ik->vtable()->initialize_vtable(false, CHECK);
  2268     ik->itable()->initialize_itable(false, CHECK);
  2271   // Allocate a simple java object for a lock.
  2272   // This needs to be a java object because during class initialization
  2273   // it can be held across a java call.
  2274   typeArrayOop r = oopFactory::new_typeArray(T_INT, 0, CHECK);
  2275   Handle h(THREAD, (oop)r);
  2276   ik->set_init_lock(h());
  2278   // restore constant pool resolved references
  2279   ik->constants()->restore_unshareable_info(CHECK);
  2281   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2284 static void clear_all_breakpoints(Method* m) {
  2285   m->clear_all_breakpoints();
  2288 void InstanceKlass::release_C_heap_structures() {
  2289   // Deallocate oop map cache
  2290   if (_oop_map_cache != NULL) {
  2291     delete _oop_map_cache;
  2292     _oop_map_cache = NULL;
  2295   // Deallocate JNI identifiers for jfieldIDs
  2296   JNIid::deallocate(jni_ids());
  2297   set_jni_ids(NULL);
  2299   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2300   if (jmeths != (jmethodID*)NULL) {
  2301     release_set_methods_jmethod_ids(NULL);
  2302     FreeHeap(jmeths);
  2305   int* indices = methods_cached_itable_indices_acquire();
  2306   if (indices != (int*)NULL) {
  2307     release_set_methods_cached_itable_indices(NULL);
  2308     FreeHeap(indices);
  2311   // release dependencies
  2312   nmethodBucket* b = _dependencies;
  2313   _dependencies = NULL;
  2314   while (b != NULL) {
  2315     nmethodBucket* next = b->next();
  2316     delete b;
  2317     b = next;
  2320   // Deallocate breakpoint records
  2321   if (breakpoints() != 0x0) {
  2322     methods_do(clear_all_breakpoints);
  2323     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2326   // deallocate information about previous versions
  2327   if (_previous_versions != NULL) {
  2328     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2329       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2330       delete pv_node;
  2332     delete _previous_versions;
  2333     _previous_versions = NULL;
  2336   // deallocate the cached class file
  2337   if (_cached_class_file_bytes != NULL) {
  2338     os::free(_cached_class_file_bytes, mtClass);
  2339     _cached_class_file_bytes = NULL;
  2340     _cached_class_file_len = 0;
  2343   // Decrement symbol reference counts associated with the unloaded class.
  2344   if (_name != NULL) _name->decrement_refcount();
  2345   // unreference array name derived from this class name (arrays of an unloaded
  2346   // class can't be referenced anymore).
  2347   if (_array_name != NULL)  _array_name->decrement_refcount();
  2348   if (_source_file_name != NULL) _source_file_name->decrement_refcount();
  2349   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2351   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2352   Atomic::dec(&_total_instanceKlass_count);
  2355 void InstanceKlass::set_source_file_name(Symbol* n) {
  2356   _source_file_name = n;
  2357   if (_source_file_name != NULL) _source_file_name->increment_refcount();
  2360 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2361   if (array == NULL) {
  2362     _source_debug_extension = NULL;
  2363   } else {
  2364     // Adding one to the attribute length in order to store a null terminator
  2365     // character could cause an overflow because the attribute length is
  2366     // already coded with an u4 in the classfile, but in practice, it's
  2367     // unlikely to happen.
  2368     assert((length+1) > length, "Overflow checking");
  2369     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2370     for (int i = 0; i < length; i++) {
  2371       sde[i] = array[i];
  2373     sde[length] = '\0';
  2374     _source_debug_extension = sde;
  2378 address InstanceKlass::static_field_addr(int offset) {
  2379   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + (intptr_t)java_mirror());
  2383 const char* InstanceKlass::signature_name() const {
  2384   const char* src = (const char*) (name()->as_C_string());
  2385   const int src_length = (int)strlen(src);
  2386   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
  2387   int src_index = 0;
  2388   int dest_index = 0;
  2389   dest[dest_index++] = 'L';
  2390   while (src_index < src_length) {
  2391     dest[dest_index++] = src[src_index++];
  2393   dest[dest_index++] = ';';
  2394   dest[dest_index] = '\0';
  2395   return dest;
  2398 // different verisons of is_same_class_package
  2399 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2400   Klass* class1 = this;
  2401   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2402   Symbol* classname1 = class1->name();
  2404   if (class2->oop_is_objArray()) {
  2405     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2407   oop classloader2;
  2408   if (class2->oop_is_instance()) {
  2409     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2410   } else {
  2411     assert(class2->oop_is_typeArray(), "should be type array");
  2412     classloader2 = NULL;
  2414   Symbol* classname2 = class2->name();
  2416   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2417                                               classloader2, classname2);
  2420 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2421   Klass* class1 = this;
  2422   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2423   Symbol* classname1 = class1->name();
  2425   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2426                                               classloader2, classname2);
  2429 // return true if two classes are in the same package, classloader
  2430 // and classname information is enough to determine a class's package
  2431 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2432                                           oop class_loader2, Symbol* class_name2) {
  2433   if (class_loader1 != class_loader2) {
  2434     return false;
  2435   } else if (class_name1 == class_name2) {
  2436     return true;                // skip painful bytewise comparison
  2437   } else {
  2438     ResourceMark rm;
  2440     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2441     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2442     // Otherwise, we just compare jbyte values between the strings.
  2443     const jbyte *name1 = class_name1->base();
  2444     const jbyte *name2 = class_name2->base();
  2446     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2447     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2449     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2450       // One of the two doesn't have a package.  Only return true
  2451       // if the other one also doesn't have a package.
  2452       return last_slash1 == last_slash2;
  2453     } else {
  2454       // Skip over '['s
  2455       if (*name1 == '[') {
  2456         do {
  2457           name1++;
  2458         } while (*name1 == '[');
  2459         if (*name1 != 'L') {
  2460           // Something is terribly wrong.  Shouldn't be here.
  2461           return false;
  2464       if (*name2 == '[') {
  2465         do {
  2466           name2++;
  2467         } while (*name2 == '[');
  2468         if (*name2 != 'L') {
  2469           // Something is terribly wrong.  Shouldn't be here.
  2470           return false;
  2474       // Check that package part is identical
  2475       int length1 = last_slash1 - name1;
  2476       int length2 = last_slash2 - name2;
  2478       return UTF8::equal(name1, length1, name2, length2);
  2483 // Returns true iff super_method can be overridden by a method in targetclassname
  2484 // See JSL 3rd edition 8.4.6.1
  2485 // Assumes name-signature match
  2486 // "this" is InstanceKlass of super_method which must exist
  2487 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2488 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2489    // Private methods can not be overridden
  2490    if (super_method->is_private()) {
  2491      return false;
  2493    // If super method is accessible, then override
  2494    if ((super_method->is_protected()) ||
  2495        (super_method->is_public())) {
  2496      return true;
  2498    // Package-private methods are not inherited outside of package
  2499    assert(super_method->is_package_private(), "must be package private");
  2500    return(is_same_class_package(targetclassloader(), targetclassname));
  2503 /* defined for now in jvm.cpp, for historical reasons *--
  2504 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2505                                                      Symbol*& simple_name_result, TRAPS) {
  2506   ...
  2508 */
  2510 // tell if two classes have the same enclosing class (at package level)
  2511 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2512                                                 Klass* class2_oop, TRAPS) {
  2513   if (class2_oop == class1())                       return true;
  2514   if (!class2_oop->oop_is_instance())  return false;
  2515   instanceKlassHandle class2(THREAD, class2_oop);
  2517   // must be in same package before we try anything else
  2518   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2519     return false;
  2521   // As long as there is an outer1.getEnclosingClass,
  2522   // shift the search outward.
  2523   instanceKlassHandle outer1 = class1;
  2524   for (;;) {
  2525     // As we walk along, look for equalities between outer1 and class2.
  2526     // Eventually, the walks will terminate as outer1 stops
  2527     // at the top-level class around the original class.
  2528     bool ignore_inner_is_member;
  2529     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2530                                                     CHECK_false);
  2531     if (next == NULL)  break;
  2532     if (next == class2())  return true;
  2533     outer1 = instanceKlassHandle(THREAD, next);
  2536   // Now do the same for class2.
  2537   instanceKlassHandle outer2 = class2;
  2538   for (;;) {
  2539     bool ignore_inner_is_member;
  2540     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2541                                                     CHECK_false);
  2542     if (next == NULL)  break;
  2543     // Might as well check the new outer against all available values.
  2544     if (next == class1())  return true;
  2545     if (next == outer1())  return true;
  2546     outer2 = instanceKlassHandle(THREAD, next);
  2549   // If by this point we have not found an equality between the
  2550   // two classes, we know they are in separate package members.
  2551   return false;
  2555 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2556   jint access = access_flags().as_int();
  2558   // But check if it happens to be member class.
  2559   instanceKlassHandle ik(THREAD, this);
  2560   InnerClassesIterator iter(ik);
  2561   for (; !iter.done(); iter.next()) {
  2562     int ioff = iter.inner_class_info_index();
  2563     // Inner class attribute can be zero, skip it.
  2564     // Strange but true:  JVM spec. allows null inner class refs.
  2565     if (ioff == 0) continue;
  2567     // only look at classes that are already loaded
  2568     // since we are looking for the flags for our self.
  2569     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2570     if ((ik->name() == inner_name)) {
  2571       // This is really a member class.
  2572       access = iter.inner_access_flags();
  2573       break;
  2576   // Remember to strip ACC_SUPER bit
  2577   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2580 jint InstanceKlass::jvmti_class_status() const {
  2581   jint result = 0;
  2583   if (is_linked()) {
  2584     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2587   if (is_initialized()) {
  2588     assert(is_linked(), "Class status is not consistent");
  2589     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2591   if (is_in_error_state()) {
  2592     result |= JVMTI_CLASS_STATUS_ERROR;
  2594   return result;
  2597 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2598   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2599   int method_table_offset_in_words = ioe->offset()/wordSize;
  2600   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2601                        / itableOffsetEntry::size();
  2603   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2604     // If the interface isn't implemented by the receiver class,
  2605     // the VM should throw IncompatibleClassChangeError.
  2606     if (cnt >= nof_interfaces) {
  2607       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2610     Klass* ik = ioe->interface_klass();
  2611     if (ik == holder) break;
  2614   itableMethodEntry* ime = ioe->first_method_entry(this);
  2615   Method* m = ime[index].method();
  2616   if (m == NULL) {
  2617     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2619   return m;
  2622 // On-stack replacement stuff
  2623 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2624   // only one compilation can be active
  2625   NEEDS_CLEANUP
  2626   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2627   OsrList_lock->lock_without_safepoint_check();
  2628   assert(n->is_osr_method(), "wrong kind of nmethod");
  2629   n->set_osr_link(osr_nmethods_head());
  2630   set_osr_nmethods_head(n);
  2631   // Raise the highest osr level if necessary
  2632   if (TieredCompilation) {
  2633     Method* m = n->method();
  2634     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2636   // Remember to unlock again
  2637   OsrList_lock->unlock();
  2639   // Get rid of the osr methods for the same bci that have lower levels.
  2640   if (TieredCompilation) {
  2641     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2642       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2643       if (inv != NULL && inv->is_in_use()) {
  2644         inv->make_not_entrant();
  2651 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2652   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2653   OsrList_lock->lock_without_safepoint_check();
  2654   assert(n->is_osr_method(), "wrong kind of nmethod");
  2655   nmethod* last = NULL;
  2656   nmethod* cur  = osr_nmethods_head();
  2657   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2658   Method* m = n->method();
  2659   // Search for match
  2660   while(cur != NULL && cur != n) {
  2661     if (TieredCompilation) {
  2662       // Find max level before n
  2663       max_level = MAX2(max_level, cur->comp_level());
  2665     last = cur;
  2666     cur = cur->osr_link();
  2668   nmethod* next = NULL;
  2669   if (cur == n) {
  2670     next = cur->osr_link();
  2671     if (last == NULL) {
  2672       // Remove first element
  2673       set_osr_nmethods_head(next);
  2674     } else {
  2675       last->set_osr_link(next);
  2678   n->set_osr_link(NULL);
  2679   if (TieredCompilation) {
  2680     cur = next;
  2681     while (cur != NULL) {
  2682       // Find max level after n
  2683       max_level = MAX2(max_level, cur->comp_level());
  2684       cur = cur->osr_link();
  2686     m->set_highest_osr_comp_level(max_level);
  2688   // Remember to unlock again
  2689   OsrList_lock->unlock();
  2692 nmethod* InstanceKlass::lookup_osr_nmethod(Method* const m, int bci, int comp_level, bool match_level) const {
  2693   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2694   OsrList_lock->lock_without_safepoint_check();
  2695   nmethod* osr = osr_nmethods_head();
  2696   nmethod* best = NULL;
  2697   while (osr != NULL) {
  2698     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2699     // There can be a time when a c1 osr method exists but we are waiting
  2700     // for a c2 version. When c2 completes its osr nmethod we will trash
  2701     // the c1 version and only be able to find the c2 version. However
  2702     // while we overflow in the c1 code at back branches we don't want to
  2703     // try and switch to the same code as we are already running
  2705     if (osr->method() == m &&
  2706         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2707       if (match_level) {
  2708         if (osr->comp_level() == comp_level) {
  2709           // Found a match - return it.
  2710           OsrList_lock->unlock();
  2711           return osr;
  2713       } else {
  2714         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2715           if (osr->comp_level() == CompLevel_highest_tier) {
  2716             // Found the best possible - return it.
  2717             OsrList_lock->unlock();
  2718             return osr;
  2720           best = osr;
  2724     osr = osr->osr_link();
  2726   OsrList_lock->unlock();
  2727   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2728     return best;
  2730   return NULL;
  2733 // -----------------------------------------------------------------------------------------------------
  2734 // Printing
  2736 #ifndef PRODUCT
  2738 #define BULLET  " - "
  2740 static const char* state_names[] = {
  2741   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  2742 };
  2744 void InstanceKlass::print_on(outputStream* st) const {
  2745   assert(is_klass(), "must be klass");
  2746   Klass::print_on(st);
  2748   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  2749   st->print(BULLET"klass size:        %d", size());                               st->cr();
  2750   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  2751   st->print(BULLET"state:             "); st->print_cr(state_names[_init_state]);
  2752   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  2753   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  2754   st->print(BULLET"sub:               ");
  2755   Klass* sub = subklass();
  2756   int n;
  2757   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  2758     if (n < MaxSubklassPrintSize) {
  2759       sub->print_value_on(st);
  2760       st->print("   ");
  2763   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  2764   st->cr();
  2766   if (is_interface()) {
  2767     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  2768     if (nof_implementors() == 1) {
  2769       st->print_cr(BULLET"implementor:    ");
  2770       st->print("   ");
  2771       implementor()->print_value_on(st);
  2772       st->cr();
  2776   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  2777   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  2778   if (Verbose) {
  2779     Array<Method*>* method_array = methods();
  2780     for(int i = 0; i < method_array->length(); i++) {
  2781       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  2784   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);       st->cr();
  2785   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  2786   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  2787   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  2788   if (class_loader_data() != NULL) {
  2789     st->print(BULLET"class loader data:  ");
  2790     class_loader_data()->print_value_on(st);
  2791     st->cr();
  2793   st->print(BULLET"protection domain: "); ((InstanceKlass*)this)->protection_domain()->print_value_on(st); st->cr();
  2794   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  2795   st->print(BULLET"signers:           "); signers()->print_value_on(st);               st->cr();
  2796   st->print(BULLET"init_lock:         "); ((oop)_init_lock)->print_value_on(st);             st->cr();
  2797   if (source_file_name() != NULL) {
  2798     st->print(BULLET"source file:       ");
  2799     source_file_name()->print_value_on(st);
  2800     st->cr();
  2802   if (source_debug_extension() != NULL) {
  2803     st->print(BULLET"source debug extension:       ");
  2804     st->print("%s", source_debug_extension());
  2805     st->cr();
  2807   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  2808   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  2809   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  2810   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  2812     ResourceMark rm;
  2813     // PreviousVersionInfo objects returned via PreviousVersionWalker
  2814     // contain a GrowableArray of handles. We have to clean up the
  2815     // GrowableArray _after_ the PreviousVersionWalker destructor
  2816     // has destroyed the handles.
  2818       bool have_pv = false;
  2819       PreviousVersionWalker pvw((InstanceKlass*)this);
  2820       for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
  2821            pv_info != NULL; pv_info = pvw.next_previous_version()) {
  2822         if (!have_pv)
  2823           st->print(BULLET"previous version:  ");
  2824         have_pv = true;
  2825         pv_info->prev_constant_pool_handle()()->print_value_on(st);
  2827       if (have_pv)  st->cr();
  2828     } // pvw is cleaned up
  2829   } // rm is cleaned up
  2831   if (generic_signature() != NULL) {
  2832     st->print(BULLET"generic signature: ");
  2833     generic_signature()->print_value_on(st);
  2834     st->cr();
  2836   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  2837   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  2838   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  2839   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  2840   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  2841   FieldPrinter print_static_field(st);
  2842   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  2843   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  2844   FieldPrinter print_nonstatic_field(st);
  2845   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  2847   st->print(BULLET"non-static oop maps: ");
  2848   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  2849   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  2850   while (map < end_map) {
  2851     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  2852     map++;
  2854   st->cr();
  2857 #endif //PRODUCT
  2859 void InstanceKlass::print_value_on(outputStream* st) const {
  2860   assert(is_klass(), "must be klass");
  2861   name()->print_value_on(st);
  2864 #ifndef PRODUCT
  2866 void FieldPrinter::do_field(fieldDescriptor* fd) {
  2867   _st->print(BULLET);
  2868    if (_obj == NULL) {
  2869      fd->print_on(_st);
  2870      _st->cr();
  2871    } else {
  2872      fd->print_on_for(_st, _obj);
  2873      _st->cr();
  2878 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  2879   Klass::oop_print_on(obj, st);
  2881   if (this == SystemDictionary::String_klass()) {
  2882     typeArrayOop value  = java_lang_String::value(obj);
  2883     juint        offset = java_lang_String::offset(obj);
  2884     juint        length = java_lang_String::length(obj);
  2885     if (value != NULL &&
  2886         value->is_typeArray() &&
  2887         offset          <= (juint) value->length() &&
  2888         offset + length <= (juint) value->length()) {
  2889       st->print(BULLET"string: ");
  2890       Handle h_obj(obj);
  2891       java_lang_String::print(h_obj, st);
  2892       st->cr();
  2893       if (!WizardMode)  return;  // that is enough
  2897   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  2898   FieldPrinter print_field(st, obj);
  2899   do_nonstatic_fields(&print_field);
  2901   if (this == SystemDictionary::Class_klass()) {
  2902     st->print(BULLET"signature: ");
  2903     java_lang_Class::print_signature(obj, st);
  2904     st->cr();
  2905     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  2906     st->print(BULLET"fake entry for mirror: ");
  2907     mirrored_klass->print_value_on_maybe_null(st);
  2908     st->cr();
  2909     Klass* array_klass = java_lang_Class::array_klass(obj);
  2910     st->print(BULLET"fake entry for array: ");
  2911     array_klass->print_value_on_maybe_null(st);
  2912     st->cr();
  2913     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  2914     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  2915     Klass* real_klass = java_lang_Class::as_Klass(obj);
  2916     if (real_klass != NULL && real_klass->oop_is_instance()) {
  2917       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  2919   } else if (this == SystemDictionary::MethodType_klass()) {
  2920     st->print(BULLET"signature: ");
  2921     java_lang_invoke_MethodType::print_signature(obj, st);
  2922     st->cr();
  2926 #endif //PRODUCT
  2928 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  2929   st->print("a ");
  2930   name()->print_value_on(st);
  2931   obj->print_address_on(st);
  2932   if (this == SystemDictionary::String_klass()
  2933       && java_lang_String::value(obj) != NULL) {
  2934     ResourceMark rm;
  2935     int len = java_lang_String::length(obj);
  2936     int plen = (len < 24 ? len : 12);
  2937     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  2938     st->print(" = \"%s\"", str);
  2939     if (len > plen)
  2940       st->print("...[%d]", len);
  2941   } else if (this == SystemDictionary::Class_klass()) {
  2942     Klass* k = java_lang_Class::as_Klass(obj);
  2943     st->print(" = ");
  2944     if (k != NULL) {
  2945       k->print_value_on(st);
  2946     } else {
  2947       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  2948       st->print("%s", tname ? tname : "type?");
  2950   } else if (this == SystemDictionary::MethodType_klass()) {
  2951     st->print(" = ");
  2952     java_lang_invoke_MethodType::print_signature(obj, st);
  2953   } else if (java_lang_boxing_object::is_instance(obj)) {
  2954     st->print(" = ");
  2955     java_lang_boxing_object::print(obj, st);
  2956   } else if (this == SystemDictionary::LambdaForm_klass()) {
  2957     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  2958     if (vmentry != NULL) {
  2959       st->print(" => ");
  2960       vmentry->print_value_on(st);
  2962   } else if (this == SystemDictionary::MemberName_klass()) {
  2963     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  2964     if (vmtarget != NULL) {
  2965       st->print(" = ");
  2966       vmtarget->print_value_on(st);
  2967     } else {
  2968       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  2969       st->print(".");
  2970       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  2975 const char* InstanceKlass::internal_name() const {
  2976   return external_name();
  2979 #if INCLUDE_SERVICES
  2980 // Size Statistics
  2981 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  2982   Klass::collect_statistics(sz);
  2984   sz->_inst_size  = HeapWordSize * size_helper();
  2985   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  2986   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  2987   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  2988         ((is_interface() || is_anonymous()) ?
  2989          align_object_offset(nonstatic_oop_map_size()) :
  2990          nonstatic_oop_map_size());
  2992   int n = 0;
  2993   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  2994   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  2995   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  2996   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  2997   n += (sz->_signers_bytes               = sz->count_array(signers()));
  2998   n += (sz->_fields_bytes                = sz->count_array(fields()));
  2999   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  3000   sz->_ro_bytes += n;
  3002   const ConstantPool* cp = constants();
  3003   if (cp) {
  3004     cp->collect_statistics(sz);
  3007   const Annotations* anno = annotations();
  3008   if (anno) {
  3009     anno->collect_statistics(sz);
  3012   const Array<Method*>* methods_array = methods();
  3013   if (methods()) {
  3014     for (int i = 0; i < methods_array->length(); i++) {
  3015       Method* method = methods_array->at(i);
  3016       if (method) {
  3017         sz->_method_count ++;
  3018         method->collect_statistics(sz);
  3023 #endif // INCLUDE_SERVICES
  3025 // Verification
  3027 class VerifyFieldClosure: public OopClosure {
  3028  protected:
  3029   template <class T> void do_oop_work(T* p) {
  3030     oop obj = oopDesc::load_decode_heap_oop(p);
  3031     if (!obj->is_oop_or_null()) {
  3032       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  3033       Universe::print();
  3034       guarantee(false, "boom");
  3037  public:
  3038   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  3039   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  3040 };
  3042 void InstanceKlass::verify_on(outputStream* st) {
  3043   Klass::verify_on(st);
  3044   Thread *thread = Thread::current();
  3046 #ifndef PRODUCT
  3047   // Avoid redundant verifies
  3048   if (_verify_count == Universe::verify_count()) return;
  3049   _verify_count = Universe::verify_count();
  3050 #endif
  3051   // Verify that klass is present in SystemDictionary
  3052   if (is_loaded() && !is_anonymous()) {
  3053     Symbol* h_name = name();
  3054     SystemDictionary::verify_obj_klass_present(h_name, class_loader_data());
  3057   // Verify static fields
  3058   VerifyFieldClosure blk;
  3060   // Verify vtables
  3061   if (is_linked()) {
  3062     ResourceMark rm(thread);
  3063     // $$$ This used to be done only for m/s collections.  Doing it
  3064     // always seemed a valid generalization.  (DLD -- 6/00)
  3065     vtable()->verify(st);
  3068   // Verify first subklass
  3069   if (subklass_oop() != NULL) {
  3070     guarantee(subklass_oop()->is_metadata(), "should be in metaspace");
  3071     guarantee(subklass_oop()->is_klass(), "should be klass");
  3074   // Verify siblings
  3075   Klass* super = this->super();
  3076   Klass* sib = next_sibling();
  3077   if (sib != NULL) {
  3078     if (sib == this) {
  3079       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3082     guarantee(sib->is_metadata(), "should be in metaspace");
  3083     guarantee(sib->is_klass(), "should be klass");
  3084     guarantee(sib->super() == super, "siblings should have same superklass");
  3087   // Verify implementor fields
  3088   Klass* im = implementor();
  3089   if (im != NULL) {
  3090     guarantee(is_interface(), "only interfaces should have implementor set");
  3091     guarantee(im->is_klass(), "should be klass");
  3092     guarantee(!im->is_interface() || im == this,
  3093       "implementors cannot be interfaces");
  3096   // Verify local interfaces
  3097   if (local_interfaces()) {
  3098     Array<Klass*>* local_interfaces = this->local_interfaces();
  3099     for (int j = 0; j < local_interfaces->length(); j++) {
  3100       Klass* e = local_interfaces->at(j);
  3101       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3105   // Verify transitive interfaces
  3106   if (transitive_interfaces() != NULL) {
  3107     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3108     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3109       Klass* e = transitive_interfaces->at(j);
  3110       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3114   // Verify methods
  3115   if (methods() != NULL) {
  3116     Array<Method*>* methods = this->methods();
  3117     for (int j = 0; j < methods->length(); j++) {
  3118       guarantee(methods->at(j)->is_metadata(), "should be in metaspace");
  3119       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3121     for (int j = 0; j < methods->length() - 1; j++) {
  3122       Method* m1 = methods->at(j);
  3123       Method* m2 = methods->at(j + 1);
  3124       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3128   // Verify method ordering
  3129   if (method_ordering() != NULL) {
  3130     Array<int>* method_ordering = this->method_ordering();
  3131     int length = method_ordering->length();
  3132     if (JvmtiExport::can_maintain_original_method_order() ||
  3133         (UseSharedSpaces && length != 0)) {
  3134       guarantee(length == methods()->length(), "invalid method ordering length");
  3135       jlong sum = 0;
  3136       for (int j = 0; j < length; j++) {
  3137         int original_index = method_ordering->at(j);
  3138         guarantee(original_index >= 0, "invalid method ordering index");
  3139         guarantee(original_index < length, "invalid method ordering index");
  3140         sum += original_index;
  3142       // Verify sum of indices 0,1,...,length-1
  3143       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3144     } else {
  3145       guarantee(length == 0, "invalid method ordering length");
  3149   // Verify JNI static field identifiers
  3150   if (jni_ids() != NULL) {
  3151     jni_ids()->verify(this);
  3154   // Verify other fields
  3155   if (array_klasses() != NULL) {
  3156     guarantee(array_klasses()->is_metadata(), "should be in metaspace");
  3157     guarantee(array_klasses()->is_klass(), "should be klass");
  3159   if (constants() != NULL) {
  3160     guarantee(constants()->is_metadata(), "should be in metaspace");
  3161     guarantee(constants()->is_constantPool(), "should be constant pool");
  3163   if (protection_domain() != NULL) {
  3164     guarantee(protection_domain()->is_oop(), "should be oop");
  3166   const Klass* host = host_klass();
  3167   if (host != NULL) {
  3168     guarantee(host->is_metadata(), "should be in metaspace");
  3169     guarantee(host->is_klass(), "should be klass");
  3171   if (signers() != NULL) {
  3172     guarantee(signers()->is_objArray(), "should be obj array");
  3176 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3177   Klass::oop_verify_on(obj, st);
  3178   VerifyFieldClosure blk;
  3179   obj->oop_iterate_no_header(&blk);
  3183 // JNIid class for jfieldIDs only
  3184 // Note to reviewers:
  3185 // These JNI functions are just moved over to column 1 and not changed
  3186 // in the compressed oops workspace.
  3187 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3188   _holder = holder;
  3189   _offset = offset;
  3190   _next = next;
  3191   debug_only(_is_static_field_id = false;)
  3195 JNIid* JNIid::find(int offset) {
  3196   JNIid* current = this;
  3197   while (current != NULL) {
  3198     if (current->offset() == offset) return current;
  3199     current = current->next();
  3201   return NULL;
  3204 void JNIid::deallocate(JNIid* current) {
  3205   while (current != NULL) {
  3206     JNIid* next = current->next();
  3207     delete current;
  3208     current = next;
  3213 void JNIid::verify(Klass* holder) {
  3214   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3215   int end_field_offset;
  3216   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3218   JNIid* current = this;
  3219   while (current != NULL) {
  3220     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3221 #ifdef ASSERT
  3222     int o = current->offset();
  3223     if (current->is_static_field_id()) {
  3224       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3226 #endif
  3227     current = current->next();
  3232 #ifdef ASSERT
  3233 void InstanceKlass::set_init_state(ClassState state) {
  3234   bool good_state = is_shared() ? (_init_state <= state)
  3235                                                : (_init_state < state);
  3236   assert(good_state || state == allocated, "illegal state transition");
  3237   _init_state = (u1)state;
  3239 #endif
  3242 // RedefineClasses() support for previous versions:
  3244 // Purge previous versions
  3245 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3246   if (ik->previous_versions() != NULL) {
  3247     // This klass has previous versions so see what we can cleanup
  3248     // while it is safe to do so.
  3250     int deleted_count = 0;    // leave debugging breadcrumbs
  3251     int live_count = 0;
  3252     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3253                        ClassLoaderData::the_null_class_loader_data() :
  3254                        ik->class_loader_data();
  3256     // RC_TRACE macro has an embedded ResourceMark
  3257     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3258       ik->external_name(), ik->previous_versions()->length()));
  3260     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3261       // check the previous versions array
  3262       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3263       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3264       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3266       ConstantPool* pvcp = cp_ref;
  3267       if (!pvcp->on_stack()) {
  3268         // If the constant pool isn't on stack, none of the methods
  3269         // are executing.  Delete all the methods, the constant pool and
  3270         // and this previous version node.
  3271         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3272         if (method_refs != NULL) {
  3273           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3274             Method* method = method_refs->at(j);
  3275             assert(method != NULL, "method ref was unexpectedly cleared");
  3276             method_refs->remove_at(j);
  3277             // method will be freed with associated class.
  3280         // Remove the constant pool
  3281         delete pv_node;
  3282         // Since we are traversing the array backwards, we don't have to
  3283         // do anything special with the index.
  3284         ik->previous_versions()->remove_at(i);
  3285         deleted_count++;
  3286         continue;
  3287       } else {
  3288         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3289         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3290         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3291         live_count++;
  3294       // At least one method is live in this previous version, clean out
  3295       // the others or mark them as obsolete.
  3296       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3297       if (method_refs != NULL) {
  3298         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3299           method_refs->length()));
  3300         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3301           Method* method = method_refs->at(j);
  3302           assert(method != NULL, "method ref was unexpectedly cleared");
  3304           // Remove the emcp method if it's not executing
  3305           // If it's been made obsolete by a redefinition of a non-emcp
  3306           // method, mark it as obsolete but leave it to clean up later.
  3307           if (!method->on_stack()) {
  3308             method_refs->remove_at(j);
  3309           } else if (emcp_method_count == 0) {
  3310             method->set_is_obsolete();
  3311           } else {
  3312             // RC_TRACE macro has an embedded ResourceMark
  3313             RC_TRACE(0x00000200,
  3314               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3315               method->name()->as_C_string(),
  3316               method->signature()->as_C_string(), j, i));
  3321     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3322     RC_TRACE(0x00000200,
  3323       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3324       deleted_count));
  3328 // External interface for use during class unloading.
  3329 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3330   // Call with >0 emcp methods since they are not currently being redefined.
  3331   purge_previous_versions_internal(ik, 1);
  3335 // Potentially add an information node that contains pointers to the
  3336 // interesting parts of the previous version of the_class.
  3337 // This is also where we clean out any unused references.
  3338 // Note that while we delete nodes from the _previous_versions
  3339 // array, we never delete the array itself until the klass is
  3340 // unloaded. The has_been_redefined() query depends on that fact.
  3341 //
  3342 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3343        BitMap* emcp_methods, int emcp_method_count) {
  3344   assert(Thread::current()->is_VM_thread(),
  3345          "only VMThread can add previous versions");
  3347   if (_previous_versions == NULL) {
  3348     // This is the first previous version so make some space.
  3349     // Start with 2 elements under the assumption that the class
  3350     // won't be redefined much.
  3351     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3352                             GrowableArray<PreviousVersionNode *>(2, true);
  3355   ConstantPool* cp_ref = ikh->constants();
  3357   // RC_TRACE macro has an embedded ResourceMark
  3358   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3359                         "on_stack=%d",
  3360     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3361     cp_ref->on_stack()));
  3363   // If the constant pool for this previous version of the class
  3364   // is not marked as being on the stack, then none of the methods
  3365   // in this previous version of the class are on the stack so
  3366   // we don't need to create a new PreviousVersionNode. However,
  3367   // we still need to examine older previous versions below.
  3368   Array<Method*>* old_methods = ikh->methods();
  3370   if (cp_ref->on_stack()) {
  3371   PreviousVersionNode * pv_node = NULL;
  3372   if (emcp_method_count == 0) {
  3373       // non-shared ConstantPool gets a reference
  3374       pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), NULL);
  3375     RC_TRACE(0x00000400,
  3376         ("add: all methods are obsolete; flushing any EMCP refs"));
  3377   } else {
  3378     int local_count = 0;
  3379       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3380         GrowableArray<Method*>(emcp_method_count, true);
  3381     for (int i = 0; i < old_methods->length(); i++) {
  3382       if (emcp_methods->at(i)) {
  3383           // this old method is EMCP. Save it only if it's on the stack
  3384           Method* old_method = old_methods->at(i);
  3385           if (old_method->on_stack()) {
  3386             method_refs->append(old_method);
  3388         if (++local_count >= emcp_method_count) {
  3389           // no more EMCP methods so bail out now
  3390           break;
  3394       // non-shared ConstantPool gets a reference
  3395       pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), method_refs);
  3397     // append new previous version.
  3398   _previous_versions->append(pv_node);
  3401   // Since the caller is the VMThread and we are at a safepoint, this
  3402   // is a good time to clear out unused references.
  3404   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3405     _previous_versions->length()));
  3407   // Purge previous versions not executing on the stack
  3408   purge_previous_versions_internal(this, emcp_method_count);
  3410   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3412   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3413       _previous_versions->length() > 0) {
  3414     // We have a mix of obsolete and EMCP methods so we have to
  3415     // clear out any matching EMCP method entries the hard way.
  3416     int local_count = 0;
  3417     for (int i = 0; i < old_methods->length(); i++) {
  3418       if (!emcp_methods->at(i)) {
  3419         // only obsolete methods are interesting
  3420         Method* old_method = old_methods->at(i);
  3421         Symbol* m_name = old_method->name();
  3422         Symbol* m_signature = old_method->signature();
  3424         // we might not have added the last entry
  3425         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3426           // check the previous versions array for non executing obsolete methods
  3427           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3429           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3430           if (method_refs == NULL) {
  3431             // We have run into a PreviousVersion generation where
  3432             // all methods were made obsolete during that generation's
  3433             // RedefineClasses() operation. At the time of that
  3434             // operation, all EMCP methods were flushed so we don't
  3435             // have to go back any further.
  3436             //
  3437             // A NULL method_refs is different than an empty method_refs.
  3438             // We cannot infer any optimizations about older generations
  3439             // from an empty method_refs for the current generation.
  3440             break;
  3443           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3444             Method* method = method_refs->at(k);
  3446             if (!method->is_obsolete() &&
  3447                 method->name() == m_name &&
  3448                 method->signature() == m_signature) {
  3449               // The current RedefineClasses() call has made all EMCP
  3450               // versions of this method obsolete so mark it as obsolete
  3451               // and remove the reference.
  3452               RC_TRACE(0x00000400,
  3453                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3454                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3456               method->set_is_obsolete();
  3457               // Leave obsolete methods on the previous version list to
  3458               // clean up later.
  3459               break;
  3463           // The previous loop may not find a matching EMCP method, but
  3464           // that doesn't mean that we can optimize and not go any
  3465           // further back in the PreviousVersion generations. The EMCP
  3466           // method for this generation could have already been deleted,
  3467           // but there still may be an older EMCP method that has not
  3468           // been deleted.
  3471         if (++local_count >= obsolete_method_count) {
  3472           // no more obsolete methods so bail out now
  3473           break;
  3478 } // end add_previous_version()
  3481 // Determine if InstanceKlass has a previous version.
  3482 bool InstanceKlass::has_previous_version() const {
  3483   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3484 } // end has_previous_version()
  3487 Method* InstanceKlass::method_with_idnum(int idnum) {
  3488   Method* m = NULL;
  3489   if (idnum < methods()->length()) {
  3490     m = methods()->at(idnum);
  3492   if (m == NULL || m->method_idnum() != idnum) {
  3493     for (int index = 0; index < methods()->length(); ++index) {
  3494       m = methods()->at(index);
  3495       if (m->method_idnum() == idnum) {
  3496         return m;
  3500   return m;
  3504 // Construct a PreviousVersionNode entry for the array hung off
  3505 // the InstanceKlass.
  3506 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3507   bool prev_cp_is_weak, GrowableArray<Method*>* prev_EMCP_methods) {
  3509   _prev_constant_pool = prev_constant_pool;
  3510   _prev_cp_is_weak = prev_cp_is_weak;
  3511   _prev_EMCP_methods = prev_EMCP_methods;
  3515 // Destroy a PreviousVersionNode
  3516 PreviousVersionNode::~PreviousVersionNode() {
  3517   if (_prev_constant_pool != NULL) {
  3518     _prev_constant_pool = NULL;
  3521   if (_prev_EMCP_methods != NULL) {
  3522     delete _prev_EMCP_methods;
  3527 // Construct a PreviousVersionInfo entry
  3528 PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) {
  3529   _prev_constant_pool_handle = constantPoolHandle();  // NULL handle
  3530   _prev_EMCP_method_handles = NULL;
  3532   ConstantPool* cp = pv_node->prev_constant_pool();
  3533   assert(cp != NULL, "constant pool ref was unexpectedly cleared");
  3534   if (cp == NULL) {
  3535     return;  // robustness
  3538   // make the ConstantPool* safe to return
  3539   _prev_constant_pool_handle = constantPoolHandle(cp);
  3541   GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3542   if (method_refs == NULL) {
  3543     // the InstanceKlass did not have any EMCP methods
  3544     return;
  3547   _prev_EMCP_method_handles = new GrowableArray<methodHandle>(10);
  3549   int n_methods = method_refs->length();
  3550   for (int i = 0; i < n_methods; i++) {
  3551     Method* method = method_refs->at(i);
  3552     assert (method != NULL, "method has been cleared");
  3553     if (method == NULL) {
  3554       continue;  // robustness
  3556     // make the Method* safe to return
  3557     _prev_EMCP_method_handles->append(methodHandle(method));
  3562 // Destroy a PreviousVersionInfo
  3563 PreviousVersionInfo::~PreviousVersionInfo() {
  3564   // Since _prev_EMCP_method_handles is not C-heap allocated, we
  3565   // don't have to delete it.
  3569 // Construct a helper for walking the previous versions array
  3570 PreviousVersionWalker::PreviousVersionWalker(InstanceKlass *ik) {
  3571   _previous_versions = ik->previous_versions();
  3572   _current_index = 0;
  3573   // _hm needs no initialization
  3574   _current_p = NULL;
  3578 // Destroy a PreviousVersionWalker
  3579 PreviousVersionWalker::~PreviousVersionWalker() {
  3580   // Delete the current info just in case the caller didn't walk to
  3581   // the end of the previous versions list. No harm if _current_p is
  3582   // already NULL.
  3583   delete _current_p;
  3585   // When _hm is destroyed, all the Handles returned in
  3586   // PreviousVersionInfo objects will be destroyed.
  3587   // Also, after this destructor is finished it will be
  3588   // safe to delete the GrowableArray allocated in the
  3589   // PreviousVersionInfo objects.
  3593 // Return the interesting information for the next previous version
  3594 // of the klass. Returns NULL if there are no more previous versions.
  3595 PreviousVersionInfo* PreviousVersionWalker::next_previous_version() {
  3596   if (_previous_versions == NULL) {
  3597     // no previous versions so nothing to return
  3598     return NULL;
  3601   delete _current_p;  // cleanup the previous info for the caller
  3602   _current_p = NULL;  // reset to NULL so we don't delete same object twice
  3604   int length = _previous_versions->length();
  3606   while (_current_index < length) {
  3607     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3608     PreviousVersionInfo * pv_info = new (ResourceObj::C_HEAP, mtClass)
  3609                                           PreviousVersionInfo(pv_node);
  3611     constantPoolHandle cp_h = pv_info->prev_constant_pool_handle();
  3612     assert (!cp_h.is_null(), "null cp found in previous version");
  3614     // The caller will need to delete pv_info when they are done with it.
  3615     _current_p = pv_info;
  3616     return pv_info;
  3619   // all of the underlying nodes' info has been deleted
  3620   return NULL;
  3621 } // end next_previous_version()

mercurial