src/share/vm/oops/instanceKlass.cpp

Thu, 26 Sep 2013 10:25:02 -0400

author
hseigel
date
Thu, 26 Sep 2013 10:25:02 -0400
changeset 5784
190899198332
parent 5755
0f37d1badced
child 5786
36b97be47bde
permissions
-rw-r--r--

7195622: CheckUnhandledOops has limited usefulness now
Summary: Enable CHECK_UNHANDLED_OOPS in fastdebug builds across all supported platforms.
Reviewed-by: coleenp, hseigel, dholmes, stefank, twisti, ihse, rdurbin
Contributed-by: lois.foltan@oracle.com

     1 /*
     2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "classfile/javaClasses.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "classfile/verifier.hpp"
    29 #include "classfile/vmSymbols.hpp"
    30 #include "compiler/compileBroker.hpp"
    31 #include "gc_implementation/shared/markSweep.inline.hpp"
    32 #include "gc_interface/collectedHeap.inline.hpp"
    33 #include "interpreter/oopMapCache.hpp"
    34 #include "interpreter/rewriter.hpp"
    35 #include "jvmtifiles/jvmti.h"
    36 #include "memory/genOopClosures.inline.hpp"
    37 #include "memory/heapInspection.hpp"
    38 #include "memory/metadataFactory.hpp"
    39 #include "memory/oopFactory.hpp"
    40 #include "oops/fieldStreams.hpp"
    41 #include "oops/instanceClassLoaderKlass.hpp"
    42 #include "oops/instanceKlass.hpp"
    43 #include "oops/instanceMirrorKlass.hpp"
    44 #include "oops/instanceOop.hpp"
    45 #include "oops/klass.inline.hpp"
    46 #include "oops/method.hpp"
    47 #include "oops/oop.inline.hpp"
    48 #include "oops/symbol.hpp"
    49 #include "prims/jvmtiExport.hpp"
    50 #include "prims/jvmtiRedefineClassesTrace.hpp"
    51 #include "prims/jvmtiRedefineClasses.hpp"
    52 #include "prims/methodComparator.hpp"
    53 #include "runtime/fieldDescriptor.hpp"
    54 #include "runtime/handles.inline.hpp"
    55 #include "runtime/javaCalls.hpp"
    56 #include "runtime/mutexLocker.hpp"
    57 #include "runtime/thread.inline.hpp"
    58 #include "services/classLoadingService.hpp"
    59 #include "services/threadService.hpp"
    60 #include "utilities/dtrace.hpp"
    61 #include "utilities/macros.hpp"
    62 #if INCLUDE_ALL_GCS
    63 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    64 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    65 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    66 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    67 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
    68 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    69 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    70 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    71 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    72 #include "oops/oop.pcgc.inline.hpp"
    73 #endif // INCLUDE_ALL_GCS
    74 #ifdef COMPILER1
    75 #include "c1/c1_Compiler.hpp"
    76 #endif
    78 #ifdef DTRACE_ENABLED
    80 #ifndef USDT2
    82 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    83   char*, intptr_t, oop, intptr_t);
    84 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    85   char*, intptr_t, oop, intptr_t, int);
    86 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    87   char*, intptr_t, oop, intptr_t, int);
    88 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    89   char*, intptr_t, oop, intptr_t, int);
    90 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    91   char*, intptr_t, oop, intptr_t, int);
    92 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    93   char*, intptr_t, oop, intptr_t, int);
    94 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
    95   char*, intptr_t, oop, intptr_t, int);
    96 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
    97   char*, intptr_t, oop, intptr_t, int);
    99 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   100   {                                                              \
   101     char* data = NULL;                                           \
   102     int len = 0;                                                 \
   103     Symbol* name = (clss)->name();                               \
   104     if (name != NULL) {                                          \
   105       data = (char*)name->bytes();                               \
   106       len = name->utf8_length();                                 \
   107     }                                                            \
   108     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   109       data, len, SOLARIS_ONLY((void *))(clss)->class_loader(), thread_type);           \
   110   }
   112 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   113   {                                                              \
   114     char* data = NULL;                                           \
   115     int len = 0;                                                 \
   116     Symbol* name = (clss)->name();                               \
   117     if (name != NULL) {                                          \
   118       data = (char*)name->bytes();                               \
   119       len = name->utf8_length();                                 \
   120     }                                                            \
   121     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   122       data, len, SOLARIS_ONLY((void *))(clss)->class_loader(), thread_type, wait);     \
   123   }
   124 #else /* USDT2 */
   126 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   127 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   128 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   129 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   130 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   131 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   132 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   133 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   134 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   135   {                                                              \
   136     char* data = NULL;                                           \
   137     int len = 0;                                                 \
   138     Symbol* name = (clss)->name();                               \
   139     if (name != NULL) {                                          \
   140       data = (char*)name->bytes();                               \
   141       len = name->utf8_length();                                 \
   142     }                                                            \
   143     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   144       data, len, (clss)->class_loader(), thread_type);           \
   145   }
   147 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   148   {                                                              \
   149     char* data = NULL;                                           \
   150     int len = 0;                                                 \
   151     Symbol* name = (clss)->name();                               \
   152     if (name != NULL) {                                          \
   153       data = (char*)name->bytes();                               \
   154       len = name->utf8_length();                                 \
   155     }                                                            \
   156     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   157       data, len, (clss)->class_loader(), thread_type, wait);     \
   158   }
   159 #endif /* USDT2 */
   161 #else //  ndef DTRACE_ENABLED
   163 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   164 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   166 #endif //  ndef DTRACE_ENABLED
   168 volatile int InstanceKlass::_total_instanceKlass_count = 0;
   170 InstanceKlass* InstanceKlass::allocate_instance_klass(
   171                                               ClassLoaderData* loader_data,
   172                                               int vtable_len,
   173                                               int itable_len,
   174                                               int static_field_size,
   175                                               int nonstatic_oop_map_size,
   176                                               ReferenceType rt,
   177                                               AccessFlags access_flags,
   178                                               Symbol* name,
   179                                               Klass* super_klass,
   180                                               bool is_anonymous,
   181                                               TRAPS) {
   183   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   184                                  access_flags.is_interface(), is_anonymous);
   186   // Allocation
   187   InstanceKlass* ik;
   188   if (rt == REF_NONE) {
   189     if (name == vmSymbols::java_lang_Class()) {
   190       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   191         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   192         access_flags, is_anonymous);
   193     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   194           (SystemDictionary::ClassLoader_klass_loaded() &&
   195           super_klass != NULL &&
   196           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   197       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   198         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   199         access_flags, is_anonymous);
   200     } else {
   201       // normal class
   202       ik = new (loader_data, size, THREAD) InstanceKlass(
   203         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   204         access_flags, is_anonymous);
   205     }
   206   } else {
   207     // reference klass
   208     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   209         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   210         access_flags, is_anonymous);
   211   }
   213   // Check for pending exception before adding to the loader data and incrementing
   214   // class count.  Can get OOM here.
   215   if (HAS_PENDING_EXCEPTION) {
   216     return NULL;
   217   }
   219   // Add all classes to our internal class loader list here,
   220   // including classes in the bootstrap (NULL) class loader.
   221   loader_data->add_class(ik);
   223   Atomic::inc(&_total_instanceKlass_count);
   224   return ik;
   225 }
   228 // copy method ordering from resource area to Metaspace
   229 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
   230   if (m != NULL) {
   231     // allocate a new array and copy contents (memcpy?)
   232     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
   233     for (int i = 0; i < m->length(); i++) {
   234       _method_ordering->at_put(i, m->at(i));
   235     }
   236   } else {
   237     _method_ordering = Universe::the_empty_int_array();
   238   }
   239 }
   242 InstanceKlass::InstanceKlass(int vtable_len,
   243                              int itable_len,
   244                              int static_field_size,
   245                              int nonstatic_oop_map_size,
   246                              ReferenceType rt,
   247                              AccessFlags access_flags,
   248                              bool is_anonymous) {
   249   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   251   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   252                                    access_flags.is_interface(), is_anonymous);
   254   set_vtable_length(vtable_len);
   255   set_itable_length(itable_len);
   256   set_static_field_size(static_field_size);
   257   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   258   set_access_flags(access_flags);
   259   _misc_flags = 0;  // initialize to zero
   260   set_is_anonymous(is_anonymous);
   261   assert(size() == iksize, "wrong size for object");
   263   set_array_klasses(NULL);
   264   set_methods(NULL);
   265   set_method_ordering(NULL);
   266   set_local_interfaces(NULL);
   267   set_transitive_interfaces(NULL);
   268   init_implementor();
   269   set_fields(NULL, 0);
   270   set_constants(NULL);
   271   set_class_loader_data(NULL);
   272   set_source_file_name_index(0);
   273   set_source_debug_extension(NULL, 0);
   274   set_array_name(NULL);
   275   set_inner_classes(NULL);
   276   set_static_oop_field_count(0);
   277   set_nonstatic_field_size(0);
   278   set_is_marked_dependent(false);
   279   set_init_state(InstanceKlass::allocated);
   280   set_init_thread(NULL);
   281   set_reference_type(rt);
   282   set_oop_map_cache(NULL);
   283   set_jni_ids(NULL);
   284   set_osr_nmethods_head(NULL);
   285   set_breakpoints(NULL);
   286   init_previous_versions();
   287   set_generic_signature_index(0);
   288   release_set_methods_jmethod_ids(NULL);
   289   set_annotations(NULL);
   290   set_jvmti_cached_class_field_map(NULL);
   291   set_initial_method_idnum(0);
   292   _dependencies = NULL;
   293   set_jvmti_cached_class_field_map(NULL);
   294   set_cached_class_file(NULL);
   295   set_initial_method_idnum(0);
   296   set_minor_version(0);
   297   set_major_version(0);
   298   NOT_PRODUCT(_verify_count = 0;)
   300   // initialize the non-header words to zero
   301   intptr_t* p = (intptr_t*)this;
   302   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
   303     p[index] = NULL_WORD;
   304   }
   306   // Set temporary value until parseClassFile updates it with the real instance
   307   // size.
   308   set_layout_helper(Klass::instance_layout_helper(0, true));
   309 }
   312 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
   313                                        Array<Method*>* methods) {
   314   if (methods != NULL && methods != Universe::the_empty_method_array()) {
   315     for (int i = 0; i < methods->length(); i++) {
   316       Method* method = methods->at(i);
   317       if (method == NULL) continue;  // maybe null if error processing
   318       // Only want to delete methods that are not executing for RedefineClasses.
   319       // The previous version will point to them so they're not totally dangling
   320       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   321       MetadataFactory::free_metadata(loader_data, method);
   322     }
   323     MetadataFactory::free_array<Method*>(loader_data, methods);
   324   }
   325 }
   327 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
   328                                           Klass* super_klass,
   329                                           Array<Klass*>* local_interfaces,
   330                                           Array<Klass*>* transitive_interfaces) {
   331   // Only deallocate transitive interfaces if not empty, same as super class
   332   // or same as local interfaces.  See code in parseClassFile.
   333   Array<Klass*>* ti = transitive_interfaces;
   334   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
   335     // check that the interfaces don't come from super class
   336     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
   337                     InstanceKlass::cast(super_klass)->transitive_interfaces();
   338     if (ti != sti) {
   339       MetadataFactory::free_array<Klass*>(loader_data, ti);
   340     }
   341   }
   343   // local interfaces can be empty
   344   if (local_interfaces != Universe::the_empty_klass_array()) {
   345     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
   346   }
   347 }
   349 // This function deallocates the metadata and C heap pointers that the
   350 // InstanceKlass points to.
   351 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   353   // Orphan the mirror first, CMS thinks it's still live.
   354   if (java_mirror() != NULL) {
   355     java_lang_Class::set_klass(java_mirror(), NULL);
   356   }
   358   // Need to take this class off the class loader data list.
   359   loader_data->remove_class(this);
   361   // The array_klass for this class is created later, after error handling.
   362   // For class redefinition, we keep the original class so this scratch class
   363   // doesn't have an array class.  Either way, assert that there is nothing
   364   // to deallocate.
   365   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   367   // Release C heap allocated data that this might point to, which includes
   368   // reference counting symbol names.
   369   release_C_heap_structures();
   371   deallocate_methods(loader_data, methods());
   372   set_methods(NULL);
   374   if (method_ordering() != Universe::the_empty_int_array()) {
   375     MetadataFactory::free_array<int>(loader_data, method_ordering());
   376   }
   377   set_method_ordering(NULL);
   379   // This array is in Klass, but remove it with the InstanceKlass since
   380   // this place would be the only caller and it can share memory with transitive
   381   // interfaces.
   382   if (secondary_supers() != Universe::the_empty_klass_array() &&
   383       secondary_supers() != transitive_interfaces()) {
   384     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   385   }
   386   set_secondary_supers(NULL);
   388   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
   389   set_transitive_interfaces(NULL);
   390   set_local_interfaces(NULL);
   392   MetadataFactory::free_array<jushort>(loader_data, fields());
   393   set_fields(NULL, 0);
   395   // If a method from a redefined class is using this constant pool, don't
   396   // delete it, yet.  The new class's previous version will point to this.
   397   if (constants() != NULL) {
   398     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   399     MetadataFactory::free_metadata(loader_data, constants());
   400     set_constants(NULL);
   401   }
   403   if (inner_classes() != Universe::the_empty_short_array()) {
   404     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   405   }
   406   set_inner_classes(NULL);
   408   // We should deallocate the Annotations instance
   409   MetadataFactory::free_metadata(loader_data, annotations());
   410   set_annotations(NULL);
   411 }
   413 bool InstanceKlass::should_be_initialized() const {
   414   return !is_initialized();
   415 }
   417 klassVtable* InstanceKlass::vtable() const {
   418   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   419 }
   421 klassItable* InstanceKlass::itable() const {
   422   return new klassItable(instanceKlassHandle(this));
   423 }
   425 void InstanceKlass::eager_initialize(Thread *thread) {
   426   if (!EagerInitialization) return;
   428   if (this->is_not_initialized()) {
   429     // abort if the the class has a class initializer
   430     if (this->class_initializer() != NULL) return;
   432     // abort if it is java.lang.Object (initialization is handled in genesis)
   433     Klass* super = this->super();
   434     if (super == NULL) return;
   436     // abort if the super class should be initialized
   437     if (!InstanceKlass::cast(super)->is_initialized()) return;
   439     // call body to expose the this pointer
   440     instanceKlassHandle this_oop(thread, this);
   441     eager_initialize_impl(this_oop);
   442   }
   443 }
   445 // JVMTI spec thinks there are signers and protection domain in the
   446 // instanceKlass.  These accessors pretend these fields are there.
   447 // The hprof specification also thinks these fields are in InstanceKlass.
   448 oop InstanceKlass::protection_domain() const {
   449   // return the protection_domain from the mirror
   450   return java_lang_Class::protection_domain(java_mirror());
   451 }
   453 // To remove these from requires an incompatible change and CCC request.
   454 objArrayOop InstanceKlass::signers() const {
   455   // return the signers from the mirror
   456   return java_lang_Class::signers(java_mirror());
   457 }
   459 volatile oop InstanceKlass::init_lock() const {
   460   // return the init lock from the mirror
   461   return java_lang_Class::init_lock(java_mirror());
   462 }
   464 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   465   EXCEPTION_MARK;
   466   volatile oop init_lock = this_oop->init_lock();
   467   ObjectLocker ol(init_lock, THREAD);
   469   // abort if someone beat us to the initialization
   470   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   472   ClassState old_state = this_oop->init_state();
   473   link_class_impl(this_oop, true, THREAD);
   474   if (HAS_PENDING_EXCEPTION) {
   475     CLEAR_PENDING_EXCEPTION;
   476     // Abort if linking the class throws an exception.
   478     // Use a test to avoid redundantly resetting the state if there's
   479     // no change.  Set_init_state() asserts that state changes make
   480     // progress, whereas here we might just be spinning in place.
   481     if( old_state != this_oop->_init_state )
   482       this_oop->set_init_state (old_state);
   483   } else {
   484     // linking successfull, mark class as initialized
   485     this_oop->set_init_state (fully_initialized);
   486     // trace
   487     if (TraceClassInitialization) {
   488       ResourceMark rm(THREAD);
   489       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   490     }
   491   }
   492 }
   495 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   496 // process. The step comments refers to the procedure described in that section.
   497 // Note: implementation moved to static method to expose the this pointer.
   498 void InstanceKlass::initialize(TRAPS) {
   499   if (this->should_be_initialized()) {
   500     HandleMark hm(THREAD);
   501     instanceKlassHandle this_oop(THREAD, this);
   502     initialize_impl(this_oop, CHECK);
   503     // Note: at this point the class may be initialized
   504     //       OR it may be in the state of being initialized
   505     //       in case of recursive initialization!
   506   } else {
   507     assert(is_initialized(), "sanity check");
   508   }
   509 }
   512 bool InstanceKlass::verify_code(
   513     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   514   // 1) Verify the bytecodes
   515   Verifier::Mode mode =
   516     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   517   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   518 }
   521 // Used exclusively by the shared spaces dump mechanism to prevent
   522 // classes mapped into the shared regions in new VMs from appearing linked.
   524 void InstanceKlass::unlink_class() {
   525   assert(is_linked(), "must be linked");
   526   _init_state = loaded;
   527 }
   529 void InstanceKlass::link_class(TRAPS) {
   530   assert(is_loaded(), "must be loaded");
   531   if (!is_linked()) {
   532     HandleMark hm(THREAD);
   533     instanceKlassHandle this_oop(THREAD, this);
   534     link_class_impl(this_oop, true, CHECK);
   535   }
   536 }
   538 // Called to verify that a class can link during initialization, without
   539 // throwing a VerifyError.
   540 bool InstanceKlass::link_class_or_fail(TRAPS) {
   541   assert(is_loaded(), "must be loaded");
   542   if (!is_linked()) {
   543     HandleMark hm(THREAD);
   544     instanceKlassHandle this_oop(THREAD, this);
   545     link_class_impl(this_oop, false, CHECK_false);
   546   }
   547   return is_linked();
   548 }
   550 bool InstanceKlass::link_class_impl(
   551     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   552   // check for error state
   553   if (this_oop->is_in_error_state()) {
   554     ResourceMark rm(THREAD);
   555     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   556                this_oop->external_name(), false);
   557   }
   558   // return if already verified
   559   if (this_oop->is_linked()) {
   560     return true;
   561   }
   563   // Timing
   564   // timer handles recursion
   565   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   566   JavaThread* jt = (JavaThread*)THREAD;
   568   // link super class before linking this class
   569   instanceKlassHandle super(THREAD, this_oop->super());
   570   if (super.not_null()) {
   571     if (super->is_interface()) {  // check if super class is an interface
   572       ResourceMark rm(THREAD);
   573       Exceptions::fthrow(
   574         THREAD_AND_LOCATION,
   575         vmSymbols::java_lang_IncompatibleClassChangeError(),
   576         "class %s has interface %s as super class",
   577         this_oop->external_name(),
   578         super->external_name()
   579       );
   580       return false;
   581     }
   583     link_class_impl(super, throw_verifyerror, CHECK_false);
   584   }
   586   // link all interfaces implemented by this class before linking this class
   587   Array<Klass*>* interfaces = this_oop->local_interfaces();
   588   int num_interfaces = interfaces->length();
   589   for (int index = 0; index < num_interfaces; index++) {
   590     HandleMark hm(THREAD);
   591     instanceKlassHandle ih(THREAD, interfaces->at(index));
   592     link_class_impl(ih, throw_verifyerror, CHECK_false);
   593   }
   595   // in case the class is linked in the process of linking its superclasses
   596   if (this_oop->is_linked()) {
   597     return true;
   598   }
   600   // trace only the link time for this klass that includes
   601   // the verification time
   602   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   603                              ClassLoader::perf_class_link_selftime(),
   604                              ClassLoader::perf_classes_linked(),
   605                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   606                              jt->get_thread_stat()->perf_timers_addr(),
   607                              PerfClassTraceTime::CLASS_LINK);
   609   // verification & rewriting
   610   {
   611     volatile oop init_lock = this_oop->init_lock();
   612     ObjectLocker ol(init_lock, THREAD);
   613     // rewritten will have been set if loader constraint error found
   614     // on an earlier link attempt
   615     // don't verify or rewrite if already rewritten
   617     if (!this_oop->is_linked()) {
   618       if (!this_oop->is_rewritten()) {
   619         {
   620           // Timer includes any side effects of class verification (resolution,
   621           // etc), but not recursive entry into verify_code().
   622           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   623                                    ClassLoader::perf_class_verify_selftime(),
   624                                    ClassLoader::perf_classes_verified(),
   625                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   626                                    jt->get_thread_stat()->perf_timers_addr(),
   627                                    PerfClassTraceTime::CLASS_VERIFY);
   628           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   629           if (!verify_ok) {
   630             return false;
   631           }
   632         }
   634         // Just in case a side-effect of verify linked this class already
   635         // (which can sometimes happen since the verifier loads classes
   636         // using custom class loaders, which are free to initialize things)
   637         if (this_oop->is_linked()) {
   638           return true;
   639         }
   641         // also sets rewritten
   642         this_oop->rewrite_class(CHECK_false);
   643       }
   645       // relocate jsrs and link methods after they are all rewritten
   646       this_oop->link_methods(CHECK_false);
   648       // Initialize the vtable and interface table after
   649       // methods have been rewritten since rewrite may
   650       // fabricate new Method*s.
   651       // also does loader constraint checking
   652       if (!this_oop()->is_shared()) {
   653         ResourceMark rm(THREAD);
   654         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   655         this_oop->itable()->initialize_itable(true, CHECK_false);
   656       }
   657 #ifdef ASSERT
   658       else {
   659         ResourceMark rm(THREAD);
   660         this_oop->vtable()->verify(tty, true);
   661         // In case itable verification is ever added.
   662         // this_oop->itable()->verify(tty, true);
   663       }
   664 #endif
   665       this_oop->set_init_state(linked);
   666       if (JvmtiExport::should_post_class_prepare()) {
   667         Thread *thread = THREAD;
   668         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   669         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   670       }
   671     }
   672   }
   673   return true;
   674 }
   677 // Rewrite the byte codes of all of the methods of a class.
   678 // The rewriter must be called exactly once. Rewriting must happen after
   679 // verification but before the first method of the class is executed.
   680 void InstanceKlass::rewrite_class(TRAPS) {
   681   assert(is_loaded(), "must be loaded");
   682   instanceKlassHandle this_oop(THREAD, this);
   683   if (this_oop->is_rewritten()) {
   684     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   685     return;
   686   }
   687   Rewriter::rewrite(this_oop, CHECK);
   688   this_oop->set_rewritten();
   689 }
   691 // Now relocate and link method entry points after class is rewritten.
   692 // This is outside is_rewritten flag. In case of an exception, it can be
   693 // executed more than once.
   694 void InstanceKlass::link_methods(TRAPS) {
   695   int len = methods()->length();
   696   for (int i = len-1; i >= 0; i--) {
   697     methodHandle m(THREAD, methods()->at(i));
   699     // Set up method entry points for compiler and interpreter    .
   700     m->link_method(m, CHECK);
   702     // This is for JVMTI and unrelated to relocator but the last thing we do
   703 #ifdef ASSERT
   704     if (StressMethodComparator) {
   705       ResourceMark rm(THREAD);
   706       static int nmc = 0;
   707       for (int j = i; j >= 0 && j >= i-4; j--) {
   708         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   709         bool z = MethodComparator::methods_EMCP(m(),
   710                    methods()->at(j));
   711         if (j == i && !z) {
   712           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   713           assert(z, "method must compare equal to itself");
   714         }
   715       }
   716     }
   717 #endif //ASSERT
   718   }
   719 }
   722 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   723   // Make sure klass is linked (verified) before initialization
   724   // A class could already be verified, since it has been reflected upon.
   725   this_oop->link_class(CHECK);
   727   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   729   bool wait = false;
   731   // refer to the JVM book page 47 for description of steps
   732   // Step 1
   733   {
   734     volatile oop init_lock = this_oop->init_lock();
   735     ObjectLocker ol(init_lock, THREAD);
   737     Thread *self = THREAD; // it's passed the current thread
   739     // Step 2
   740     // If we were to use wait() instead of waitInterruptibly() then
   741     // we might end up throwing IE from link/symbol resolution sites
   742     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   743     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   744         wait = true;
   745       ol.waitUninterruptibly(CHECK);
   746     }
   748     // Step 3
   749     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   750       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   751       return;
   752     }
   754     // Step 4
   755     if (this_oop->is_initialized()) {
   756       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   757       return;
   758     }
   760     // Step 5
   761     if (this_oop->is_in_error_state()) {
   762       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   763       ResourceMark rm(THREAD);
   764       const char* desc = "Could not initialize class ";
   765       const char* className = this_oop->external_name();
   766       size_t msglen = strlen(desc) + strlen(className) + 1;
   767       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   768       if (NULL == message) {
   769         // Out of memory: can't create detailed error message
   770         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   771       } else {
   772         jio_snprintf(message, msglen, "%s%s", desc, className);
   773         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   774       }
   775     }
   777     // Step 6
   778     this_oop->set_init_state(being_initialized);
   779     this_oop->set_init_thread(self);
   780   }
   782   // Step 7
   783   Klass* super_klass = this_oop->super();
   784   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   785     super_klass->initialize(THREAD);
   787     if (HAS_PENDING_EXCEPTION) {
   788       Handle e(THREAD, PENDING_EXCEPTION);
   789       CLEAR_PENDING_EXCEPTION;
   790       {
   791         EXCEPTION_MARK;
   792         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   793         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   794       }
   795       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   796       THROW_OOP(e());
   797     }
   798   }
   800   if (this_oop->has_default_methods()) {
   801     // Step 7.5: initialize any interfaces which have default methods
   802     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   803       Klass* iface = this_oop->local_interfaces()->at(i);
   804       InstanceKlass* ik = InstanceKlass::cast(iface);
   805       if (ik->has_default_methods() && ik->should_be_initialized()) {
   806         ik->initialize(THREAD);
   808         if (HAS_PENDING_EXCEPTION) {
   809           Handle e(THREAD, PENDING_EXCEPTION);
   810           CLEAR_PENDING_EXCEPTION;
   811           {
   812             EXCEPTION_MARK;
   813             // Locks object, set state, and notify all waiting threads
   814             this_oop->set_initialization_state_and_notify(
   815                 initialization_error, THREAD);
   817             // ignore any exception thrown, superclass initialization error is
   818             // thrown below
   819             CLEAR_PENDING_EXCEPTION;
   820           }
   821           DTRACE_CLASSINIT_PROBE_WAIT(
   822               super__failed, InstanceKlass::cast(this_oop()), -1, wait);
   823           THROW_OOP(e());
   824         }
   825       }
   826     }
   827   }
   829   // Step 8
   830   {
   831     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   832     JavaThread* jt = (JavaThread*)THREAD;
   833     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   834     // Timer includes any side effects of class initialization (resolution,
   835     // etc), but not recursive entry into call_class_initializer().
   836     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   837                              ClassLoader::perf_class_init_selftime(),
   838                              ClassLoader::perf_classes_inited(),
   839                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   840                              jt->get_thread_stat()->perf_timers_addr(),
   841                              PerfClassTraceTime::CLASS_CLINIT);
   842     this_oop->call_class_initializer(THREAD);
   843   }
   845   // Step 9
   846   if (!HAS_PENDING_EXCEPTION) {
   847     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   848     { ResourceMark rm(THREAD);
   849       debug_only(this_oop->vtable()->verify(tty, true);)
   850     }
   851   }
   852   else {
   853     // Step 10 and 11
   854     Handle e(THREAD, PENDING_EXCEPTION);
   855     CLEAR_PENDING_EXCEPTION;
   856     {
   857       EXCEPTION_MARK;
   858       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   859       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   860     }
   861     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   862     if (e->is_a(SystemDictionary::Error_klass())) {
   863       THROW_OOP(e());
   864     } else {
   865       JavaCallArguments args(e);
   866       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   867                 vmSymbols::throwable_void_signature(),
   868                 &args);
   869     }
   870   }
   871   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   872 }
   875 // Note: implementation moved to static method to expose the this pointer.
   876 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   877   instanceKlassHandle kh(THREAD, this);
   878   set_initialization_state_and_notify_impl(kh, state, CHECK);
   879 }
   881 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   882   volatile oop init_lock = this_oop->init_lock();
   883   ObjectLocker ol(init_lock, THREAD);
   884   this_oop->set_init_state(state);
   885   ol.notify_all(CHECK);
   886 }
   888 // The embedded _implementor field can only record one implementor.
   889 // When there are more than one implementors, the _implementor field
   890 // is set to the interface Klass* itself. Following are the possible
   891 // values for the _implementor field:
   892 //   NULL                  - no implementor
   893 //   implementor Klass*    - one implementor
   894 //   self                  - more than one implementor
   895 //
   896 // The _implementor field only exists for interfaces.
   897 void InstanceKlass::add_implementor(Klass* k) {
   898   assert(Compile_lock->owned_by_self(), "");
   899   assert(is_interface(), "not interface");
   900   // Filter out my subinterfaces.
   901   // (Note: Interfaces are never on the subklass list.)
   902   if (InstanceKlass::cast(k)->is_interface()) return;
   904   // Filter out subclasses whose supers already implement me.
   905   // (Note: CHA must walk subclasses of direct implementors
   906   // in order to locate indirect implementors.)
   907   Klass* sk = InstanceKlass::cast(k)->super();
   908   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   909     // We only need to check one immediate superclass, since the
   910     // implements_interface query looks at transitive_interfaces.
   911     // Any supers of the super have the same (or fewer) transitive_interfaces.
   912     return;
   914   Klass* ik = implementor();
   915   if (ik == NULL) {
   916     set_implementor(k);
   917   } else if (ik != this) {
   918     // There is already an implementor. Use itself as an indicator of
   919     // more than one implementors.
   920     set_implementor(this);
   921   }
   923   // The implementor also implements the transitive_interfaces
   924   for (int index = 0; index < local_interfaces()->length(); index++) {
   925     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
   926   }
   927 }
   929 void InstanceKlass::init_implementor() {
   930   if (is_interface()) {
   931     set_implementor(NULL);
   932   }
   933 }
   936 void InstanceKlass::process_interfaces(Thread *thread) {
   937   // link this class into the implementors list of every interface it implements
   938   Klass* this_as_klass_oop = this;
   939   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
   940     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
   941     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
   942     assert(interf->is_interface(), "expected interface");
   943     interf->add_implementor(this_as_klass_oop);
   944   }
   945 }
   947 bool InstanceKlass::can_be_primary_super_slow() const {
   948   if (is_interface())
   949     return false;
   950   else
   951     return Klass::can_be_primary_super_slow();
   952 }
   954 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
   955   // The secondaries are the implemented interfaces.
   956   InstanceKlass* ik = InstanceKlass::cast(this);
   957   Array<Klass*>* interfaces = ik->transitive_interfaces();
   958   int num_secondaries = num_extra_slots + interfaces->length();
   959   if (num_secondaries == 0) {
   960     // Must share this for correct bootstrapping!
   961     set_secondary_supers(Universe::the_empty_klass_array());
   962     return NULL;
   963   } else if (num_extra_slots == 0) {
   964     // The secondary super list is exactly the same as the transitive interfaces.
   965     // Redefine classes has to be careful not to delete this!
   966     set_secondary_supers(interfaces);
   967     return NULL;
   968   } else {
   969     // Copy transitive interfaces to a temporary growable array to be constructed
   970     // into the secondary super list with extra slots.
   971     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
   972     for (int i = 0; i < interfaces->length(); i++) {
   973       secondaries->push(interfaces->at(i));
   974     }
   975     return secondaries;
   976   }
   977 }
   979 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
   980   if (k->is_interface()) {
   981     return implements_interface(k);
   982   } else {
   983     return Klass::compute_is_subtype_of(k);
   984   }
   985 }
   987 bool InstanceKlass::implements_interface(Klass* k) const {
   988   if (this == k) return true;
   989   assert(k->is_interface(), "should be an interface class");
   990   for (int i = 0; i < transitive_interfaces()->length(); i++) {
   991     if (transitive_interfaces()->at(i) == k) {
   992       return true;
   993     }
   994   }
   995   return false;
   996 }
   998 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
   999   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  1000   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
  1001     report_java_out_of_memory("Requested array size exceeds VM limit");
  1002     JvmtiExport::post_array_size_exhausted();
  1003     THROW_OOP_0(Universe::out_of_memory_error_array_size());
  1005   int size = objArrayOopDesc::object_size(length);
  1006   Klass* ak = array_klass(n, CHECK_NULL);
  1007   KlassHandle h_ak (THREAD, ak);
  1008   objArrayOop o =
  1009     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  1010   return o;
  1013 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
  1014   if (TraceFinalizerRegistration) {
  1015     tty->print("Registered ");
  1016     i->print_value_on(tty);
  1017     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  1019   instanceHandle h_i(THREAD, i);
  1020   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  1021   JavaValue result(T_VOID);
  1022   JavaCallArguments args(h_i);
  1023   methodHandle mh (THREAD, Universe::finalizer_register_method());
  1024   JavaCalls::call(&result, mh, &args, CHECK_NULL);
  1025   return h_i();
  1028 instanceOop InstanceKlass::allocate_instance(TRAPS) {
  1029   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  1030   int size = size_helper();  // Query before forming handle.
  1032   KlassHandle h_k(THREAD, this);
  1034   instanceOop i;
  1036   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1037   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1038     i = register_finalizer(i, CHECK_NULL);
  1040   return i;
  1043 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1044   if (is_interface() || is_abstract()) {
  1045     ResourceMark rm(THREAD);
  1046     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1047               : vmSymbols::java_lang_InstantiationException(), external_name());
  1049   if (this == SystemDictionary::Class_klass()) {
  1050     ResourceMark rm(THREAD);
  1051     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1052               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1056 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1057   instanceKlassHandle this_oop(THREAD, this);
  1058   return array_klass_impl(this_oop, or_null, n, THREAD);
  1061 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1062   if (this_oop->array_klasses() == NULL) {
  1063     if (or_null) return NULL;
  1065     ResourceMark rm;
  1066     JavaThread *jt = (JavaThread *)THREAD;
  1068       // Atomic creation of array_klasses
  1069       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1070       MutexLocker ma(MultiArray_lock, THREAD);
  1072       // Check if update has already taken place
  1073       if (this_oop->array_klasses() == NULL) {
  1074         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1075         this_oop->set_array_klasses(k);
  1079   // _this will always be set at this point
  1080   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1081   if (or_null) {
  1082     return oak->array_klass_or_null(n);
  1084   return oak->array_klass(n, CHECK_NULL);
  1087 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1088   return array_klass_impl(or_null, 1, THREAD);
  1091 void InstanceKlass::call_class_initializer(TRAPS) {
  1092   instanceKlassHandle ik (THREAD, this);
  1093   call_class_initializer_impl(ik, THREAD);
  1096 static int call_class_initializer_impl_counter = 0;   // for debugging
  1098 Method* InstanceKlass::class_initializer() {
  1099   Method* clinit = find_method(
  1100       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1101   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1102     return clinit;
  1104   return NULL;
  1107 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1108   if (ReplayCompiles &&
  1109       (ReplaySuppressInitializers == 1 ||
  1110        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1111     // Hide the existence of the initializer for the purpose of replaying the compile
  1112     return;
  1115   methodHandle h_method(THREAD, this_oop->class_initializer());
  1116   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1117   if (TraceClassInitialization) {
  1118     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1119     this_oop->name()->print_value();
  1120     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1122   if (h_method() != NULL) {
  1123     JavaCallArguments args; // No arguments
  1124     JavaValue result(T_VOID);
  1125     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1130 void InstanceKlass::mask_for(methodHandle method, int bci,
  1131   InterpreterOopMap* entry_for) {
  1132   // Dirty read, then double-check under a lock.
  1133   if (_oop_map_cache == NULL) {
  1134     // Otherwise, allocate a new one.
  1135     MutexLocker x(OopMapCacheAlloc_lock);
  1136     // First time use. Allocate a cache in C heap
  1137     if (_oop_map_cache == NULL) {
  1138       _oop_map_cache = new OopMapCache();
  1141   // _oop_map_cache is constant after init; lookup below does is own locking.
  1142   _oop_map_cache->lookup(method, bci, entry_for);
  1146 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1147   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1148     Symbol* f_name = fs.name();
  1149     Symbol* f_sig  = fs.signature();
  1150     if (f_name == name && f_sig == sig) {
  1151       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1152       return true;
  1155   return false;
  1159 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1160   const int n = local_interfaces()->length();
  1161   for (int i = 0; i < n; i++) {
  1162     Klass* intf1 = local_interfaces()->at(i);
  1163     assert(intf1->is_interface(), "just checking type");
  1164     // search for field in current interface
  1165     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1166       assert(fd->is_static(), "interface field must be static");
  1167       return intf1;
  1169     // search for field in direct superinterfaces
  1170     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1171     if (intf2 != NULL) return intf2;
  1173   // otherwise field lookup fails
  1174   return NULL;
  1178 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1179   // search order according to newest JVM spec (5.4.3.2, p.167).
  1180   // 1) search for field in current klass
  1181   if (find_local_field(name, sig, fd)) {
  1182     return const_cast<InstanceKlass*>(this);
  1184   // 2) search for field recursively in direct superinterfaces
  1185   { Klass* intf = find_interface_field(name, sig, fd);
  1186     if (intf != NULL) return intf;
  1188   // 3) apply field lookup recursively if superclass exists
  1189   { Klass* supr = super();
  1190     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1192   // 4) otherwise field lookup fails
  1193   return NULL;
  1197 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1198   // search order according to newest JVM spec (5.4.3.2, p.167).
  1199   // 1) search for field in current klass
  1200   if (find_local_field(name, sig, fd)) {
  1201     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1203   // 2) search for field recursively in direct superinterfaces
  1204   if (is_static) {
  1205     Klass* intf = find_interface_field(name, sig, fd);
  1206     if (intf != NULL) return intf;
  1208   // 3) apply field lookup recursively if superclass exists
  1209   { Klass* supr = super();
  1210     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1212   // 4) otherwise field lookup fails
  1213   return NULL;
  1217 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1218   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1219     if (fs.offset() == offset) {
  1220       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1221       if (fd->is_static() == is_static) return true;
  1224   return false;
  1228 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1229   Klass* klass = const_cast<InstanceKlass*>(this);
  1230   while (klass != NULL) {
  1231     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1232       return true;
  1234     klass = klass->super();
  1236   return false;
  1240 void InstanceKlass::methods_do(void f(Method* method)) {
  1241   int len = methods()->length();
  1242   for (int index = 0; index < len; index++) {
  1243     Method* m = methods()->at(index);
  1244     assert(m->is_method(), "must be method");
  1245     f(m);
  1250 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1251   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1252     if (fs.access_flags().is_static()) {
  1253       fieldDescriptor& fd = fs.field_descriptor();
  1254       cl->do_field(&fd);
  1260 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
  1261   instanceKlassHandle h_this(THREAD, this);
  1262   do_local_static_fields_impl(h_this, f, CHECK);
  1266 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
  1267   for (JavaFieldStream fs(this_oop()); !fs.done(); fs.next()) {
  1268     if (fs.access_flags().is_static()) {
  1269       fieldDescriptor& fd = fs.field_descriptor();
  1270       f(&fd, CHECK);
  1276 static int compare_fields_by_offset(int* a, int* b) {
  1277   return a[0] - b[0];
  1280 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1281   InstanceKlass* super = superklass();
  1282   if (super != NULL) {
  1283     super->do_nonstatic_fields(cl);
  1285   fieldDescriptor fd;
  1286   int length = java_fields_count();
  1287   // In DebugInfo nonstatic fields are sorted by offset.
  1288   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1289   int j = 0;
  1290   for (int i = 0; i < length; i += 1) {
  1291     fd.reinitialize(this, i);
  1292     if (!fd.is_static()) {
  1293       fields_sorted[j + 0] = fd.offset();
  1294       fields_sorted[j + 1] = i;
  1295       j += 2;
  1298   if (j > 0) {
  1299     length = j;
  1300     // _sort_Fn is defined in growableArray.hpp.
  1301     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1302     for (int i = 0; i < length; i += 2) {
  1303       fd.reinitialize(this, fields_sorted[i + 1]);
  1304       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1305       cl->do_field(&fd);
  1308   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1312 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1313   if (array_klasses() != NULL)
  1314     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1317 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1318   if (array_klasses() != NULL)
  1319     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1322 #ifdef ASSERT
  1323 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1324   int len = methods->length();
  1325   for (int index = 0; index < len; index++) {
  1326     Method* m = methods->at(index);
  1327     assert(m->is_method(), "must be method");
  1328     if (m->signature() == signature && m->name() == name) {
  1329        return index;
  1332   return -1;
  1334 #endif
  1336 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1337   int len = methods->length();
  1338   // methods are sorted, so do binary search
  1339   int l = 0;
  1340   int h = len - 1;
  1341   while (l <= h) {
  1342     int mid = (l + h) >> 1;
  1343     Method* m = methods->at(mid);
  1344     assert(m->is_method(), "must be method");
  1345     int res = m->name()->fast_compare(name);
  1346     if (res == 0) {
  1347       return mid;
  1348     } else if (res < 0) {
  1349       l = mid + 1;
  1350     } else {
  1351       h = mid - 1;
  1354   return -1;
  1357 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1358   return InstanceKlass::find_method(methods(), name, signature);
  1361 Method* InstanceKlass::find_method(
  1362     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1363   int hit = binary_search(methods, name);
  1364   if (hit != -1) {
  1365     Method* m = methods->at(hit);
  1366     // Do linear search to find matching signature.  First, quick check
  1367     // for common case
  1368     if (m->signature() == signature) return m;
  1369     // search downwards through overloaded methods
  1370     int i;
  1371     for (i = hit - 1; i >= 0; --i) {
  1372         Method* m = methods->at(i);
  1373         assert(m->is_method(), "must be method");
  1374         if (m->name() != name) break;
  1375         if (m->signature() == signature) return m;
  1377     // search upwards
  1378     for (i = hit + 1; i < methods->length(); ++i) {
  1379         Method* m = methods->at(i);
  1380         assert(m->is_method(), "must be method");
  1381         if (m->name() != name) break;
  1382         if (m->signature() == signature) return m;
  1384     // not found
  1385 #ifdef ASSERT
  1386     int index = linear_search(methods, name, signature);
  1387     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1388 #endif
  1390   return NULL;
  1393 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1394   return find_method_by_name(methods(), name, end);
  1397 int InstanceKlass::find_method_by_name(
  1398     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1399   assert(end_ptr != NULL, "just checking");
  1400   int start = binary_search(methods, name);
  1401   int end = start + 1;
  1402   if (start != -1) {
  1403     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1404     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1405     *end_ptr = end;
  1406     return start;
  1408   return -1;
  1411 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
  1412   Klass* klass = const_cast<InstanceKlass*>(this);
  1413   while (klass != NULL) {
  1414     Method* method = InstanceKlass::cast(klass)->find_method(name, signature);
  1415     if (method != NULL) return method;
  1416     klass = InstanceKlass::cast(klass)->super();
  1418   return NULL;
  1421 // lookup a method in all the interfaces that this class implements
  1422 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1423                                                          Symbol* signature) const {
  1424   Array<Klass*>* all_ifs = transitive_interfaces();
  1425   int num_ifs = all_ifs->length();
  1426   InstanceKlass *ik = NULL;
  1427   for (int i = 0; i < num_ifs; i++) {
  1428     ik = InstanceKlass::cast(all_ifs->at(i));
  1429     Method* m = ik->lookup_method(name, signature);
  1430     if (m != NULL) {
  1431       return m;
  1434   return NULL;
  1437 /* jni_id_for_impl for jfieldIds only */
  1438 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1439   MutexLocker ml(JfieldIdCreation_lock);
  1440   // Retry lookup after we got the lock
  1441   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1442   if (probe == NULL) {
  1443     // Slow case, allocate new static field identifier
  1444     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1445     this_oop->set_jni_ids(probe);
  1447   return probe;
  1451 /* jni_id_for for jfieldIds only */
  1452 JNIid* InstanceKlass::jni_id_for(int offset) {
  1453   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1454   if (probe == NULL) {
  1455     probe = jni_id_for_impl(this, offset);
  1457   return probe;
  1460 u2 InstanceKlass::enclosing_method_data(int offset) {
  1461   Array<jushort>* inner_class_list = inner_classes();
  1462   if (inner_class_list == NULL) {
  1463     return 0;
  1465   int length = inner_class_list->length();
  1466   if (length % inner_class_next_offset == 0) {
  1467     return 0;
  1468   } else {
  1469     int index = length - enclosing_method_attribute_size;
  1470     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1471     return inner_class_list->at(index + offset);
  1475 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1476                                                  u2 method_index) {
  1477   Array<jushort>* inner_class_list = inner_classes();
  1478   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1479   int length = inner_class_list->length();
  1480   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1481     int index = length - enclosing_method_attribute_size;
  1482     inner_class_list->at_put(
  1483       index + enclosing_method_class_index_offset, class_index);
  1484     inner_class_list->at_put(
  1485       index + enclosing_method_method_index_offset, method_index);
  1489 // Lookup or create a jmethodID.
  1490 // This code is called by the VMThread and JavaThreads so the
  1491 // locking has to be done very carefully to avoid deadlocks
  1492 // and/or other cache consistency problems.
  1493 //
  1494 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1495   size_t idnum = (size_t)method_h->method_idnum();
  1496   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1497   size_t length = 0;
  1498   jmethodID id = NULL;
  1500   // We use a double-check locking idiom here because this cache is
  1501   // performance sensitive. In the normal system, this cache only
  1502   // transitions from NULL to non-NULL which is safe because we use
  1503   // release_set_methods_jmethod_ids() to advertise the new cache.
  1504   // A partially constructed cache should never be seen by a racing
  1505   // thread. We also use release_store_ptr() to save a new jmethodID
  1506   // in the cache so a partially constructed jmethodID should never be
  1507   // seen either. Cache reads of existing jmethodIDs proceed without a
  1508   // lock, but cache writes of a new jmethodID requires uniqueness and
  1509   // creation of the cache itself requires no leaks so a lock is
  1510   // generally acquired in those two cases.
  1511   //
  1512   // If the RedefineClasses() API has been used, then this cache can
  1513   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1514   // Cache creation requires no leaks and we require safety between all
  1515   // cache accesses and freeing of the old cache so a lock is generally
  1516   // acquired when the RedefineClasses() API has been used.
  1518   if (jmeths != NULL) {
  1519     // the cache already exists
  1520     if (!ik_h->idnum_can_increment()) {
  1521       // the cache can't grow so we can just get the current values
  1522       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1523     } else {
  1524       // cache can grow so we have to be more careful
  1525       if (Threads::number_of_threads() == 0 ||
  1526           SafepointSynchronize::is_at_safepoint()) {
  1527         // we're single threaded or at a safepoint - no locking needed
  1528         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1529       } else {
  1530         MutexLocker ml(JmethodIdCreation_lock);
  1531         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1535   // implied else:
  1536   // we need to allocate a cache so default length and id values are good
  1538   if (jmeths == NULL ||   // no cache yet
  1539       length <= idnum ||  // cache is too short
  1540       id == NULL) {       // cache doesn't contain entry
  1542     // This function can be called by the VMThread so we have to do all
  1543     // things that might block on a safepoint before grabbing the lock.
  1544     // Otherwise, we can deadlock with the VMThread or have a cache
  1545     // consistency issue. These vars keep track of what we might have
  1546     // to free after the lock is dropped.
  1547     jmethodID  to_dealloc_id     = NULL;
  1548     jmethodID* to_dealloc_jmeths = NULL;
  1550     // may not allocate new_jmeths or use it if we allocate it
  1551     jmethodID* new_jmeths = NULL;
  1552     if (length <= idnum) {
  1553       // allocate a new cache that might be used
  1554       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1555       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1556       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1557       // cache size is stored in element[0], other elements offset by one
  1558       new_jmeths[0] = (jmethodID)size;
  1561     // allocate a new jmethodID that might be used
  1562     jmethodID new_id = NULL;
  1563     if (method_h->is_old() && !method_h->is_obsolete()) {
  1564       // The method passed in is old (but not obsolete), we need to use the current version
  1565       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1566       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1567       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1568     } else {
  1569       // It is the current version of the method or an obsolete method,
  1570       // use the version passed in
  1571       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1574     if (Threads::number_of_threads() == 0 ||
  1575         SafepointSynchronize::is_at_safepoint()) {
  1576       // we're single threaded or at a safepoint - no locking needed
  1577       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1578                                           &to_dealloc_id, &to_dealloc_jmeths);
  1579     } else {
  1580       MutexLocker ml(JmethodIdCreation_lock);
  1581       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1582                                           &to_dealloc_id, &to_dealloc_jmeths);
  1585     // The lock has been dropped so we can free resources.
  1586     // Free up either the old cache or the new cache if we allocated one.
  1587     if (to_dealloc_jmeths != NULL) {
  1588       FreeHeap(to_dealloc_jmeths);
  1590     // free up the new ID since it wasn't needed
  1591     if (to_dealloc_id != NULL) {
  1592       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1595   return id;
  1599 // Common code to fetch the jmethodID from the cache or update the
  1600 // cache with the new jmethodID. This function should never do anything
  1601 // that causes the caller to go to a safepoint or we can deadlock with
  1602 // the VMThread or have cache consistency issues.
  1603 //
  1604 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1605             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1606             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1607             jmethodID** to_dealloc_jmeths_p) {
  1608   assert(new_id != NULL, "sanity check");
  1609   assert(to_dealloc_id_p != NULL, "sanity check");
  1610   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1611   assert(Threads::number_of_threads() == 0 ||
  1612          SafepointSynchronize::is_at_safepoint() ||
  1613          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1615   // reacquire the cache - we are locked, single threaded or at a safepoint
  1616   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1617   jmethodID  id     = NULL;
  1618   size_t     length = 0;
  1620   if (jmeths == NULL ||                         // no cache yet
  1621       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1622     if (jmeths != NULL) {
  1623       // copy any existing entries from the old cache
  1624       for (size_t index = 0; index < length; index++) {
  1625         new_jmeths[index+1] = jmeths[index+1];
  1627       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1629     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1630   } else {
  1631     // fetch jmethodID (if any) from the existing cache
  1632     id = jmeths[idnum+1];
  1633     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1635   if (id == NULL) {
  1636     // No matching jmethodID in the existing cache or we have a new
  1637     // cache or we just grew the cache. This cache write is done here
  1638     // by the first thread to win the foot race because a jmethodID
  1639     // needs to be unique once it is generally available.
  1640     id = new_id;
  1642     // The jmethodID cache can be read while unlocked so we have to
  1643     // make sure the new jmethodID is complete before installing it
  1644     // in the cache.
  1645     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1646   } else {
  1647     *to_dealloc_id_p = new_id; // save new id for later delete
  1649   return id;
  1653 // Common code to get the jmethodID cache length and the jmethodID
  1654 // value at index idnum if there is one.
  1655 //
  1656 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1657        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1658   assert(cache != NULL, "sanity check");
  1659   assert(length_p != NULL, "sanity check");
  1660   assert(id_p != NULL, "sanity check");
  1662   // cache size is stored in element[0], other elements offset by one
  1663   *length_p = (size_t)cache[0];
  1664   if (*length_p <= idnum) {  // cache is too short
  1665     *id_p = NULL;
  1666   } else {
  1667     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1672 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1673 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1674   size_t idnum = (size_t)method->method_idnum();
  1675   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1676   size_t length;                                // length assigned as debugging crumb
  1677   jmethodID id = NULL;
  1678   if (jmeths != NULL &&                         // If there is a cache
  1679       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1680     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1682   return id;
  1686 //
  1687 // Walk the list of dependent nmethods searching for nmethods which
  1688 // are dependent on the changes that were passed in and mark them for
  1689 // deoptimization.  Returns the number of nmethods found.
  1690 //
  1691 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1692   assert_locked_or_safepoint(CodeCache_lock);
  1693   int found = 0;
  1694   nmethodBucket* b = _dependencies;
  1695   while (b != NULL) {
  1696     nmethod* nm = b->get_nmethod();
  1697     // since dependencies aren't removed until an nmethod becomes a zombie,
  1698     // the dependency list may contain nmethods which aren't alive.
  1699     if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1700       if (TraceDependencies) {
  1701         ResourceMark rm;
  1702         tty->print_cr("Marked for deoptimization");
  1703         tty->print_cr("  context = %s", this->external_name());
  1704         changes.print();
  1705         nm->print();
  1706         nm->print_dependencies();
  1708       nm->mark_for_deoptimization();
  1709       found++;
  1711     b = b->next();
  1713   return found;
  1717 //
  1718 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1719 // It's possible that an nmethod has multiple dependencies on this klass
  1720 // so a count is kept for each bucket to guarantee that creation and
  1721 // deletion of dependencies is consistent.
  1722 //
  1723 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1724   assert_locked_or_safepoint(CodeCache_lock);
  1725   nmethodBucket* b = _dependencies;
  1726   nmethodBucket* last = NULL;
  1727   while (b != NULL) {
  1728     if (nm == b->get_nmethod()) {
  1729       b->increment();
  1730       return;
  1732     b = b->next();
  1734   _dependencies = new nmethodBucket(nm, _dependencies);
  1738 //
  1739 // Decrement count of the nmethod in the dependency list and remove
  1740 // the bucket competely when the count goes to 0.  This method must
  1741 // find a corresponding bucket otherwise there's a bug in the
  1742 // recording of dependecies.
  1743 //
  1744 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1745   assert_locked_or_safepoint(CodeCache_lock);
  1746   nmethodBucket* b = _dependencies;
  1747   nmethodBucket* last = NULL;
  1748   while (b != NULL) {
  1749     if (nm == b->get_nmethod()) {
  1750       if (b->decrement() == 0) {
  1751         if (last == NULL) {
  1752           _dependencies = b->next();
  1753         } else {
  1754           last->set_next(b->next());
  1756         delete b;
  1758       return;
  1760     last = b;
  1761     b = b->next();
  1763 #ifdef ASSERT
  1764   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1765   nm->print();
  1766 #endif // ASSERT
  1767   ShouldNotReachHere();
  1771 #ifndef PRODUCT
  1772 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1773   nmethodBucket* b = _dependencies;
  1774   int idx = 0;
  1775   while (b != NULL) {
  1776     nmethod* nm = b->get_nmethod();
  1777     tty->print("[%d] count=%d { ", idx++, b->count());
  1778     if (!verbose) {
  1779       nm->print_on(tty, "nmethod");
  1780       tty->print_cr(" } ");
  1781     } else {
  1782       nm->print();
  1783       nm->print_dependencies();
  1784       tty->print_cr("--- } ");
  1786     b = b->next();
  1791 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  1792   nmethodBucket* b = _dependencies;
  1793   while (b != NULL) {
  1794     if (nm == b->get_nmethod()) {
  1795       return true;
  1797     b = b->next();
  1799   return false;
  1801 #endif //PRODUCT
  1804 // Garbage collection
  1806 #ifdef ASSERT
  1807 template <class T> void assert_is_in(T *p) {
  1808   T heap_oop = oopDesc::load_heap_oop(p);
  1809   if (!oopDesc::is_null(heap_oop)) {
  1810     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1811     assert(Universe::heap()->is_in(o), "should be in heap");
  1814 template <class T> void assert_is_in_closed_subset(T *p) {
  1815   T heap_oop = oopDesc::load_heap_oop(p);
  1816   if (!oopDesc::is_null(heap_oop)) {
  1817     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1818     assert(Universe::heap()->is_in_closed_subset(o),
  1819            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  1822 template <class T> void assert_is_in_reserved(T *p) {
  1823   T heap_oop = oopDesc::load_heap_oop(p);
  1824   if (!oopDesc::is_null(heap_oop)) {
  1825     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1826     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  1829 template <class T> void assert_nothing(T *p) {}
  1831 #else
  1832 template <class T> void assert_is_in(T *p) {}
  1833 template <class T> void assert_is_in_closed_subset(T *p) {}
  1834 template <class T> void assert_is_in_reserved(T *p) {}
  1835 template <class T> void assert_nothing(T *p) {}
  1836 #endif // ASSERT
  1838 //
  1839 // Macros that iterate over areas of oops which are specialized on type of
  1840 // oop pointer either narrow or wide, depending on UseCompressedOops
  1841 //
  1842 // Parameters are:
  1843 //   T         - type of oop to point to (either oop or narrowOop)
  1844 //   start_p   - starting pointer for region to iterate over
  1845 //   count     - number of oops or narrowOops to iterate over
  1846 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  1847 //               makes it more efficient to put in a macro rather than making
  1848 //               it a template function)
  1849 //   assert_fn - assert function which is template function because performance
  1850 //               doesn't matter when enabled.
  1851 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  1852   T, start_p, count, do_oop,                \
  1853   assert_fn)                                \
  1854 {                                           \
  1855   T* p         = (T*)(start_p);             \
  1856   T* const end = p + (count);               \
  1857   while (p < end) {                         \
  1858     (assert_fn)(p);                         \
  1859     do_oop;                                 \
  1860     ++p;                                    \
  1861   }                                         \
  1864 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  1865   T, start_p, count, do_oop,                \
  1866   assert_fn)                                \
  1867 {                                           \
  1868   T* const start = (T*)(start_p);           \
  1869   T*       p     = start + (count);         \
  1870   while (start < p) {                       \
  1871     --p;                                    \
  1872     (assert_fn)(p);                         \
  1873     do_oop;                                 \
  1874   }                                         \
  1877 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  1878   T, start_p, count, low, high,             \
  1879   do_oop, assert_fn)                        \
  1880 {                                           \
  1881   T* const l = (T*)(low);                   \
  1882   T* const h = (T*)(high);                  \
  1883   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  1884          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  1885          "bounded region must be properly aligned"); \
  1886   T* p       = (T*)(start_p);               \
  1887   T* end     = p + (count);                 \
  1888   if (p < l) p = l;                         \
  1889   if (end > h) end = h;                     \
  1890   while (p < end) {                         \
  1891     (assert_fn)(p);                         \
  1892     do_oop;                                 \
  1893     ++p;                                    \
  1894   }                                         \
  1898 // The following macros call specialized macros, passing either oop or
  1899 // narrowOop as the specialization type.  These test the UseCompressedOops
  1900 // flag.
  1901 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  1902 {                                                                        \
  1903   /* Compute oopmap block range. The common case                         \
  1904      is nonstatic_oop_map_size == 1. */                                  \
  1905   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  1906   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  1907   if (UseCompressedOops) {                                               \
  1908     while (map < end_map) {                                              \
  1909       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  1910         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1911         do_oop, assert_fn)                                               \
  1912       ++map;                                                             \
  1913     }                                                                    \
  1914   } else {                                                               \
  1915     while (map < end_map) {                                              \
  1916       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  1917         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1918         do_oop, assert_fn)                                               \
  1919       ++map;                                                             \
  1920     }                                                                    \
  1921   }                                                                      \
  1924 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  1925 {                                                                        \
  1926   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  1927   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  1928   if (UseCompressedOops) {                                               \
  1929     while (start_map < map) {                                            \
  1930       --map;                                                             \
  1931       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  1932         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1933         do_oop, assert_fn)                                               \
  1934     }                                                                    \
  1935   } else {                                                               \
  1936     while (start_map < map) {                                            \
  1937       --map;                                                             \
  1938       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  1939         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1940         do_oop, assert_fn)                                               \
  1941     }                                                                    \
  1942   }                                                                      \
  1945 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  1946                                               assert_fn)                 \
  1947 {                                                                        \
  1948   /* Compute oopmap block range. The common case is                      \
  1949      nonstatic_oop_map_size == 1, so we accept the                       \
  1950      usually non-existent extra overhead of examining                    \
  1951      all the maps. */                                                    \
  1952   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  1953   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  1954   if (UseCompressedOops) {                                               \
  1955     while (map < end_map) {                                              \
  1956       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  1957         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  1958         low, high,                                                       \
  1959         do_oop, assert_fn)                                               \
  1960       ++map;                                                             \
  1961     }                                                                    \
  1962   } else {                                                               \
  1963     while (map < end_map) {                                              \
  1964       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  1965         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  1966         low, high,                                                       \
  1967         do_oop, assert_fn)                                               \
  1968       ++map;                                                             \
  1969     }                                                                    \
  1970   }                                                                      \
  1973 void InstanceKlass::oop_follow_contents(oop obj) {
  1974   assert(obj != NULL, "can't follow the content of NULL object");
  1975   MarkSweep::follow_klass(obj->klass());
  1976   InstanceKlass_OOP_MAP_ITERATE( \
  1977     obj, \
  1978     MarkSweep::mark_and_push(p), \
  1979     assert_is_in_closed_subset)
  1982 #if INCLUDE_ALL_GCS
  1983 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  1984                                         oop obj) {
  1985   assert(obj != NULL, "can't follow the content of NULL object");
  1986   PSParallelCompact::follow_klass(cm, obj->klass());
  1987   // Only mark the header and let the scan of the meta-data mark
  1988   // everything else.
  1989   InstanceKlass_OOP_MAP_ITERATE( \
  1990     obj, \
  1991     PSParallelCompact::mark_and_push(cm, p), \
  1992     assert_is_in)
  1994 #endif // INCLUDE_ALL_GCS
  1996 // closure's do_metadata() method dictates whether the given closure should be
  1997 // applied to the klass ptr in the object header.
  1999 #define if_do_metadata_checked(closure, nv_suffix)                    \
  2000   /* Make sure the non-virtual and the virtual versions match. */     \
  2001   assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
  2002       "Inconsistency in do_metadata");                                \
  2003   if (closure->do_metadata##nv_suffix())
  2005 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2007 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2008   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2009   /* header */                                                          \
  2010   if_do_metadata_checked(closure, nv_suffix) {                          \
  2011     closure->do_klass##nv_suffix(obj->klass());                         \
  2012   }                                                                     \
  2013   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2014     obj,                                                                \
  2015     SpecializationStats::                                               \
  2016       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2017     (closure)->do_oop##nv_suffix(p),                                    \
  2018     assert_is_in_closed_subset)                                         \
  2019   return size_helper();                                                 \
  2022 #if INCLUDE_ALL_GCS
  2023 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2025 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2026                                               OopClosureType* closure) {        \
  2027   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2028   /* header */                                                                  \
  2029   if_do_metadata_checked(closure, nv_suffix) {                                  \
  2030     closure->do_klass##nv_suffix(obj->klass());                                 \
  2031   }                                                                             \
  2032   /* instance variables */                                                      \
  2033   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2034     obj,                                                                        \
  2035     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2036     (closure)->do_oop##nv_suffix(p),                                            \
  2037     assert_is_in_closed_subset)                                                 \
  2038    return size_helper();                                                        \
  2040 #endif // INCLUDE_ALL_GCS
  2042 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2044 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2045                                                   OopClosureType* closure, \
  2046                                                   MemRegion mr) {          \
  2047   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2048   if_do_metadata_checked(closure, nv_suffix) {                           \
  2049     if (mr.contains(obj)) {                                              \
  2050       closure->do_klass##nv_suffix(obj->klass());                        \
  2051     }                                                                    \
  2052   }                                                                      \
  2053   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2054     obj, mr.start(), mr.end(),                                           \
  2055     (closure)->do_oop##nv_suffix(p),                                     \
  2056     assert_is_in_closed_subset)                                          \
  2057   return size_helper();                                                  \
  2060 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2061 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2062 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2063 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2064 #if INCLUDE_ALL_GCS
  2065 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2066 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2067 #endif // INCLUDE_ALL_GCS
  2069 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2070   int size = size_helper();
  2071   InstanceKlass_OOP_MAP_ITERATE( \
  2072     obj, \
  2073     MarkSweep::adjust_pointer(p), \
  2074     assert_is_in)
  2075   MarkSweep::adjust_klass(obj->klass());
  2076   return size;
  2079 #if INCLUDE_ALL_GCS
  2080 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2081   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2082     obj, \
  2083     if (PSScavenge::should_scavenge(p)) { \
  2084       pm->claim_or_forward_depth(p); \
  2085     }, \
  2086     assert_nothing )
  2089 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2090   int size = size_helper();
  2091   InstanceKlass_OOP_MAP_ITERATE( \
  2092     obj, \
  2093     PSParallelCompact::adjust_pointer(p), \
  2094     assert_is_in)
  2095   obj->update_header(cm);
  2096   return size;
  2099 #endif // INCLUDE_ALL_GCS
  2101 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2102   assert(is_loader_alive(is_alive), "this klass should be live");
  2103   if (is_interface()) {
  2104     if (ClassUnloading) {
  2105       Klass* impl = implementor();
  2106       if (impl != NULL) {
  2107         if (!impl->is_loader_alive(is_alive)) {
  2108           // remove this guy
  2109           Klass** klass = adr_implementor();
  2110           assert(klass != NULL, "null klass");
  2111           if (klass != NULL) {
  2112             *klass = NULL;
  2120 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2121   for (int m = 0; m < methods()->length(); m++) {
  2122     MethodData* mdo = methods()->at(m)->method_data();
  2123     if (mdo != NULL) {
  2124       for (ProfileData* data = mdo->first_data();
  2125            mdo->is_valid(data);
  2126            data = mdo->next_data(data)) {
  2127         data->clean_weak_klass_links(is_alive);
  2134 static void remove_unshareable_in_class(Klass* k) {
  2135   // remove klass's unshareable info
  2136   k->remove_unshareable_info();
  2139 void InstanceKlass::remove_unshareable_info() {
  2140   Klass::remove_unshareable_info();
  2141   // Unlink the class
  2142   if (is_linked()) {
  2143     unlink_class();
  2145   init_implementor();
  2147   constants()->remove_unshareable_info();
  2149   for (int i = 0; i < methods()->length(); i++) {
  2150     Method* m = methods()->at(i);
  2151     m->remove_unshareable_info();
  2154   // do array classes also.
  2155   array_klasses_do(remove_unshareable_in_class);
  2158 void restore_unshareable_in_class(Klass* k, TRAPS) {
  2159   k->restore_unshareable_info(CHECK);
  2162 void InstanceKlass::restore_unshareable_info(TRAPS) {
  2163   Klass::restore_unshareable_info(CHECK);
  2164   instanceKlassHandle ik(THREAD, this);
  2166   Array<Method*>* methods = ik->methods();
  2167   int num_methods = methods->length();
  2168   for (int index2 = 0; index2 < num_methods; ++index2) {
  2169     methodHandle m(THREAD, methods->at(index2));
  2170     m()->link_method(m, CHECK);
  2171     // restore method's vtable by calling a virtual function
  2172     m->restore_vtable();
  2174   if (JvmtiExport::has_redefined_a_class()) {
  2175     // Reinitialize vtable because RedefineClasses may have changed some
  2176     // entries in this vtable for super classes so the CDS vtable might
  2177     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2178     // vtables in the shared system dictionary, only the main one.
  2179     // It also redefines the itable too so fix that too.
  2180     ResourceMark rm(THREAD);
  2181     ik->vtable()->initialize_vtable(false, CHECK);
  2182     ik->itable()->initialize_itable(false, CHECK);
  2185   // restore constant pool resolved references
  2186   ik->constants()->restore_unshareable_info(CHECK);
  2188   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2191 static void clear_all_breakpoints(Method* m) {
  2192   m->clear_all_breakpoints();
  2196 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
  2197   // notify the debugger
  2198   if (JvmtiExport::should_post_class_unload()) {
  2199     JvmtiExport::post_class_unload(ik);
  2202   // notify ClassLoadingService of class unload
  2203   ClassLoadingService::notify_class_unloaded(ik);
  2206 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
  2207   // Clean up C heap
  2208   ik->release_C_heap_structures();
  2209   ik->constants()->release_C_heap_structures();
  2212 void InstanceKlass::release_C_heap_structures() {
  2214   // Can't release the constant pool here because the constant pool can be
  2215   // deallocated separately from the InstanceKlass for default methods and
  2216   // redefine classes.
  2218   // Deallocate oop map cache
  2219   if (_oop_map_cache != NULL) {
  2220     delete _oop_map_cache;
  2221     _oop_map_cache = NULL;
  2224   // Deallocate JNI identifiers for jfieldIDs
  2225   JNIid::deallocate(jni_ids());
  2226   set_jni_ids(NULL);
  2228   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2229   if (jmeths != (jmethodID*)NULL) {
  2230     release_set_methods_jmethod_ids(NULL);
  2231     FreeHeap(jmeths);
  2234   // Deallocate MemberNameTable
  2236     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
  2237     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
  2238     MemberNameTable* mnt = member_names();
  2239     if (mnt != NULL) {
  2240       delete mnt;
  2241       set_member_names(NULL);
  2245   // release dependencies
  2246   nmethodBucket* b = _dependencies;
  2247   _dependencies = NULL;
  2248   while (b != NULL) {
  2249     nmethodBucket* next = b->next();
  2250     delete b;
  2251     b = next;
  2254   // Deallocate breakpoint records
  2255   if (breakpoints() != 0x0) {
  2256     methods_do(clear_all_breakpoints);
  2257     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2260   // deallocate information about previous versions
  2261   if (_previous_versions != NULL) {
  2262     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2263       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2264       delete pv_node;
  2266     delete _previous_versions;
  2267     _previous_versions = NULL;
  2270   // deallocate the cached class file
  2271   if (_cached_class_file != NULL) {
  2272     os::free(_cached_class_file, mtClass);
  2273     _cached_class_file = NULL;
  2276   // Decrement symbol reference counts associated with the unloaded class.
  2277   if (_name != NULL) _name->decrement_refcount();
  2278   // unreference array name derived from this class name (arrays of an unloaded
  2279   // class can't be referenced anymore).
  2280   if (_array_name != NULL)  _array_name->decrement_refcount();
  2281   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2283   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2284   Atomic::dec(&_total_instanceKlass_count);
  2287 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2288   if (array == NULL) {
  2289     _source_debug_extension = NULL;
  2290   } else {
  2291     // Adding one to the attribute length in order to store a null terminator
  2292     // character could cause an overflow because the attribute length is
  2293     // already coded with an u4 in the classfile, but in practice, it's
  2294     // unlikely to happen.
  2295     assert((length+1) > length, "Overflow checking");
  2296     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2297     for (int i = 0; i < length; i++) {
  2298       sde[i] = array[i];
  2300     sde[length] = '\0';
  2301     _source_debug_extension = sde;
  2305 address InstanceKlass::static_field_addr(int offset) {
  2306   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
  2310 const char* InstanceKlass::signature_name() const {
  2311   const char* src = (const char*) (name()->as_C_string());
  2312   const int src_length = (int)strlen(src);
  2313   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
  2314   int src_index = 0;
  2315   int dest_index = 0;
  2316   dest[dest_index++] = 'L';
  2317   while (src_index < src_length) {
  2318     dest[dest_index++] = src[src_index++];
  2320   dest[dest_index++] = ';';
  2321   dest[dest_index] = '\0';
  2322   return dest;
  2325 // different verisons of is_same_class_package
  2326 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2327   Klass* class1 = this;
  2328   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2329   Symbol* classname1 = class1->name();
  2331   if (class2->oop_is_objArray()) {
  2332     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2334   oop classloader2;
  2335   if (class2->oop_is_instance()) {
  2336     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2337   } else {
  2338     assert(class2->oop_is_typeArray(), "should be type array");
  2339     classloader2 = NULL;
  2341   Symbol* classname2 = class2->name();
  2343   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2344                                               classloader2, classname2);
  2347 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2348   Klass* class1 = this;
  2349   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2350   Symbol* classname1 = class1->name();
  2352   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2353                                               classloader2, classname2);
  2356 // return true if two classes are in the same package, classloader
  2357 // and classname information is enough to determine a class's package
  2358 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2359                                           oop class_loader2, Symbol* class_name2) {
  2360   if (class_loader1 != class_loader2) {
  2361     return false;
  2362   } else if (class_name1 == class_name2) {
  2363     return true;                // skip painful bytewise comparison
  2364   } else {
  2365     ResourceMark rm;
  2367     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2368     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2369     // Otherwise, we just compare jbyte values between the strings.
  2370     const jbyte *name1 = class_name1->base();
  2371     const jbyte *name2 = class_name2->base();
  2373     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2374     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2376     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2377       // One of the two doesn't have a package.  Only return true
  2378       // if the other one also doesn't have a package.
  2379       return last_slash1 == last_slash2;
  2380     } else {
  2381       // Skip over '['s
  2382       if (*name1 == '[') {
  2383         do {
  2384           name1++;
  2385         } while (*name1 == '[');
  2386         if (*name1 != 'L') {
  2387           // Something is terribly wrong.  Shouldn't be here.
  2388           return false;
  2391       if (*name2 == '[') {
  2392         do {
  2393           name2++;
  2394         } while (*name2 == '[');
  2395         if (*name2 != 'L') {
  2396           // Something is terribly wrong.  Shouldn't be here.
  2397           return false;
  2401       // Check that package part is identical
  2402       int length1 = last_slash1 - name1;
  2403       int length2 = last_slash2 - name2;
  2405       return UTF8::equal(name1, length1, name2, length2);
  2410 // Returns true iff super_method can be overridden by a method in targetclassname
  2411 // See JSL 3rd edition 8.4.6.1
  2412 // Assumes name-signature match
  2413 // "this" is InstanceKlass of super_method which must exist
  2414 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2415 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2416    // Private methods can not be overridden
  2417    if (super_method->is_private()) {
  2418      return false;
  2420    // If super method is accessible, then override
  2421    if ((super_method->is_protected()) ||
  2422        (super_method->is_public())) {
  2423      return true;
  2425    // Package-private methods are not inherited outside of package
  2426    assert(super_method->is_package_private(), "must be package private");
  2427    return(is_same_class_package(targetclassloader(), targetclassname));
  2430 /* defined for now in jvm.cpp, for historical reasons *--
  2431 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2432                                                      Symbol*& simple_name_result, TRAPS) {
  2433   ...
  2435 */
  2437 // tell if two classes have the same enclosing class (at package level)
  2438 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2439                                                 Klass* class2_oop, TRAPS) {
  2440   if (class2_oop == class1())                       return true;
  2441   if (!class2_oop->oop_is_instance())  return false;
  2442   instanceKlassHandle class2(THREAD, class2_oop);
  2444   // must be in same package before we try anything else
  2445   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2446     return false;
  2448   // As long as there is an outer1.getEnclosingClass,
  2449   // shift the search outward.
  2450   instanceKlassHandle outer1 = class1;
  2451   for (;;) {
  2452     // As we walk along, look for equalities between outer1 and class2.
  2453     // Eventually, the walks will terminate as outer1 stops
  2454     // at the top-level class around the original class.
  2455     bool ignore_inner_is_member;
  2456     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2457                                                     CHECK_false);
  2458     if (next == NULL)  break;
  2459     if (next == class2())  return true;
  2460     outer1 = instanceKlassHandle(THREAD, next);
  2463   // Now do the same for class2.
  2464   instanceKlassHandle outer2 = class2;
  2465   for (;;) {
  2466     bool ignore_inner_is_member;
  2467     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2468                                                     CHECK_false);
  2469     if (next == NULL)  break;
  2470     // Might as well check the new outer against all available values.
  2471     if (next == class1())  return true;
  2472     if (next == outer1())  return true;
  2473     outer2 = instanceKlassHandle(THREAD, next);
  2476   // If by this point we have not found an equality between the
  2477   // two classes, we know they are in separate package members.
  2478   return false;
  2482 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2483   jint access = access_flags().as_int();
  2485   // But check if it happens to be member class.
  2486   instanceKlassHandle ik(THREAD, this);
  2487   InnerClassesIterator iter(ik);
  2488   for (; !iter.done(); iter.next()) {
  2489     int ioff = iter.inner_class_info_index();
  2490     // Inner class attribute can be zero, skip it.
  2491     // Strange but true:  JVM spec. allows null inner class refs.
  2492     if (ioff == 0) continue;
  2494     // only look at classes that are already loaded
  2495     // since we are looking for the flags for our self.
  2496     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2497     if ((ik->name() == inner_name)) {
  2498       // This is really a member class.
  2499       access = iter.inner_access_flags();
  2500       break;
  2503   // Remember to strip ACC_SUPER bit
  2504   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2507 jint InstanceKlass::jvmti_class_status() const {
  2508   jint result = 0;
  2510   if (is_linked()) {
  2511     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2514   if (is_initialized()) {
  2515     assert(is_linked(), "Class status is not consistent");
  2516     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2518   if (is_in_error_state()) {
  2519     result |= JVMTI_CLASS_STATUS_ERROR;
  2521   return result;
  2524 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2525   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2526   int method_table_offset_in_words = ioe->offset()/wordSize;
  2527   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2528                        / itableOffsetEntry::size();
  2530   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2531     // If the interface isn't implemented by the receiver class,
  2532     // the VM should throw IncompatibleClassChangeError.
  2533     if (cnt >= nof_interfaces) {
  2534       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2537     Klass* ik = ioe->interface_klass();
  2538     if (ik == holder) break;
  2541   itableMethodEntry* ime = ioe->first_method_entry(this);
  2542   Method* m = ime[index].method();
  2543   if (m == NULL) {
  2544     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2546   return m;
  2549 // On-stack replacement stuff
  2550 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2551   // only one compilation can be active
  2552   NEEDS_CLEANUP
  2553   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2554   OsrList_lock->lock_without_safepoint_check();
  2555   assert(n->is_osr_method(), "wrong kind of nmethod");
  2556   n->set_osr_link(osr_nmethods_head());
  2557   set_osr_nmethods_head(n);
  2558   // Raise the highest osr level if necessary
  2559   if (TieredCompilation) {
  2560     Method* m = n->method();
  2561     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2563   // Remember to unlock again
  2564   OsrList_lock->unlock();
  2566   // Get rid of the osr methods for the same bci that have lower levels.
  2567   if (TieredCompilation) {
  2568     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2569       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2570       if (inv != NULL && inv->is_in_use()) {
  2571         inv->make_not_entrant();
  2578 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2579   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2580   OsrList_lock->lock_without_safepoint_check();
  2581   assert(n->is_osr_method(), "wrong kind of nmethod");
  2582   nmethod* last = NULL;
  2583   nmethod* cur  = osr_nmethods_head();
  2584   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2585   Method* m = n->method();
  2586   // Search for match
  2587   while(cur != NULL && cur != n) {
  2588     if (TieredCompilation) {
  2589       // Find max level before n
  2590       max_level = MAX2(max_level, cur->comp_level());
  2592     last = cur;
  2593     cur = cur->osr_link();
  2595   nmethod* next = NULL;
  2596   if (cur == n) {
  2597     next = cur->osr_link();
  2598     if (last == NULL) {
  2599       // Remove first element
  2600       set_osr_nmethods_head(next);
  2601     } else {
  2602       last->set_osr_link(next);
  2605   n->set_osr_link(NULL);
  2606   if (TieredCompilation) {
  2607     cur = next;
  2608     while (cur != NULL) {
  2609       // Find max level after n
  2610       max_level = MAX2(max_level, cur->comp_level());
  2611       cur = cur->osr_link();
  2613     m->set_highest_osr_comp_level(max_level);
  2615   // Remember to unlock again
  2616   OsrList_lock->unlock();
  2619 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
  2620   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2621   OsrList_lock->lock_without_safepoint_check();
  2622   nmethod* osr = osr_nmethods_head();
  2623   nmethod* best = NULL;
  2624   while (osr != NULL) {
  2625     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2626     // There can be a time when a c1 osr method exists but we are waiting
  2627     // for a c2 version. When c2 completes its osr nmethod we will trash
  2628     // the c1 version and only be able to find the c2 version. However
  2629     // while we overflow in the c1 code at back branches we don't want to
  2630     // try and switch to the same code as we are already running
  2632     if (osr->method() == m &&
  2633         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2634       if (match_level) {
  2635         if (osr->comp_level() == comp_level) {
  2636           // Found a match - return it.
  2637           OsrList_lock->unlock();
  2638           return osr;
  2640       } else {
  2641         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2642           if (osr->comp_level() == CompLevel_highest_tier) {
  2643             // Found the best possible - return it.
  2644             OsrList_lock->unlock();
  2645             return osr;
  2647           best = osr;
  2651     osr = osr->osr_link();
  2653   OsrList_lock->unlock();
  2654   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2655     return best;
  2657   return NULL;
  2660 void InstanceKlass::add_member_name(int index, Handle mem_name) {
  2661   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  2662   MutexLocker ml(MemberNameTable_lock);
  2663   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  2664   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2666   if (_member_names == NULL) {
  2667     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
  2669   _member_names->add_member_name(index, mem_name_wref);
  2672 oop InstanceKlass::get_member_name(int index) {
  2673   MutexLocker ml(MemberNameTable_lock);
  2674   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  2675   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2677   if (_member_names == NULL) {
  2678     return NULL;
  2680   oop mem_name =_member_names->get_member_name(index);
  2681   return mem_name;
  2684 // -----------------------------------------------------------------------------------------------------
  2685 // Printing
  2687 #ifndef PRODUCT
  2689 #define BULLET  " - "
  2691 static const char* state_names[] = {
  2692   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  2693 };
  2695 static void print_vtable(intptr_t* start, int len, outputStream* st) {
  2696   for (int i = 0; i < len; i++) {
  2697     intptr_t e = start[i];
  2698     st->print("%d : " INTPTR_FORMAT, i, e);
  2699     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
  2700       st->print(" ");
  2701       ((Metadata*)e)->print_value_on(st);
  2703     st->cr();
  2707 void InstanceKlass::print_on(outputStream* st) const {
  2708   assert(is_klass(), "must be klass");
  2709   Klass::print_on(st);
  2711   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  2712   st->print(BULLET"klass size:        %d", size());                               st->cr();
  2713   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  2714   st->print(BULLET"state:             "); st->print_cr(state_names[_init_state]);
  2715   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  2716   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  2717   st->print(BULLET"sub:               ");
  2718   Klass* sub = subklass();
  2719   int n;
  2720   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  2721     if (n < MaxSubklassPrintSize) {
  2722       sub->print_value_on(st);
  2723       st->print("   ");
  2726   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  2727   st->cr();
  2729   if (is_interface()) {
  2730     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  2731     if (nof_implementors() == 1) {
  2732       st->print_cr(BULLET"implementor:    ");
  2733       st->print("   ");
  2734       implementor()->print_value_on(st);
  2735       st->cr();
  2739   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  2740   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  2741   if (Verbose || WizardMode) {
  2742     Array<Method*>* method_array = methods();
  2743     for(int i = 0; i < method_array->length(); i++) {
  2744       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  2747   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);       st->cr();
  2748   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  2749   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  2750   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  2751   if (class_loader_data() != NULL) {
  2752     st->print(BULLET"class loader data:  ");
  2753     class_loader_data()->print_value_on(st);
  2754     st->cr();
  2756   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  2757   if (source_file_name() != NULL) {
  2758     st->print(BULLET"source file:       ");
  2759     source_file_name()->print_value_on(st);
  2760     st->cr();
  2762   if (source_debug_extension() != NULL) {
  2763     st->print(BULLET"source debug extension:       ");
  2764     st->print("%s", source_debug_extension());
  2765     st->cr();
  2767   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  2768   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  2769   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  2770   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  2772     bool have_pv = false;
  2773     PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  2774     for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  2775          pv_node != NULL; pv_node = pvw.next_previous_version()) {
  2776       if (!have_pv)
  2777         st->print(BULLET"previous version:  ");
  2778       have_pv = true;
  2779       pv_node->prev_constant_pool()->print_value_on(st);
  2781     if (have_pv) st->cr();
  2782   } // pvw is cleaned up
  2784   if (generic_signature() != NULL) {
  2785     st->print(BULLET"generic signature: ");
  2786     generic_signature()->print_value_on(st);
  2787     st->cr();
  2789   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  2790   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  2791   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  2792   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
  2793   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  2794   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
  2795   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  2796   FieldPrinter print_static_field(st);
  2797   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  2798   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  2799   FieldPrinter print_nonstatic_field(st);
  2800   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  2802   st->print(BULLET"non-static oop maps: ");
  2803   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  2804   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  2805   while (map < end_map) {
  2806     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  2807     map++;
  2809   st->cr();
  2812 #endif //PRODUCT
  2814 void InstanceKlass::print_value_on(outputStream* st) const {
  2815   assert(is_klass(), "must be klass");
  2816   if (Verbose || WizardMode)  access_flags().print_on(st);
  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     Klass* array_klass = java_lang_Class::array_klass(obj);
  2866     st->print(BULLET"fake entry for array: ");
  2867     array_klass->print_value_on_maybe_null(st);
  2868     st->cr();
  2869     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  2870     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  2871     Klass* real_klass = java_lang_Class::as_Klass(obj);
  2872     if (real_klass != NULL && real_klass->oop_is_instance()) {
  2873       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  2875   } else if (this == SystemDictionary::MethodType_klass()) {
  2876     st->print(BULLET"signature: ");
  2877     java_lang_invoke_MethodType::print_signature(obj, st);
  2878     st->cr();
  2882 #endif //PRODUCT
  2884 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  2885   st->print("a ");
  2886   name()->print_value_on(st);
  2887   obj->print_address_on(st);
  2888   if (this == SystemDictionary::String_klass()
  2889       && java_lang_String::value(obj) != NULL) {
  2890     ResourceMark rm;
  2891     int len = java_lang_String::length(obj);
  2892     int plen = (len < 24 ? len : 12);
  2893     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  2894     st->print(" = \"%s\"", str);
  2895     if (len > plen)
  2896       st->print("...[%d]", len);
  2897   } else if (this == SystemDictionary::Class_klass()) {
  2898     Klass* k = java_lang_Class::as_Klass(obj);
  2899     st->print(" = ");
  2900     if (k != NULL) {
  2901       k->print_value_on(st);
  2902     } else {
  2903       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  2904       st->print("%s", tname ? tname : "type?");
  2906   } else if (this == SystemDictionary::MethodType_klass()) {
  2907     st->print(" = ");
  2908     java_lang_invoke_MethodType::print_signature(obj, st);
  2909   } else if (java_lang_boxing_object::is_instance(obj)) {
  2910     st->print(" = ");
  2911     java_lang_boxing_object::print(obj, st);
  2912   } else if (this == SystemDictionary::LambdaForm_klass()) {
  2913     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  2914     if (vmentry != NULL) {
  2915       st->print(" => ");
  2916       vmentry->print_value_on(st);
  2918   } else if (this == SystemDictionary::MemberName_klass()) {
  2919     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  2920     if (vmtarget != NULL) {
  2921       st->print(" = ");
  2922       vmtarget->print_value_on(st);
  2923     } else {
  2924       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  2925       st->print(".");
  2926       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  2931 const char* InstanceKlass::internal_name() const {
  2932   return external_name();
  2935 #if INCLUDE_SERVICES
  2936 // Size Statistics
  2937 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  2938   Klass::collect_statistics(sz);
  2940   sz->_inst_size  = HeapWordSize * size_helper();
  2941   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  2942   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  2943   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  2944         ((is_interface() || is_anonymous()) ?
  2945          align_object_offset(nonstatic_oop_map_size()) :
  2946          nonstatic_oop_map_size());
  2948   int n = 0;
  2949   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  2950   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  2951   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  2952   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  2953   n += (sz->_fields_bytes                = sz->count_array(fields()));
  2954   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  2955   sz->_ro_bytes += n;
  2957   const ConstantPool* cp = constants();
  2958   if (cp) {
  2959     cp->collect_statistics(sz);
  2962   const Annotations* anno = annotations();
  2963   if (anno) {
  2964     anno->collect_statistics(sz);
  2967   const Array<Method*>* methods_array = methods();
  2968   if (methods()) {
  2969     for (int i = 0; i < methods_array->length(); i++) {
  2970       Method* method = methods_array->at(i);
  2971       if (method) {
  2972         sz->_method_count ++;
  2973         method->collect_statistics(sz);
  2978 #endif // INCLUDE_SERVICES
  2980 // Verification
  2982 class VerifyFieldClosure: public OopClosure {
  2983  protected:
  2984   template <class T> void do_oop_work(T* p) {
  2985     oop obj = oopDesc::load_decode_heap_oop(p);
  2986     if (!obj->is_oop_or_null()) {
  2987       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  2988       Universe::print();
  2989       guarantee(false, "boom");
  2992  public:
  2993   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  2994   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  2995 };
  2997 void InstanceKlass::verify_on(outputStream* st, bool check_dictionary) {
  2998 #ifndef PRODUCT
  2999   // Avoid redundant verifies, this really should be in product.
  3000   if (_verify_count == Universe::verify_count()) return;
  3001   _verify_count = Universe::verify_count();
  3002 #endif
  3004   // Verify Klass
  3005   Klass::verify_on(st, check_dictionary);
  3007   // Verify that klass is present in SystemDictionary if not already
  3008   // verifying the SystemDictionary.
  3009   if (is_loaded() && !is_anonymous() && check_dictionary) {
  3010     Symbol* h_name = name();
  3011     SystemDictionary::verify_obj_klass_present(h_name, class_loader_data());
  3014   // Verify vtables
  3015   if (is_linked()) {
  3016     ResourceMark rm;
  3017     // $$$ This used to be done only for m/s collections.  Doing it
  3018     // always seemed a valid generalization.  (DLD -- 6/00)
  3019     vtable()->verify(st);
  3022   // Verify first subklass
  3023   if (subklass_oop() != NULL) {
  3024     guarantee(subklass_oop()->is_klass(), "should be klass");
  3027   // Verify siblings
  3028   Klass* super = this->super();
  3029   Klass* sib = next_sibling();
  3030   if (sib != NULL) {
  3031     if (sib == this) {
  3032       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3035     guarantee(sib->is_klass(), "should be klass");
  3036     guarantee(sib->super() == super, "siblings should have same superklass");
  3039   // Verify implementor fields
  3040   Klass* im = implementor();
  3041   if (im != NULL) {
  3042     guarantee(is_interface(), "only interfaces should have implementor set");
  3043     guarantee(im->is_klass(), "should be klass");
  3044     guarantee(!im->is_interface() || im == this,
  3045       "implementors cannot be interfaces");
  3048   // Verify local interfaces
  3049   if (local_interfaces()) {
  3050     Array<Klass*>* local_interfaces = this->local_interfaces();
  3051     for (int j = 0; j < local_interfaces->length(); j++) {
  3052       Klass* e = local_interfaces->at(j);
  3053       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3057   // Verify transitive interfaces
  3058   if (transitive_interfaces() != NULL) {
  3059     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3060     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3061       Klass* e = transitive_interfaces->at(j);
  3062       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3066   // Verify methods
  3067   if (methods() != NULL) {
  3068     Array<Method*>* methods = this->methods();
  3069     for (int j = 0; j < methods->length(); j++) {
  3070       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3072     for (int j = 0; j < methods->length() - 1; j++) {
  3073       Method* m1 = methods->at(j);
  3074       Method* m2 = methods->at(j + 1);
  3075       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3079   // Verify method ordering
  3080   if (method_ordering() != NULL) {
  3081     Array<int>* method_ordering = this->method_ordering();
  3082     int length = method_ordering->length();
  3083     if (JvmtiExport::can_maintain_original_method_order() ||
  3084         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
  3085       guarantee(length == methods()->length(), "invalid method ordering length");
  3086       jlong sum = 0;
  3087       for (int j = 0; j < length; j++) {
  3088         int original_index = method_ordering->at(j);
  3089         guarantee(original_index >= 0, "invalid method ordering index");
  3090         guarantee(original_index < length, "invalid method ordering index");
  3091         sum += original_index;
  3093       // Verify sum of indices 0,1,...,length-1
  3094       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3095     } else {
  3096       guarantee(length == 0, "invalid method ordering length");
  3100   // Verify JNI static field identifiers
  3101   if (jni_ids() != NULL) {
  3102     jni_ids()->verify(this);
  3105   // Verify other fields
  3106   if (array_klasses() != NULL) {
  3107     guarantee(array_klasses()->is_klass(), "should be klass");
  3109   if (constants() != NULL) {
  3110     guarantee(constants()->is_constantPool(), "should be constant pool");
  3112   const Klass* host = host_klass();
  3113   if (host != NULL) {
  3114     guarantee(host->is_klass(), "should be klass");
  3118 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3119   Klass::oop_verify_on(obj, st);
  3120   VerifyFieldClosure blk;
  3121   obj->oop_iterate_no_header(&blk);
  3125 // JNIid class for jfieldIDs only
  3126 // Note to reviewers:
  3127 // These JNI functions are just moved over to column 1 and not changed
  3128 // in the compressed oops workspace.
  3129 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3130   _holder = holder;
  3131   _offset = offset;
  3132   _next = next;
  3133   debug_only(_is_static_field_id = false;)
  3137 JNIid* JNIid::find(int offset) {
  3138   JNIid* current = this;
  3139   while (current != NULL) {
  3140     if (current->offset() == offset) return current;
  3141     current = current->next();
  3143   return NULL;
  3146 void JNIid::deallocate(JNIid* current) {
  3147   while (current != NULL) {
  3148     JNIid* next = current->next();
  3149     delete current;
  3150     current = next;
  3155 void JNIid::verify(Klass* holder) {
  3156   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3157   int end_field_offset;
  3158   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3160   JNIid* current = this;
  3161   while (current != NULL) {
  3162     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3163 #ifdef ASSERT
  3164     int o = current->offset();
  3165     if (current->is_static_field_id()) {
  3166       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3168 #endif
  3169     current = current->next();
  3174 #ifdef ASSERT
  3175 void InstanceKlass::set_init_state(ClassState state) {
  3176   bool good_state = is_shared() ? (_init_state <= state)
  3177                                                : (_init_state < state);
  3178   assert(good_state || state == allocated, "illegal state transition");
  3179   _init_state = (u1)state;
  3181 #endif
  3184 // RedefineClasses() support for previous versions:
  3186 // Purge previous versions
  3187 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3188   if (ik->previous_versions() != NULL) {
  3189     // This klass has previous versions so see what we can cleanup
  3190     // while it is safe to do so.
  3192     int deleted_count = 0;    // leave debugging breadcrumbs
  3193     int live_count = 0;
  3194     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3195                        ClassLoaderData::the_null_class_loader_data() :
  3196                        ik->class_loader_data();
  3198     // RC_TRACE macro has an embedded ResourceMark
  3199     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3200       ik->external_name(), ik->previous_versions()->length()));
  3202     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3203       // check the previous versions array
  3204       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3205       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3206       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3208       ConstantPool* pvcp = cp_ref;
  3209       if (!pvcp->on_stack()) {
  3210         // If the constant pool isn't on stack, none of the methods
  3211         // are executing.  Delete all the methods, the constant pool and
  3212         // and this previous version node.
  3213         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3214         if (method_refs != NULL) {
  3215           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3216             Method* method = method_refs->at(j);
  3217             assert(method != NULL, "method ref was unexpectedly cleared");
  3218             method_refs->remove_at(j);
  3219             // method will be freed with associated class.
  3222         // Remove the constant pool
  3223         delete pv_node;
  3224         // Since we are traversing the array backwards, we don't have to
  3225         // do anything special with the index.
  3226         ik->previous_versions()->remove_at(i);
  3227         deleted_count++;
  3228         continue;
  3229       } else {
  3230         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3231         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3232         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3233         live_count++;
  3236       // At least one method is live in this previous version, clean out
  3237       // the others or mark them as obsolete.
  3238       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3239       if (method_refs != NULL) {
  3240         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3241           method_refs->length()));
  3242         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3243           Method* method = method_refs->at(j);
  3244           assert(method != NULL, "method ref was unexpectedly cleared");
  3246           // Remove the emcp method if it's not executing
  3247           // If it's been made obsolete by a redefinition of a non-emcp
  3248           // method, mark it as obsolete but leave it to clean up later.
  3249           if (!method->on_stack()) {
  3250             method_refs->remove_at(j);
  3251           } else if (emcp_method_count == 0) {
  3252             method->set_is_obsolete();
  3253           } else {
  3254             // RC_TRACE macro has an embedded ResourceMark
  3255             RC_TRACE(0x00000200,
  3256               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3257               method->name()->as_C_string(),
  3258               method->signature()->as_C_string(), j, i));
  3263     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3264     RC_TRACE(0x00000200,
  3265       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3266       deleted_count));
  3270 // External interface for use during class unloading.
  3271 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3272   // Call with >0 emcp methods since they are not currently being redefined.
  3273   purge_previous_versions_internal(ik, 1);
  3277 // Potentially add an information node that contains pointers to the
  3278 // interesting parts of the previous version of the_class.
  3279 // This is also where we clean out any unused references.
  3280 // Note that while we delete nodes from the _previous_versions
  3281 // array, we never delete the array itself until the klass is
  3282 // unloaded. The has_been_redefined() query depends on that fact.
  3283 //
  3284 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3285        BitMap* emcp_methods, int emcp_method_count) {
  3286   assert(Thread::current()->is_VM_thread(),
  3287          "only VMThread can add previous versions");
  3289   if (_previous_versions == NULL) {
  3290     // This is the first previous version so make some space.
  3291     // Start with 2 elements under the assumption that the class
  3292     // won't be redefined much.
  3293     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3294                             GrowableArray<PreviousVersionNode *>(2, true);
  3297   ConstantPool* cp_ref = ikh->constants();
  3299   // RC_TRACE macro has an embedded ResourceMark
  3300   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3301                         "on_stack=%d",
  3302     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3303     cp_ref->on_stack()));
  3305   // If the constant pool for this previous version of the class
  3306   // is not marked as being on the stack, then none of the methods
  3307   // in this previous version of the class are on the stack so
  3308   // we don't need to create a new PreviousVersionNode. However,
  3309   // we still need to examine older previous versions below.
  3310   Array<Method*>* old_methods = ikh->methods();
  3312   if (cp_ref->on_stack()) {
  3313     PreviousVersionNode * pv_node = NULL;
  3314     if (emcp_method_count == 0) {
  3315       // non-shared ConstantPool gets a reference
  3316       pv_node = new PreviousVersionNode(cp_ref, NULL);
  3317       RC_TRACE(0x00000400,
  3318           ("add: all methods are obsolete; flushing any EMCP refs"));
  3319     } else {
  3320       int local_count = 0;
  3321       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3322           GrowableArray<Method*>(emcp_method_count, true);
  3323       for (int i = 0; i < old_methods->length(); i++) {
  3324         if (emcp_methods->at(i)) {
  3325             // this old method is EMCP. Save it only if it's on the stack
  3326             Method* old_method = old_methods->at(i);
  3327             if (old_method->on_stack()) {
  3328               method_refs->append(old_method);
  3330           if (++local_count >= emcp_method_count) {
  3331             // no more EMCP methods so bail out now
  3332             break;
  3336       // non-shared ConstantPool gets a reference
  3337       pv_node = new PreviousVersionNode(cp_ref, method_refs);
  3339     // append new previous version.
  3340     _previous_versions->append(pv_node);
  3343   // Since the caller is the VMThread and we are at a safepoint, this
  3344   // is a good time to clear out unused references.
  3346   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3347     _previous_versions->length()));
  3349   // Purge previous versions not executing on the stack
  3350   purge_previous_versions_internal(this, emcp_method_count);
  3352   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3354   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3355       _previous_versions->length() > 0) {
  3356     // We have a mix of obsolete and EMCP methods so we have to
  3357     // clear out any matching EMCP method entries the hard way.
  3358     int local_count = 0;
  3359     for (int i = 0; i < old_methods->length(); i++) {
  3360       if (!emcp_methods->at(i)) {
  3361         // only obsolete methods are interesting
  3362         Method* old_method = old_methods->at(i);
  3363         Symbol* m_name = old_method->name();
  3364         Symbol* m_signature = old_method->signature();
  3366         // we might not have added the last entry
  3367         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3368           // check the previous versions array for non executing obsolete methods
  3369           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3371           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3372           if (method_refs == NULL) {
  3373             // We have run into a PreviousVersion generation where
  3374             // all methods were made obsolete during that generation's
  3375             // RedefineClasses() operation. At the time of that
  3376             // operation, all EMCP methods were flushed so we don't
  3377             // have to go back any further.
  3378             //
  3379             // A NULL method_refs is different than an empty method_refs.
  3380             // We cannot infer any optimizations about older generations
  3381             // from an empty method_refs for the current generation.
  3382             break;
  3385           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3386             Method* method = method_refs->at(k);
  3388             if (!method->is_obsolete() &&
  3389                 method->name() == m_name &&
  3390                 method->signature() == m_signature) {
  3391               // The current RedefineClasses() call has made all EMCP
  3392               // versions of this method obsolete so mark it as obsolete
  3393               // and remove the reference.
  3394               RC_TRACE(0x00000400,
  3395                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3396                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3398               method->set_is_obsolete();
  3399               // Leave obsolete methods on the previous version list to
  3400               // clean up later.
  3401               break;
  3405           // The previous loop may not find a matching EMCP method, but
  3406           // that doesn't mean that we can optimize and not go any
  3407           // further back in the PreviousVersion generations. The EMCP
  3408           // method for this generation could have already been deleted,
  3409           // but there still may be an older EMCP method that has not
  3410           // been deleted.
  3413         if (++local_count >= obsolete_method_count) {
  3414           // no more obsolete methods so bail out now
  3415           break;
  3420 } // end add_previous_version()
  3423 // Determine if InstanceKlass has a previous version.
  3424 bool InstanceKlass::has_previous_version() const {
  3425   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3426 } // end has_previous_version()
  3429 Method* InstanceKlass::method_with_idnum(int idnum) {
  3430   Method* m = NULL;
  3431   if (idnum < methods()->length()) {
  3432     m = methods()->at(idnum);
  3434   if (m == NULL || m->method_idnum() != idnum) {
  3435     for (int index = 0; index < methods()->length(); ++index) {
  3436       m = methods()->at(index);
  3437       if (m->method_idnum() == idnum) {
  3438         return m;
  3441     // None found, return null for the caller to handle.
  3442     return NULL;
  3444   return m;
  3447 jint InstanceKlass::get_cached_class_file_len() {
  3448   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
  3451 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
  3452   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
  3456 // Construct a PreviousVersionNode entry for the array hung off
  3457 // the InstanceKlass.
  3458 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3459   GrowableArray<Method*>* prev_EMCP_methods) {
  3461   _prev_constant_pool = prev_constant_pool;
  3462   _prev_EMCP_methods = prev_EMCP_methods;
  3466 // Destroy a PreviousVersionNode
  3467 PreviousVersionNode::~PreviousVersionNode() {
  3468   if (_prev_constant_pool != NULL) {
  3469     _prev_constant_pool = NULL;
  3472   if (_prev_EMCP_methods != NULL) {
  3473     delete _prev_EMCP_methods;
  3477 // Construct a helper for walking the previous versions array
  3478 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
  3479   _thread = thread;
  3480   _previous_versions = ik->previous_versions();
  3481   _current_index = 0;
  3482   _current_p = NULL;
  3483   _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
  3487 // Return the interesting information for the next previous version
  3488 // of the klass. Returns NULL if there are no more previous versions.
  3489 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
  3490   if (_previous_versions == NULL) {
  3491     // no previous versions so nothing to return
  3492     return NULL;
  3495   _current_p = NULL;  // reset to NULL
  3496   _current_constant_pool_handle = NULL;
  3498   int length = _previous_versions->length();
  3500   while (_current_index < length) {
  3501     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3503     // Save a handle to the constant pool for this previous version,
  3504     // which keeps all the methods from being deallocated.
  3505     _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
  3506     _current_p = pv_node;
  3507     return pv_node;
  3510   return NULL;
  3511 } // end next_previous_version()

mercurial