src/share/vm/oops/instanceKlass.cpp

Thu, 20 Dec 2012 10:22:19 +0100

author
stefank
date
Thu, 20 Dec 2012 10:22:19 +0100
changeset 4393
35431a769282
parent 4299
f34d701e952e
child 4395
cc6a617fffd2
permissions
-rw-r--r--

8004823: Add VM support for type annotation reflection
Reviewed-by: dholmes, coleenp
Contributed-by: joel.franck@oracle.com

     1 /*
     2  * Copyright (c) 1997, 2012, 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/metadataFactory.hpp"
    38 #include "memory/oopFactory.hpp"
    39 #include "oops/fieldStreams.hpp"
    40 #include "oops/instanceClassLoaderKlass.hpp"
    41 #include "oops/instanceKlass.hpp"
    42 #include "oops/instanceMirrorKlass.hpp"
    43 #include "oops/instanceOop.hpp"
    44 #include "oops/klass.inline.hpp"
    45 #include "oops/method.hpp"
    46 #include "oops/oop.inline.hpp"
    47 #include "oops/symbol.hpp"
    48 #include "prims/jvmtiExport.hpp"
    49 #include "prims/jvmtiRedefineClassesTrace.hpp"
    50 #include "runtime/fieldDescriptor.hpp"
    51 #include "runtime/handles.inline.hpp"
    52 #include "runtime/javaCalls.hpp"
    53 #include "runtime/mutexLocker.hpp"
    54 #include "runtime/thread.inline.hpp"
    55 #include "services/threadService.hpp"
    56 #include "utilities/dtrace.hpp"
    57 #ifndef SERIALGC
    58 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    59 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    60 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    61 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    62 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
    63 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    64 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    65 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    66 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    67 #include "oops/oop.pcgc.inline.hpp"
    68 #endif
    69 #ifdef COMPILER1
    70 #include "c1/c1_Compiler.hpp"
    71 #endif
    73 #ifdef DTRACE_ENABLED
    75 #ifndef USDT2
    77 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    78   char*, intptr_t, oop, intptr_t);
    79 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    80   char*, intptr_t, oop, intptr_t, int);
    81 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    82   char*, intptr_t, oop, intptr_t, int);
    83 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    84   char*, intptr_t, oop, intptr_t, int);
    85 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    86   char*, intptr_t, oop, intptr_t, int);
    87 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    88   char*, intptr_t, oop, intptr_t, int);
    89 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
    90   char*, intptr_t, oop, intptr_t, int);
    91 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
    92   char*, intptr_t, oop, intptr_t, int);
    94 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
    95   {                                                              \
    96     char* data = NULL;                                           \
    97     int len = 0;                                                 \
    98     Symbol* name = (clss)->name();                               \
    99     if (name != NULL) {                                          \
   100       data = (char*)name->bytes();                               \
   101       len = name->utf8_length();                                 \
   102     }                                                            \
   103     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   104       data, len, (clss)->class_loader(), thread_type);           \
   105   }
   107 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   108   {                                                              \
   109     char* data = NULL;                                           \
   110     int len = 0;                                                 \
   111     Symbol* name = (clss)->name();                               \
   112     if (name != NULL) {                                          \
   113       data = (char*)name->bytes();                               \
   114       len = name->utf8_length();                                 \
   115     }                                                            \
   116     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   117       data, len, (clss)->class_loader(), thread_type, wait);     \
   118   }
   119 #else /* USDT2 */
   121 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   122 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   123 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   124 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   125 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   126 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   127 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   128 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   129 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   130   {                                                              \
   131     char* data = NULL;                                           \
   132     int len = 0;                                                 \
   133     Symbol* name = (clss)->name();                               \
   134     if (name != NULL) {                                          \
   135       data = (char*)name->bytes();                               \
   136       len = name->utf8_length();                                 \
   137     }                                                            \
   138     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   139       data, len, (clss)->class_loader(), thread_type);           \
   140   }
   142 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   143   {                                                              \
   144     char* data = NULL;                                           \
   145     int len = 0;                                                 \
   146     Symbol* name = (clss)->name();                               \
   147     if (name != NULL) {                                          \
   148       data = (char*)name->bytes();                               \
   149       len = name->utf8_length();                                 \
   150     }                                                            \
   151     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   152       data, len, (clss)->class_loader(), thread_type, wait);     \
   153   }
   154 #endif /* USDT2 */
   156 #else //  ndef DTRACE_ENABLED
   158 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   159 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   161 #endif //  ndef DTRACE_ENABLED
   163 Klass* InstanceKlass::allocate_instance_klass(ClassLoaderData* loader_data,
   164                                                 int vtable_len,
   165                                                 int itable_len,
   166                                                 int static_field_size,
   167                                                 int nonstatic_oop_map_size,
   168                                                 ReferenceType rt,
   169                                                 AccessFlags access_flags,
   170                                                 Symbol* name,
   171                                               Klass* super_klass,
   172                                                 KlassHandle host_klass,
   173                                                 TRAPS) {
   175   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   176                                  access_flags.is_interface(),
   177                                  !host_klass.is_null());
   179   // Allocation
   180   InstanceKlass* ik;
   181   if (rt == REF_NONE) {
   182     if (name == vmSymbols::java_lang_Class()) {
   183       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   184         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   185         access_flags, !host_klass.is_null());
   186     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   187           (SystemDictionary::ClassLoader_klass_loaded() &&
   188           super_klass != NULL &&
   189           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   190       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   191         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   192         access_flags, !host_klass.is_null());
   193     } else {
   194       // normal class
   195       ik = new (loader_data, size, THREAD) InstanceKlass(
   196         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   197         access_flags, !host_klass.is_null());
   198     }
   199   } else {
   200     // reference klass
   201     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   202         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   203         access_flags, !host_klass.is_null());
   204   }
   206   return ik;
   207 }
   209 InstanceKlass::InstanceKlass(int vtable_len,
   210                              int itable_len,
   211                              int static_field_size,
   212                              int nonstatic_oop_map_size,
   213                              ReferenceType rt,
   214                              AccessFlags access_flags,
   215                              bool is_anonymous) {
   216   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   218   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   219                                  access_flags.is_interface(), is_anonymous);
   221   // The sizes of these these three variables are used for determining the
   222   // size of the instanceKlassOop. It is critical that these are set to the right
   223   // sizes before the first GC, i.e., when we allocate the mirror.
   224   this->set_vtable_length(vtable_len);
   225   this->set_itable_length(itable_len);
   226   this->set_static_field_size(static_field_size);
   227   this->set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   228   this->set_access_flags(access_flags);
   229   this->set_is_anonymous(is_anonymous);
   230   assert(this->size() == size, "wrong size for object");
   232   this->set_array_klasses(NULL);
   233   this->set_methods(NULL);
   234   this->set_method_ordering(NULL);
   235   this->set_local_interfaces(NULL);
   236   this->set_transitive_interfaces(NULL);
   237   this->init_implementor();
   238   this->set_fields(NULL, 0);
   239   this->set_constants(NULL);
   240   this->set_class_loader_data(NULL);
   241   this->set_protection_domain(NULL);
   242   this->set_signers(NULL);
   243   this->set_source_file_name(NULL);
   244   this->set_source_debug_extension(NULL, 0);
   245   this->set_array_name(NULL);
   246   this->set_inner_classes(NULL);
   247   this->set_static_oop_field_count(0);
   248   this->set_nonstatic_field_size(0);
   249   this->set_is_marked_dependent(false);
   250   this->set_init_state(InstanceKlass::allocated);
   251   this->set_init_thread(NULL);
   252   this->set_init_lock(NULL);
   253   this->set_reference_type(rt);
   254   this->set_oop_map_cache(NULL);
   255   this->set_jni_ids(NULL);
   256   this->set_osr_nmethods_head(NULL);
   257   this->set_breakpoints(NULL);
   258   this->init_previous_versions();
   259   this->set_generic_signature(NULL);
   260   this->release_set_methods_jmethod_ids(NULL);
   261   this->release_set_methods_cached_itable_indices(NULL);
   262   this->set_annotations(NULL);
   263   this->set_jvmti_cached_class_field_map(NULL);
   264   this->set_initial_method_idnum(0);
   266   // initialize the non-header words to zero
   267   intptr_t* p = (intptr_t*)this;
   268   for (int index = InstanceKlass::header_size(); index < size; index++) {
   269     p[index] = NULL_WORD;
   270   }
   272   // Set temporary value until parseClassFile updates it with the real instance
   273   // size.
   274   this->set_layout_helper(Klass::instance_layout_helper(0, true));
   275 }
   278 // This function deallocates the metadata and C heap pointers that the
   279 // InstanceKlass points to.
   280 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   282   // Orphan the mirror first, CMS thinks it's still live.
   283   java_lang_Class::set_klass(java_mirror(), NULL);
   285   // Need to take this class off the class loader data list.
   286   loader_data->remove_class(this);
   288   // The array_klass for this class is created later, after error handling.
   289   // For class redefinition, we keep the original class so this scratch class
   290   // doesn't have an array class.  Either way, assert that there is nothing
   291   // to deallocate.
   292   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   294   // Release C heap allocated data that this might point to, which includes
   295   // reference counting symbol names.
   296   release_C_heap_structures();
   298   Array<Method*>* ms = methods();
   299   if (ms != Universe::the_empty_method_array()) {
   300     for (int i = 0; i <= methods()->length() -1 ; i++) {
   301       Method* method = methods()->at(i);
   302       // Only want to delete methods that are not executing for RedefineClasses.
   303       // The previous version will point to them so they're not totally dangling
   304       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   305       MetadataFactory::free_metadata(loader_data, method);
   306     }
   307     MetadataFactory::free_array<Method*>(loader_data, methods());
   308   }
   309   set_methods(NULL);
   311   if (method_ordering() != Universe::the_empty_int_array()) {
   312     MetadataFactory::free_array<int>(loader_data, method_ordering());
   313   }
   314   set_method_ordering(NULL);
   316   // This array is in Klass, but remove it with the InstanceKlass since
   317   // this place would be the only caller and it can share memory with transitive
   318   // interfaces.
   319   if (secondary_supers() != Universe::the_empty_klass_array() &&
   320       secondary_supers() != transitive_interfaces()) {
   321     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   322   }
   323   set_secondary_supers(NULL);
   325   // Only deallocate transitive interfaces if not empty, same as super class
   326   // or same as local interfaces.   See code in parseClassFile.
   327   Array<Klass*>* ti = transitive_interfaces();
   328   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces()) {
   329     // check that the interfaces don't come from super class
   330     Array<Klass*>* sti = (super() == NULL) ? NULL :
   331        InstanceKlass::cast(super())->transitive_interfaces();
   332     if (ti != sti) {
   333       MetadataFactory::free_array<Klass*>(loader_data, ti);
   334     }
   335   }
   336   set_transitive_interfaces(NULL);
   338   // local interfaces can be empty
   339   Array<Klass*>* li = local_interfaces();
   340   if (li != Universe::the_empty_klass_array()) {
   341     MetadataFactory::free_array<Klass*>(loader_data, li);
   342   }
   343   set_local_interfaces(NULL);
   345   MetadataFactory::free_array<jushort>(loader_data, fields());
   346   set_fields(NULL, 0);
   348   // If a method from a redefined class is using this constant pool, don't
   349   // delete it, yet.  The new class's previous version will point to this.
   350   assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   351   MetadataFactory::free_metadata(loader_data, constants());
   352   set_constants(NULL);
   354   if (inner_classes() != Universe::the_empty_short_array()) {
   355     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   356   }
   357   set_inner_classes(NULL);
   359   // Null out Java heap objects, although these won't be walked to keep
   360   // alive once this InstanceKlass is deallocated.
   361   set_protection_domain(NULL);
   362   set_signers(NULL);
   363   set_init_lock(NULL);
   365   // We should deallocate the Annotations instance
   366   MetadataFactory::free_metadata(loader_data, annotations());
   367   set_annotations(NULL);
   368 }
   370 volatile oop InstanceKlass::init_lock() const {
   371   volatile oop lock = _init_lock;  // read once
   372   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   373          "only fully initialized state can have a null lock");
   374   return lock;
   375 }
   377 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   378 // threads to get this lock will see a null lock and will not lock.
   379 // That's okay because they all check for initialized state after getting
   380 // the lock and return.
   381 void InstanceKlass::fence_and_clear_init_lock() {
   382   // make sure previous stores are all done, notably the init_state.
   383   OrderAccess::storestore();
   384   klass_oop_store(&_init_lock, NULL);
   385   assert(!is_not_initialized(), "class must be initialized now");
   386 }
   389 bool InstanceKlass::should_be_initialized() const {
   390   return !is_initialized();
   391 }
   393 klassVtable* InstanceKlass::vtable() const {
   394   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   395 }
   397 klassItable* InstanceKlass::itable() const {
   398   return new klassItable(instanceKlassHandle(this));
   399 }
   401 void InstanceKlass::eager_initialize(Thread *thread) {
   402   if (!EagerInitialization) return;
   404   if (this->is_not_initialized()) {
   405     // abort if the the class has a class initializer
   406     if (this->class_initializer() != NULL) return;
   408     // abort if it is java.lang.Object (initialization is handled in genesis)
   409     Klass* super = this->super();
   410     if (super == NULL) return;
   412     // abort if the super class should be initialized
   413     if (!InstanceKlass::cast(super)->is_initialized()) return;
   415     // call body to expose the this pointer
   416     instanceKlassHandle this_oop(thread, this);
   417     eager_initialize_impl(this_oop);
   418   }
   419 }
   422 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   423   EXCEPTION_MARK;
   424   volatile oop init_lock = this_oop->init_lock();
   425   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   427   // abort if someone beat us to the initialization
   428   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   430   ClassState old_state = this_oop->init_state();
   431   link_class_impl(this_oop, true, THREAD);
   432   if (HAS_PENDING_EXCEPTION) {
   433     CLEAR_PENDING_EXCEPTION;
   434     // Abort if linking the class throws an exception.
   436     // Use a test to avoid redundantly resetting the state if there's
   437     // no change.  Set_init_state() asserts that state changes make
   438     // progress, whereas here we might just be spinning in place.
   439     if( old_state != this_oop->_init_state )
   440       this_oop->set_init_state (old_state);
   441   } else {
   442     // linking successfull, mark class as initialized
   443     this_oop->set_init_state (fully_initialized);
   444     this_oop->fence_and_clear_init_lock();
   445     // trace
   446     if (TraceClassInitialization) {
   447       ResourceMark rm(THREAD);
   448       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   449     }
   450   }
   451 }
   454 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   455 // process. The step comments refers to the procedure described in that section.
   456 // Note: implementation moved to static method to expose the this pointer.
   457 void InstanceKlass::initialize(TRAPS) {
   458   if (this->should_be_initialized()) {
   459     HandleMark hm(THREAD);
   460     instanceKlassHandle this_oop(THREAD, this);
   461     initialize_impl(this_oop, CHECK);
   462     // Note: at this point the class may be initialized
   463     //       OR it may be in the state of being initialized
   464     //       in case of recursive initialization!
   465   } else {
   466     assert(is_initialized(), "sanity check");
   467   }
   468 }
   471 bool InstanceKlass::verify_code(
   472     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   473   // 1) Verify the bytecodes
   474   Verifier::Mode mode =
   475     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   476   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   477 }
   480 // Used exclusively by the shared spaces dump mechanism to prevent
   481 // classes mapped into the shared regions in new VMs from appearing linked.
   483 void InstanceKlass::unlink_class() {
   484   assert(is_linked(), "must be linked");
   485   _init_state = loaded;
   486 }
   488 void InstanceKlass::link_class(TRAPS) {
   489   assert(is_loaded(), "must be loaded");
   490   if (!is_linked()) {
   491     HandleMark hm(THREAD);
   492     instanceKlassHandle this_oop(THREAD, this);
   493     link_class_impl(this_oop, true, CHECK);
   494   }
   495 }
   497 // Called to verify that a class can link during initialization, without
   498 // throwing a VerifyError.
   499 bool InstanceKlass::link_class_or_fail(TRAPS) {
   500   assert(is_loaded(), "must be loaded");
   501   if (!is_linked()) {
   502     HandleMark hm(THREAD);
   503     instanceKlassHandle this_oop(THREAD, this);
   504     link_class_impl(this_oop, false, CHECK_false);
   505   }
   506   return is_linked();
   507 }
   509 bool InstanceKlass::link_class_impl(
   510     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   511   // check for error state
   512   if (this_oop->is_in_error_state()) {
   513     ResourceMark rm(THREAD);
   514     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   515                this_oop->external_name(), false);
   516   }
   517   // return if already verified
   518   if (this_oop->is_linked()) {
   519     return true;
   520   }
   522   // Timing
   523   // timer handles recursion
   524   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   525   JavaThread* jt = (JavaThread*)THREAD;
   527   // link super class before linking this class
   528   instanceKlassHandle super(THREAD, this_oop->super());
   529   if (super.not_null()) {
   530     if (super->is_interface()) {  // check if super class is an interface
   531       ResourceMark rm(THREAD);
   532       Exceptions::fthrow(
   533         THREAD_AND_LOCATION,
   534         vmSymbols::java_lang_IncompatibleClassChangeError(),
   535         "class %s has interface %s as super class",
   536         this_oop->external_name(),
   537         super->external_name()
   538       );
   539       return false;
   540     }
   542     link_class_impl(super, throw_verifyerror, CHECK_false);
   543   }
   545   // link all interfaces implemented by this class before linking this class
   546   Array<Klass*>* interfaces = this_oop->local_interfaces();
   547   int num_interfaces = interfaces->length();
   548   for (int index = 0; index < num_interfaces; index++) {
   549     HandleMark hm(THREAD);
   550     instanceKlassHandle ih(THREAD, interfaces->at(index));
   551     link_class_impl(ih, throw_verifyerror, CHECK_false);
   552   }
   554   // in case the class is linked in the process of linking its superclasses
   555   if (this_oop->is_linked()) {
   556     return true;
   557   }
   559   // trace only the link time for this klass that includes
   560   // the verification time
   561   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   562                              ClassLoader::perf_class_link_selftime(),
   563                              ClassLoader::perf_classes_linked(),
   564                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   565                              jt->get_thread_stat()->perf_timers_addr(),
   566                              PerfClassTraceTime::CLASS_LINK);
   568   // verification & rewriting
   569   {
   570     volatile oop init_lock = this_oop->init_lock();
   571     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   572     // rewritten will have been set if loader constraint error found
   573     // on an earlier link attempt
   574     // don't verify or rewrite if already rewritten
   576     if (!this_oop->is_linked()) {
   577       if (!this_oop->is_rewritten()) {
   578         {
   579           // Timer includes any side effects of class verification (resolution,
   580           // etc), but not recursive entry into verify_code().
   581           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   582                                    ClassLoader::perf_class_verify_selftime(),
   583                                    ClassLoader::perf_classes_verified(),
   584                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   585                                    jt->get_thread_stat()->perf_timers_addr(),
   586                                    PerfClassTraceTime::CLASS_VERIFY);
   587           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   588           if (!verify_ok) {
   589             return false;
   590           }
   591         }
   593         // Just in case a side-effect of verify linked this class already
   594         // (which can sometimes happen since the verifier loads classes
   595         // using custom class loaders, which are free to initialize things)
   596         if (this_oop->is_linked()) {
   597           return true;
   598         }
   600         // also sets rewritten
   601         this_oop->rewrite_class(CHECK_false);
   602       }
   604       // relocate jsrs and link methods after they are all rewritten
   605       this_oop->relocate_and_link_methods(CHECK_false);
   607       // Initialize the vtable and interface table after
   608       // methods have been rewritten since rewrite may
   609       // fabricate new Method*s.
   610       // also does loader constraint checking
   611       if (!this_oop()->is_shared()) {
   612         ResourceMark rm(THREAD);
   613         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   614         this_oop->itable()->initialize_itable(true, CHECK_false);
   615       }
   616 #ifdef ASSERT
   617       else {
   618         ResourceMark rm(THREAD);
   619         this_oop->vtable()->verify(tty, true);
   620         // In case itable verification is ever added.
   621         // this_oop->itable()->verify(tty, true);
   622       }
   623 #endif
   624       this_oop->set_init_state(linked);
   625       if (JvmtiExport::should_post_class_prepare()) {
   626         Thread *thread = THREAD;
   627         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   628         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   629       }
   630     }
   631   }
   632   return true;
   633 }
   636 // Rewrite the byte codes of all of the methods of a class.
   637 // The rewriter must be called exactly once. Rewriting must happen after
   638 // verification but before the first method of the class is executed.
   639 void InstanceKlass::rewrite_class(TRAPS) {
   640   assert(is_loaded(), "must be loaded");
   641   instanceKlassHandle this_oop(THREAD, this);
   642   if (this_oop->is_rewritten()) {
   643     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   644     return;
   645   }
   646   Rewriter::rewrite(this_oop, CHECK);
   647   this_oop->set_rewritten();
   648 }
   650 // Now relocate and link method entry points after class is rewritten.
   651 // This is outside is_rewritten flag. In case of an exception, it can be
   652 // executed more than once.
   653 void InstanceKlass::relocate_and_link_methods(TRAPS) {
   654   assert(is_loaded(), "must be loaded");
   655   instanceKlassHandle this_oop(THREAD, this);
   656   Rewriter::relocate_and_link(this_oop, CHECK);
   657 }
   660 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   661   // Make sure klass is linked (verified) before initialization
   662   // A class could already be verified, since it has been reflected upon.
   663   this_oop->link_class(CHECK);
   665   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   667   bool wait = false;
   669   // refer to the JVM book page 47 for description of steps
   670   // Step 1
   671   {
   672     volatile oop init_lock = this_oop->init_lock();
   673     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   675     Thread *self = THREAD; // it's passed the current thread
   677     // Step 2
   678     // If we were to use wait() instead of waitInterruptibly() then
   679     // we might end up throwing IE from link/symbol resolution sites
   680     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   681     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   682         wait = true;
   683       ol.waitUninterruptibly(CHECK);
   684     }
   686     // Step 3
   687     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   688       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   689       return;
   690     }
   692     // Step 4
   693     if (this_oop->is_initialized()) {
   694       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   695       return;
   696     }
   698     // Step 5
   699     if (this_oop->is_in_error_state()) {
   700       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   701       ResourceMark rm(THREAD);
   702       const char* desc = "Could not initialize class ";
   703       const char* className = this_oop->external_name();
   704       size_t msglen = strlen(desc) + strlen(className) + 1;
   705       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   706       if (NULL == message) {
   707         // Out of memory: can't create detailed error message
   708         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   709       } else {
   710         jio_snprintf(message, msglen, "%s%s", desc, className);
   711         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   712       }
   713     }
   715     // Step 6
   716     this_oop->set_init_state(being_initialized);
   717     this_oop->set_init_thread(self);
   718   }
   720   // Step 7
   721   Klass* super_klass = this_oop->super();
   722   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   723     super_klass->initialize(THREAD);
   725     if (HAS_PENDING_EXCEPTION) {
   726       Handle e(THREAD, PENDING_EXCEPTION);
   727       CLEAR_PENDING_EXCEPTION;
   728       {
   729         EXCEPTION_MARK;
   730         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   731         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   732       }
   733       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   734       THROW_OOP(e());
   735     }
   736   }
   738   if (this_oop->has_default_methods()) {
   739     // Step 7.5: initialize any interfaces which have default methods
   740     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   741       Klass* iface = this_oop->local_interfaces()->at(i);
   742       InstanceKlass* ik = InstanceKlass::cast(iface);
   743       if (ik->has_default_methods() && ik->should_be_initialized()) {
   744         ik->initialize(THREAD);
   746         if (HAS_PENDING_EXCEPTION) {
   747           Handle e(THREAD, PENDING_EXCEPTION);
   748           CLEAR_PENDING_EXCEPTION;
   749           {
   750             EXCEPTION_MARK;
   751             // Locks object, set state, and notify all waiting threads
   752             this_oop->set_initialization_state_and_notify(
   753                 initialization_error, THREAD);
   755             // ignore any exception thrown, superclass initialization error is
   756             // thrown below
   757             CLEAR_PENDING_EXCEPTION;
   758           }
   759           DTRACE_CLASSINIT_PROBE_WAIT(
   760               super__failed, InstanceKlass::cast(this_oop()), -1, wait);
   761           THROW_OOP(e());
   762         }
   763       }
   764     }
   765   }
   767   // Step 8
   768   {
   769     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   770     JavaThread* jt = (JavaThread*)THREAD;
   771     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   772     // Timer includes any side effects of class initialization (resolution,
   773     // etc), but not recursive entry into call_class_initializer().
   774     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   775                              ClassLoader::perf_class_init_selftime(),
   776                              ClassLoader::perf_classes_inited(),
   777                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   778                              jt->get_thread_stat()->perf_timers_addr(),
   779                              PerfClassTraceTime::CLASS_CLINIT);
   780     this_oop->call_class_initializer(THREAD);
   781   }
   783   // Step 9
   784   if (!HAS_PENDING_EXCEPTION) {
   785     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   786     { ResourceMark rm(THREAD);
   787       debug_only(this_oop->vtable()->verify(tty, true);)
   788     }
   789   }
   790   else {
   791     // Step 10 and 11
   792     Handle e(THREAD, PENDING_EXCEPTION);
   793     CLEAR_PENDING_EXCEPTION;
   794     {
   795       EXCEPTION_MARK;
   796       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   797       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   798     }
   799     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   800     if (e->is_a(SystemDictionary::Error_klass())) {
   801       THROW_OOP(e());
   802     } else {
   803       JavaCallArguments args(e);
   804       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   805                 vmSymbols::throwable_void_signature(),
   806                 &args);
   807     }
   808   }
   809   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   810 }
   813 // Note: implementation moved to static method to expose the this pointer.
   814 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   815   instanceKlassHandle kh(THREAD, this);
   816   set_initialization_state_and_notify_impl(kh, state, CHECK);
   817 }
   819 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   820   volatile oop init_lock = this_oop->init_lock();
   821   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   822   this_oop->set_init_state(state);
   823   this_oop->fence_and_clear_init_lock();
   824   ol.notify_all(CHECK);
   825 }
   827 // The embedded _implementor field can only record one implementor.
   828 // When there are more than one implementors, the _implementor field
   829 // is set to the interface Klass* itself. Following are the possible
   830 // values for the _implementor field:
   831 //   NULL                  - no implementor
   832 //   implementor Klass*    - one implementor
   833 //   self                  - more than one implementor
   834 //
   835 // The _implementor field only exists for interfaces.
   836 void InstanceKlass::add_implementor(Klass* k) {
   837   assert(Compile_lock->owned_by_self(), "");
   838   assert(is_interface(), "not interface");
   839   // Filter out my subinterfaces.
   840   // (Note: Interfaces are never on the subklass list.)
   841   if (InstanceKlass::cast(k)->is_interface()) return;
   843   // Filter out subclasses whose supers already implement me.
   844   // (Note: CHA must walk subclasses of direct implementors
   845   // in order to locate indirect implementors.)
   846   Klass* sk = InstanceKlass::cast(k)->super();
   847   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   848     // We only need to check one immediate superclass, since the
   849     // implements_interface query looks at transitive_interfaces.
   850     // Any supers of the super have the same (or fewer) transitive_interfaces.
   851     return;
   853   Klass* ik = implementor();
   854   if (ik == NULL) {
   855     set_implementor(k);
   856   } else if (ik != this) {
   857     // There is already an implementor. Use itself as an indicator of
   858     // more than one implementors.
   859     set_implementor(this);
   860   }
   862   // The implementor also implements the transitive_interfaces
   863   for (int index = 0; index < local_interfaces()->length(); index++) {
   864     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
   865   }
   866 }
   868 void InstanceKlass::init_implementor() {
   869   if (is_interface()) {
   870     set_implementor(NULL);
   871   }
   872 }
   875 void InstanceKlass::process_interfaces(Thread *thread) {
   876   // link this class into the implementors list of every interface it implements
   877   Klass* this_as_klass_oop = this;
   878   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
   879     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
   880     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
   881     assert(interf->is_interface(), "expected interface");
   882     interf->add_implementor(this_as_klass_oop);
   883   }
   884 }
   886 bool InstanceKlass::can_be_primary_super_slow() const {
   887   if (is_interface())
   888     return false;
   889   else
   890     return Klass::can_be_primary_super_slow();
   891 }
   893 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
   894   // The secondaries are the implemented interfaces.
   895   InstanceKlass* ik = InstanceKlass::cast(this);
   896   Array<Klass*>* interfaces = ik->transitive_interfaces();
   897   int num_secondaries = num_extra_slots + interfaces->length();
   898   if (num_secondaries == 0) {
   899     // Must share this for correct bootstrapping!
   900     set_secondary_supers(Universe::the_empty_klass_array());
   901     return NULL;
   902   } else if (num_extra_slots == 0) {
   903     // The secondary super list is exactly the same as the transitive interfaces.
   904     // Redefine classes has to be careful not to delete this!
   905     set_secondary_supers(interfaces);
   906     return NULL;
   907   } else {
   908     // Copy transitive interfaces to a temporary growable array to be constructed
   909     // into the secondary super list with extra slots.
   910     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
   911     for (int i = 0; i < interfaces->length(); i++) {
   912       secondaries->push(interfaces->at(i));
   913     }
   914     return secondaries;
   915   }
   916 }
   918 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
   919   if (k->is_interface()) {
   920     return implements_interface(k);
   921   } else {
   922     return Klass::compute_is_subtype_of(k);
   923   }
   924 }
   926 bool InstanceKlass::implements_interface(Klass* k) const {
   927   if (this == k) return true;
   928   assert(k->is_interface(), "should be an interface class");
   929   for (int i = 0; i < transitive_interfaces()->length(); i++) {
   930     if (transitive_interfaces()->at(i) == k) {
   931       return true;
   932     }
   933   }
   934   return false;
   935 }
   937 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
   938   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
   939   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
   940     report_java_out_of_memory("Requested array size exceeds VM limit");
   941     JvmtiExport::post_array_size_exhausted();
   942     THROW_OOP_0(Universe::out_of_memory_error_array_size());
   943   }
   944   int size = objArrayOopDesc::object_size(length);
   945   Klass* ak = array_klass(n, CHECK_NULL);
   946   KlassHandle h_ak (THREAD, ak);
   947   objArrayOop o =
   948     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
   949   return o;
   950 }
   952 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
   953   if (TraceFinalizerRegistration) {
   954     tty->print("Registered ");
   955     i->print_value_on(tty);
   956     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
   957   }
   958   instanceHandle h_i(THREAD, i);
   959   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
   960   JavaValue result(T_VOID);
   961   JavaCallArguments args(h_i);
   962   methodHandle mh (THREAD, Universe::finalizer_register_method());
   963   JavaCalls::call(&result, mh, &args, CHECK_NULL);
   964   return h_i();
   965 }
   967 instanceOop InstanceKlass::allocate_instance(TRAPS) {
   968   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
   969   int size = size_helper();  // Query before forming handle.
   971   KlassHandle h_k(THREAD, this);
   973   instanceOop i;
   975   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
   976   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
   977     i = register_finalizer(i, CHECK_NULL);
   978   }
   979   return i;
   980 }
   982 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
   983   if (is_interface() || is_abstract()) {
   984     ResourceMark rm(THREAD);
   985     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
   986               : vmSymbols::java_lang_InstantiationException(), external_name());
   987   }
   988   if (this == SystemDictionary::Class_klass()) {
   989     ResourceMark rm(THREAD);
   990     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
   991               : vmSymbols::java_lang_IllegalAccessException(), external_name());
   992   }
   993 }
   995 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
   996   instanceKlassHandle this_oop(THREAD, this);
   997   return array_klass_impl(this_oop, or_null, n, THREAD);
   998 }
  1000 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1001   if (this_oop->array_klasses() == NULL) {
  1002     if (or_null) return NULL;
  1004     ResourceMark rm;
  1005     JavaThread *jt = (JavaThread *)THREAD;
  1007       // Atomic creation of array_klasses
  1008       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1009       MutexLocker ma(MultiArray_lock, THREAD);
  1011       // Check if update has already taken place
  1012       if (this_oop->array_klasses() == NULL) {
  1013         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1014         this_oop->set_array_klasses(k);
  1018   // _this will always be set at this point
  1019   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1020   if (or_null) {
  1021     return oak->array_klass_or_null(n);
  1023   return oak->array_klass(n, CHECK_NULL);
  1026 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1027   return array_klass_impl(or_null, 1, THREAD);
  1030 void InstanceKlass::call_class_initializer(TRAPS) {
  1031   instanceKlassHandle ik (THREAD, this);
  1032   call_class_initializer_impl(ik, THREAD);
  1035 static int call_class_initializer_impl_counter = 0;   // for debugging
  1037 Method* InstanceKlass::class_initializer() {
  1038   Method* clinit = find_method(
  1039       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1040   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1041     return clinit;
  1043   return NULL;
  1046 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1047   if (ReplayCompiles &&
  1048       (ReplaySuppressInitializers == 1 ||
  1049        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1050     // Hide the existence of the initializer for the purpose of replaying the compile
  1051     return;
  1054   methodHandle h_method(THREAD, this_oop->class_initializer());
  1055   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1056   if (TraceClassInitialization) {
  1057     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1058     this_oop->name()->print_value();
  1059     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1061   if (h_method() != NULL) {
  1062     JavaCallArguments args; // No arguments
  1063     JavaValue result(T_VOID);
  1064     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1069 void InstanceKlass::mask_for(methodHandle method, int bci,
  1070   InterpreterOopMap* entry_for) {
  1071   // Dirty read, then double-check under a lock.
  1072   if (_oop_map_cache == NULL) {
  1073     // Otherwise, allocate a new one.
  1074     MutexLocker x(OopMapCacheAlloc_lock);
  1075     // First time use. Allocate a cache in C heap
  1076     if (_oop_map_cache == NULL) {
  1077       _oop_map_cache = new OopMapCache();
  1080   // _oop_map_cache is constant after init; lookup below does is own locking.
  1081   _oop_map_cache->lookup(method, bci, entry_for);
  1085 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1086   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1087     Symbol* f_name = fs.name();
  1088     Symbol* f_sig  = fs.signature();
  1089     if (f_name == name && f_sig == sig) {
  1090       fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
  1091       return true;
  1094   return false;
  1098 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1099   const int n = local_interfaces()->length();
  1100   for (int i = 0; i < n; i++) {
  1101     Klass* intf1 = local_interfaces()->at(i);
  1102     assert(intf1->is_interface(), "just checking type");
  1103     // search for field in current interface
  1104     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1105       assert(fd->is_static(), "interface field must be static");
  1106       return intf1;
  1108     // search for field in direct superinterfaces
  1109     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1110     if (intf2 != NULL) return intf2;
  1112   // otherwise field lookup fails
  1113   return NULL;
  1117 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1118   // search order according to newest JVM spec (5.4.3.2, p.167).
  1119   // 1) search for field in current klass
  1120   if (find_local_field(name, sig, fd)) {
  1121     return const_cast<InstanceKlass*>(this);
  1123   // 2) search for field recursively in direct superinterfaces
  1124   { Klass* intf = find_interface_field(name, sig, fd);
  1125     if (intf != NULL) return intf;
  1127   // 3) apply field lookup recursively if superclass exists
  1128   { Klass* supr = super();
  1129     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1131   // 4) otherwise field lookup fails
  1132   return NULL;
  1136 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1137   // search order according to newest JVM spec (5.4.3.2, p.167).
  1138   // 1) search for field in current klass
  1139   if (find_local_field(name, sig, fd)) {
  1140     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1142   // 2) search for field recursively in direct superinterfaces
  1143   if (is_static) {
  1144     Klass* intf = find_interface_field(name, sig, fd);
  1145     if (intf != NULL) return intf;
  1147   // 3) apply field lookup recursively if superclass exists
  1148   { Klass* supr = super();
  1149     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1151   // 4) otherwise field lookup fails
  1152   return NULL;
  1156 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1157   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1158     if (fs.offset() == offset) {
  1159       fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
  1160       if (fd->is_static() == is_static) return true;
  1163   return false;
  1167 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1168   Klass* klass = const_cast<InstanceKlass*>(this);
  1169   while (klass != NULL) {
  1170     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1171       return true;
  1173     klass = klass->super();
  1175   return false;
  1179 void InstanceKlass::methods_do(void f(Method* method)) {
  1180   int len = methods()->length();
  1181   for (int index = 0; index < len; index++) {
  1182     Method* m = methods()->at(index);
  1183     assert(m->is_method(), "must be method");
  1184     f(m);
  1189 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1190   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1191     if (fs.access_flags().is_static()) {
  1192       fieldDescriptor fd;
  1193       fd.initialize(this, fs.index());
  1194       cl->do_field(&fd);
  1200 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
  1201   instanceKlassHandle h_this(THREAD, this);
  1202   do_local_static_fields_impl(h_this, f, CHECK);
  1206 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
  1207   for (JavaFieldStream fs(this_oop()); !fs.done(); fs.next()) {
  1208     if (fs.access_flags().is_static()) {
  1209       fieldDescriptor fd;
  1210       fd.initialize(this_oop(), fs.index());
  1211       f(&fd, CHECK);
  1217 static int compare_fields_by_offset(int* a, int* b) {
  1218   return a[0] - b[0];
  1221 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1222   InstanceKlass* super = superklass();
  1223   if (super != NULL) {
  1224     super->do_nonstatic_fields(cl);
  1226   fieldDescriptor fd;
  1227   int length = java_fields_count();
  1228   // In DebugInfo nonstatic fields are sorted by offset.
  1229   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1230   int j = 0;
  1231   for (int i = 0; i < length; i += 1) {
  1232     fd.initialize(this, i);
  1233     if (!fd.is_static()) {
  1234       fields_sorted[j + 0] = fd.offset();
  1235       fields_sorted[j + 1] = i;
  1236       j += 2;
  1239   if (j > 0) {
  1240     length = j;
  1241     // _sort_Fn is defined in growableArray.hpp.
  1242     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1243     for (int i = 0; i < length; i += 2) {
  1244       fd.initialize(this, fields_sorted[i + 1]);
  1245       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1246       cl->do_field(&fd);
  1249   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1253 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1254   if (array_klasses() != NULL)
  1255     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1258 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1259   if (array_klasses() != NULL)
  1260     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1264 void InstanceKlass::with_array_klasses_do(void f(Klass* k)) {
  1265   f(this);
  1266   array_klasses_do(f);
  1269 #ifdef ASSERT
  1270 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1271   int len = methods->length();
  1272   for (int index = 0; index < len; index++) {
  1273     Method* m = methods->at(index);
  1274     assert(m->is_method(), "must be method");
  1275     if (m->signature() == signature && m->name() == name) {
  1276        return index;
  1279   return -1;
  1281 #endif
  1283 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1284   int len = methods->length();
  1285   // methods are sorted, so do binary search
  1286   int l = 0;
  1287   int h = len - 1;
  1288   while (l <= h) {
  1289     int mid = (l + h) >> 1;
  1290     Method* m = methods->at(mid);
  1291     assert(m->is_method(), "must be method");
  1292     int res = m->name()->fast_compare(name);
  1293     if (res == 0) {
  1294       return mid;
  1295     } else if (res < 0) {
  1296       l = mid + 1;
  1297     } else {
  1298       h = mid - 1;
  1301   return -1;
  1304 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1305   return InstanceKlass::find_method(methods(), name, signature);
  1308 Method* InstanceKlass::find_method(
  1309     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1310   int hit = binary_search(methods, name);
  1311   if (hit != -1) {
  1312     Method* m = methods->at(hit);
  1313     // Do linear search to find matching signature.  First, quick check
  1314     // for common case
  1315     if (m->signature() == signature) return m;
  1316     // search downwards through overloaded methods
  1317     int i;
  1318     for (i = hit - 1; i >= 0; --i) {
  1319         Method* m = methods->at(i);
  1320         assert(m->is_method(), "must be method");
  1321         if (m->name() != name) break;
  1322         if (m->signature() == signature) return m;
  1324     // search upwards
  1325     for (i = hit + 1; i < methods->length(); ++i) {
  1326         Method* m = methods->at(i);
  1327         assert(m->is_method(), "must be method");
  1328         if (m->name() != name) break;
  1329         if (m->signature() == signature) return m;
  1331     // not found
  1332 #ifdef ASSERT
  1333     int index = linear_search(methods, name, signature);
  1334     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1335 #endif
  1337   return NULL;
  1340 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1341   return find_method_by_name(methods(), name, end);
  1344 int InstanceKlass::find_method_by_name(
  1345     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1346   assert(end_ptr != NULL, "just checking");
  1347   int start = binary_search(methods, name);
  1348   int end = start + 1;
  1349   if (start != -1) {
  1350     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1351     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1352     *end_ptr = end;
  1353     return start;
  1355   return -1;
  1358 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
  1359   Klass* klass = const_cast<InstanceKlass*>(this);
  1360   while (klass != NULL) {
  1361     Method* method = InstanceKlass::cast(klass)->find_method(name, signature);
  1362     if (method != NULL) return method;
  1363     klass = InstanceKlass::cast(klass)->super();
  1365   return NULL;
  1368 // lookup a method in all the interfaces that this class implements
  1369 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1370                                                          Symbol* signature) const {
  1371   Array<Klass*>* all_ifs = transitive_interfaces();
  1372   int num_ifs = all_ifs->length();
  1373   InstanceKlass *ik = NULL;
  1374   for (int i = 0; i < num_ifs; i++) {
  1375     ik = InstanceKlass::cast(all_ifs->at(i));
  1376     Method* m = ik->lookup_method(name, signature);
  1377     if (m != NULL) {
  1378       return m;
  1381   return NULL;
  1384 /* jni_id_for_impl for jfieldIds only */
  1385 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1386   MutexLocker ml(JfieldIdCreation_lock);
  1387   // Retry lookup after we got the lock
  1388   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1389   if (probe == NULL) {
  1390     // Slow case, allocate new static field identifier
  1391     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1392     this_oop->set_jni_ids(probe);
  1394   return probe;
  1398 /* jni_id_for for jfieldIds only */
  1399 JNIid* InstanceKlass::jni_id_for(int offset) {
  1400   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1401   if (probe == NULL) {
  1402     probe = jni_id_for_impl(this, offset);
  1404   return probe;
  1407 u2 InstanceKlass::enclosing_method_data(int offset) {
  1408   Array<jushort>* inner_class_list = inner_classes();
  1409   if (inner_class_list == NULL) {
  1410     return 0;
  1412   int length = inner_class_list->length();
  1413   if (length % inner_class_next_offset == 0) {
  1414     return 0;
  1415   } else {
  1416     int index = length - enclosing_method_attribute_size;
  1417     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1418     return inner_class_list->at(index + offset);
  1422 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1423                                                  u2 method_index) {
  1424   Array<jushort>* inner_class_list = inner_classes();
  1425   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1426   int length = inner_class_list->length();
  1427   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1428     int index = length - enclosing_method_attribute_size;
  1429     inner_class_list->at_put(
  1430       index + enclosing_method_class_index_offset, class_index);
  1431     inner_class_list->at_put(
  1432       index + enclosing_method_method_index_offset, method_index);
  1436 // Lookup or create a jmethodID.
  1437 // This code is called by the VMThread and JavaThreads so the
  1438 // locking has to be done very carefully to avoid deadlocks
  1439 // and/or other cache consistency problems.
  1440 //
  1441 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1442   size_t idnum = (size_t)method_h->method_idnum();
  1443   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1444   size_t length = 0;
  1445   jmethodID id = NULL;
  1447   // We use a double-check locking idiom here because this cache is
  1448   // performance sensitive. In the normal system, this cache only
  1449   // transitions from NULL to non-NULL which is safe because we use
  1450   // release_set_methods_jmethod_ids() to advertise the new cache.
  1451   // A partially constructed cache should never be seen by a racing
  1452   // thread. We also use release_store_ptr() to save a new jmethodID
  1453   // in the cache so a partially constructed jmethodID should never be
  1454   // seen either. Cache reads of existing jmethodIDs proceed without a
  1455   // lock, but cache writes of a new jmethodID requires uniqueness and
  1456   // creation of the cache itself requires no leaks so a lock is
  1457   // generally acquired in those two cases.
  1458   //
  1459   // If the RedefineClasses() API has been used, then this cache can
  1460   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1461   // Cache creation requires no leaks and we require safety between all
  1462   // cache accesses and freeing of the old cache so a lock is generally
  1463   // acquired when the RedefineClasses() API has been used.
  1465   if (jmeths != NULL) {
  1466     // the cache already exists
  1467     if (!ik_h->idnum_can_increment()) {
  1468       // the cache can't grow so we can just get the current values
  1469       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1470     } else {
  1471       // cache can grow so we have to be more careful
  1472       if (Threads::number_of_threads() == 0 ||
  1473           SafepointSynchronize::is_at_safepoint()) {
  1474         // we're single threaded or at a safepoint - no locking needed
  1475         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1476       } else {
  1477         MutexLocker ml(JmethodIdCreation_lock);
  1478         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1482   // implied else:
  1483   // we need to allocate a cache so default length and id values are good
  1485   if (jmeths == NULL ||   // no cache yet
  1486       length <= idnum ||  // cache is too short
  1487       id == NULL) {       // cache doesn't contain entry
  1489     // This function can be called by the VMThread so we have to do all
  1490     // things that might block on a safepoint before grabbing the lock.
  1491     // Otherwise, we can deadlock with the VMThread or have a cache
  1492     // consistency issue. These vars keep track of what we might have
  1493     // to free after the lock is dropped.
  1494     jmethodID  to_dealloc_id     = NULL;
  1495     jmethodID* to_dealloc_jmeths = NULL;
  1497     // may not allocate new_jmeths or use it if we allocate it
  1498     jmethodID* new_jmeths = NULL;
  1499     if (length <= idnum) {
  1500       // allocate a new cache that might be used
  1501       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1502       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1503       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1504       // cache size is stored in element[0], other elements offset by one
  1505       new_jmeths[0] = (jmethodID)size;
  1508     // allocate a new jmethodID that might be used
  1509     jmethodID new_id = NULL;
  1510     if (method_h->is_old() && !method_h->is_obsolete()) {
  1511       // The method passed in is old (but not obsolete), we need to use the current version
  1512       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1513       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1514       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1515     } else {
  1516       // It is the current version of the method or an obsolete method,
  1517       // use the version passed in
  1518       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1521     if (Threads::number_of_threads() == 0 ||
  1522         SafepointSynchronize::is_at_safepoint()) {
  1523       // we're single threaded or at a safepoint - no locking needed
  1524       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1525                                           &to_dealloc_id, &to_dealloc_jmeths);
  1526     } else {
  1527       MutexLocker ml(JmethodIdCreation_lock);
  1528       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1529                                           &to_dealloc_id, &to_dealloc_jmeths);
  1532     // The lock has been dropped so we can free resources.
  1533     // Free up either the old cache or the new cache if we allocated one.
  1534     if (to_dealloc_jmeths != NULL) {
  1535       FreeHeap(to_dealloc_jmeths);
  1537     // free up the new ID since it wasn't needed
  1538     if (to_dealloc_id != NULL) {
  1539       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1542   return id;
  1546 // Common code to fetch the jmethodID from the cache or update the
  1547 // cache with the new jmethodID. This function should never do anything
  1548 // that causes the caller to go to a safepoint or we can deadlock with
  1549 // the VMThread or have cache consistency issues.
  1550 //
  1551 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1552             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1553             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1554             jmethodID** to_dealloc_jmeths_p) {
  1555   assert(new_id != NULL, "sanity check");
  1556   assert(to_dealloc_id_p != NULL, "sanity check");
  1557   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1558   assert(Threads::number_of_threads() == 0 ||
  1559          SafepointSynchronize::is_at_safepoint() ||
  1560          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1562   // reacquire the cache - we are locked, single threaded or at a safepoint
  1563   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1564   jmethodID  id     = NULL;
  1565   size_t     length = 0;
  1567   if (jmeths == NULL ||                         // no cache yet
  1568       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1569     if (jmeths != NULL) {
  1570       // copy any existing entries from the old cache
  1571       for (size_t index = 0; index < length; index++) {
  1572         new_jmeths[index+1] = jmeths[index+1];
  1574       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1576     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1577   } else {
  1578     // fetch jmethodID (if any) from the existing cache
  1579     id = jmeths[idnum+1];
  1580     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1582   if (id == NULL) {
  1583     // No matching jmethodID in the existing cache or we have a new
  1584     // cache or we just grew the cache. This cache write is done here
  1585     // by the first thread to win the foot race because a jmethodID
  1586     // needs to be unique once it is generally available.
  1587     id = new_id;
  1589     // The jmethodID cache can be read while unlocked so we have to
  1590     // make sure the new jmethodID is complete before installing it
  1591     // in the cache.
  1592     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1593   } else {
  1594     *to_dealloc_id_p = new_id; // save new id for later delete
  1596   return id;
  1600 // Common code to get the jmethodID cache length and the jmethodID
  1601 // value at index idnum if there is one.
  1602 //
  1603 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1604        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1605   assert(cache != NULL, "sanity check");
  1606   assert(length_p != NULL, "sanity check");
  1607   assert(id_p != NULL, "sanity check");
  1609   // cache size is stored in element[0], other elements offset by one
  1610   *length_p = (size_t)cache[0];
  1611   if (*length_p <= idnum) {  // cache is too short
  1612     *id_p = NULL;
  1613   } else {
  1614     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1619 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1620 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1621   size_t idnum = (size_t)method->method_idnum();
  1622   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1623   size_t length;                                // length assigned as debugging crumb
  1624   jmethodID id = NULL;
  1625   if (jmeths != NULL &&                         // If there is a cache
  1626       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1627     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1629   return id;
  1633 // Cache an itable index
  1634 void InstanceKlass::set_cached_itable_index(size_t idnum, int index) {
  1635   int* indices = methods_cached_itable_indices_acquire();
  1636   int* to_dealloc_indices = NULL;
  1638   // We use a double-check locking idiom here because this cache is
  1639   // performance sensitive. In the normal system, this cache only
  1640   // transitions from NULL to non-NULL which is safe because we use
  1641   // release_set_methods_cached_itable_indices() to advertise the
  1642   // new cache. A partially constructed cache should never be seen
  1643   // by a racing thread. Cache reads and writes proceed without a
  1644   // lock, but creation of the cache itself requires no leaks so a
  1645   // lock is generally acquired in that case.
  1646   //
  1647   // If the RedefineClasses() API has been used, then this cache can
  1648   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1649   // Cache creation requires no leaks and we require safety between all
  1650   // cache accesses and freeing of the old cache so a lock is generally
  1651   // acquired when the RedefineClasses() API has been used.
  1653   if (indices == NULL || idnum_can_increment()) {
  1654     // we need a cache or the cache can grow
  1655     MutexLocker ml(JNICachedItableIndex_lock);
  1656     // reacquire the cache to see if another thread already did the work
  1657     indices = methods_cached_itable_indices_acquire();
  1658     size_t length = 0;
  1659     // cache size is stored in element[0], other elements offset by one
  1660     if (indices == NULL || (length = (size_t)indices[0]) <= idnum) {
  1661       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
  1662       int* new_indices = NEW_C_HEAP_ARRAY(int, size+1, mtClass);
  1663       new_indices[0] = (int)size;
  1664       // copy any existing entries
  1665       size_t i;
  1666       for (i = 0; i < length; i++) {
  1667         new_indices[i+1] = indices[i+1];
  1669       // Set all the rest to -1
  1670       for (i = length; i < size; i++) {
  1671         new_indices[i+1] = -1;
  1673       if (indices != NULL) {
  1674         // We have an old cache to delete so save it for after we
  1675         // drop the lock.
  1676         to_dealloc_indices = indices;
  1678       release_set_methods_cached_itable_indices(indices = new_indices);
  1681     if (idnum_can_increment()) {
  1682       // this cache can grow so we have to write to it safely
  1683       indices[idnum+1] = index;
  1685   } else {
  1686     CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
  1689   if (!idnum_can_increment()) {
  1690     // The cache cannot grow and this JNI itable index value does not
  1691     // have to be unique like a jmethodID. If there is a race to set it,
  1692     // it doesn't matter.
  1693     indices[idnum+1] = index;
  1696   if (to_dealloc_indices != NULL) {
  1697     // we allocated a new cache so free the old one
  1698     FreeHeap(to_dealloc_indices);
  1703 // Retrieve a cached itable index
  1704 int InstanceKlass::cached_itable_index(size_t idnum) {
  1705   int* indices = methods_cached_itable_indices_acquire();
  1706   if (indices != NULL && ((size_t)indices[0]) > idnum) {
  1707      // indices exist and are long enough, retrieve possible cached
  1708     return indices[idnum+1];
  1710   return -1;
  1714 //
  1715 // Walk the list of dependent nmethods searching for nmethods which
  1716 // are dependent on the changes that were passed in and mark them for
  1717 // deoptimization.  Returns the number of nmethods found.
  1718 //
  1719 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1720   assert_locked_or_safepoint(CodeCache_lock);
  1721   int found = 0;
  1722   nmethodBucket* b = _dependencies;
  1723   while (b != NULL) {
  1724     nmethod* nm = b->get_nmethod();
  1725     // since dependencies aren't removed until an nmethod becomes a zombie,
  1726     // the dependency list may contain nmethods which aren't alive.
  1727     if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1728       if (TraceDependencies) {
  1729         ResourceMark rm;
  1730         tty->print_cr("Marked for deoptimization");
  1731         tty->print_cr("  context = %s", this->external_name());
  1732         changes.print();
  1733         nm->print();
  1734         nm->print_dependencies();
  1736       nm->mark_for_deoptimization();
  1737       found++;
  1739     b = b->next();
  1741   return found;
  1745 //
  1746 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1747 // It's possible that an nmethod has multiple dependencies on this klass
  1748 // so a count is kept for each bucket to guarantee that creation and
  1749 // deletion of dependencies is consistent.
  1750 //
  1751 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1752   assert_locked_or_safepoint(CodeCache_lock);
  1753   nmethodBucket* b = _dependencies;
  1754   nmethodBucket* last = NULL;
  1755   while (b != NULL) {
  1756     if (nm == b->get_nmethod()) {
  1757       b->increment();
  1758       return;
  1760     b = b->next();
  1762   _dependencies = new nmethodBucket(nm, _dependencies);
  1766 //
  1767 // Decrement count of the nmethod in the dependency list and remove
  1768 // the bucket competely when the count goes to 0.  This method must
  1769 // find a corresponding bucket otherwise there's a bug in the
  1770 // recording of dependecies.
  1771 //
  1772 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1773   assert_locked_or_safepoint(CodeCache_lock);
  1774   nmethodBucket* b = _dependencies;
  1775   nmethodBucket* last = NULL;
  1776   while (b != NULL) {
  1777     if (nm == b->get_nmethod()) {
  1778       if (b->decrement() == 0) {
  1779         if (last == NULL) {
  1780           _dependencies = b->next();
  1781         } else {
  1782           last->set_next(b->next());
  1784         delete b;
  1786       return;
  1788     last = b;
  1789     b = b->next();
  1791 #ifdef ASSERT
  1792   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1793   nm->print();
  1794 #endif // ASSERT
  1795   ShouldNotReachHere();
  1799 #ifndef PRODUCT
  1800 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1801   nmethodBucket* b = _dependencies;
  1802   int idx = 0;
  1803   while (b != NULL) {
  1804     nmethod* nm = b->get_nmethod();
  1805     tty->print("[%d] count=%d { ", idx++, b->count());
  1806     if (!verbose) {
  1807       nm->print_on(tty, "nmethod");
  1808       tty->print_cr(" } ");
  1809     } else {
  1810       nm->print();
  1811       nm->print_dependencies();
  1812       tty->print_cr("--- } ");
  1814     b = b->next();
  1819 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  1820   nmethodBucket* b = _dependencies;
  1821   while (b != NULL) {
  1822     if (nm == b->get_nmethod()) {
  1823       return true;
  1825     b = b->next();
  1827   return false;
  1829 #endif //PRODUCT
  1832 // Garbage collection
  1834 void InstanceKlass::oops_do(OopClosure* cl) {
  1835   Klass::oops_do(cl);
  1837   cl->do_oop(adr_protection_domain());
  1838   cl->do_oop(adr_signers());
  1839   cl->do_oop(adr_init_lock());
  1841   // Don't walk the arrays since they are walked from the ClassLoaderData objects.
  1844 #ifdef ASSERT
  1845 template <class T> void assert_is_in(T *p) {
  1846   T heap_oop = oopDesc::load_heap_oop(p);
  1847   if (!oopDesc::is_null(heap_oop)) {
  1848     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1849     assert(Universe::heap()->is_in(o), "should be in heap");
  1852 template <class T> void assert_is_in_closed_subset(T *p) {
  1853   T heap_oop = oopDesc::load_heap_oop(p);
  1854   if (!oopDesc::is_null(heap_oop)) {
  1855     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1856     assert(Universe::heap()->is_in_closed_subset(o),
  1857            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  1860 template <class T> void assert_is_in_reserved(T *p) {
  1861   T heap_oop = oopDesc::load_heap_oop(p);
  1862   if (!oopDesc::is_null(heap_oop)) {
  1863     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1864     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  1867 template <class T> void assert_nothing(T *p) {}
  1869 #else
  1870 template <class T> void assert_is_in(T *p) {}
  1871 template <class T> void assert_is_in_closed_subset(T *p) {}
  1872 template <class T> void assert_is_in_reserved(T *p) {}
  1873 template <class T> void assert_nothing(T *p) {}
  1874 #endif // ASSERT
  1876 //
  1877 // Macros that iterate over areas of oops which are specialized on type of
  1878 // oop pointer either narrow or wide, depending on UseCompressedOops
  1879 //
  1880 // Parameters are:
  1881 //   T         - type of oop to point to (either oop or narrowOop)
  1882 //   start_p   - starting pointer for region to iterate over
  1883 //   count     - number of oops or narrowOops to iterate over
  1884 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  1885 //               makes it more efficient to put in a macro rather than making
  1886 //               it a template function)
  1887 //   assert_fn - assert function which is template function because performance
  1888 //               doesn't matter when enabled.
  1889 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  1890   T, start_p, count, do_oop,                \
  1891   assert_fn)                                \
  1892 {                                           \
  1893   T* p         = (T*)(start_p);             \
  1894   T* const end = p + (count);               \
  1895   while (p < end) {                         \
  1896     (assert_fn)(p);                         \
  1897     do_oop;                                 \
  1898     ++p;                                    \
  1899   }                                         \
  1902 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  1903   T, start_p, count, do_oop,                \
  1904   assert_fn)                                \
  1905 {                                           \
  1906   T* const start = (T*)(start_p);           \
  1907   T*       p     = start + (count);         \
  1908   while (start < p) {                       \
  1909     --p;                                    \
  1910     (assert_fn)(p);                         \
  1911     do_oop;                                 \
  1912   }                                         \
  1915 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  1916   T, start_p, count, low, high,             \
  1917   do_oop, assert_fn)                        \
  1918 {                                           \
  1919   T* const l = (T*)(low);                   \
  1920   T* const h = (T*)(high);                  \
  1921   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  1922          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  1923          "bounded region must be properly aligned"); \
  1924   T* p       = (T*)(start_p);               \
  1925   T* end     = p + (count);                 \
  1926   if (p < l) p = l;                         \
  1927   if (end > h) end = h;                     \
  1928   while (p < end) {                         \
  1929     (assert_fn)(p);                         \
  1930     do_oop;                                 \
  1931     ++p;                                    \
  1932   }                                         \
  1936 // The following macros call specialized macros, passing either oop or
  1937 // narrowOop as the specialization type.  These test the UseCompressedOops
  1938 // flag.
  1939 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  1940 {                                                                        \
  1941   /* Compute oopmap block range. The common case                         \
  1942      is nonstatic_oop_map_size == 1. */                                  \
  1943   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  1944   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  1945   if (UseCompressedOops) {                                               \
  1946     while (map < end_map) {                                              \
  1947       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  1948         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1949         do_oop, assert_fn)                                               \
  1950       ++map;                                                             \
  1951     }                                                                    \
  1952   } else {                                                               \
  1953     while (map < end_map) {                                              \
  1954       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  1955         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1956         do_oop, assert_fn)                                               \
  1957       ++map;                                                             \
  1958     }                                                                    \
  1959   }                                                                      \
  1962 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  1963 {                                                                        \
  1964   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  1965   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  1966   if (UseCompressedOops) {                                               \
  1967     while (start_map < map) {                                            \
  1968       --map;                                                             \
  1969       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  1970         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1971         do_oop, assert_fn)                                               \
  1972     }                                                                    \
  1973   } else {                                                               \
  1974     while (start_map < map) {                                            \
  1975       --map;                                                             \
  1976       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  1977         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1978         do_oop, assert_fn)                                               \
  1979     }                                                                    \
  1980   }                                                                      \
  1983 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  1984                                               assert_fn)                 \
  1985 {                                                                        \
  1986   /* Compute oopmap block range. The common case is                      \
  1987      nonstatic_oop_map_size == 1, so we accept the                       \
  1988      usually non-existent extra overhead of examining                    \
  1989      all the maps. */                                                    \
  1990   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  1991   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  1992   if (UseCompressedOops) {                                               \
  1993     while (map < end_map) {                                              \
  1994       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  1995         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1996         low, high,                                                       \
  1997         do_oop, assert_fn)                                               \
  1998       ++map;                                                             \
  1999     }                                                                    \
  2000   } else {                                                               \
  2001     while (map < end_map) {                                              \
  2002       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2003         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2004         low, high,                                                       \
  2005         do_oop, assert_fn)                                               \
  2006       ++map;                                                             \
  2007     }                                                                    \
  2008   }                                                                      \
  2011 void InstanceKlass::oop_follow_contents(oop obj) {
  2012   assert(obj != NULL, "can't follow the content of NULL object");
  2013   MarkSweep::follow_klass(obj->klass());
  2014   InstanceKlass_OOP_MAP_ITERATE( \
  2015     obj, \
  2016     MarkSweep::mark_and_push(p), \
  2017     assert_is_in_closed_subset)
  2020 #ifndef SERIALGC
  2021 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2022                                         oop obj) {
  2023   assert(obj != NULL, "can't follow the content of NULL object");
  2024   PSParallelCompact::follow_klass(cm, obj->klass());
  2025   // Only mark the header and let the scan of the meta-data mark
  2026   // everything else.
  2027   InstanceKlass_OOP_MAP_ITERATE( \
  2028     obj, \
  2029     PSParallelCompact::mark_and_push(cm, p), \
  2030     assert_is_in)
  2032 #endif // SERIALGC
  2034 // closure's do_metadata() method dictates whether the given closure should be
  2035 // applied to the klass ptr in the object header.
  2037 #define if_do_metadata_checked(closure, nv_suffix)                    \
  2038   /* Make sure the non-virtual and the virtual versions match. */     \
  2039   assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
  2040       "Inconsistency in do_metadata");                                \
  2041   if (closure->do_metadata##nv_suffix())
  2043 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2045 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2046   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2047   /* header */                                                          \
  2048   if_do_metadata_checked(closure, nv_suffix) {                          \
  2049     closure->do_klass##nv_suffix(obj->klass());                         \
  2050   }                                                                     \
  2051   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2052     obj,                                                                \
  2053     SpecializationStats::                                               \
  2054       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2055     (closure)->do_oop##nv_suffix(p),                                    \
  2056     assert_is_in_closed_subset)                                         \
  2057   return size_helper();                                                 \
  2060 #ifndef SERIALGC
  2061 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2063 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2064                                               OopClosureType* closure) {        \
  2065   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2066   /* header */                                                                  \
  2067   if_do_metadata_checked(closure, nv_suffix) {                                  \
  2068     closure->do_klass##nv_suffix(obj->klass());                                 \
  2069   }                                                                             \
  2070   /* instance variables */                                                      \
  2071   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2072     obj,                                                                        \
  2073     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2074     (closure)->do_oop##nv_suffix(p),                                            \
  2075     assert_is_in_closed_subset)                                                 \
  2076    return size_helper();                                                        \
  2078 #endif // !SERIALGC
  2080 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2082 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2083                                                   OopClosureType* closure, \
  2084                                                   MemRegion mr) {          \
  2085   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2086   if_do_metadata_checked(closure, nv_suffix) {                           \
  2087     if (mr.contains(obj)) {                                              \
  2088       closure->do_klass##nv_suffix(obj->klass());                        \
  2089     }                                                                    \
  2090   }                                                                      \
  2091   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2092     obj, mr.start(), mr.end(),                                           \
  2093     (closure)->do_oop##nv_suffix(p),                                     \
  2094     assert_is_in_closed_subset)                                          \
  2095   return size_helper();                                                  \
  2098 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2099 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2100 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2101 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2102 #ifndef SERIALGC
  2103 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2104 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2105 #endif // !SERIALGC
  2107 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2108   int size = size_helper();
  2109   InstanceKlass_OOP_MAP_ITERATE( \
  2110     obj, \
  2111     MarkSweep::adjust_pointer(p), \
  2112     assert_is_in)
  2113   MarkSweep::adjust_klass(obj->klass());
  2114   return size;
  2117 #ifndef SERIALGC
  2118 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2119   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2120     obj, \
  2121     if (PSScavenge::should_scavenge(p)) { \
  2122       pm->claim_or_forward_depth(p); \
  2123     }, \
  2124     assert_nothing )
  2127 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2128   int size = size_helper();
  2129   InstanceKlass_OOP_MAP_ITERATE( \
  2130     obj, \
  2131     PSParallelCompact::adjust_pointer(p), \
  2132     assert_is_in)
  2133   obj->update_header(cm);
  2134   return size;
  2137 #endif // SERIALGC
  2139 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2140   assert(is_loader_alive(is_alive), "this klass should be live");
  2141   if (is_interface()) {
  2142     if (ClassUnloading) {
  2143       Klass* impl = implementor();
  2144       if (impl != NULL) {
  2145         if (!impl->is_loader_alive(is_alive)) {
  2146           // remove this guy
  2147           *adr_implementor() = NULL;
  2154 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2155 #ifdef COMPILER2
  2156   // Currently only used by C2.
  2157   for (int m = 0; m < methods()->length(); m++) {
  2158     MethodData* mdo = methods()->at(m)->method_data();
  2159     if (mdo != NULL) {
  2160       for (ProfileData* data = mdo->first_data();
  2161            mdo->is_valid(data);
  2162            data = mdo->next_data(data)) {
  2163         data->clean_weak_klass_links(is_alive);
  2167 #else
  2168 #ifdef ASSERT
  2169   // Verify that we haven't started to use MDOs for C1.
  2170   for (int m = 0; m < methods()->length(); m++) {
  2171     MethodData* mdo = methods()->at(m)->method_data();
  2172     assert(mdo == NULL, "Didn't expect C1 to use MDOs");
  2174 #endif // ASSERT
  2175 #endif // !COMPILER2
  2179 static void remove_unshareable_in_class(Klass* k) {
  2180   // remove klass's unshareable info
  2181   k->remove_unshareable_info();
  2184 void InstanceKlass::remove_unshareable_info() {
  2185   Klass::remove_unshareable_info();
  2186   // Unlink the class
  2187   if (is_linked()) {
  2188     unlink_class();
  2190   init_implementor();
  2192   constants()->remove_unshareable_info();
  2194   for (int i = 0; i < methods()->length(); i++) {
  2195     Method* m = methods()->at(i);
  2196     m->remove_unshareable_info();
  2199   // Need to reinstate when reading back the class.
  2200   set_init_lock(NULL);
  2202   // do array classes also.
  2203   array_klasses_do(remove_unshareable_in_class);
  2206 void restore_unshareable_in_class(Klass* k, TRAPS) {
  2207   k->restore_unshareable_info(CHECK);
  2210 void InstanceKlass::restore_unshareable_info(TRAPS) {
  2211   Klass::restore_unshareable_info(CHECK);
  2212   instanceKlassHandle ik(THREAD, this);
  2214   Array<Method*>* methods = ik->methods();
  2215   int num_methods = methods->length();
  2216   for (int index2 = 0; index2 < num_methods; ++index2) {
  2217     methodHandle m(THREAD, methods->at(index2));
  2218     m()->link_method(m, CHECK);
  2219     // restore method's vtable by calling a virtual function
  2220     m->restore_vtable();
  2222   if (JvmtiExport::has_redefined_a_class()) {
  2223     // Reinitialize vtable because RedefineClasses may have changed some
  2224     // entries in this vtable for super classes so the CDS vtable might
  2225     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2226     // vtables in the shared system dictionary, only the main one.
  2227     // It also redefines the itable too so fix that too.
  2228     ResourceMark rm(THREAD);
  2229     ik->vtable()->initialize_vtable(false, CHECK);
  2230     ik->itable()->initialize_itable(false, CHECK);
  2233   // Allocate a simple java object for a lock.
  2234   // This needs to be a java object because during class initialization
  2235   // it can be held across a java call.
  2236   typeArrayOop r = oopFactory::new_typeArray(T_INT, 0, CHECK);
  2237   Handle h(THREAD, (oop)r);
  2238   ik->set_init_lock(h());
  2240   // restore constant pool resolved references
  2241   ik->constants()->restore_unshareable_info(CHECK);
  2243   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2246 static void clear_all_breakpoints(Method* m) {
  2247   m->clear_all_breakpoints();
  2250 void InstanceKlass::release_C_heap_structures() {
  2251   // Deallocate oop map cache
  2252   if (_oop_map_cache != NULL) {
  2253     delete _oop_map_cache;
  2254     _oop_map_cache = NULL;
  2257   // Deallocate JNI identifiers for jfieldIDs
  2258   JNIid::deallocate(jni_ids());
  2259   set_jni_ids(NULL);
  2261   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2262   if (jmeths != (jmethodID*)NULL) {
  2263     release_set_methods_jmethod_ids(NULL);
  2264     FreeHeap(jmeths);
  2267   int* indices = methods_cached_itable_indices_acquire();
  2268   if (indices != (int*)NULL) {
  2269     release_set_methods_cached_itable_indices(NULL);
  2270     FreeHeap(indices);
  2273   // release dependencies
  2274   nmethodBucket* b = _dependencies;
  2275   _dependencies = NULL;
  2276   while (b != NULL) {
  2277     nmethodBucket* next = b->next();
  2278     delete b;
  2279     b = next;
  2282   // Deallocate breakpoint records
  2283   if (breakpoints() != 0x0) {
  2284     methods_do(clear_all_breakpoints);
  2285     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2288   // deallocate information about previous versions
  2289   if (_previous_versions != NULL) {
  2290     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2291       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2292       delete pv_node;
  2294     delete _previous_versions;
  2295     _previous_versions = NULL;
  2298   // deallocate the cached class file
  2299   if (_cached_class_file_bytes != NULL) {
  2300     os::free(_cached_class_file_bytes, mtClass);
  2301     _cached_class_file_bytes = NULL;
  2302     _cached_class_file_len = 0;
  2305   // Decrement symbol reference counts associated with the unloaded class.
  2306   if (_name != NULL) _name->decrement_refcount();
  2307   // unreference array name derived from this class name (arrays of an unloaded
  2308   // class can't be referenced anymore).
  2309   if (_array_name != NULL)  _array_name->decrement_refcount();
  2310   if (_source_file_name != NULL) _source_file_name->decrement_refcount();
  2311   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2314 void InstanceKlass::set_source_file_name(Symbol* n) {
  2315   _source_file_name = n;
  2316   if (_source_file_name != NULL) _source_file_name->increment_refcount();
  2319 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2320   if (array == NULL) {
  2321     _source_debug_extension = NULL;
  2322   } else {
  2323     // Adding one to the attribute length in order to store a null terminator
  2324     // character could cause an overflow because the attribute length is
  2325     // already coded with an u4 in the classfile, but in practice, it's
  2326     // unlikely to happen.
  2327     assert((length+1) > length, "Overflow checking");
  2328     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2329     for (int i = 0; i < length; i++) {
  2330       sde[i] = array[i];
  2332     sde[length] = '\0';
  2333     _source_debug_extension = sde;
  2337 address InstanceKlass::static_field_addr(int offset) {
  2338   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + (intptr_t)java_mirror());
  2342 const char* InstanceKlass::signature_name() const {
  2343   const char* src = (const char*) (name()->as_C_string());
  2344   const int src_length = (int)strlen(src);
  2345   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
  2346   int src_index = 0;
  2347   int dest_index = 0;
  2348   dest[dest_index++] = 'L';
  2349   while (src_index < src_length) {
  2350     dest[dest_index++] = src[src_index++];
  2352   dest[dest_index++] = ';';
  2353   dest[dest_index] = '\0';
  2354   return dest;
  2357 // different verisons of is_same_class_package
  2358 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2359   Klass* class1 = this;
  2360   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2361   Symbol* classname1 = class1->name();
  2363   if (class2->oop_is_objArray()) {
  2364     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2366   oop classloader2;
  2367   if (class2->oop_is_instance()) {
  2368     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2369   } else {
  2370     assert(class2->oop_is_typeArray(), "should be type array");
  2371     classloader2 = NULL;
  2373   Symbol* classname2 = class2->name();
  2375   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2376                                               classloader2, classname2);
  2379 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2380   Klass* class1 = this;
  2381   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2382   Symbol* classname1 = class1->name();
  2384   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2385                                               classloader2, classname2);
  2388 // return true if two classes are in the same package, classloader
  2389 // and classname information is enough to determine a class's package
  2390 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2391                                           oop class_loader2, Symbol* class_name2) {
  2392   if (class_loader1 != class_loader2) {
  2393     return false;
  2394   } else if (class_name1 == class_name2) {
  2395     return true;                // skip painful bytewise comparison
  2396   } else {
  2397     ResourceMark rm;
  2399     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2400     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2401     // Otherwise, we just compare jbyte values between the strings.
  2402     const jbyte *name1 = class_name1->base();
  2403     const jbyte *name2 = class_name2->base();
  2405     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2406     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2408     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2409       // One of the two doesn't have a package.  Only return true
  2410       // if the other one also doesn't have a package.
  2411       return last_slash1 == last_slash2;
  2412     } else {
  2413       // Skip over '['s
  2414       if (*name1 == '[') {
  2415         do {
  2416           name1++;
  2417         } while (*name1 == '[');
  2418         if (*name1 != 'L') {
  2419           // Something is terribly wrong.  Shouldn't be here.
  2420           return false;
  2423       if (*name2 == '[') {
  2424         do {
  2425           name2++;
  2426         } while (*name2 == '[');
  2427         if (*name2 != 'L') {
  2428           // Something is terribly wrong.  Shouldn't be here.
  2429           return false;
  2433       // Check that package part is identical
  2434       int length1 = last_slash1 - name1;
  2435       int length2 = last_slash2 - name2;
  2437       return UTF8::equal(name1, length1, name2, length2);
  2442 // Returns true iff super_method can be overridden by a method in targetclassname
  2443 // See JSL 3rd edition 8.4.6.1
  2444 // Assumes name-signature match
  2445 // "this" is InstanceKlass of super_method which must exist
  2446 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2447 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2448    // Private methods can not be overridden
  2449    if (super_method->is_private()) {
  2450      return false;
  2452    // If super method is accessible, then override
  2453    if ((super_method->is_protected()) ||
  2454        (super_method->is_public())) {
  2455      return true;
  2457    // Package-private methods are not inherited outside of package
  2458    assert(super_method->is_package_private(), "must be package private");
  2459    return(is_same_class_package(targetclassloader(), targetclassname));
  2462 /* defined for now in jvm.cpp, for historical reasons *--
  2463 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2464                                                      Symbol*& simple_name_result, TRAPS) {
  2465   ...
  2467 */
  2469 // tell if two classes have the same enclosing class (at package level)
  2470 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2471                                                 Klass* class2_oop, TRAPS) {
  2472   if (class2_oop == class1())                       return true;
  2473   if (!class2_oop->oop_is_instance())  return false;
  2474   instanceKlassHandle class2(THREAD, class2_oop);
  2476   // must be in same package before we try anything else
  2477   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2478     return false;
  2480   // As long as there is an outer1.getEnclosingClass,
  2481   // shift the search outward.
  2482   instanceKlassHandle outer1 = class1;
  2483   for (;;) {
  2484     // As we walk along, look for equalities between outer1 and class2.
  2485     // Eventually, the walks will terminate as outer1 stops
  2486     // at the top-level class around the original class.
  2487     bool ignore_inner_is_member;
  2488     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2489                                                     CHECK_false);
  2490     if (next == NULL)  break;
  2491     if (next == class2())  return true;
  2492     outer1 = instanceKlassHandle(THREAD, next);
  2495   // Now do the same for class2.
  2496   instanceKlassHandle outer2 = class2;
  2497   for (;;) {
  2498     bool ignore_inner_is_member;
  2499     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2500                                                     CHECK_false);
  2501     if (next == NULL)  break;
  2502     // Might as well check the new outer against all available values.
  2503     if (next == class1())  return true;
  2504     if (next == outer1())  return true;
  2505     outer2 = instanceKlassHandle(THREAD, next);
  2508   // If by this point we have not found an equality between the
  2509   // two classes, we know they are in separate package members.
  2510   return false;
  2514 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2515   jint access = access_flags().as_int();
  2517   // But check if it happens to be member class.
  2518   instanceKlassHandle ik(THREAD, this);
  2519   InnerClassesIterator iter(ik);
  2520   for (; !iter.done(); iter.next()) {
  2521     int ioff = iter.inner_class_info_index();
  2522     // Inner class attribute can be zero, skip it.
  2523     // Strange but true:  JVM spec. allows null inner class refs.
  2524     if (ioff == 0) continue;
  2526     // only look at classes that are already loaded
  2527     // since we are looking for the flags for our self.
  2528     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2529     if ((ik->name() == inner_name)) {
  2530       // This is really a member class.
  2531       access = iter.inner_access_flags();
  2532       break;
  2535   // Remember to strip ACC_SUPER bit
  2536   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2539 jint InstanceKlass::jvmti_class_status() const {
  2540   jint result = 0;
  2542   if (is_linked()) {
  2543     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2546   if (is_initialized()) {
  2547     assert(is_linked(), "Class status is not consistent");
  2548     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2550   if (is_in_error_state()) {
  2551     result |= JVMTI_CLASS_STATUS_ERROR;
  2553   return result;
  2556 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2557   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2558   int method_table_offset_in_words = ioe->offset()/wordSize;
  2559   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2560                        / itableOffsetEntry::size();
  2562   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2563     // If the interface isn't implemented by the receiver class,
  2564     // the VM should throw IncompatibleClassChangeError.
  2565     if (cnt >= nof_interfaces) {
  2566       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2569     Klass* ik = ioe->interface_klass();
  2570     if (ik == holder) break;
  2573   itableMethodEntry* ime = ioe->first_method_entry(this);
  2574   Method* m = ime[index].method();
  2575   if (m == NULL) {
  2576     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2578   return m;
  2581 // On-stack replacement stuff
  2582 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2583   // only one compilation can be active
  2584   NEEDS_CLEANUP
  2585   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2586   OsrList_lock->lock_without_safepoint_check();
  2587   assert(n->is_osr_method(), "wrong kind of nmethod");
  2588   n->set_osr_link(osr_nmethods_head());
  2589   set_osr_nmethods_head(n);
  2590   // Raise the highest osr level if necessary
  2591   if (TieredCompilation) {
  2592     Method* m = n->method();
  2593     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2595   // Remember to unlock again
  2596   OsrList_lock->unlock();
  2598   // Get rid of the osr methods for the same bci that have lower levels.
  2599   if (TieredCompilation) {
  2600     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2601       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2602       if (inv != NULL && inv->is_in_use()) {
  2603         inv->make_not_entrant();
  2610 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2611   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2612   OsrList_lock->lock_without_safepoint_check();
  2613   assert(n->is_osr_method(), "wrong kind of nmethod");
  2614   nmethod* last = NULL;
  2615   nmethod* cur  = osr_nmethods_head();
  2616   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2617   Method* m = n->method();
  2618   // Search for match
  2619   while(cur != NULL && cur != n) {
  2620     if (TieredCompilation) {
  2621       // Find max level before n
  2622       max_level = MAX2(max_level, cur->comp_level());
  2624     last = cur;
  2625     cur = cur->osr_link();
  2627   nmethod* next = NULL;
  2628   if (cur == n) {
  2629     next = cur->osr_link();
  2630     if (last == NULL) {
  2631       // Remove first element
  2632       set_osr_nmethods_head(next);
  2633     } else {
  2634       last->set_osr_link(next);
  2637   n->set_osr_link(NULL);
  2638   if (TieredCompilation) {
  2639     cur = next;
  2640     while (cur != NULL) {
  2641       // Find max level after n
  2642       max_level = MAX2(max_level, cur->comp_level());
  2643       cur = cur->osr_link();
  2645     m->set_highest_osr_comp_level(max_level);
  2647   // Remember to unlock again
  2648   OsrList_lock->unlock();
  2651 nmethod* InstanceKlass::lookup_osr_nmethod(Method* const m, int bci, int comp_level, bool match_level) const {
  2652   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2653   OsrList_lock->lock_without_safepoint_check();
  2654   nmethod* osr = osr_nmethods_head();
  2655   nmethod* best = NULL;
  2656   while (osr != NULL) {
  2657     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2658     // There can be a time when a c1 osr method exists but we are waiting
  2659     // for a c2 version. When c2 completes its osr nmethod we will trash
  2660     // the c1 version and only be able to find the c2 version. However
  2661     // while we overflow in the c1 code at back branches we don't want to
  2662     // try and switch to the same code as we are already running
  2664     if (osr->method() == m &&
  2665         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2666       if (match_level) {
  2667         if (osr->comp_level() == comp_level) {
  2668           // Found a match - return it.
  2669           OsrList_lock->unlock();
  2670           return osr;
  2672       } else {
  2673         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2674           if (osr->comp_level() == CompLevel_highest_tier) {
  2675             // Found the best possible - return it.
  2676             OsrList_lock->unlock();
  2677             return osr;
  2679           best = osr;
  2683     osr = osr->osr_link();
  2685   OsrList_lock->unlock();
  2686   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2687     return best;
  2689   return NULL;
  2692 // -----------------------------------------------------------------------------------------------------
  2693 // Printing
  2695 #ifndef PRODUCT
  2697 #define BULLET  " - "
  2699 static const char* state_names[] = {
  2700   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  2701 };
  2703 void InstanceKlass::print_on(outputStream* st) const {
  2704   assert(is_klass(), "must be klass");
  2705   Klass::print_on(st);
  2707   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  2708   st->print(BULLET"klass size:        %d", size());                               st->cr();
  2709   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  2710   st->print(BULLET"state:             "); st->print_cr(state_names[_init_state]);
  2711   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  2712   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  2713   st->print(BULLET"sub:               ");
  2714   Klass* sub = subklass();
  2715   int n;
  2716   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  2717     if (n < MaxSubklassPrintSize) {
  2718       sub->print_value_on(st);
  2719       st->print("   ");
  2722   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  2723   st->cr();
  2725   if (is_interface()) {
  2726     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  2727     if (nof_implementors() == 1) {
  2728       st->print_cr(BULLET"implementor:    ");
  2729       st->print("   ");
  2730       implementor()->print_value_on(st);
  2731       st->cr();
  2735   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  2736   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  2737   if (Verbose) {
  2738     Array<Method*>* method_array = methods();
  2739     for(int i = 0; i < method_array->length(); i++) {
  2740       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  2743   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);       st->cr();
  2744   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  2745   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  2746   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  2747   if (class_loader_data() != NULL) {
  2748     st->print(BULLET"class loader data:  ");
  2749     class_loader_data()->print_value_on(st);
  2750     st->cr();
  2752   st->print(BULLET"protection domain: "); ((InstanceKlass*)this)->protection_domain()->print_value_on(st); st->cr();
  2753   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  2754   st->print(BULLET"signers:           "); signers()->print_value_on(st);               st->cr();
  2755   st->print(BULLET"init_lock:         "); ((oop)init_lock())->print_value_on(st);             st->cr();
  2756   if (source_file_name() != NULL) {
  2757     st->print(BULLET"source file:       ");
  2758     source_file_name()->print_value_on(st);
  2759     st->cr();
  2761   if (source_debug_extension() != NULL) {
  2762     st->print(BULLET"source debug extension:       ");
  2763     st->print("%s", source_debug_extension());
  2764     st->cr();
  2766   st->print(BULLET"annotations:       "); annotations()->print_value_on(st); st->cr();
  2768     ResourceMark rm;
  2769     // PreviousVersionInfo objects returned via PreviousVersionWalker
  2770     // contain a GrowableArray of handles. We have to clean up the
  2771     // GrowableArray _after_ the PreviousVersionWalker destructor
  2772     // has destroyed the handles.
  2774       bool have_pv = false;
  2775       PreviousVersionWalker pvw((InstanceKlass*)this);
  2776       for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
  2777            pv_info != NULL; pv_info = pvw.next_previous_version()) {
  2778         if (!have_pv)
  2779           st->print(BULLET"previous version:  ");
  2780         have_pv = true;
  2781         pv_info->prev_constant_pool_handle()()->print_value_on(st);
  2783       if (have_pv)  st->cr();
  2784     } // pvw is cleaned up
  2785   } // rm is cleaned up
  2787   if (generic_signature() != NULL) {
  2788     st->print(BULLET"generic signature: ");
  2789     generic_signature()->print_value_on(st);
  2790     st->cr();
  2792   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  2793   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  2794   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  2795   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  2796   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  2797   FieldPrinter print_static_field(st);
  2798   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  2799   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  2800   FieldPrinter print_nonstatic_field(st);
  2801   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  2803   st->print(BULLET"non-static oop maps: ");
  2804   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  2805   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  2806   while (map < end_map) {
  2807     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  2808     map++;
  2810   st->cr();
  2813 #endif //PRODUCT
  2815 void InstanceKlass::print_value_on(outputStream* st) const {
  2816   assert(is_klass(), "must be klass");
  2817   name()->print_value_on(st);
  2820 #ifndef PRODUCT
  2822 void FieldPrinter::do_field(fieldDescriptor* fd) {
  2823   _st->print(BULLET);
  2824    if (_obj == NULL) {
  2825      fd->print_on(_st);
  2826      _st->cr();
  2827    } else {
  2828      fd->print_on_for(_st, _obj);
  2829      _st->cr();
  2834 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  2835   Klass::oop_print_on(obj, st);
  2837   if (this == SystemDictionary::String_klass()) {
  2838     typeArrayOop value  = java_lang_String::value(obj);
  2839     juint        offset = java_lang_String::offset(obj);
  2840     juint        length = java_lang_String::length(obj);
  2841     if (value != NULL &&
  2842         value->is_typeArray() &&
  2843         offset          <= (juint) value->length() &&
  2844         offset + length <= (juint) value->length()) {
  2845       st->print(BULLET"string: ");
  2846       Handle h_obj(obj);
  2847       java_lang_String::print(h_obj, st);
  2848       st->cr();
  2849       if (!WizardMode)  return;  // that is enough
  2853   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  2854   FieldPrinter print_field(st, obj);
  2855   do_nonstatic_fields(&print_field);
  2857   if (this == SystemDictionary::Class_klass()) {
  2858     st->print(BULLET"signature: ");
  2859     java_lang_Class::print_signature(obj, st);
  2860     st->cr();
  2861     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  2862     st->print(BULLET"fake entry for mirror: ");
  2863     mirrored_klass->print_value_on_maybe_null(st);
  2864     st->cr();
  2865     st->print(BULLET"fake entry resolved_constructor: ");
  2866     Method* ctor = java_lang_Class::resolved_constructor(obj);
  2867     ctor->print_value_on_maybe_null(st);
  2868     Klass* array_klass = java_lang_Class::array_klass(obj);
  2869     st->cr();
  2870     st->print(BULLET"fake entry for array: ");
  2871     array_klass->print_value_on_maybe_null(st);
  2872     st->cr();
  2873     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  2874     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  2875     Klass* real_klass = java_lang_Class::as_Klass(obj);
  2876     if (real_klass != NULL && real_klass->oop_is_instance()) {
  2877       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  2879   } else if (this == SystemDictionary::MethodType_klass()) {
  2880     st->print(BULLET"signature: ");
  2881     java_lang_invoke_MethodType::print_signature(obj, st);
  2882     st->cr();
  2886 #endif //PRODUCT
  2888 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  2889   st->print("a ");
  2890   name()->print_value_on(st);
  2891   obj->print_address_on(st);
  2892   if (this == SystemDictionary::String_klass()
  2893       && java_lang_String::value(obj) != NULL) {
  2894     ResourceMark rm;
  2895     int len = java_lang_String::length(obj);
  2896     int plen = (len < 24 ? len : 12);
  2897     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  2898     st->print(" = \"%s\"", str);
  2899     if (len > plen)
  2900       st->print("...[%d]", len);
  2901   } else if (this == SystemDictionary::Class_klass()) {
  2902     Klass* k = java_lang_Class::as_Klass(obj);
  2903     st->print(" = ");
  2904     if (k != NULL) {
  2905       k->print_value_on(st);
  2906     } else {
  2907       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  2908       st->print("%s", tname ? tname : "type?");
  2910   } else if (this == SystemDictionary::MethodType_klass()) {
  2911     st->print(" = ");
  2912     java_lang_invoke_MethodType::print_signature(obj, st);
  2913   } else if (java_lang_boxing_object::is_instance(obj)) {
  2914     st->print(" = ");
  2915     java_lang_boxing_object::print(obj, st);
  2916   } else if (this == SystemDictionary::LambdaForm_klass()) {
  2917     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  2918     if (vmentry != NULL) {
  2919       st->print(" => ");
  2920       vmentry->print_value_on(st);
  2922   } else if (this == SystemDictionary::MemberName_klass()) {
  2923     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  2924     if (vmtarget != NULL) {
  2925       st->print(" = ");
  2926       vmtarget->print_value_on(st);
  2927     } else {
  2928       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  2929       st->print(".");
  2930       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  2935 const char* InstanceKlass::internal_name() const {
  2936   return external_name();
  2939 // Verification
  2941 class VerifyFieldClosure: public OopClosure {
  2942  protected:
  2943   template <class T> void do_oop_work(T* p) {
  2944     oop obj = oopDesc::load_decode_heap_oop(p);
  2945     if (!obj->is_oop_or_null()) {
  2946       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  2947       Universe::print();
  2948       guarantee(false, "boom");
  2951  public:
  2952   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  2953   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  2954 };
  2956 void InstanceKlass::verify_on(outputStream* st) {
  2957   Klass::verify_on(st);
  2958   Thread *thread = Thread::current();
  2960 #ifndef PRODUCT
  2961   // Avoid redundant verifies
  2962   if (_verify_count == Universe::verify_count()) return;
  2963   _verify_count = Universe::verify_count();
  2964 #endif
  2965   // Verify that klass is present in SystemDictionary
  2966   if (is_loaded() && !is_anonymous()) {
  2967     Symbol* h_name = name();
  2968     SystemDictionary::verify_obj_klass_present(h_name, class_loader_data());
  2971   // Verify static fields
  2972   VerifyFieldClosure blk;
  2974   // Verify vtables
  2975   if (is_linked()) {
  2976     ResourceMark rm(thread);
  2977     // $$$ This used to be done only for m/s collections.  Doing it
  2978     // always seemed a valid generalization.  (DLD -- 6/00)
  2979     vtable()->verify(st);
  2982   // Verify first subklass
  2983   if (subklass_oop() != NULL) {
  2984     guarantee(subklass_oop()->is_metadata(), "should be in metaspace");
  2985     guarantee(subklass_oop()->is_klass(), "should be klass");
  2988   // Verify siblings
  2989   Klass* super = this->super();
  2990   Klass* sib = next_sibling();
  2991   if (sib != NULL) {
  2992     if (sib == this) {
  2993       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  2996     guarantee(sib->is_metadata(), "should be in metaspace");
  2997     guarantee(sib->is_klass(), "should be klass");
  2998     guarantee(sib->super() == super, "siblings should have same superklass");
  3001   // Verify implementor fields
  3002   Klass* im = implementor();
  3003   if (im != NULL) {
  3004     guarantee(is_interface(), "only interfaces should have implementor set");
  3005     guarantee(im->is_klass(), "should be klass");
  3006     guarantee(!im->is_interface() || im == this,
  3007       "implementors cannot be interfaces");
  3010   // Verify local interfaces
  3011   if (local_interfaces()) {
  3012     Array<Klass*>* local_interfaces = this->local_interfaces();
  3013     for (int j = 0; j < local_interfaces->length(); j++) {
  3014       Klass* e = local_interfaces->at(j);
  3015       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3019   // Verify transitive interfaces
  3020   if (transitive_interfaces() != NULL) {
  3021     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3022     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3023       Klass* e = transitive_interfaces->at(j);
  3024       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3028   // Verify methods
  3029   if (methods() != NULL) {
  3030     Array<Method*>* methods = this->methods();
  3031     for (int j = 0; j < methods->length(); j++) {
  3032       guarantee(methods->at(j)->is_metadata(), "should be in metaspace");
  3033       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3035     for (int j = 0; j < methods->length() - 1; j++) {
  3036       Method* m1 = methods->at(j);
  3037       Method* m2 = methods->at(j + 1);
  3038       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3042   // Verify method ordering
  3043   if (method_ordering() != NULL) {
  3044     Array<int>* method_ordering = this->method_ordering();
  3045     int length = method_ordering->length();
  3046     if (JvmtiExport::can_maintain_original_method_order() ||
  3047         (UseSharedSpaces && length != 0)) {
  3048       guarantee(length == methods()->length(), "invalid method ordering length");
  3049       jlong sum = 0;
  3050       for (int j = 0; j < length; j++) {
  3051         int original_index = method_ordering->at(j);
  3052         guarantee(original_index >= 0, "invalid method ordering index");
  3053         guarantee(original_index < length, "invalid method ordering index");
  3054         sum += original_index;
  3056       // Verify sum of indices 0,1,...,length-1
  3057       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3058     } else {
  3059       guarantee(length == 0, "invalid method ordering length");
  3063   // Verify JNI static field identifiers
  3064   if (jni_ids() != NULL) {
  3065     jni_ids()->verify(this);
  3068   // Verify other fields
  3069   if (array_klasses() != NULL) {
  3070     guarantee(array_klasses()->is_metadata(), "should be in metaspace");
  3071     guarantee(array_klasses()->is_klass(), "should be klass");
  3073   if (constants() != NULL) {
  3074     guarantee(constants()->is_metadata(), "should be in metaspace");
  3075     guarantee(constants()->is_constantPool(), "should be constant pool");
  3077   if (protection_domain() != NULL) {
  3078     guarantee(protection_domain()->is_oop(), "should be oop");
  3080   if (host_klass() != NULL) {
  3081     guarantee(host_klass()->is_metadata(), "should be in metaspace");
  3082     guarantee(host_klass()->is_klass(), "should be klass");
  3084   if (signers() != NULL) {
  3085     guarantee(signers()->is_objArray(), "should be obj array");
  3089 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3090   Klass::oop_verify_on(obj, st);
  3091   VerifyFieldClosure blk;
  3092   obj->oop_iterate_no_header(&blk);
  3096 // JNIid class for jfieldIDs only
  3097 // Note to reviewers:
  3098 // These JNI functions are just moved over to column 1 and not changed
  3099 // in the compressed oops workspace.
  3100 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3101   _holder = holder;
  3102   _offset = offset;
  3103   _next = next;
  3104   debug_only(_is_static_field_id = false;)
  3108 JNIid* JNIid::find(int offset) {
  3109   JNIid* current = this;
  3110   while (current != NULL) {
  3111     if (current->offset() == offset) return current;
  3112     current = current->next();
  3114   return NULL;
  3117 void JNIid::deallocate(JNIid* current) {
  3118   while (current != NULL) {
  3119     JNIid* next = current->next();
  3120     delete current;
  3121     current = next;
  3126 void JNIid::verify(Klass* holder) {
  3127   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3128   int end_field_offset;
  3129   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3131   JNIid* current = this;
  3132   while (current != NULL) {
  3133     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3134 #ifdef ASSERT
  3135     int o = current->offset();
  3136     if (current->is_static_field_id()) {
  3137       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3139 #endif
  3140     current = current->next();
  3145 #ifdef ASSERT
  3146 void InstanceKlass::set_init_state(ClassState state) {
  3147   bool good_state = is_shared() ? (_init_state <= state)
  3148                                                : (_init_state < state);
  3149   assert(good_state || state == allocated, "illegal state transition");
  3150   _init_state = (u1)state;
  3152 #endif
  3155 // RedefineClasses() support for previous versions:
  3157 // Purge previous versions
  3158 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3159   if (ik->previous_versions() != NULL) {
  3160     // This klass has previous versions so see what we can cleanup
  3161     // while it is safe to do so.
  3163     int deleted_count = 0;    // leave debugging breadcrumbs
  3164     int live_count = 0;
  3165     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3166                        ClassLoaderData::the_null_class_loader_data() :
  3167                        ik->class_loader_data();
  3169     // RC_TRACE macro has an embedded ResourceMark
  3170     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3171       ik->external_name(), ik->previous_versions()->length()));
  3173     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3174       // check the previous versions array
  3175       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3176       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3177       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3179       ConstantPool* pvcp = cp_ref;
  3180       if (!pvcp->on_stack()) {
  3181         // If the constant pool isn't on stack, none of the methods
  3182         // are executing.  Delete all the methods, the constant pool and
  3183         // and this previous version node.
  3184         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3185         if (method_refs != NULL) {
  3186           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3187             Method* method = method_refs->at(j);
  3188             assert(method != NULL, "method ref was unexpectedly cleared");
  3189             method_refs->remove_at(j);
  3190             // method will be freed with associated class.
  3193         // Remove the constant pool
  3194         delete pv_node;
  3195         // Since we are traversing the array backwards, we don't have to
  3196         // do anything special with the index.
  3197         ik->previous_versions()->remove_at(i);
  3198         deleted_count++;
  3199         continue;
  3200       } else {
  3201         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3202         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3203         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3204         live_count++;
  3207       // At least one method is live in this previous version, clean out
  3208       // the others or mark them as obsolete.
  3209       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3210       if (method_refs != NULL) {
  3211         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3212           method_refs->length()));
  3213         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3214           Method* method = method_refs->at(j);
  3215           assert(method != NULL, "method ref was unexpectedly cleared");
  3217           // Remove the emcp method if it's not executing
  3218           // If it's been made obsolete by a redefinition of a non-emcp
  3219           // method, mark it as obsolete but leave it to clean up later.
  3220           if (!method->on_stack()) {
  3221             method_refs->remove_at(j);
  3222           } else if (emcp_method_count == 0) {
  3223             method->set_is_obsolete();
  3224           } else {
  3225             // RC_TRACE macro has an embedded ResourceMark
  3226             RC_TRACE(0x00000200,
  3227               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3228               method->name()->as_C_string(),
  3229               method->signature()->as_C_string(), j, i));
  3234     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3235     RC_TRACE(0x00000200,
  3236       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3237       deleted_count));
  3241 // External interface for use during class unloading.
  3242 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3243   // Call with >0 emcp methods since they are not currently being redefined.
  3244   purge_previous_versions_internal(ik, 1);
  3248 // Potentially add an information node that contains pointers to the
  3249 // interesting parts of the previous version of the_class.
  3250 // This is also where we clean out any unused references.
  3251 // Note that while we delete nodes from the _previous_versions
  3252 // array, we never delete the array itself until the klass is
  3253 // unloaded. The has_been_redefined() query depends on that fact.
  3254 //
  3255 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3256        BitMap* emcp_methods, int emcp_method_count) {
  3257   assert(Thread::current()->is_VM_thread(),
  3258          "only VMThread can add previous versions");
  3260   if (_previous_versions == NULL) {
  3261     // This is the first previous version so make some space.
  3262     // Start with 2 elements under the assumption that the class
  3263     // won't be redefined much.
  3264     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3265                             GrowableArray<PreviousVersionNode *>(2, true);
  3268   ConstantPool* cp_ref = ikh->constants();
  3270   // RC_TRACE macro has an embedded ResourceMark
  3271   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3272                         "on_stack=%d",
  3273     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3274     cp_ref->on_stack()));
  3276   // If the constant pool for this previous version of the class
  3277   // is not marked as being on the stack, then none of the methods
  3278   // in this previous version of the class are on the stack so
  3279   // we don't need to create a new PreviousVersionNode. However,
  3280   // we still need to examine older previous versions below.
  3281   Array<Method*>* old_methods = ikh->methods();
  3283   if (cp_ref->on_stack()) {
  3284   PreviousVersionNode * pv_node = NULL;
  3285   if (emcp_method_count == 0) {
  3286       // non-shared ConstantPool gets a reference
  3287       pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), NULL);
  3288     RC_TRACE(0x00000400,
  3289         ("add: all methods are obsolete; flushing any EMCP refs"));
  3290   } else {
  3291     int local_count = 0;
  3292       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3293         GrowableArray<Method*>(emcp_method_count, true);
  3294     for (int i = 0; i < old_methods->length(); i++) {
  3295       if (emcp_methods->at(i)) {
  3296           // this old method is EMCP. Save it only if it's on the stack
  3297           Method* old_method = old_methods->at(i);
  3298           if (old_method->on_stack()) {
  3299             method_refs->append(old_method);
  3301         if (++local_count >= emcp_method_count) {
  3302           // no more EMCP methods so bail out now
  3303           break;
  3307       // non-shared ConstantPool gets a reference
  3308       pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), method_refs);
  3310     // append new previous version.
  3311   _previous_versions->append(pv_node);
  3314   // Since the caller is the VMThread and we are at a safepoint, this
  3315   // is a good time to clear out unused references.
  3317   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3318     _previous_versions->length()));
  3320   // Purge previous versions not executing on the stack
  3321   purge_previous_versions_internal(this, emcp_method_count);
  3323   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3325   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3326       _previous_versions->length() > 0) {
  3327     // We have a mix of obsolete and EMCP methods so we have to
  3328     // clear out any matching EMCP method entries the hard way.
  3329     int local_count = 0;
  3330     for (int i = 0; i < old_methods->length(); i++) {
  3331       if (!emcp_methods->at(i)) {
  3332         // only obsolete methods are interesting
  3333         Method* old_method = old_methods->at(i);
  3334         Symbol* m_name = old_method->name();
  3335         Symbol* m_signature = old_method->signature();
  3337         // we might not have added the last entry
  3338         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3339           // check the previous versions array for non executing obsolete methods
  3340           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3342           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3343           if (method_refs == NULL) {
  3344             // We have run into a PreviousVersion generation where
  3345             // all methods were made obsolete during that generation's
  3346             // RedefineClasses() operation. At the time of that
  3347             // operation, all EMCP methods were flushed so we don't
  3348             // have to go back any further.
  3349             //
  3350             // A NULL method_refs is different than an empty method_refs.
  3351             // We cannot infer any optimizations about older generations
  3352             // from an empty method_refs for the current generation.
  3353             break;
  3356           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3357             Method* method = method_refs->at(k);
  3359             if (!method->is_obsolete() &&
  3360                 method->name() == m_name &&
  3361                 method->signature() == m_signature) {
  3362               // The current RedefineClasses() call has made all EMCP
  3363               // versions of this method obsolete so mark it as obsolete
  3364               // and remove the reference.
  3365               RC_TRACE(0x00000400,
  3366                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3367                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3369               method->set_is_obsolete();
  3370               // Leave obsolete methods on the previous version list to
  3371               // clean up later.
  3372               break;
  3376           // The previous loop may not find a matching EMCP method, but
  3377           // that doesn't mean that we can optimize and not go any
  3378           // further back in the PreviousVersion generations. The EMCP
  3379           // method for this generation could have already been deleted,
  3380           // but there still may be an older EMCP method that has not
  3381           // been deleted.
  3384         if (++local_count >= obsolete_method_count) {
  3385           // no more obsolete methods so bail out now
  3386           break;
  3391 } // end add_previous_version()
  3394 // Determine if InstanceKlass has a previous version.
  3395 bool InstanceKlass::has_previous_version() const {
  3396   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3397 } // end has_previous_version()
  3400 Method* InstanceKlass::method_with_idnum(int idnum) {
  3401   Method* m = NULL;
  3402   if (idnum < methods()->length()) {
  3403     m = methods()->at(idnum);
  3405   if (m == NULL || m->method_idnum() != idnum) {
  3406     for (int index = 0; index < methods()->length(); ++index) {
  3407       m = methods()->at(index);
  3408       if (m->method_idnum() == idnum) {
  3409         return m;
  3413   return m;
  3417 // Construct a PreviousVersionNode entry for the array hung off
  3418 // the InstanceKlass.
  3419 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3420   bool prev_cp_is_weak, GrowableArray<Method*>* prev_EMCP_methods) {
  3422   _prev_constant_pool = prev_constant_pool;
  3423   _prev_cp_is_weak = prev_cp_is_weak;
  3424   _prev_EMCP_methods = prev_EMCP_methods;
  3428 // Destroy a PreviousVersionNode
  3429 PreviousVersionNode::~PreviousVersionNode() {
  3430   if (_prev_constant_pool != NULL) {
  3431     _prev_constant_pool = NULL;
  3434   if (_prev_EMCP_methods != NULL) {
  3435     delete _prev_EMCP_methods;
  3440 // Construct a PreviousVersionInfo entry
  3441 PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) {
  3442   _prev_constant_pool_handle = constantPoolHandle();  // NULL handle
  3443   _prev_EMCP_method_handles = NULL;
  3445   ConstantPool* cp = pv_node->prev_constant_pool();
  3446   assert(cp != NULL, "constant pool ref was unexpectedly cleared");
  3447   if (cp == NULL) {
  3448     return;  // robustness
  3451   // make the ConstantPool* safe to return
  3452   _prev_constant_pool_handle = constantPoolHandle(cp);
  3454   GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3455   if (method_refs == NULL) {
  3456     // the InstanceKlass did not have any EMCP methods
  3457     return;
  3460   _prev_EMCP_method_handles = new GrowableArray<methodHandle>(10);
  3462   int n_methods = method_refs->length();
  3463   for (int i = 0; i < n_methods; i++) {
  3464     Method* method = method_refs->at(i);
  3465     assert (method != NULL, "method has been cleared");
  3466     if (method == NULL) {
  3467       continue;  // robustness
  3469     // make the Method* safe to return
  3470     _prev_EMCP_method_handles->append(methodHandle(method));
  3475 // Destroy a PreviousVersionInfo
  3476 PreviousVersionInfo::~PreviousVersionInfo() {
  3477   // Since _prev_EMCP_method_handles is not C-heap allocated, we
  3478   // don't have to delete it.
  3482 // Construct a helper for walking the previous versions array
  3483 PreviousVersionWalker::PreviousVersionWalker(InstanceKlass *ik) {
  3484   _previous_versions = ik->previous_versions();
  3485   _current_index = 0;
  3486   // _hm needs no initialization
  3487   _current_p = NULL;
  3491 // Destroy a PreviousVersionWalker
  3492 PreviousVersionWalker::~PreviousVersionWalker() {
  3493   // Delete the current info just in case the caller didn't walk to
  3494   // the end of the previous versions list. No harm if _current_p is
  3495   // already NULL.
  3496   delete _current_p;
  3498   // When _hm is destroyed, all the Handles returned in
  3499   // PreviousVersionInfo objects will be destroyed.
  3500   // Also, after this destructor is finished it will be
  3501   // safe to delete the GrowableArray allocated in the
  3502   // PreviousVersionInfo objects.
  3506 // Return the interesting information for the next previous version
  3507 // of the klass. Returns NULL if there are no more previous versions.
  3508 PreviousVersionInfo* PreviousVersionWalker::next_previous_version() {
  3509   if (_previous_versions == NULL) {
  3510     // no previous versions so nothing to return
  3511     return NULL;
  3514   delete _current_p;  // cleanup the previous info for the caller
  3515   _current_p = NULL;  // reset to NULL so we don't delete same object twice
  3517   int length = _previous_versions->length();
  3519   while (_current_index < length) {
  3520     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3521     PreviousVersionInfo * pv_info = new (ResourceObj::C_HEAP, mtClass)
  3522                                           PreviousVersionInfo(pv_node);
  3524     constantPoolHandle cp_h = pv_info->prev_constant_pool_handle();
  3525     assert (!cp_h.is_null(), "null cp found in previous version");
  3527     // The caller will need to delete pv_info when they are done with it.
  3528     _current_p = pv_info;
  3529     return pv_info;
  3532   // all of the underlying nodes' info has been deleted
  3533   return NULL;
  3534 } // end next_previous_version()

mercurial