src/share/vm/oops/instanceKlass.cpp

Tue, 29 Apr 2014 15:17:27 +0200

author
goetz
date
Tue, 29 Apr 2014 15:17:27 +0200
changeset 6911
ce8f6bb717c9
parent 6718
bd4d69d9cb7d
child 6975
27188ae8bbbb
permissions
-rw-r--r--

8042195: Introduce umbrella header orderAccess.inline.hpp.
Reviewed-by: dholmes, kvn, stefank, twisti

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

mercurial