src/share/vm/oops/instanceKlass.cpp

Tue, 05 Mar 2013 18:03:36 -0800

author
morris
date
Tue, 05 Mar 2013 18:03:36 -0800
changeset 4693
872b3feace55
parent 4572
927a311d00f9
child 4714
35ef86296a5d
permissions
-rw-r--r--

8008750: [partfait] Null pointer deference in hotspot/src/share/vm/oops/instanceKlass.hpp
Summary: fix null pointer
Reviewed-by: kvn, coleenp

     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 size = 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   this->set_vtable_length(vtable_len);
   230   this->set_itable_length(itable_len);
   231   this->set_static_field_size(static_field_size);
   232   this->set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   233   this->set_access_flags(access_flags);
   234   this->set_is_anonymous(is_anonymous);
   235   assert(this->size() == size, "wrong size for object");
   237   this->set_array_klasses(NULL);
   238   this->set_methods(NULL);
   239   this->set_method_ordering(NULL);
   240   this->set_local_interfaces(NULL);
   241   this->set_transitive_interfaces(NULL);
   242   this->init_implementor();
   243   this->set_fields(NULL, 0);
   244   this->set_constants(NULL);
   245   this->set_class_loader_data(NULL);
   246   this->set_protection_domain(NULL);
   247   this->set_signers(NULL);
   248   this->set_source_file_name(NULL);
   249   this->set_source_debug_extension(NULL, 0);
   250   this->set_array_name(NULL);
   251   this->set_inner_classes(NULL);
   252   this->set_static_oop_field_count(0);
   253   this->set_nonstatic_field_size(0);
   254   this->set_is_marked_dependent(false);
   255   this->set_init_state(InstanceKlass::allocated);
   256   this->set_init_thread(NULL);
   257   this->set_init_lock(NULL);
   258   this->set_reference_type(rt);
   259   this->set_oop_map_cache(NULL);
   260   this->set_jni_ids(NULL);
   261   this->set_osr_nmethods_head(NULL);
   262   this->set_breakpoints(NULL);
   263   this->init_previous_versions();
   264   this->set_generic_signature(NULL);
   265   this->release_set_methods_jmethod_ids(NULL);
   266   this->release_set_methods_cached_itable_indices(NULL);
   267   this->set_annotations(NULL);
   268   this->set_jvmti_cached_class_field_map(NULL);
   269   this->set_initial_method_idnum(0);
   271   // initialize the non-header words to zero
   272   intptr_t* p = (intptr_t*)this;
   273   for (int index = InstanceKlass::header_size(); index < size; index++) {
   274     p[index] = NULL_WORD;
   275   }
   277   // Set temporary value until parseClassFile updates it with the real instance
   278   // size.
   279   this->set_layout_helper(Klass::instance_layout_helper(0, true));
   280 }
   283 // This function deallocates the metadata and C heap pointers that the
   284 // InstanceKlass points to.
   285 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   287   // Orphan the mirror first, CMS thinks it's still live.
   288   java_lang_Class::set_klass(java_mirror(), NULL);
   290   // Need to take this class off the class loader data list.
   291   loader_data->remove_class(this);
   293   // The array_klass for this class is created later, after error handling.
   294   // For class redefinition, we keep the original class so this scratch class
   295   // doesn't have an array class.  Either way, assert that there is nothing
   296   // to deallocate.
   297   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   299   // Release C heap allocated data that this might point to, which includes
   300   // reference counting symbol names.
   301   release_C_heap_structures();
   303   Array<Method*>* ms = methods();
   304   if (ms != Universe::the_empty_method_array()) {
   305     for (int i = 0; i <= methods()->length() -1 ; i++) {
   306       Method* method = methods()->at(i);
   307       // Only want to delete methods that are not executing for RedefineClasses.
   308       // The previous version will point to them so they're not totally dangling
   309       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   310       MetadataFactory::free_metadata(loader_data, method);
   311     }
   312     MetadataFactory::free_array<Method*>(loader_data, methods());
   313   }
   314   set_methods(NULL);
   316   if (method_ordering() != Universe::the_empty_int_array()) {
   317     MetadataFactory::free_array<int>(loader_data, method_ordering());
   318   }
   319   set_method_ordering(NULL);
   321   // This array is in Klass, but remove it with the InstanceKlass since
   322   // this place would be the only caller and it can share memory with transitive
   323   // interfaces.
   324   if (secondary_supers() != Universe::the_empty_klass_array() &&
   325       secondary_supers() != transitive_interfaces()) {
   326     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   327   }
   328   set_secondary_supers(NULL);
   330   // Only deallocate transitive interfaces if not empty, same as super class
   331   // or same as local interfaces.   See code in parseClassFile.
   332   Array<Klass*>* ti = transitive_interfaces();
   333   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces()) {
   334     // check that the interfaces don't come from super class
   335     Array<Klass*>* sti = (super() == NULL) ? NULL :
   336        InstanceKlass::cast(super())->transitive_interfaces();
   337     if (ti != sti) {
   338       MetadataFactory::free_array<Klass*>(loader_data, ti);
   339     }
   340   }
   341   set_transitive_interfaces(NULL);
   343   // local interfaces can be empty
   344   Array<Klass*>* li = local_interfaces();
   345   if (li != Universe::the_empty_klass_array()) {
   346     MetadataFactory::free_array<Klass*>(loader_data, li);
   347   }
   348   set_local_interfaces(NULL);
   350   MetadataFactory::free_array<jushort>(loader_data, fields());
   351   set_fields(NULL, 0);
   353   // If a method from a redefined class is using this constant pool, don't
   354   // delete it, yet.  The new class's previous version will point to this.
   355   assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   356   MetadataFactory::free_metadata(loader_data, constants());
   357   set_constants(NULL);
   359   if (inner_classes() != Universe::the_empty_short_array()) {
   360     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   361   }
   362   set_inner_classes(NULL);
   364   // Null out Java heap objects, although these won't be walked to keep
   365   // alive once this InstanceKlass is deallocated.
   366   set_protection_domain(NULL);
   367   set_signers(NULL);
   368   set_init_lock(NULL);
   370   // We should deallocate the Annotations instance
   371   MetadataFactory::free_metadata(loader_data, annotations());
   372   set_annotations(NULL);
   373 }
   375 volatile oop InstanceKlass::init_lock() const {
   376   volatile oop lock = _init_lock;  // read once
   377   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   378          "only fully initialized state can have a null lock");
   379   return lock;
   380 }
   382 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   383 // threads to get this lock will see a null lock and will not lock.
   384 // That's okay because they all check for initialized state after getting
   385 // the lock and return.
   386 void InstanceKlass::fence_and_clear_init_lock() {
   387   // make sure previous stores are all done, notably the init_state.
   388   OrderAccess::storestore();
   389   klass_oop_store(&_init_lock, NULL);
   390   assert(!is_not_initialized(), "class must be initialized now");
   391 }
   394 bool InstanceKlass::should_be_initialized() const {
   395   return !is_initialized();
   396 }
   398 klassVtable* InstanceKlass::vtable() const {
   399   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   400 }
   402 klassItable* InstanceKlass::itable() const {
   403   return new klassItable(instanceKlassHandle(this));
   404 }
   406 void InstanceKlass::eager_initialize(Thread *thread) {
   407   if (!EagerInitialization) return;
   409   if (this->is_not_initialized()) {
   410     // abort if the the class has a class initializer
   411     if (this->class_initializer() != NULL) return;
   413     // abort if it is java.lang.Object (initialization is handled in genesis)
   414     Klass* super = this->super();
   415     if (super == NULL) return;
   417     // abort if the super class should be initialized
   418     if (!InstanceKlass::cast(super)->is_initialized()) return;
   420     // call body to expose the this pointer
   421     instanceKlassHandle this_oop(thread, this);
   422     eager_initialize_impl(this_oop);
   423   }
   424 }
   427 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   428   EXCEPTION_MARK;
   429   volatile oop init_lock = this_oop->init_lock();
   430   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   432   // abort if someone beat us to the initialization
   433   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   435   ClassState old_state = this_oop->init_state();
   436   link_class_impl(this_oop, true, THREAD);
   437   if (HAS_PENDING_EXCEPTION) {
   438     CLEAR_PENDING_EXCEPTION;
   439     // Abort if linking the class throws an exception.
   441     // Use a test to avoid redundantly resetting the state if there's
   442     // no change.  Set_init_state() asserts that state changes make
   443     // progress, whereas here we might just be spinning in place.
   444     if( old_state != this_oop->_init_state )
   445       this_oop->set_init_state (old_state);
   446   } else {
   447     // linking successfull, mark class as initialized
   448     this_oop->set_init_state (fully_initialized);
   449     this_oop->fence_and_clear_init_lock();
   450     // trace
   451     if (TraceClassInitialization) {
   452       ResourceMark rm(THREAD);
   453       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   454     }
   455   }
   456 }
   459 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   460 // process. The step comments refers to the procedure described in that section.
   461 // Note: implementation moved to static method to expose the this pointer.
   462 void InstanceKlass::initialize(TRAPS) {
   463   if (this->should_be_initialized()) {
   464     HandleMark hm(THREAD);
   465     instanceKlassHandle this_oop(THREAD, this);
   466     initialize_impl(this_oop, CHECK);
   467     // Note: at this point the class may be initialized
   468     //       OR it may be in the state of being initialized
   469     //       in case of recursive initialization!
   470   } else {
   471     assert(is_initialized(), "sanity check");
   472   }
   473 }
   476 bool InstanceKlass::verify_code(
   477     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   478   // 1) Verify the bytecodes
   479   Verifier::Mode mode =
   480     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   481   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   482 }
   485 // Used exclusively by the shared spaces dump mechanism to prevent
   486 // classes mapped into the shared regions in new VMs from appearing linked.
   488 void InstanceKlass::unlink_class() {
   489   assert(is_linked(), "must be linked");
   490   _init_state = loaded;
   491 }
   493 void InstanceKlass::link_class(TRAPS) {
   494   assert(is_loaded(), "must be loaded");
   495   if (!is_linked()) {
   496     HandleMark hm(THREAD);
   497     instanceKlassHandle this_oop(THREAD, this);
   498     link_class_impl(this_oop, true, CHECK);
   499   }
   500 }
   502 // Called to verify that a class can link during initialization, without
   503 // throwing a VerifyError.
   504 bool InstanceKlass::link_class_or_fail(TRAPS) {
   505   assert(is_loaded(), "must be loaded");
   506   if (!is_linked()) {
   507     HandleMark hm(THREAD);
   508     instanceKlassHandle this_oop(THREAD, this);
   509     link_class_impl(this_oop, false, CHECK_false);
   510   }
   511   return is_linked();
   512 }
   514 bool InstanceKlass::link_class_impl(
   515     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   516   // check for error state
   517   if (this_oop->is_in_error_state()) {
   518     ResourceMark rm(THREAD);
   519     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   520                this_oop->external_name(), false);
   521   }
   522   // return if already verified
   523   if (this_oop->is_linked()) {
   524     return true;
   525   }
   527   // Timing
   528   // timer handles recursion
   529   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   530   JavaThread* jt = (JavaThread*)THREAD;
   532   // link super class before linking this class
   533   instanceKlassHandle super(THREAD, this_oop->super());
   534   if (super.not_null()) {
   535     if (super->is_interface()) {  // check if super class is an interface
   536       ResourceMark rm(THREAD);
   537       Exceptions::fthrow(
   538         THREAD_AND_LOCATION,
   539         vmSymbols::java_lang_IncompatibleClassChangeError(),
   540         "class %s has interface %s as super class",
   541         this_oop->external_name(),
   542         super->external_name()
   543       );
   544       return false;
   545     }
   547     link_class_impl(super, throw_verifyerror, CHECK_false);
   548   }
   550   // link all interfaces implemented by this class before linking this class
   551   Array<Klass*>* interfaces = this_oop->local_interfaces();
   552   int num_interfaces = interfaces->length();
   553   for (int index = 0; index < num_interfaces; index++) {
   554     HandleMark hm(THREAD);
   555     instanceKlassHandle ih(THREAD, interfaces->at(index));
   556     link_class_impl(ih, throw_verifyerror, CHECK_false);
   557   }
   559   // in case the class is linked in the process of linking its superclasses
   560   if (this_oop->is_linked()) {
   561     return true;
   562   }
   564   // trace only the link time for this klass that includes
   565   // the verification time
   566   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   567                              ClassLoader::perf_class_link_selftime(),
   568                              ClassLoader::perf_classes_linked(),
   569                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   570                              jt->get_thread_stat()->perf_timers_addr(),
   571                              PerfClassTraceTime::CLASS_LINK);
   573   // verification & rewriting
   574   {
   575     volatile oop init_lock = this_oop->init_lock();
   576     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   577     // rewritten will have been set if loader constraint error found
   578     // on an earlier link attempt
   579     // don't verify or rewrite if already rewritten
   581     if (!this_oop->is_linked()) {
   582       if (!this_oop->is_rewritten()) {
   583         {
   584           // Timer includes any side effects of class verification (resolution,
   585           // etc), but not recursive entry into verify_code().
   586           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   587                                    ClassLoader::perf_class_verify_selftime(),
   588                                    ClassLoader::perf_classes_verified(),
   589                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   590                                    jt->get_thread_stat()->perf_timers_addr(),
   591                                    PerfClassTraceTime::CLASS_VERIFY);
   592           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   593           if (!verify_ok) {
   594             return false;
   595           }
   596         }
   598         // Just in case a side-effect of verify linked this class already
   599         // (which can sometimes happen since the verifier loads classes
   600         // using custom class loaders, which are free to initialize things)
   601         if (this_oop->is_linked()) {
   602           return true;
   603         }
   605         // also sets rewritten
   606         this_oop->rewrite_class(CHECK_false);
   607       }
   609       // relocate jsrs and link methods after they are all rewritten
   610       this_oop->link_methods(CHECK_false);
   612       // Initialize the vtable and interface table after
   613       // methods have been rewritten since rewrite may
   614       // fabricate new Method*s.
   615       // also does loader constraint checking
   616       if (!this_oop()->is_shared()) {
   617         ResourceMark rm(THREAD);
   618         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   619         this_oop->itable()->initialize_itable(true, CHECK_false);
   620       }
   621 #ifdef ASSERT
   622       else {
   623         ResourceMark rm(THREAD);
   624         this_oop->vtable()->verify(tty, true);
   625         // In case itable verification is ever added.
   626         // this_oop->itable()->verify(tty, true);
   627       }
   628 #endif
   629       this_oop->set_init_state(linked);
   630       if (JvmtiExport::should_post_class_prepare()) {
   631         Thread *thread = THREAD;
   632         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   633         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   634       }
   635     }
   636   }
   637   return true;
   638 }
   641 // Rewrite the byte codes of all of the methods of a class.
   642 // The rewriter must be called exactly once. Rewriting must happen after
   643 // verification but before the first method of the class is executed.
   644 void InstanceKlass::rewrite_class(TRAPS) {
   645   assert(is_loaded(), "must be loaded");
   646   instanceKlassHandle this_oop(THREAD, this);
   647   if (this_oop->is_rewritten()) {
   648     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   649     return;
   650   }
   651   Rewriter::rewrite(this_oop, CHECK);
   652   this_oop->set_rewritten();
   653 }
   655 // Now relocate and link method entry points after class is rewritten.
   656 // This is outside is_rewritten flag. In case of an exception, it can be
   657 // executed more than once.
   658 void InstanceKlass::link_methods(TRAPS) {
   659   int len = methods()->length();
   660   for (int i = len-1; i >= 0; i--) {
   661     methodHandle m(THREAD, methods()->at(i));
   663     // Set up method entry points for compiler and interpreter    .
   664     m->link_method(m, CHECK);
   666     // This is for JVMTI and unrelated to relocator but the last thing we do
   667 #ifdef ASSERT
   668     if (StressMethodComparator) {
   669       ResourceMark rm(THREAD);
   670       static int nmc = 0;
   671       for (int j = i; j >= 0 && j >= i-4; j--) {
   672         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   673         bool z = MethodComparator::methods_EMCP(m(),
   674                    methods()->at(j));
   675         if (j == i && !z) {
   676           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   677           assert(z, "method must compare equal to itself");
   678         }
   679       }
   680     }
   681 #endif //ASSERT
   682   }
   683 }
   686 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   687   // Make sure klass is linked (verified) before initialization
   688   // A class could already be verified, since it has been reflected upon.
   689   this_oop->link_class(CHECK);
   691   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   693   bool wait = false;
   695   // refer to the JVM book page 47 for description of steps
   696   // Step 1
   697   {
   698     volatile oop init_lock = this_oop->init_lock();
   699     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   701     Thread *self = THREAD; // it's passed the current thread
   703     // Step 2
   704     // If we were to use wait() instead of waitInterruptibly() then
   705     // we might end up throwing IE from link/symbol resolution sites
   706     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   707     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   708         wait = true;
   709       ol.waitUninterruptibly(CHECK);
   710     }
   712     // Step 3
   713     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   714       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   715       return;
   716     }
   718     // Step 4
   719     if (this_oop->is_initialized()) {
   720       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   721       return;
   722     }
   724     // Step 5
   725     if (this_oop->is_in_error_state()) {
   726       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   727       ResourceMark rm(THREAD);
   728       const char* desc = "Could not initialize class ";
   729       const char* className = this_oop->external_name();
   730       size_t msglen = strlen(desc) + strlen(className) + 1;
   731       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   732       if (NULL == message) {
   733         // Out of memory: can't create detailed error message
   734         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   735       } else {
   736         jio_snprintf(message, msglen, "%s%s", desc, className);
   737         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   738       }
   739     }
   741     // Step 6
   742     this_oop->set_init_state(being_initialized);
   743     this_oop->set_init_thread(self);
   744   }
   746   // Step 7
   747   Klass* super_klass = this_oop->super();
   748   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   749     super_klass->initialize(THREAD);
   751     if (HAS_PENDING_EXCEPTION) {
   752       Handle e(THREAD, PENDING_EXCEPTION);
   753       CLEAR_PENDING_EXCEPTION;
   754       {
   755         EXCEPTION_MARK;
   756         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   757         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   758       }
   759       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   760       THROW_OOP(e());
   761     }
   762   }
   764   if (this_oop->has_default_methods()) {
   765     // Step 7.5: initialize any interfaces which have default methods
   766     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   767       Klass* iface = this_oop->local_interfaces()->at(i);
   768       InstanceKlass* ik = InstanceKlass::cast(iface);
   769       if (ik->has_default_methods() && ik->should_be_initialized()) {
   770         ik->initialize(THREAD);
   772         if (HAS_PENDING_EXCEPTION) {
   773           Handle e(THREAD, PENDING_EXCEPTION);
   774           CLEAR_PENDING_EXCEPTION;
   775           {
   776             EXCEPTION_MARK;
   777             // Locks object, set state, and notify all waiting threads
   778             this_oop->set_initialization_state_and_notify(
   779                 initialization_error, THREAD);
   781             // ignore any exception thrown, superclass initialization error is
   782             // thrown below
   783             CLEAR_PENDING_EXCEPTION;
   784           }
   785           DTRACE_CLASSINIT_PROBE_WAIT(
   786               super__failed, InstanceKlass::cast(this_oop()), -1, wait);
   787           THROW_OOP(e());
   788         }
   789       }
   790     }
   791   }
   793   // Step 8
   794   {
   795     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   796     JavaThread* jt = (JavaThread*)THREAD;
   797     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   798     // Timer includes any side effects of class initialization (resolution,
   799     // etc), but not recursive entry into call_class_initializer().
   800     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   801                              ClassLoader::perf_class_init_selftime(),
   802                              ClassLoader::perf_classes_inited(),
   803                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   804                              jt->get_thread_stat()->perf_timers_addr(),
   805                              PerfClassTraceTime::CLASS_CLINIT);
   806     this_oop->call_class_initializer(THREAD);
   807   }
   809   // Step 9
   810   if (!HAS_PENDING_EXCEPTION) {
   811     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   812     { ResourceMark rm(THREAD);
   813       debug_only(this_oop->vtable()->verify(tty, true);)
   814     }
   815   }
   816   else {
   817     // Step 10 and 11
   818     Handle e(THREAD, PENDING_EXCEPTION);
   819     CLEAR_PENDING_EXCEPTION;
   820     {
   821       EXCEPTION_MARK;
   822       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   823       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   824     }
   825     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   826     if (e->is_a(SystemDictionary::Error_klass())) {
   827       THROW_OOP(e());
   828     } else {
   829       JavaCallArguments args(e);
   830       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   831                 vmSymbols::throwable_void_signature(),
   832                 &args);
   833     }
   834   }
   835   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   836 }
   839 // Note: implementation moved to static method to expose the this pointer.
   840 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   841   instanceKlassHandle kh(THREAD, this);
   842   set_initialization_state_and_notify_impl(kh, state, CHECK);
   843 }
   845 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   846   volatile oop init_lock = this_oop->init_lock();
   847   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   848   this_oop->set_init_state(state);
   849   this_oop->fence_and_clear_init_lock();
   850   ol.notify_all(CHECK);
   851 }
   853 // The embedded _implementor field can only record one implementor.
   854 // When there are more than one implementors, the _implementor field
   855 // is set to the interface Klass* itself. Following are the possible
   856 // values for the _implementor field:
   857 //   NULL                  - no implementor
   858 //   implementor Klass*    - one implementor
   859 //   self                  - more than one implementor
   860 //
   861 // The _implementor field only exists for interfaces.
   862 void InstanceKlass::add_implementor(Klass* k) {
   863   assert(Compile_lock->owned_by_self(), "");
   864   assert(is_interface(), "not interface");
   865   // Filter out my subinterfaces.
   866   // (Note: Interfaces are never on the subklass list.)
   867   if (InstanceKlass::cast(k)->is_interface()) return;
   869   // Filter out subclasses whose supers already implement me.
   870   // (Note: CHA must walk subclasses of direct implementors
   871   // in order to locate indirect implementors.)
   872   Klass* sk = InstanceKlass::cast(k)->super();
   873   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   874     // We only need to check one immediate superclass, since the
   875     // implements_interface query looks at transitive_interfaces.
   876     // Any supers of the super have the same (or fewer) transitive_interfaces.
   877     return;
   879   Klass* ik = implementor();
   880   if (ik == NULL) {
   881     set_implementor(k);
   882   } else if (ik != this) {
   883     // There is already an implementor. Use itself as an indicator of
   884     // more than one implementors.
   885     set_implementor(this);
   886   }
   888   // The implementor also implements the transitive_interfaces
   889   for (int index = 0; index < local_interfaces()->length(); index++) {
   890     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
   891   }
   892 }
   894 void InstanceKlass::init_implementor() {
   895   if (is_interface()) {
   896     set_implementor(NULL);
   897   }
   898 }
   901 void InstanceKlass::process_interfaces(Thread *thread) {
   902   // link this class into the implementors list of every interface it implements
   903   Klass* this_as_klass_oop = this;
   904   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
   905     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
   906     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
   907     assert(interf->is_interface(), "expected interface");
   908     interf->add_implementor(this_as_klass_oop);
   909   }
   910 }
   912 bool InstanceKlass::can_be_primary_super_slow() const {
   913   if (is_interface())
   914     return false;
   915   else
   916     return Klass::can_be_primary_super_slow();
   917 }
   919 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
   920   // The secondaries are the implemented interfaces.
   921   InstanceKlass* ik = InstanceKlass::cast(this);
   922   Array<Klass*>* interfaces = ik->transitive_interfaces();
   923   int num_secondaries = num_extra_slots + interfaces->length();
   924   if (num_secondaries == 0) {
   925     // Must share this for correct bootstrapping!
   926     set_secondary_supers(Universe::the_empty_klass_array());
   927     return NULL;
   928   } else if (num_extra_slots == 0) {
   929     // The secondary super list is exactly the same as the transitive interfaces.
   930     // Redefine classes has to be careful not to delete this!
   931     set_secondary_supers(interfaces);
   932     return NULL;
   933   } else {
   934     // Copy transitive interfaces to a temporary growable array to be constructed
   935     // into the secondary super list with extra slots.
   936     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
   937     for (int i = 0; i < interfaces->length(); i++) {
   938       secondaries->push(interfaces->at(i));
   939     }
   940     return secondaries;
   941   }
   942 }
   944 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
   945   if (k->is_interface()) {
   946     return implements_interface(k);
   947   } else {
   948     return Klass::compute_is_subtype_of(k);
   949   }
   950 }
   952 bool InstanceKlass::implements_interface(Klass* k) const {
   953   if (this == k) return true;
   954   assert(k->is_interface(), "should be an interface class");
   955   for (int i = 0; i < transitive_interfaces()->length(); i++) {
   956     if (transitive_interfaces()->at(i) == k) {
   957       return true;
   958     }
   959   }
   960   return false;
   961 }
   963 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
   964   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
   965   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
   966     report_java_out_of_memory("Requested array size exceeds VM limit");
   967     JvmtiExport::post_array_size_exhausted();
   968     THROW_OOP_0(Universe::out_of_memory_error_array_size());
   969   }
   970   int size = objArrayOopDesc::object_size(length);
   971   Klass* ak = array_klass(n, CHECK_NULL);
   972   KlassHandle h_ak (THREAD, ak);
   973   objArrayOop o =
   974     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
   975   return o;
   976 }
   978 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
   979   if (TraceFinalizerRegistration) {
   980     tty->print("Registered ");
   981     i->print_value_on(tty);
   982     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
   983   }
   984   instanceHandle h_i(THREAD, i);
   985   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
   986   JavaValue result(T_VOID);
   987   JavaCallArguments args(h_i);
   988   methodHandle mh (THREAD, Universe::finalizer_register_method());
   989   JavaCalls::call(&result, mh, &args, CHECK_NULL);
   990   return h_i();
   991 }
   993 instanceOop InstanceKlass::allocate_instance(TRAPS) {
   994   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
   995   int size = size_helper();  // Query before forming handle.
   997   KlassHandle h_k(THREAD, this);
   999   instanceOop i;
  1001   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1002   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1003     i = register_finalizer(i, CHECK_NULL);
  1005   return i;
  1008 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1009   if (is_interface() || is_abstract()) {
  1010     ResourceMark rm(THREAD);
  1011     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1012               : vmSymbols::java_lang_InstantiationException(), external_name());
  1014   if (this == SystemDictionary::Class_klass()) {
  1015     ResourceMark rm(THREAD);
  1016     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1017               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1021 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1022   instanceKlassHandle this_oop(THREAD, this);
  1023   return array_klass_impl(this_oop, or_null, n, THREAD);
  1026 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1027   if (this_oop->array_klasses() == NULL) {
  1028     if (or_null) return NULL;
  1030     ResourceMark rm;
  1031     JavaThread *jt = (JavaThread *)THREAD;
  1033       // Atomic creation of array_klasses
  1034       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1035       MutexLocker ma(MultiArray_lock, THREAD);
  1037       // Check if update has already taken place
  1038       if (this_oop->array_klasses() == NULL) {
  1039         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1040         this_oop->set_array_klasses(k);
  1044   // _this will always be set at this point
  1045   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1046   if (or_null) {
  1047     return oak->array_klass_or_null(n);
  1049   return oak->array_klass(n, CHECK_NULL);
  1052 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1053   return array_klass_impl(or_null, 1, THREAD);
  1056 void InstanceKlass::call_class_initializer(TRAPS) {
  1057   instanceKlassHandle ik (THREAD, this);
  1058   call_class_initializer_impl(ik, THREAD);
  1061 static int call_class_initializer_impl_counter = 0;   // for debugging
  1063 Method* InstanceKlass::class_initializer() {
  1064   Method* clinit = find_method(
  1065       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1066   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1067     return clinit;
  1069   return NULL;
  1072 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1073   if (ReplayCompiles &&
  1074       (ReplaySuppressInitializers == 1 ||
  1075        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1076     // Hide the existence of the initializer for the purpose of replaying the compile
  1077     return;
  1080   methodHandle h_method(THREAD, this_oop->class_initializer());
  1081   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1082   if (TraceClassInitialization) {
  1083     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1084     this_oop->name()->print_value();
  1085     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1087   if (h_method() != NULL) {
  1088     JavaCallArguments args; // No arguments
  1089     JavaValue result(T_VOID);
  1090     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1095 void InstanceKlass::mask_for(methodHandle method, int bci,
  1096   InterpreterOopMap* entry_for) {
  1097   // Dirty read, then double-check under a lock.
  1098   if (_oop_map_cache == NULL) {
  1099     // Otherwise, allocate a new one.
  1100     MutexLocker x(OopMapCacheAlloc_lock);
  1101     // First time use. Allocate a cache in C heap
  1102     if (_oop_map_cache == NULL) {
  1103       _oop_map_cache = new OopMapCache();
  1106   // _oop_map_cache is constant after init; lookup below does is own locking.
  1107   _oop_map_cache->lookup(method, bci, entry_for);
  1111 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1112   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1113     Symbol* f_name = fs.name();
  1114     Symbol* f_sig  = fs.signature();
  1115     if (f_name == name && f_sig == sig) {
  1116       fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
  1117       return true;
  1120   return false;
  1124 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1125   const int n = local_interfaces()->length();
  1126   for (int i = 0; i < n; i++) {
  1127     Klass* intf1 = local_interfaces()->at(i);
  1128     assert(intf1->is_interface(), "just checking type");
  1129     // search for field in current interface
  1130     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1131       assert(fd->is_static(), "interface field must be static");
  1132       return intf1;
  1134     // search for field in direct superinterfaces
  1135     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1136     if (intf2 != NULL) return intf2;
  1138   // otherwise field lookup fails
  1139   return NULL;
  1143 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1144   // search order according to newest JVM spec (5.4.3.2, p.167).
  1145   // 1) search for field in current klass
  1146   if (find_local_field(name, sig, fd)) {
  1147     return const_cast<InstanceKlass*>(this);
  1149   // 2) search for field recursively in direct superinterfaces
  1150   { Klass* intf = find_interface_field(name, sig, fd);
  1151     if (intf != NULL) return intf;
  1153   // 3) apply field lookup recursively if superclass exists
  1154   { Klass* supr = super();
  1155     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1157   // 4) otherwise field lookup fails
  1158   return NULL;
  1162 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1163   // search order according to newest JVM spec (5.4.3.2, p.167).
  1164   // 1) search for field in current klass
  1165   if (find_local_field(name, sig, fd)) {
  1166     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1168   // 2) search for field recursively in direct superinterfaces
  1169   if (is_static) {
  1170     Klass* intf = find_interface_field(name, sig, fd);
  1171     if (intf != NULL) return intf;
  1173   // 3) apply field lookup recursively if superclass exists
  1174   { Klass* supr = super();
  1175     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1177   // 4) otherwise field lookup fails
  1178   return NULL;
  1182 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1183   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1184     if (fs.offset() == offset) {
  1185       fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
  1186       if (fd->is_static() == is_static) return true;
  1189   return false;
  1193 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1194   Klass* klass = const_cast<InstanceKlass*>(this);
  1195   while (klass != NULL) {
  1196     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1197       return true;
  1199     klass = klass->super();
  1201   return false;
  1205 void InstanceKlass::methods_do(void f(Method* method)) {
  1206   int len = methods()->length();
  1207   for (int index = 0; index < len; index++) {
  1208     Method* m = methods()->at(index);
  1209     assert(m->is_method(), "must be method");
  1210     f(m);
  1215 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1216   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1217     if (fs.access_flags().is_static()) {
  1218       fieldDescriptor fd;
  1219       fd.initialize(this, fs.index());
  1220       cl->do_field(&fd);
  1226 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
  1227   instanceKlassHandle h_this(THREAD, this);
  1228   do_local_static_fields_impl(h_this, f, CHECK);
  1232 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
  1233   for (JavaFieldStream fs(this_oop()); !fs.done(); fs.next()) {
  1234     if (fs.access_flags().is_static()) {
  1235       fieldDescriptor fd;
  1236       fd.initialize(this_oop(), fs.index());
  1237       f(&fd, CHECK);
  1243 static int compare_fields_by_offset(int* a, int* b) {
  1244   return a[0] - b[0];
  1247 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1248   InstanceKlass* super = superklass();
  1249   if (super != NULL) {
  1250     super->do_nonstatic_fields(cl);
  1252   fieldDescriptor fd;
  1253   int length = java_fields_count();
  1254   // In DebugInfo nonstatic fields are sorted by offset.
  1255   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1256   int j = 0;
  1257   for (int i = 0; i < length; i += 1) {
  1258     fd.initialize(this, i);
  1259     if (!fd.is_static()) {
  1260       fields_sorted[j + 0] = fd.offset();
  1261       fields_sorted[j + 1] = i;
  1262       j += 2;
  1265   if (j > 0) {
  1266     length = j;
  1267     // _sort_Fn is defined in growableArray.hpp.
  1268     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1269     for (int i = 0; i < length; i += 2) {
  1270       fd.initialize(this, fields_sorted[i + 1]);
  1271       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1272       cl->do_field(&fd);
  1275   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1279 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1280   if (array_klasses() != NULL)
  1281     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1284 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1285   if (array_klasses() != NULL)
  1286     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1290 void InstanceKlass::with_array_klasses_do(void f(Klass* k)) {
  1291   f(this);
  1292   array_klasses_do(f);
  1295 #ifdef ASSERT
  1296 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1297   int len = methods->length();
  1298   for (int index = 0; index < len; index++) {
  1299     Method* m = methods->at(index);
  1300     assert(m->is_method(), "must be method");
  1301     if (m->signature() == signature && m->name() == name) {
  1302        return index;
  1305   return -1;
  1307 #endif
  1309 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1310   int len = methods->length();
  1311   // methods are sorted, so do binary search
  1312   int l = 0;
  1313   int h = len - 1;
  1314   while (l <= h) {
  1315     int mid = (l + h) >> 1;
  1316     Method* m = methods->at(mid);
  1317     assert(m->is_method(), "must be method");
  1318     int res = m->name()->fast_compare(name);
  1319     if (res == 0) {
  1320       return mid;
  1321     } else if (res < 0) {
  1322       l = mid + 1;
  1323     } else {
  1324       h = mid - 1;
  1327   return -1;
  1330 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1331   return InstanceKlass::find_method(methods(), name, signature);
  1334 Method* InstanceKlass::find_method(
  1335     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1336   int hit = binary_search(methods, name);
  1337   if (hit != -1) {
  1338     Method* m = methods->at(hit);
  1339     // Do linear search to find matching signature.  First, quick check
  1340     // for common case
  1341     if (m->signature() == signature) return m;
  1342     // search downwards through overloaded methods
  1343     int i;
  1344     for (i = hit - 1; i >= 0; --i) {
  1345         Method* m = methods->at(i);
  1346         assert(m->is_method(), "must be method");
  1347         if (m->name() != name) break;
  1348         if (m->signature() == signature) return m;
  1350     // search upwards
  1351     for (i = hit + 1; i < methods->length(); ++i) {
  1352         Method* m = methods->at(i);
  1353         assert(m->is_method(), "must be method");
  1354         if (m->name() != name) break;
  1355         if (m->signature() == signature) return m;
  1357     // not found
  1358 #ifdef ASSERT
  1359     int index = linear_search(methods, name, signature);
  1360     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1361 #endif
  1363   return NULL;
  1366 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1367   return find_method_by_name(methods(), name, end);
  1370 int InstanceKlass::find_method_by_name(
  1371     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1372   assert(end_ptr != NULL, "just checking");
  1373   int start = binary_search(methods, name);
  1374   int end = start + 1;
  1375   if (start != -1) {
  1376     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1377     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1378     *end_ptr = end;
  1379     return start;
  1381   return -1;
  1384 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
  1385   Klass* klass = const_cast<InstanceKlass*>(this);
  1386   while (klass != NULL) {
  1387     Method* method = InstanceKlass::cast(klass)->find_method(name, signature);
  1388     if (method != NULL) return method;
  1389     klass = InstanceKlass::cast(klass)->super();
  1391   return NULL;
  1394 // lookup a method in all the interfaces that this class implements
  1395 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1396                                                          Symbol* signature) const {
  1397   Array<Klass*>* all_ifs = transitive_interfaces();
  1398   int num_ifs = all_ifs->length();
  1399   InstanceKlass *ik = NULL;
  1400   for (int i = 0; i < num_ifs; i++) {
  1401     ik = InstanceKlass::cast(all_ifs->at(i));
  1402     Method* m = ik->lookup_method(name, signature);
  1403     if (m != NULL) {
  1404       return m;
  1407   return NULL;
  1410 /* jni_id_for_impl for jfieldIds only */
  1411 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1412   MutexLocker ml(JfieldIdCreation_lock);
  1413   // Retry lookup after we got the lock
  1414   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1415   if (probe == NULL) {
  1416     // Slow case, allocate new static field identifier
  1417     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1418     this_oop->set_jni_ids(probe);
  1420   return probe;
  1424 /* jni_id_for for jfieldIds only */
  1425 JNIid* InstanceKlass::jni_id_for(int offset) {
  1426   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1427   if (probe == NULL) {
  1428     probe = jni_id_for_impl(this, offset);
  1430   return probe;
  1433 u2 InstanceKlass::enclosing_method_data(int offset) {
  1434   Array<jushort>* inner_class_list = inner_classes();
  1435   if (inner_class_list == NULL) {
  1436     return 0;
  1438   int length = inner_class_list->length();
  1439   if (length % inner_class_next_offset == 0) {
  1440     return 0;
  1441   } else {
  1442     int index = length - enclosing_method_attribute_size;
  1443     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1444     return inner_class_list->at(index + offset);
  1448 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1449                                                  u2 method_index) {
  1450   Array<jushort>* inner_class_list = inner_classes();
  1451   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1452   int length = inner_class_list->length();
  1453   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1454     int index = length - enclosing_method_attribute_size;
  1455     inner_class_list->at_put(
  1456       index + enclosing_method_class_index_offset, class_index);
  1457     inner_class_list->at_put(
  1458       index + enclosing_method_method_index_offset, method_index);
  1462 // Lookup or create a jmethodID.
  1463 // This code is called by the VMThread and JavaThreads so the
  1464 // locking has to be done very carefully to avoid deadlocks
  1465 // and/or other cache consistency problems.
  1466 //
  1467 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1468   size_t idnum = (size_t)method_h->method_idnum();
  1469   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1470   size_t length = 0;
  1471   jmethodID id = NULL;
  1473   // We use a double-check locking idiom here because this cache is
  1474   // performance sensitive. In the normal system, this cache only
  1475   // transitions from NULL to non-NULL which is safe because we use
  1476   // release_set_methods_jmethod_ids() to advertise the new cache.
  1477   // A partially constructed cache should never be seen by a racing
  1478   // thread. We also use release_store_ptr() to save a new jmethodID
  1479   // in the cache so a partially constructed jmethodID should never be
  1480   // seen either. Cache reads of existing jmethodIDs proceed without a
  1481   // lock, but cache writes of a new jmethodID requires uniqueness and
  1482   // creation of the cache itself requires no leaks so a lock is
  1483   // generally acquired in those two cases.
  1484   //
  1485   // If the RedefineClasses() API has been used, then this cache can
  1486   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1487   // Cache creation requires no leaks and we require safety between all
  1488   // cache accesses and freeing of the old cache so a lock is generally
  1489   // acquired when the RedefineClasses() API has been used.
  1491   if (jmeths != NULL) {
  1492     // the cache already exists
  1493     if (!ik_h->idnum_can_increment()) {
  1494       // the cache can't grow so we can just get the current values
  1495       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1496     } else {
  1497       // cache can grow so we have to be more careful
  1498       if (Threads::number_of_threads() == 0 ||
  1499           SafepointSynchronize::is_at_safepoint()) {
  1500         // we're single threaded or at a safepoint - no locking needed
  1501         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1502       } else {
  1503         MutexLocker ml(JmethodIdCreation_lock);
  1504         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1508   // implied else:
  1509   // we need to allocate a cache so default length and id values are good
  1511   if (jmeths == NULL ||   // no cache yet
  1512       length <= idnum ||  // cache is too short
  1513       id == NULL) {       // cache doesn't contain entry
  1515     // This function can be called by the VMThread so we have to do all
  1516     // things that might block on a safepoint before grabbing the lock.
  1517     // Otherwise, we can deadlock with the VMThread or have a cache
  1518     // consistency issue. These vars keep track of what we might have
  1519     // to free after the lock is dropped.
  1520     jmethodID  to_dealloc_id     = NULL;
  1521     jmethodID* to_dealloc_jmeths = NULL;
  1523     // may not allocate new_jmeths or use it if we allocate it
  1524     jmethodID* new_jmeths = NULL;
  1525     if (length <= idnum) {
  1526       // allocate a new cache that might be used
  1527       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1528       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1529       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1530       // cache size is stored in element[0], other elements offset by one
  1531       new_jmeths[0] = (jmethodID)size;
  1534     // allocate a new jmethodID that might be used
  1535     jmethodID new_id = NULL;
  1536     if (method_h->is_old() && !method_h->is_obsolete()) {
  1537       // The method passed in is old (but not obsolete), we need to use the current version
  1538       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1539       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1540       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1541     } else {
  1542       // It is the current version of the method or an obsolete method,
  1543       // use the version passed in
  1544       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1547     if (Threads::number_of_threads() == 0 ||
  1548         SafepointSynchronize::is_at_safepoint()) {
  1549       // we're single threaded or at a safepoint - no locking needed
  1550       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1551                                           &to_dealloc_id, &to_dealloc_jmeths);
  1552     } else {
  1553       MutexLocker ml(JmethodIdCreation_lock);
  1554       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1555                                           &to_dealloc_id, &to_dealloc_jmeths);
  1558     // The lock has been dropped so we can free resources.
  1559     // Free up either the old cache or the new cache if we allocated one.
  1560     if (to_dealloc_jmeths != NULL) {
  1561       FreeHeap(to_dealloc_jmeths);
  1563     // free up the new ID since it wasn't needed
  1564     if (to_dealloc_id != NULL) {
  1565       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1568   return id;
  1572 // Common code to fetch the jmethodID from the cache or update the
  1573 // cache with the new jmethodID. This function should never do anything
  1574 // that causes the caller to go to a safepoint or we can deadlock with
  1575 // the VMThread or have cache consistency issues.
  1576 //
  1577 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1578             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1579             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1580             jmethodID** to_dealloc_jmeths_p) {
  1581   assert(new_id != NULL, "sanity check");
  1582   assert(to_dealloc_id_p != NULL, "sanity check");
  1583   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1584   assert(Threads::number_of_threads() == 0 ||
  1585          SafepointSynchronize::is_at_safepoint() ||
  1586          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1588   // reacquire the cache - we are locked, single threaded or at a safepoint
  1589   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1590   jmethodID  id     = NULL;
  1591   size_t     length = 0;
  1593   if (jmeths == NULL ||                         // no cache yet
  1594       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1595     if (jmeths != NULL) {
  1596       // copy any existing entries from the old cache
  1597       for (size_t index = 0; index < length; index++) {
  1598         new_jmeths[index+1] = jmeths[index+1];
  1600       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1602     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1603   } else {
  1604     // fetch jmethodID (if any) from the existing cache
  1605     id = jmeths[idnum+1];
  1606     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1608   if (id == NULL) {
  1609     // No matching jmethodID in the existing cache or we have a new
  1610     // cache or we just grew the cache. This cache write is done here
  1611     // by the first thread to win the foot race because a jmethodID
  1612     // needs to be unique once it is generally available.
  1613     id = new_id;
  1615     // The jmethodID cache can be read while unlocked so we have to
  1616     // make sure the new jmethodID is complete before installing it
  1617     // in the cache.
  1618     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1619   } else {
  1620     *to_dealloc_id_p = new_id; // save new id for later delete
  1622   return id;
  1626 // Common code to get the jmethodID cache length and the jmethodID
  1627 // value at index idnum if there is one.
  1628 //
  1629 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1630        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1631   assert(cache != NULL, "sanity check");
  1632   assert(length_p != NULL, "sanity check");
  1633   assert(id_p != NULL, "sanity check");
  1635   // cache size is stored in element[0], other elements offset by one
  1636   *length_p = (size_t)cache[0];
  1637   if (*length_p <= idnum) {  // cache is too short
  1638     *id_p = NULL;
  1639   } else {
  1640     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1645 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1646 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1647   size_t idnum = (size_t)method->method_idnum();
  1648   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1649   size_t length;                                // length assigned as debugging crumb
  1650   jmethodID id = NULL;
  1651   if (jmeths != NULL &&                         // If there is a cache
  1652       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1653     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1655   return id;
  1659 // Cache an itable index
  1660 void InstanceKlass::set_cached_itable_index(size_t idnum, int index) {
  1661   int* indices = methods_cached_itable_indices_acquire();
  1662   int* to_dealloc_indices = NULL;
  1664   // We use a double-check locking idiom here because this cache is
  1665   // performance sensitive. In the normal system, this cache only
  1666   // transitions from NULL to non-NULL which is safe because we use
  1667   // release_set_methods_cached_itable_indices() to advertise the
  1668   // new cache. A partially constructed cache should never be seen
  1669   // by a racing thread. Cache reads and writes proceed without a
  1670   // lock, but creation of the cache itself requires no leaks so a
  1671   // lock is generally acquired in that case.
  1672   //
  1673   // If the RedefineClasses() API has been used, then this cache can
  1674   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1675   // Cache creation requires no leaks and we require safety between all
  1676   // cache accesses and freeing of the old cache so a lock is generally
  1677   // acquired when the RedefineClasses() API has been used.
  1679   if (indices == NULL || idnum_can_increment()) {
  1680     // we need a cache or the cache can grow
  1681     MutexLocker ml(JNICachedItableIndex_lock);
  1682     // reacquire the cache to see if another thread already did the work
  1683     indices = methods_cached_itable_indices_acquire();
  1684     size_t length = 0;
  1685     // cache size is stored in element[0], other elements offset by one
  1686     if (indices == NULL || (length = (size_t)indices[0]) <= idnum) {
  1687       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
  1688       int* new_indices = NEW_C_HEAP_ARRAY(int, size+1, mtClass);
  1689       new_indices[0] = (int)size;
  1690       // copy any existing entries
  1691       size_t i;
  1692       for (i = 0; i < length; i++) {
  1693         new_indices[i+1] = indices[i+1];
  1695       // Set all the rest to -1
  1696       for (i = length; i < size; i++) {
  1697         new_indices[i+1] = -1;
  1699       if (indices != NULL) {
  1700         // We have an old cache to delete so save it for after we
  1701         // drop the lock.
  1702         to_dealloc_indices = indices;
  1704       release_set_methods_cached_itable_indices(indices = new_indices);
  1707     if (idnum_can_increment()) {
  1708       // this cache can grow so we have to write to it safely
  1709       indices[idnum+1] = index;
  1711   } else {
  1712     CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
  1715   if (!idnum_can_increment()) {
  1716     // The cache cannot grow and this JNI itable index value does not
  1717     // have to be unique like a jmethodID. If there is a race to set it,
  1718     // it doesn't matter.
  1719     indices[idnum+1] = index;
  1722   if (to_dealloc_indices != NULL) {
  1723     // we allocated a new cache so free the old one
  1724     FreeHeap(to_dealloc_indices);
  1729 // Retrieve a cached itable index
  1730 int InstanceKlass::cached_itable_index(size_t idnum) {
  1731   int* indices = methods_cached_itable_indices_acquire();
  1732   if (indices != NULL && ((size_t)indices[0]) > idnum) {
  1733      // indices exist and are long enough, retrieve possible cached
  1734     return indices[idnum+1];
  1736   return -1;
  1740 //
  1741 // Walk the list of dependent nmethods searching for nmethods which
  1742 // are dependent on the changes that were passed in and mark them for
  1743 // deoptimization.  Returns the number of nmethods found.
  1744 //
  1745 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1746   assert_locked_or_safepoint(CodeCache_lock);
  1747   int found = 0;
  1748   nmethodBucket* b = _dependencies;
  1749   while (b != NULL) {
  1750     nmethod* nm = b->get_nmethod();
  1751     // since dependencies aren't removed until an nmethod becomes a zombie,
  1752     // the dependency list may contain nmethods which aren't alive.
  1753     if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1754       if (TraceDependencies) {
  1755         ResourceMark rm;
  1756         tty->print_cr("Marked for deoptimization");
  1757         tty->print_cr("  context = %s", this->external_name());
  1758         changes.print();
  1759         nm->print();
  1760         nm->print_dependencies();
  1762       nm->mark_for_deoptimization();
  1763       found++;
  1765     b = b->next();
  1767   return found;
  1771 //
  1772 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1773 // It's possible that an nmethod has multiple dependencies on this klass
  1774 // so a count is kept for each bucket to guarantee that creation and
  1775 // deletion of dependencies is consistent.
  1776 //
  1777 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1778   assert_locked_or_safepoint(CodeCache_lock);
  1779   nmethodBucket* b = _dependencies;
  1780   nmethodBucket* last = NULL;
  1781   while (b != NULL) {
  1782     if (nm == b->get_nmethod()) {
  1783       b->increment();
  1784       return;
  1786     b = b->next();
  1788   _dependencies = new nmethodBucket(nm, _dependencies);
  1792 //
  1793 // Decrement count of the nmethod in the dependency list and remove
  1794 // the bucket competely when the count goes to 0.  This method must
  1795 // find a corresponding bucket otherwise there's a bug in the
  1796 // recording of dependecies.
  1797 //
  1798 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1799   assert_locked_or_safepoint(CodeCache_lock);
  1800   nmethodBucket* b = _dependencies;
  1801   nmethodBucket* last = NULL;
  1802   while (b != NULL) {
  1803     if (nm == b->get_nmethod()) {
  1804       if (b->decrement() == 0) {
  1805         if (last == NULL) {
  1806           _dependencies = b->next();
  1807         } else {
  1808           last->set_next(b->next());
  1810         delete b;
  1812       return;
  1814     last = b;
  1815     b = b->next();
  1817 #ifdef ASSERT
  1818   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1819   nm->print();
  1820 #endif // ASSERT
  1821   ShouldNotReachHere();
  1825 #ifndef PRODUCT
  1826 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1827   nmethodBucket* b = _dependencies;
  1828   int idx = 0;
  1829   while (b != NULL) {
  1830     nmethod* nm = b->get_nmethod();
  1831     tty->print("[%d] count=%d { ", idx++, b->count());
  1832     if (!verbose) {
  1833       nm->print_on(tty, "nmethod");
  1834       tty->print_cr(" } ");
  1835     } else {
  1836       nm->print();
  1837       nm->print_dependencies();
  1838       tty->print_cr("--- } ");
  1840     b = b->next();
  1845 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  1846   nmethodBucket* b = _dependencies;
  1847   while (b != NULL) {
  1848     if (nm == b->get_nmethod()) {
  1849       return true;
  1851     b = b->next();
  1853   return false;
  1855 #endif //PRODUCT
  1858 // Garbage collection
  1860 void InstanceKlass::oops_do(OopClosure* cl) {
  1861   Klass::oops_do(cl);
  1863   cl->do_oop(adr_protection_domain());
  1864   cl->do_oop(adr_signers());
  1865   cl->do_oop(adr_init_lock());
  1867   // Don't walk the arrays since they are walked from the ClassLoaderData objects.
  1870 #ifdef ASSERT
  1871 template <class T> void assert_is_in(T *p) {
  1872   T heap_oop = oopDesc::load_heap_oop(p);
  1873   if (!oopDesc::is_null(heap_oop)) {
  1874     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1875     assert(Universe::heap()->is_in(o), "should be in heap");
  1878 template <class T> void assert_is_in_closed_subset(T *p) {
  1879   T heap_oop = oopDesc::load_heap_oop(p);
  1880   if (!oopDesc::is_null(heap_oop)) {
  1881     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1882     assert(Universe::heap()->is_in_closed_subset(o),
  1883            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  1886 template <class T> void assert_is_in_reserved(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_reserved(o), "should be in reserved");
  1893 template <class T> void assert_nothing(T *p) {}
  1895 #else
  1896 template <class T> void assert_is_in(T *p) {}
  1897 template <class T> void assert_is_in_closed_subset(T *p) {}
  1898 template <class T> void assert_is_in_reserved(T *p) {}
  1899 template <class T> void assert_nothing(T *p) {}
  1900 #endif // ASSERT
  1902 //
  1903 // Macros that iterate over areas of oops which are specialized on type of
  1904 // oop pointer either narrow or wide, depending on UseCompressedOops
  1905 //
  1906 // Parameters are:
  1907 //   T         - type of oop to point to (either oop or narrowOop)
  1908 //   start_p   - starting pointer for region to iterate over
  1909 //   count     - number of oops or narrowOops to iterate over
  1910 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  1911 //               makes it more efficient to put in a macro rather than making
  1912 //               it a template function)
  1913 //   assert_fn - assert function which is template function because performance
  1914 //               doesn't matter when enabled.
  1915 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  1916   T, start_p, count, do_oop,                \
  1917   assert_fn)                                \
  1918 {                                           \
  1919   T* p         = (T*)(start_p);             \
  1920   T* const end = p + (count);               \
  1921   while (p < end) {                         \
  1922     (assert_fn)(p);                         \
  1923     do_oop;                                 \
  1924     ++p;                                    \
  1925   }                                         \
  1928 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  1929   T, start_p, count, do_oop,                \
  1930   assert_fn)                                \
  1931 {                                           \
  1932   T* const start = (T*)(start_p);           \
  1933   T*       p     = start + (count);         \
  1934   while (start < p) {                       \
  1935     --p;                                    \
  1936     (assert_fn)(p);                         \
  1937     do_oop;                                 \
  1938   }                                         \
  1941 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  1942   T, start_p, count, low, high,             \
  1943   do_oop, assert_fn)                        \
  1944 {                                           \
  1945   T* const l = (T*)(low);                   \
  1946   T* const h = (T*)(high);                  \
  1947   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  1948          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  1949          "bounded region must be properly aligned"); \
  1950   T* p       = (T*)(start_p);               \
  1951   T* end     = p + (count);                 \
  1952   if (p < l) p = l;                         \
  1953   if (end > h) end = h;                     \
  1954   while (p < end) {                         \
  1955     (assert_fn)(p);                         \
  1956     do_oop;                                 \
  1957     ++p;                                    \
  1958   }                                         \
  1962 // The following macros call specialized macros, passing either oop or
  1963 // narrowOop as the specialization type.  These test the UseCompressedOops
  1964 // flag.
  1965 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  1966 {                                                                        \
  1967   /* Compute oopmap block range. The common case                         \
  1968      is nonstatic_oop_map_size == 1. */                                  \
  1969   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  1970   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  1971   if (UseCompressedOops) {                                               \
  1972     while (map < end_map) {                                              \
  1973       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  1974         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1975         do_oop, assert_fn)                                               \
  1976       ++map;                                                             \
  1977     }                                                                    \
  1978   } else {                                                               \
  1979     while (map < end_map) {                                              \
  1980       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  1981         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1982         do_oop, assert_fn)                                               \
  1983       ++map;                                                             \
  1984     }                                                                    \
  1985   }                                                                      \
  1988 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  1989 {                                                                        \
  1990   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  1991   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  1992   if (UseCompressedOops) {                                               \
  1993     while (start_map < map) {                                            \
  1994       --map;                                                             \
  1995       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  1996         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1997         do_oop, assert_fn)                                               \
  1998     }                                                                    \
  1999   } else {                                                               \
  2000     while (start_map < map) {                                            \
  2001       --map;                                                             \
  2002       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  2003         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2004         do_oop, assert_fn)                                               \
  2005     }                                                                    \
  2006   }                                                                      \
  2009 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  2010                                               assert_fn)                 \
  2011 {                                                                        \
  2012   /* Compute oopmap block range. The common case is                      \
  2013      nonstatic_oop_map_size == 1, so we accept the                       \
  2014      usually non-existent extra overhead of examining                    \
  2015      all the maps. */                                                    \
  2016   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2017   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2018   if (UseCompressedOops) {                                               \
  2019     while (map < end_map) {                                              \
  2020       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  2021         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2022         low, high,                                                       \
  2023         do_oop, assert_fn)                                               \
  2024       ++map;                                                             \
  2025     }                                                                    \
  2026   } else {                                                               \
  2027     while (map < end_map) {                                              \
  2028       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2029         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2030         low, high,                                                       \
  2031         do_oop, assert_fn)                                               \
  2032       ++map;                                                             \
  2033     }                                                                    \
  2034   }                                                                      \
  2037 void InstanceKlass::oop_follow_contents(oop obj) {
  2038   assert(obj != NULL, "can't follow the content of NULL object");
  2039   MarkSweep::follow_klass(obj->klass());
  2040   InstanceKlass_OOP_MAP_ITERATE( \
  2041     obj, \
  2042     MarkSweep::mark_and_push(p), \
  2043     assert_is_in_closed_subset)
  2046 #if INCLUDE_ALL_GCS
  2047 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2048                                         oop obj) {
  2049   assert(obj != NULL, "can't follow the content of NULL object");
  2050   PSParallelCompact::follow_klass(cm, obj->klass());
  2051   // Only mark the header and let the scan of the meta-data mark
  2052   // everything else.
  2053   InstanceKlass_OOP_MAP_ITERATE( \
  2054     obj, \
  2055     PSParallelCompact::mark_and_push(cm, p), \
  2056     assert_is_in)
  2058 #endif // INCLUDE_ALL_GCS
  2060 // closure's do_metadata() method dictates whether the given closure should be
  2061 // applied to the klass ptr in the object header.
  2063 #define if_do_metadata_checked(closure, nv_suffix)                    \
  2064   /* Make sure the non-virtual and the virtual versions match. */     \
  2065   assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
  2066       "Inconsistency in do_metadata");                                \
  2067   if (closure->do_metadata##nv_suffix())
  2069 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2071 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2072   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2073   /* header */                                                          \
  2074   if_do_metadata_checked(closure, nv_suffix) {                          \
  2075     closure->do_klass##nv_suffix(obj->klass());                         \
  2076   }                                                                     \
  2077   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2078     obj,                                                                \
  2079     SpecializationStats::                                               \
  2080       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2081     (closure)->do_oop##nv_suffix(p),                                    \
  2082     assert_is_in_closed_subset)                                         \
  2083   return size_helper();                                                 \
  2086 #if INCLUDE_ALL_GCS
  2087 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2089 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2090                                               OopClosureType* closure) {        \
  2091   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2092   /* header */                                                                  \
  2093   if_do_metadata_checked(closure, nv_suffix) {                                  \
  2094     closure->do_klass##nv_suffix(obj->klass());                                 \
  2095   }                                                                             \
  2096   /* instance variables */                                                      \
  2097   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2098     obj,                                                                        \
  2099     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2100     (closure)->do_oop##nv_suffix(p),                                            \
  2101     assert_is_in_closed_subset)                                                 \
  2102    return size_helper();                                                        \
  2104 #endif // INCLUDE_ALL_GCS
  2106 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2108 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2109                                                   OopClosureType* closure, \
  2110                                                   MemRegion mr) {          \
  2111   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2112   if_do_metadata_checked(closure, nv_suffix) {                           \
  2113     if (mr.contains(obj)) {                                              \
  2114       closure->do_klass##nv_suffix(obj->klass());                        \
  2115     }                                                                    \
  2116   }                                                                      \
  2117   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2118     obj, mr.start(), mr.end(),                                           \
  2119     (closure)->do_oop##nv_suffix(p),                                     \
  2120     assert_is_in_closed_subset)                                          \
  2121   return size_helper();                                                  \
  2124 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2125 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2126 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2127 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2128 #if INCLUDE_ALL_GCS
  2129 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2130 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2131 #endif // INCLUDE_ALL_GCS
  2133 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2134   int size = size_helper();
  2135   InstanceKlass_OOP_MAP_ITERATE( \
  2136     obj, \
  2137     MarkSweep::adjust_pointer(p), \
  2138     assert_is_in)
  2139   MarkSweep::adjust_klass(obj->klass());
  2140   return size;
  2143 #if INCLUDE_ALL_GCS
  2144 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2145   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2146     obj, \
  2147     if (PSScavenge::should_scavenge(p)) { \
  2148       pm->claim_or_forward_depth(p); \
  2149     }, \
  2150     assert_nothing )
  2153 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2154   int size = size_helper();
  2155   InstanceKlass_OOP_MAP_ITERATE( \
  2156     obj, \
  2157     PSParallelCompact::adjust_pointer(p), \
  2158     assert_is_in)
  2159   obj->update_header(cm);
  2160   return size;
  2163 #endif // INCLUDE_ALL_GCS
  2165 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2166   assert(is_loader_alive(is_alive), "this klass should be live");
  2167   if (is_interface()) {
  2168     if (ClassUnloading) {
  2169       Klass* impl = implementor();
  2170       if (impl != NULL) {
  2171         if (!impl->is_loader_alive(is_alive)) {
  2172           // remove this guy
  2173           Klass** klass = adr_implementor();
  2174           assert(klass != NULL, "null klass");
  2175           if (klass != NULL) {
  2176             *klass = NULL;
  2184 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2185 #ifdef COMPILER2
  2186   // Currently only used by C2.
  2187   for (int m = 0; m < methods()->length(); m++) {
  2188     MethodData* mdo = methods()->at(m)->method_data();
  2189     if (mdo != NULL) {
  2190       for (ProfileData* data = mdo->first_data();
  2191            mdo->is_valid(data);
  2192            data = mdo->next_data(data)) {
  2193         data->clean_weak_klass_links(is_alive);
  2197 #else
  2198 #ifdef ASSERT
  2199   // Verify that we haven't started to use MDOs for C1.
  2200   for (int m = 0; m < methods()->length(); m++) {
  2201     MethodData* mdo = methods()->at(m)->method_data();
  2202     assert(mdo == NULL, "Didn't expect C1 to use MDOs");
  2204 #endif // ASSERT
  2205 #endif // !COMPILER2
  2209 static void remove_unshareable_in_class(Klass* k) {
  2210   // remove klass's unshareable info
  2211   k->remove_unshareable_info();
  2214 void InstanceKlass::remove_unshareable_info() {
  2215   Klass::remove_unshareable_info();
  2216   // Unlink the class
  2217   if (is_linked()) {
  2218     unlink_class();
  2220   init_implementor();
  2222   constants()->remove_unshareable_info();
  2224   for (int i = 0; i < methods()->length(); i++) {
  2225     Method* m = methods()->at(i);
  2226     m->remove_unshareable_info();
  2229   // Need to reinstate when reading back the class.
  2230   set_init_lock(NULL);
  2232   // do array classes also.
  2233   array_klasses_do(remove_unshareable_in_class);
  2236 void restore_unshareable_in_class(Klass* k, TRAPS) {
  2237   k->restore_unshareable_info(CHECK);
  2240 void InstanceKlass::restore_unshareable_info(TRAPS) {
  2241   Klass::restore_unshareable_info(CHECK);
  2242   instanceKlassHandle ik(THREAD, this);
  2244   Array<Method*>* methods = ik->methods();
  2245   int num_methods = methods->length();
  2246   for (int index2 = 0; index2 < num_methods; ++index2) {
  2247     methodHandle m(THREAD, methods->at(index2));
  2248     m()->link_method(m, CHECK);
  2249     // restore method's vtable by calling a virtual function
  2250     m->restore_vtable();
  2252   if (JvmtiExport::has_redefined_a_class()) {
  2253     // Reinitialize vtable because RedefineClasses may have changed some
  2254     // entries in this vtable for super classes so the CDS vtable might
  2255     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2256     // vtables in the shared system dictionary, only the main one.
  2257     // It also redefines the itable too so fix that too.
  2258     ResourceMark rm(THREAD);
  2259     ik->vtable()->initialize_vtable(false, CHECK);
  2260     ik->itable()->initialize_itable(false, CHECK);
  2263   // Allocate a simple java object for a lock.
  2264   // This needs to be a java object because during class initialization
  2265   // it can be held across a java call.
  2266   typeArrayOop r = oopFactory::new_typeArray(T_INT, 0, CHECK);
  2267   Handle h(THREAD, (oop)r);
  2268   ik->set_init_lock(h());
  2270   // restore constant pool resolved references
  2271   ik->constants()->restore_unshareable_info(CHECK);
  2273   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2276 static void clear_all_breakpoints(Method* m) {
  2277   m->clear_all_breakpoints();
  2280 void InstanceKlass::release_C_heap_structures() {
  2281   // Deallocate oop map cache
  2282   if (_oop_map_cache != NULL) {
  2283     delete _oop_map_cache;
  2284     _oop_map_cache = NULL;
  2287   // Deallocate JNI identifiers for jfieldIDs
  2288   JNIid::deallocate(jni_ids());
  2289   set_jni_ids(NULL);
  2291   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2292   if (jmeths != (jmethodID*)NULL) {
  2293     release_set_methods_jmethod_ids(NULL);
  2294     FreeHeap(jmeths);
  2297   int* indices = methods_cached_itable_indices_acquire();
  2298   if (indices != (int*)NULL) {
  2299     release_set_methods_cached_itable_indices(NULL);
  2300     FreeHeap(indices);
  2303   // release dependencies
  2304   nmethodBucket* b = _dependencies;
  2305   _dependencies = NULL;
  2306   while (b != NULL) {
  2307     nmethodBucket* next = b->next();
  2308     delete b;
  2309     b = next;
  2312   // Deallocate breakpoint records
  2313   if (breakpoints() != 0x0) {
  2314     methods_do(clear_all_breakpoints);
  2315     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2318   // deallocate information about previous versions
  2319   if (_previous_versions != NULL) {
  2320     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2321       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2322       delete pv_node;
  2324     delete _previous_versions;
  2325     _previous_versions = NULL;
  2328   // deallocate the cached class file
  2329   if (_cached_class_file_bytes != NULL) {
  2330     os::free(_cached_class_file_bytes, mtClass);
  2331     _cached_class_file_bytes = NULL;
  2332     _cached_class_file_len = 0;
  2335   // Decrement symbol reference counts associated with the unloaded class.
  2336   if (_name != NULL) _name->decrement_refcount();
  2337   // unreference array name derived from this class name (arrays of an unloaded
  2338   // class can't be referenced anymore).
  2339   if (_array_name != NULL)  _array_name->decrement_refcount();
  2340   if (_source_file_name != NULL) _source_file_name->decrement_refcount();
  2341   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2343   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2344   Atomic::dec(&_total_instanceKlass_count);
  2347 void InstanceKlass::set_source_file_name(Symbol* n) {
  2348   _source_file_name = n;
  2349   if (_source_file_name != NULL) _source_file_name->increment_refcount();
  2352 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2353   if (array == NULL) {
  2354     _source_debug_extension = NULL;
  2355   } else {
  2356     // Adding one to the attribute length in order to store a null terminator
  2357     // character could cause an overflow because the attribute length is
  2358     // already coded with an u4 in the classfile, but in practice, it's
  2359     // unlikely to happen.
  2360     assert((length+1) > length, "Overflow checking");
  2361     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2362     for (int i = 0; i < length; i++) {
  2363       sde[i] = array[i];
  2365     sde[length] = '\0';
  2366     _source_debug_extension = sde;
  2370 address InstanceKlass::static_field_addr(int offset) {
  2371   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + (intptr_t)java_mirror());
  2375 const char* InstanceKlass::signature_name() const {
  2376   const char* src = (const char*) (name()->as_C_string());
  2377   const int src_length = (int)strlen(src);
  2378   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
  2379   int src_index = 0;
  2380   int dest_index = 0;
  2381   dest[dest_index++] = 'L';
  2382   while (src_index < src_length) {
  2383     dest[dest_index++] = src[src_index++];
  2385   dest[dest_index++] = ';';
  2386   dest[dest_index] = '\0';
  2387   return dest;
  2390 // different verisons of is_same_class_package
  2391 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2392   Klass* class1 = this;
  2393   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2394   Symbol* classname1 = class1->name();
  2396   if (class2->oop_is_objArray()) {
  2397     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2399   oop classloader2;
  2400   if (class2->oop_is_instance()) {
  2401     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2402   } else {
  2403     assert(class2->oop_is_typeArray(), "should be type array");
  2404     classloader2 = NULL;
  2406   Symbol* classname2 = class2->name();
  2408   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2409                                               classloader2, classname2);
  2412 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2413   Klass* class1 = this;
  2414   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2415   Symbol* classname1 = class1->name();
  2417   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2418                                               classloader2, classname2);
  2421 // return true if two classes are in the same package, classloader
  2422 // and classname information is enough to determine a class's package
  2423 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2424                                           oop class_loader2, Symbol* class_name2) {
  2425   if (class_loader1 != class_loader2) {
  2426     return false;
  2427   } else if (class_name1 == class_name2) {
  2428     return true;                // skip painful bytewise comparison
  2429   } else {
  2430     ResourceMark rm;
  2432     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2433     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2434     // Otherwise, we just compare jbyte values between the strings.
  2435     const jbyte *name1 = class_name1->base();
  2436     const jbyte *name2 = class_name2->base();
  2438     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2439     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2441     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2442       // One of the two doesn't have a package.  Only return true
  2443       // if the other one also doesn't have a package.
  2444       return last_slash1 == last_slash2;
  2445     } else {
  2446       // Skip over '['s
  2447       if (*name1 == '[') {
  2448         do {
  2449           name1++;
  2450         } while (*name1 == '[');
  2451         if (*name1 != 'L') {
  2452           // Something is terribly wrong.  Shouldn't be here.
  2453           return false;
  2456       if (*name2 == '[') {
  2457         do {
  2458           name2++;
  2459         } while (*name2 == '[');
  2460         if (*name2 != 'L') {
  2461           // Something is terribly wrong.  Shouldn't be here.
  2462           return false;
  2466       // Check that package part is identical
  2467       int length1 = last_slash1 - name1;
  2468       int length2 = last_slash2 - name2;
  2470       return UTF8::equal(name1, length1, name2, length2);
  2475 // Returns true iff super_method can be overridden by a method in targetclassname
  2476 // See JSL 3rd edition 8.4.6.1
  2477 // Assumes name-signature match
  2478 // "this" is InstanceKlass of super_method which must exist
  2479 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2480 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2481    // Private methods can not be overridden
  2482    if (super_method->is_private()) {
  2483      return false;
  2485    // If super method is accessible, then override
  2486    if ((super_method->is_protected()) ||
  2487        (super_method->is_public())) {
  2488      return true;
  2490    // Package-private methods are not inherited outside of package
  2491    assert(super_method->is_package_private(), "must be package private");
  2492    return(is_same_class_package(targetclassloader(), targetclassname));
  2495 /* defined for now in jvm.cpp, for historical reasons *--
  2496 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2497                                                      Symbol*& simple_name_result, TRAPS) {
  2498   ...
  2500 */
  2502 // tell if two classes have the same enclosing class (at package level)
  2503 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2504                                                 Klass* class2_oop, TRAPS) {
  2505   if (class2_oop == class1())                       return true;
  2506   if (!class2_oop->oop_is_instance())  return false;
  2507   instanceKlassHandle class2(THREAD, class2_oop);
  2509   // must be in same package before we try anything else
  2510   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2511     return false;
  2513   // As long as there is an outer1.getEnclosingClass,
  2514   // shift the search outward.
  2515   instanceKlassHandle outer1 = class1;
  2516   for (;;) {
  2517     // As we walk along, look for equalities between outer1 and class2.
  2518     // Eventually, the walks will terminate as outer1 stops
  2519     // at the top-level class around the original class.
  2520     bool ignore_inner_is_member;
  2521     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2522                                                     CHECK_false);
  2523     if (next == NULL)  break;
  2524     if (next == class2())  return true;
  2525     outer1 = instanceKlassHandle(THREAD, next);
  2528   // Now do the same for class2.
  2529   instanceKlassHandle outer2 = class2;
  2530   for (;;) {
  2531     bool ignore_inner_is_member;
  2532     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2533                                                     CHECK_false);
  2534     if (next == NULL)  break;
  2535     // Might as well check the new outer against all available values.
  2536     if (next == class1())  return true;
  2537     if (next == outer1())  return true;
  2538     outer2 = instanceKlassHandle(THREAD, next);
  2541   // If by this point we have not found an equality between the
  2542   // two classes, we know they are in separate package members.
  2543   return false;
  2547 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2548   jint access = access_flags().as_int();
  2550   // But check if it happens to be member class.
  2551   instanceKlassHandle ik(THREAD, this);
  2552   InnerClassesIterator iter(ik);
  2553   for (; !iter.done(); iter.next()) {
  2554     int ioff = iter.inner_class_info_index();
  2555     // Inner class attribute can be zero, skip it.
  2556     // Strange but true:  JVM spec. allows null inner class refs.
  2557     if (ioff == 0) continue;
  2559     // only look at classes that are already loaded
  2560     // since we are looking for the flags for our self.
  2561     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2562     if ((ik->name() == inner_name)) {
  2563       // This is really a member class.
  2564       access = iter.inner_access_flags();
  2565       break;
  2568   // Remember to strip ACC_SUPER bit
  2569   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2572 jint InstanceKlass::jvmti_class_status() const {
  2573   jint result = 0;
  2575   if (is_linked()) {
  2576     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2579   if (is_initialized()) {
  2580     assert(is_linked(), "Class status is not consistent");
  2581     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2583   if (is_in_error_state()) {
  2584     result |= JVMTI_CLASS_STATUS_ERROR;
  2586   return result;
  2589 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2590   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2591   int method_table_offset_in_words = ioe->offset()/wordSize;
  2592   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2593                        / itableOffsetEntry::size();
  2595   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2596     // If the interface isn't implemented by the receiver class,
  2597     // the VM should throw IncompatibleClassChangeError.
  2598     if (cnt >= nof_interfaces) {
  2599       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2602     Klass* ik = ioe->interface_klass();
  2603     if (ik == holder) break;
  2606   itableMethodEntry* ime = ioe->first_method_entry(this);
  2607   Method* m = ime[index].method();
  2608   if (m == NULL) {
  2609     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2611   return m;
  2614 // On-stack replacement stuff
  2615 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2616   // only one compilation can be active
  2617   NEEDS_CLEANUP
  2618   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2619   OsrList_lock->lock_without_safepoint_check();
  2620   assert(n->is_osr_method(), "wrong kind of nmethod");
  2621   n->set_osr_link(osr_nmethods_head());
  2622   set_osr_nmethods_head(n);
  2623   // Raise the highest osr level if necessary
  2624   if (TieredCompilation) {
  2625     Method* m = n->method();
  2626     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2628   // Remember to unlock again
  2629   OsrList_lock->unlock();
  2631   // Get rid of the osr methods for the same bci that have lower levels.
  2632   if (TieredCompilation) {
  2633     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2634       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2635       if (inv != NULL && inv->is_in_use()) {
  2636         inv->make_not_entrant();
  2643 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2644   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2645   OsrList_lock->lock_without_safepoint_check();
  2646   assert(n->is_osr_method(), "wrong kind of nmethod");
  2647   nmethod* last = NULL;
  2648   nmethod* cur  = osr_nmethods_head();
  2649   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2650   Method* m = n->method();
  2651   // Search for match
  2652   while(cur != NULL && cur != n) {
  2653     if (TieredCompilation) {
  2654       // Find max level before n
  2655       max_level = MAX2(max_level, cur->comp_level());
  2657     last = cur;
  2658     cur = cur->osr_link();
  2660   nmethod* next = NULL;
  2661   if (cur == n) {
  2662     next = cur->osr_link();
  2663     if (last == NULL) {
  2664       // Remove first element
  2665       set_osr_nmethods_head(next);
  2666     } else {
  2667       last->set_osr_link(next);
  2670   n->set_osr_link(NULL);
  2671   if (TieredCompilation) {
  2672     cur = next;
  2673     while (cur != NULL) {
  2674       // Find max level after n
  2675       max_level = MAX2(max_level, cur->comp_level());
  2676       cur = cur->osr_link();
  2678     m->set_highest_osr_comp_level(max_level);
  2680   // Remember to unlock again
  2681   OsrList_lock->unlock();
  2684 nmethod* InstanceKlass::lookup_osr_nmethod(Method* const m, int bci, int comp_level, bool match_level) const {
  2685   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2686   OsrList_lock->lock_without_safepoint_check();
  2687   nmethod* osr = osr_nmethods_head();
  2688   nmethod* best = NULL;
  2689   while (osr != NULL) {
  2690     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2691     // There can be a time when a c1 osr method exists but we are waiting
  2692     // for a c2 version. When c2 completes its osr nmethod we will trash
  2693     // the c1 version and only be able to find the c2 version. However
  2694     // while we overflow in the c1 code at back branches we don't want to
  2695     // try and switch to the same code as we are already running
  2697     if (osr->method() == m &&
  2698         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2699       if (match_level) {
  2700         if (osr->comp_level() == comp_level) {
  2701           // Found a match - return it.
  2702           OsrList_lock->unlock();
  2703           return osr;
  2705       } else {
  2706         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2707           if (osr->comp_level() == CompLevel_highest_tier) {
  2708             // Found the best possible - return it.
  2709             OsrList_lock->unlock();
  2710             return osr;
  2712           best = osr;
  2716     osr = osr->osr_link();
  2718   OsrList_lock->unlock();
  2719   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2720     return best;
  2722   return NULL;
  2725 // -----------------------------------------------------------------------------------------------------
  2726 // Printing
  2728 #ifndef PRODUCT
  2730 #define BULLET  " - "
  2732 static const char* state_names[] = {
  2733   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  2734 };
  2736 void InstanceKlass::print_on(outputStream* st) const {
  2737   assert(is_klass(), "must be klass");
  2738   Klass::print_on(st);
  2740   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  2741   st->print(BULLET"klass size:        %d", size());                               st->cr();
  2742   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  2743   st->print(BULLET"state:             "); st->print_cr(state_names[_init_state]);
  2744   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  2745   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  2746   st->print(BULLET"sub:               ");
  2747   Klass* sub = subklass();
  2748   int n;
  2749   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  2750     if (n < MaxSubklassPrintSize) {
  2751       sub->print_value_on(st);
  2752       st->print("   ");
  2755   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  2756   st->cr();
  2758   if (is_interface()) {
  2759     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  2760     if (nof_implementors() == 1) {
  2761       st->print_cr(BULLET"implementor:    ");
  2762       st->print("   ");
  2763       implementor()->print_value_on(st);
  2764       st->cr();
  2768   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  2769   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  2770   if (Verbose) {
  2771     Array<Method*>* method_array = methods();
  2772     for(int i = 0; i < method_array->length(); i++) {
  2773       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  2776   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);       st->cr();
  2777   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  2778   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  2779   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  2780   if (class_loader_data() != NULL) {
  2781     st->print(BULLET"class loader data:  ");
  2782     class_loader_data()->print_value_on(st);
  2783     st->cr();
  2785   st->print(BULLET"protection domain: "); ((InstanceKlass*)this)->protection_domain()->print_value_on(st); st->cr();
  2786   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  2787   st->print(BULLET"signers:           "); signers()->print_value_on(st);               st->cr();
  2788   st->print(BULLET"init_lock:         "); ((oop)init_lock())->print_value_on(st);             st->cr();
  2789   if (source_file_name() != NULL) {
  2790     st->print(BULLET"source file:       ");
  2791     source_file_name()->print_value_on(st);
  2792     st->cr();
  2794   if (source_debug_extension() != NULL) {
  2795     st->print(BULLET"source debug extension:       ");
  2796     st->print("%s", source_debug_extension());
  2797     st->cr();
  2799   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  2800   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  2801   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  2802   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  2804     ResourceMark rm;
  2805     // PreviousVersionInfo objects returned via PreviousVersionWalker
  2806     // contain a GrowableArray of handles. We have to clean up the
  2807     // GrowableArray _after_ the PreviousVersionWalker destructor
  2808     // has destroyed the handles.
  2810       bool have_pv = false;
  2811       PreviousVersionWalker pvw((InstanceKlass*)this);
  2812       for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
  2813            pv_info != NULL; pv_info = pvw.next_previous_version()) {
  2814         if (!have_pv)
  2815           st->print(BULLET"previous version:  ");
  2816         have_pv = true;
  2817         pv_info->prev_constant_pool_handle()()->print_value_on(st);
  2819       if (have_pv)  st->cr();
  2820     } // pvw is cleaned up
  2821   } // rm is cleaned up
  2823   if (generic_signature() != NULL) {
  2824     st->print(BULLET"generic signature: ");
  2825     generic_signature()->print_value_on(st);
  2826     st->cr();
  2828   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  2829   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  2830   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  2831   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  2832   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  2833   FieldPrinter print_static_field(st);
  2834   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  2835   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  2836   FieldPrinter print_nonstatic_field(st);
  2837   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  2839   st->print(BULLET"non-static oop maps: ");
  2840   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  2841   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  2842   while (map < end_map) {
  2843     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  2844     map++;
  2846   st->cr();
  2849 #endif //PRODUCT
  2851 void InstanceKlass::print_value_on(outputStream* st) const {
  2852   assert(is_klass(), "must be klass");
  2853   name()->print_value_on(st);
  2856 #ifndef PRODUCT
  2858 void FieldPrinter::do_field(fieldDescriptor* fd) {
  2859   _st->print(BULLET);
  2860    if (_obj == NULL) {
  2861      fd->print_on(_st);
  2862      _st->cr();
  2863    } else {
  2864      fd->print_on_for(_st, _obj);
  2865      _st->cr();
  2870 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  2871   Klass::oop_print_on(obj, st);
  2873   if (this == SystemDictionary::String_klass()) {
  2874     typeArrayOop value  = java_lang_String::value(obj);
  2875     juint        offset = java_lang_String::offset(obj);
  2876     juint        length = java_lang_String::length(obj);
  2877     if (value != NULL &&
  2878         value->is_typeArray() &&
  2879         offset          <= (juint) value->length() &&
  2880         offset + length <= (juint) value->length()) {
  2881       st->print(BULLET"string: ");
  2882       Handle h_obj(obj);
  2883       java_lang_String::print(h_obj, st);
  2884       st->cr();
  2885       if (!WizardMode)  return;  // that is enough
  2889   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  2890   FieldPrinter print_field(st, obj);
  2891   do_nonstatic_fields(&print_field);
  2893   if (this == SystemDictionary::Class_klass()) {
  2894     st->print(BULLET"signature: ");
  2895     java_lang_Class::print_signature(obj, st);
  2896     st->cr();
  2897     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  2898     st->print(BULLET"fake entry for mirror: ");
  2899     mirrored_klass->print_value_on_maybe_null(st);
  2900     st->cr();
  2901     Klass* array_klass = java_lang_Class::array_klass(obj);
  2902     st->print(BULLET"fake entry for array: ");
  2903     array_klass->print_value_on_maybe_null(st);
  2904     st->cr();
  2905     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  2906     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  2907     Klass* real_klass = java_lang_Class::as_Klass(obj);
  2908     if (real_klass != NULL && real_klass->oop_is_instance()) {
  2909       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  2911   } else if (this == SystemDictionary::MethodType_klass()) {
  2912     st->print(BULLET"signature: ");
  2913     java_lang_invoke_MethodType::print_signature(obj, st);
  2914     st->cr();
  2918 #endif //PRODUCT
  2920 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  2921   st->print("a ");
  2922   name()->print_value_on(st);
  2923   obj->print_address_on(st);
  2924   if (this == SystemDictionary::String_klass()
  2925       && java_lang_String::value(obj) != NULL) {
  2926     ResourceMark rm;
  2927     int len = java_lang_String::length(obj);
  2928     int plen = (len < 24 ? len : 12);
  2929     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  2930     st->print(" = \"%s\"", str);
  2931     if (len > plen)
  2932       st->print("...[%d]", len);
  2933   } else if (this == SystemDictionary::Class_klass()) {
  2934     Klass* k = java_lang_Class::as_Klass(obj);
  2935     st->print(" = ");
  2936     if (k != NULL) {
  2937       k->print_value_on(st);
  2938     } else {
  2939       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  2940       st->print("%s", tname ? tname : "type?");
  2942   } else if (this == SystemDictionary::MethodType_klass()) {
  2943     st->print(" = ");
  2944     java_lang_invoke_MethodType::print_signature(obj, st);
  2945   } else if (java_lang_boxing_object::is_instance(obj)) {
  2946     st->print(" = ");
  2947     java_lang_boxing_object::print(obj, st);
  2948   } else if (this == SystemDictionary::LambdaForm_klass()) {
  2949     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  2950     if (vmentry != NULL) {
  2951       st->print(" => ");
  2952       vmentry->print_value_on(st);
  2954   } else if (this == SystemDictionary::MemberName_klass()) {
  2955     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  2956     if (vmtarget != NULL) {
  2957       st->print(" = ");
  2958       vmtarget->print_value_on(st);
  2959     } else {
  2960       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  2961       st->print(".");
  2962       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  2967 const char* InstanceKlass::internal_name() const {
  2968   return external_name();
  2971 #if INCLUDE_SERVICES
  2972 // Size Statistics
  2973 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  2974   Klass::collect_statistics(sz);
  2976   sz->_inst_size  = HeapWordSize * size_helper();
  2977   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  2978   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  2979   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  2980         ((is_interface() || is_anonymous()) ?
  2981          align_object_offset(nonstatic_oop_map_size()) :
  2982          nonstatic_oop_map_size());
  2984   int n = 0;
  2985   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  2986   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  2987   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  2988   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  2989   n += (sz->_signers_bytes               = sz->count_array(signers()));
  2990   n += (sz->_fields_bytes                = sz->count_array(fields()));
  2991   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  2992   sz->_ro_bytes += n;
  2994   const ConstantPool* cp = constants();
  2995   if (cp) {
  2996     cp->collect_statistics(sz);
  2999   const Annotations* anno = annotations();
  3000   if (anno) {
  3001     anno->collect_statistics(sz);
  3004   const Array<Method*>* methods_array = methods();
  3005   if (methods()) {
  3006     for (int i = 0; i < methods_array->length(); i++) {
  3007       Method* method = methods_array->at(i);
  3008       if (method) {
  3009         sz->_method_count ++;
  3010         method->collect_statistics(sz);
  3015 #endif // INCLUDE_SERVICES
  3017 // Verification
  3019 class VerifyFieldClosure: public OopClosure {
  3020  protected:
  3021   template <class T> void do_oop_work(T* p) {
  3022     oop obj = oopDesc::load_decode_heap_oop(p);
  3023     if (!obj->is_oop_or_null()) {
  3024       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  3025       Universe::print();
  3026       guarantee(false, "boom");
  3029  public:
  3030   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  3031   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  3032 };
  3034 void InstanceKlass::verify_on(outputStream* st) {
  3035   Klass::verify_on(st);
  3036   Thread *thread = Thread::current();
  3038 #ifndef PRODUCT
  3039   // Avoid redundant verifies
  3040   if (_verify_count == Universe::verify_count()) return;
  3041   _verify_count = Universe::verify_count();
  3042 #endif
  3043   // Verify that klass is present in SystemDictionary
  3044   if (is_loaded() && !is_anonymous()) {
  3045     Symbol* h_name = name();
  3046     SystemDictionary::verify_obj_klass_present(h_name, class_loader_data());
  3049   // Verify static fields
  3050   VerifyFieldClosure blk;
  3052   // Verify vtables
  3053   if (is_linked()) {
  3054     ResourceMark rm(thread);
  3055     // $$$ This used to be done only for m/s collections.  Doing it
  3056     // always seemed a valid generalization.  (DLD -- 6/00)
  3057     vtable()->verify(st);
  3060   // Verify first subklass
  3061   if (subklass_oop() != NULL) {
  3062     guarantee(subklass_oop()->is_metadata(), "should be in metaspace");
  3063     guarantee(subklass_oop()->is_klass(), "should be klass");
  3066   // Verify siblings
  3067   Klass* super = this->super();
  3068   Klass* sib = next_sibling();
  3069   if (sib != NULL) {
  3070     if (sib == this) {
  3071       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3074     guarantee(sib->is_metadata(), "should be in metaspace");
  3075     guarantee(sib->is_klass(), "should be klass");
  3076     guarantee(sib->super() == super, "siblings should have same superklass");
  3079   // Verify implementor fields
  3080   Klass* im = implementor();
  3081   if (im != NULL) {
  3082     guarantee(is_interface(), "only interfaces should have implementor set");
  3083     guarantee(im->is_klass(), "should be klass");
  3084     guarantee(!im->is_interface() || im == this,
  3085       "implementors cannot be interfaces");
  3088   // Verify local interfaces
  3089   if (local_interfaces()) {
  3090     Array<Klass*>* local_interfaces = this->local_interfaces();
  3091     for (int j = 0; j < local_interfaces->length(); j++) {
  3092       Klass* e = local_interfaces->at(j);
  3093       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3097   // Verify transitive interfaces
  3098   if (transitive_interfaces() != NULL) {
  3099     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3100     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3101       Klass* e = transitive_interfaces->at(j);
  3102       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3106   // Verify methods
  3107   if (methods() != NULL) {
  3108     Array<Method*>* methods = this->methods();
  3109     for (int j = 0; j < methods->length(); j++) {
  3110       guarantee(methods->at(j)->is_metadata(), "should be in metaspace");
  3111       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3113     for (int j = 0; j < methods->length() - 1; j++) {
  3114       Method* m1 = methods->at(j);
  3115       Method* m2 = methods->at(j + 1);
  3116       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3120   // Verify method ordering
  3121   if (method_ordering() != NULL) {
  3122     Array<int>* method_ordering = this->method_ordering();
  3123     int length = method_ordering->length();
  3124     if (JvmtiExport::can_maintain_original_method_order() ||
  3125         (UseSharedSpaces && length != 0)) {
  3126       guarantee(length == methods()->length(), "invalid method ordering length");
  3127       jlong sum = 0;
  3128       for (int j = 0; j < length; j++) {
  3129         int original_index = method_ordering->at(j);
  3130         guarantee(original_index >= 0, "invalid method ordering index");
  3131         guarantee(original_index < length, "invalid method ordering index");
  3132         sum += original_index;
  3134       // Verify sum of indices 0,1,...,length-1
  3135       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3136     } else {
  3137       guarantee(length == 0, "invalid method ordering length");
  3141   // Verify JNI static field identifiers
  3142   if (jni_ids() != NULL) {
  3143     jni_ids()->verify(this);
  3146   // Verify other fields
  3147   if (array_klasses() != NULL) {
  3148     guarantee(array_klasses()->is_metadata(), "should be in metaspace");
  3149     guarantee(array_klasses()->is_klass(), "should be klass");
  3151   if (constants() != NULL) {
  3152     guarantee(constants()->is_metadata(), "should be in metaspace");
  3153     guarantee(constants()->is_constantPool(), "should be constant pool");
  3155   if (protection_domain() != NULL) {
  3156     guarantee(protection_domain()->is_oop(), "should be oop");
  3158   const Klass* host = host_klass();
  3159   if (host != NULL) {
  3160     guarantee(host->is_metadata(), "should be in metaspace");
  3161     guarantee(host->is_klass(), "should be klass");
  3163   if (signers() != NULL) {
  3164     guarantee(signers()->is_objArray(), "should be obj array");
  3168 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3169   Klass::oop_verify_on(obj, st);
  3170   VerifyFieldClosure blk;
  3171   obj->oop_iterate_no_header(&blk);
  3175 // JNIid class for jfieldIDs only
  3176 // Note to reviewers:
  3177 // These JNI functions are just moved over to column 1 and not changed
  3178 // in the compressed oops workspace.
  3179 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3180   _holder = holder;
  3181   _offset = offset;
  3182   _next = next;
  3183   debug_only(_is_static_field_id = false;)
  3187 JNIid* JNIid::find(int offset) {
  3188   JNIid* current = this;
  3189   while (current != NULL) {
  3190     if (current->offset() == offset) return current;
  3191     current = current->next();
  3193   return NULL;
  3196 void JNIid::deallocate(JNIid* current) {
  3197   while (current != NULL) {
  3198     JNIid* next = current->next();
  3199     delete current;
  3200     current = next;
  3205 void JNIid::verify(Klass* holder) {
  3206   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3207   int end_field_offset;
  3208   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3210   JNIid* current = this;
  3211   while (current != NULL) {
  3212     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3213 #ifdef ASSERT
  3214     int o = current->offset();
  3215     if (current->is_static_field_id()) {
  3216       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3218 #endif
  3219     current = current->next();
  3224 #ifdef ASSERT
  3225 void InstanceKlass::set_init_state(ClassState state) {
  3226   bool good_state = is_shared() ? (_init_state <= state)
  3227                                                : (_init_state < state);
  3228   assert(good_state || state == allocated, "illegal state transition");
  3229   _init_state = (u1)state;
  3231 #endif
  3234 // RedefineClasses() support for previous versions:
  3236 // Purge previous versions
  3237 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3238   if (ik->previous_versions() != NULL) {
  3239     // This klass has previous versions so see what we can cleanup
  3240     // while it is safe to do so.
  3242     int deleted_count = 0;    // leave debugging breadcrumbs
  3243     int live_count = 0;
  3244     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3245                        ClassLoaderData::the_null_class_loader_data() :
  3246                        ik->class_loader_data();
  3248     // RC_TRACE macro has an embedded ResourceMark
  3249     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3250       ik->external_name(), ik->previous_versions()->length()));
  3252     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3253       // check the previous versions array
  3254       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3255       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3256       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3258       ConstantPool* pvcp = cp_ref;
  3259       if (!pvcp->on_stack()) {
  3260         // If the constant pool isn't on stack, none of the methods
  3261         // are executing.  Delete all the methods, the constant pool and
  3262         // and this previous version node.
  3263         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3264         if (method_refs != NULL) {
  3265           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3266             Method* method = method_refs->at(j);
  3267             assert(method != NULL, "method ref was unexpectedly cleared");
  3268             method_refs->remove_at(j);
  3269             // method will be freed with associated class.
  3272         // Remove the constant pool
  3273         delete pv_node;
  3274         // Since we are traversing the array backwards, we don't have to
  3275         // do anything special with the index.
  3276         ik->previous_versions()->remove_at(i);
  3277         deleted_count++;
  3278         continue;
  3279       } else {
  3280         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3281         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3282         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3283         live_count++;
  3286       // At least one method is live in this previous version, clean out
  3287       // the others or mark them as obsolete.
  3288       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3289       if (method_refs != NULL) {
  3290         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3291           method_refs->length()));
  3292         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3293           Method* method = method_refs->at(j);
  3294           assert(method != NULL, "method ref was unexpectedly cleared");
  3296           // Remove the emcp method if it's not executing
  3297           // If it's been made obsolete by a redefinition of a non-emcp
  3298           // method, mark it as obsolete but leave it to clean up later.
  3299           if (!method->on_stack()) {
  3300             method_refs->remove_at(j);
  3301           } else if (emcp_method_count == 0) {
  3302             method->set_is_obsolete();
  3303           } else {
  3304             // RC_TRACE macro has an embedded ResourceMark
  3305             RC_TRACE(0x00000200,
  3306               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3307               method->name()->as_C_string(),
  3308               method->signature()->as_C_string(), j, i));
  3313     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3314     RC_TRACE(0x00000200,
  3315       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3316       deleted_count));
  3320 // External interface for use during class unloading.
  3321 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3322   // Call with >0 emcp methods since they are not currently being redefined.
  3323   purge_previous_versions_internal(ik, 1);
  3327 // Potentially add an information node that contains pointers to the
  3328 // interesting parts of the previous version of the_class.
  3329 // This is also where we clean out any unused references.
  3330 // Note that while we delete nodes from the _previous_versions
  3331 // array, we never delete the array itself until the klass is
  3332 // unloaded. The has_been_redefined() query depends on that fact.
  3333 //
  3334 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3335        BitMap* emcp_methods, int emcp_method_count) {
  3336   assert(Thread::current()->is_VM_thread(),
  3337          "only VMThread can add previous versions");
  3339   if (_previous_versions == NULL) {
  3340     // This is the first previous version so make some space.
  3341     // Start with 2 elements under the assumption that the class
  3342     // won't be redefined much.
  3343     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3344                             GrowableArray<PreviousVersionNode *>(2, true);
  3347   ConstantPool* cp_ref = ikh->constants();
  3349   // RC_TRACE macro has an embedded ResourceMark
  3350   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3351                         "on_stack=%d",
  3352     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3353     cp_ref->on_stack()));
  3355   // If the constant pool for this previous version of the class
  3356   // is not marked as being on the stack, then none of the methods
  3357   // in this previous version of the class are on the stack so
  3358   // we don't need to create a new PreviousVersionNode. However,
  3359   // we still need to examine older previous versions below.
  3360   Array<Method*>* old_methods = ikh->methods();
  3362   if (cp_ref->on_stack()) {
  3363   PreviousVersionNode * pv_node = NULL;
  3364   if (emcp_method_count == 0) {
  3365       // non-shared ConstantPool gets a reference
  3366       pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), NULL);
  3367     RC_TRACE(0x00000400,
  3368         ("add: all methods are obsolete; flushing any EMCP refs"));
  3369   } else {
  3370     int local_count = 0;
  3371       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3372         GrowableArray<Method*>(emcp_method_count, true);
  3373     for (int i = 0; i < old_methods->length(); i++) {
  3374       if (emcp_methods->at(i)) {
  3375           // this old method is EMCP. Save it only if it's on the stack
  3376           Method* old_method = old_methods->at(i);
  3377           if (old_method->on_stack()) {
  3378             method_refs->append(old_method);
  3380         if (++local_count >= emcp_method_count) {
  3381           // no more EMCP methods so bail out now
  3382           break;
  3386       // non-shared ConstantPool gets a reference
  3387       pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), method_refs);
  3389     // append new previous version.
  3390   _previous_versions->append(pv_node);
  3393   // Since the caller is the VMThread and we are at a safepoint, this
  3394   // is a good time to clear out unused references.
  3396   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3397     _previous_versions->length()));
  3399   // Purge previous versions not executing on the stack
  3400   purge_previous_versions_internal(this, emcp_method_count);
  3402   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3404   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3405       _previous_versions->length() > 0) {
  3406     // We have a mix of obsolete and EMCP methods so we have to
  3407     // clear out any matching EMCP method entries the hard way.
  3408     int local_count = 0;
  3409     for (int i = 0; i < old_methods->length(); i++) {
  3410       if (!emcp_methods->at(i)) {
  3411         // only obsolete methods are interesting
  3412         Method* old_method = old_methods->at(i);
  3413         Symbol* m_name = old_method->name();
  3414         Symbol* m_signature = old_method->signature();
  3416         // we might not have added the last entry
  3417         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3418           // check the previous versions array for non executing obsolete methods
  3419           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3421           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3422           if (method_refs == NULL) {
  3423             // We have run into a PreviousVersion generation where
  3424             // all methods were made obsolete during that generation's
  3425             // RedefineClasses() operation. At the time of that
  3426             // operation, all EMCP methods were flushed so we don't
  3427             // have to go back any further.
  3428             //
  3429             // A NULL method_refs is different than an empty method_refs.
  3430             // We cannot infer any optimizations about older generations
  3431             // from an empty method_refs for the current generation.
  3432             break;
  3435           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3436             Method* method = method_refs->at(k);
  3438             if (!method->is_obsolete() &&
  3439                 method->name() == m_name &&
  3440                 method->signature() == m_signature) {
  3441               // The current RedefineClasses() call has made all EMCP
  3442               // versions of this method obsolete so mark it as obsolete
  3443               // and remove the reference.
  3444               RC_TRACE(0x00000400,
  3445                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3446                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3448               method->set_is_obsolete();
  3449               // Leave obsolete methods on the previous version list to
  3450               // clean up later.
  3451               break;
  3455           // The previous loop may not find a matching EMCP method, but
  3456           // that doesn't mean that we can optimize and not go any
  3457           // further back in the PreviousVersion generations. The EMCP
  3458           // method for this generation could have already been deleted,
  3459           // but there still may be an older EMCP method that has not
  3460           // been deleted.
  3463         if (++local_count >= obsolete_method_count) {
  3464           // no more obsolete methods so bail out now
  3465           break;
  3470 } // end add_previous_version()
  3473 // Determine if InstanceKlass has a previous version.
  3474 bool InstanceKlass::has_previous_version() const {
  3475   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3476 } // end has_previous_version()
  3479 Method* InstanceKlass::method_with_idnum(int idnum) {
  3480   Method* m = NULL;
  3481   if (idnum < methods()->length()) {
  3482     m = methods()->at(idnum);
  3484   if (m == NULL || m->method_idnum() != idnum) {
  3485     for (int index = 0; index < methods()->length(); ++index) {
  3486       m = methods()->at(index);
  3487       if (m->method_idnum() == idnum) {
  3488         return m;
  3492   return m;
  3496 // Construct a PreviousVersionNode entry for the array hung off
  3497 // the InstanceKlass.
  3498 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3499   bool prev_cp_is_weak, GrowableArray<Method*>* prev_EMCP_methods) {
  3501   _prev_constant_pool = prev_constant_pool;
  3502   _prev_cp_is_weak = prev_cp_is_weak;
  3503   _prev_EMCP_methods = prev_EMCP_methods;
  3507 // Destroy a PreviousVersionNode
  3508 PreviousVersionNode::~PreviousVersionNode() {
  3509   if (_prev_constant_pool != NULL) {
  3510     _prev_constant_pool = NULL;
  3513   if (_prev_EMCP_methods != NULL) {
  3514     delete _prev_EMCP_methods;
  3519 // Construct a PreviousVersionInfo entry
  3520 PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) {
  3521   _prev_constant_pool_handle = constantPoolHandle();  // NULL handle
  3522   _prev_EMCP_method_handles = NULL;
  3524   ConstantPool* cp = pv_node->prev_constant_pool();
  3525   assert(cp != NULL, "constant pool ref was unexpectedly cleared");
  3526   if (cp == NULL) {
  3527     return;  // robustness
  3530   // make the ConstantPool* safe to return
  3531   _prev_constant_pool_handle = constantPoolHandle(cp);
  3533   GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3534   if (method_refs == NULL) {
  3535     // the InstanceKlass did not have any EMCP methods
  3536     return;
  3539   _prev_EMCP_method_handles = new GrowableArray<methodHandle>(10);
  3541   int n_methods = method_refs->length();
  3542   for (int i = 0; i < n_methods; i++) {
  3543     Method* method = method_refs->at(i);
  3544     assert (method != NULL, "method has been cleared");
  3545     if (method == NULL) {
  3546       continue;  // robustness
  3548     // make the Method* safe to return
  3549     _prev_EMCP_method_handles->append(methodHandle(method));
  3554 // Destroy a PreviousVersionInfo
  3555 PreviousVersionInfo::~PreviousVersionInfo() {
  3556   // Since _prev_EMCP_method_handles is not C-heap allocated, we
  3557   // don't have to delete it.
  3561 // Construct a helper for walking the previous versions array
  3562 PreviousVersionWalker::PreviousVersionWalker(InstanceKlass *ik) {
  3563   _previous_versions = ik->previous_versions();
  3564   _current_index = 0;
  3565   // _hm needs no initialization
  3566   _current_p = NULL;
  3570 // Destroy a PreviousVersionWalker
  3571 PreviousVersionWalker::~PreviousVersionWalker() {
  3572   // Delete the current info just in case the caller didn't walk to
  3573   // the end of the previous versions list. No harm if _current_p is
  3574   // already NULL.
  3575   delete _current_p;
  3577   // When _hm is destroyed, all the Handles returned in
  3578   // PreviousVersionInfo objects will be destroyed.
  3579   // Also, after this destructor is finished it will be
  3580   // safe to delete the GrowableArray allocated in the
  3581   // PreviousVersionInfo objects.
  3585 // Return the interesting information for the next previous version
  3586 // of the klass. Returns NULL if there are no more previous versions.
  3587 PreviousVersionInfo* PreviousVersionWalker::next_previous_version() {
  3588   if (_previous_versions == NULL) {
  3589     // no previous versions so nothing to return
  3590     return NULL;
  3593   delete _current_p;  // cleanup the previous info for the caller
  3594   _current_p = NULL;  // reset to NULL so we don't delete same object twice
  3596   int length = _previous_versions->length();
  3598   while (_current_index < length) {
  3599     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3600     PreviousVersionInfo * pv_info = new (ResourceObj::C_HEAP, mtClass)
  3601                                           PreviousVersionInfo(pv_node);
  3603     constantPoolHandle cp_h = pv_info->prev_constant_pool_handle();
  3604     assert (!cp_h.is_null(), "null cp found in previous version");
  3606     // The caller will need to delete pv_info when they are done with it.
  3607     _current_p = pv_info;
  3608     return pv_info;
  3611   // all of the underlying nodes' info has been deleted
  3612   return NULL;
  3613 } // end next_previous_version()

mercurial