src/share/vm/oops/instanceKlass.cpp

Thu, 21 Aug 2014 13:57:51 -0700

author
iklam
date
Thu, 21 Aug 2014 13:57:51 -0700
changeset 7089
6e0cb14ce59b
parent 6993
870c03421152
child 7097
14b8221771dc
permissions
-rw-r--r--

8046070: Class Data Sharing clean up and refactoring
Summary: Cleaned up CDS to be more configurable, maintainable and extensible
Reviewed-by: dholmes, coleenp, acorn, mchung

     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/iterator.inline.hpp"
    39 #include "memory/metadataFactory.hpp"
    40 #include "memory/oopFactory.hpp"
    41 #include "oops/fieldStreams.hpp"
    42 #include "oops/instanceClassLoaderKlass.hpp"
    43 #include "oops/instanceKlass.hpp"
    44 #include "oops/instanceMirrorKlass.hpp"
    45 #include "oops/instanceOop.hpp"
    46 #include "oops/klass.inline.hpp"
    47 #include "oops/method.hpp"
    48 #include "oops/oop.inline.hpp"
    49 #include "oops/symbol.hpp"
    50 #include "prims/jvmtiExport.hpp"
    51 #include "prims/jvmtiRedefineClassesTrace.hpp"
    52 #include "prims/jvmtiRedefineClasses.hpp"
    53 #include "prims/methodComparator.hpp"
    54 #include "runtime/fieldDescriptor.hpp"
    55 #include "runtime/handles.inline.hpp"
    56 #include "runtime/javaCalls.hpp"
    57 #include "runtime/mutexLocker.hpp"
    58 #include "runtime/orderAccess.inline.hpp"
    59 #include "runtime/thread.inline.hpp"
    60 #include "services/classLoadingService.hpp"
    61 #include "services/threadService.hpp"
    62 #include "utilities/dtrace.hpp"
    63 #include "utilities/macros.hpp"
    64 #if INCLUDE_ALL_GCS
    65 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    66 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    67 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    68 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    69 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
    70 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    71 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    72 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    73 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    74 #include "oops/oop.pcgc.inline.hpp"
    75 #endif // INCLUDE_ALL_GCS
    76 #ifdef COMPILER1
    77 #include "c1/c1_Compiler.hpp"
    78 #endif
    80 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    82 #ifdef DTRACE_ENABLED
    84 #ifndef USDT2
    86 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    87   char*, intptr_t, oop, intptr_t);
    88 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    89   char*, intptr_t, oop, intptr_t, int);
    90 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    91   char*, intptr_t, oop, intptr_t, int);
    92 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    93   char*, intptr_t, oop, intptr_t, int);
    94 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    95   char*, intptr_t, oop, intptr_t, int);
    96 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    97   char*, intptr_t, oop, intptr_t, int);
    98 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
    99   char*, intptr_t, oop, intptr_t, int);
   100 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
   101   char*, intptr_t, oop, intptr_t, int);
   103 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   104   {                                                              \
   105     char* data = NULL;                                           \
   106     int len = 0;                                                 \
   107     Symbol* name = (clss)->name();                               \
   108     if (name != NULL) {                                          \
   109       data = (char*)name->bytes();                               \
   110       len = name->utf8_length();                                 \
   111     }                                                            \
   112     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   113       data, len, SOLARIS_ONLY((void *))(clss)->class_loader(), thread_type);           \
   114   }
   116 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   117   {                                                              \
   118     char* data = NULL;                                           \
   119     int len = 0;                                                 \
   120     Symbol* name = (clss)->name();                               \
   121     if (name != NULL) {                                          \
   122       data = (char*)name->bytes();                               \
   123       len = name->utf8_length();                                 \
   124     }                                                            \
   125     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   126       data, len, SOLARIS_ONLY((void *))(clss)->class_loader(), thread_type, wait);     \
   127   }
   128 #else /* USDT2 */
   130 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   131 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   132 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   133 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   134 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   135 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   136 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   137 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   138 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   139   {                                                              \
   140     char* data = NULL;                                           \
   141     int len = 0;                                                 \
   142     Symbol* name = (clss)->name();                               \
   143     if (name != NULL) {                                          \
   144       data = (char*)name->bytes();                               \
   145       len = name->utf8_length();                                 \
   146     }                                                            \
   147     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   148       data, len, (clss)->class_loader(), thread_type);           \
   149   }
   151 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   152   {                                                              \
   153     char* data = NULL;                                           \
   154     int len = 0;                                                 \
   155     Symbol* name = (clss)->name();                               \
   156     if (name != NULL) {                                          \
   157       data = (char*)name->bytes();                               \
   158       len = name->utf8_length();                                 \
   159     }                                                            \
   160     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   161       data, len, (clss)->class_loader(), thread_type, wait);     \
   162   }
   163 #endif /* USDT2 */
   165 #else //  ndef DTRACE_ENABLED
   167 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   168 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   170 #endif //  ndef DTRACE_ENABLED
   172 volatile int InstanceKlass::_total_instanceKlass_count = 0;
   174 InstanceKlass* InstanceKlass::allocate_instance_klass(
   175                                               ClassLoaderData* loader_data,
   176                                               int vtable_len,
   177                                               int itable_len,
   178                                               int static_field_size,
   179                                               int nonstatic_oop_map_size,
   180                                               ReferenceType rt,
   181                                               AccessFlags access_flags,
   182                                               Symbol* name,
   183                                               Klass* super_klass,
   184                                               bool is_anonymous,
   185                                               TRAPS) {
   187   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   188                                  access_flags.is_interface(), is_anonymous);
   190   // Allocation
   191   InstanceKlass* ik;
   192   if (rt == REF_NONE) {
   193     if (name == vmSymbols::java_lang_Class()) {
   194       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   195         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   196         access_flags, is_anonymous);
   197     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   198           (SystemDictionary::ClassLoader_klass_loaded() &&
   199           super_klass != NULL &&
   200           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   201       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   202         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   203         access_flags, is_anonymous);
   204     } else {
   205       // normal class
   206       ik = new (loader_data, size, THREAD) InstanceKlass(
   207         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   208         access_flags, is_anonymous);
   209     }
   210   } else {
   211     // reference klass
   212     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   213         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   214         access_flags, is_anonymous);
   215   }
   217   // Check for pending exception before adding to the loader data and incrementing
   218   // class count.  Can get OOM here.
   219   if (HAS_PENDING_EXCEPTION) {
   220     return NULL;
   221   }
   223   // Add all classes to our internal class loader list here,
   224   // including classes in the bootstrap (NULL) class loader.
   225   loader_data->add_class(ik);
   227   Atomic::inc(&_total_instanceKlass_count);
   228   return ik;
   229 }
   232 // copy method ordering from resource area to Metaspace
   233 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
   234   if (m != NULL) {
   235     // allocate a new array and copy contents (memcpy?)
   236     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
   237     for (int i = 0; i < m->length(); i++) {
   238       _method_ordering->at_put(i, m->at(i));
   239     }
   240   } else {
   241     _method_ordering = Universe::the_empty_int_array();
   242   }
   243 }
   245 // create a new array of vtable_indices for default methods
   246 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
   247   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
   248   assert(default_vtable_indices() == NULL, "only create once");
   249   set_default_vtable_indices(vtable_indices);
   250   return vtable_indices;
   251 }
   253 InstanceKlass::InstanceKlass(int vtable_len,
   254                              int itable_len,
   255                              int static_field_size,
   256                              int nonstatic_oop_map_size,
   257                              ReferenceType rt,
   258                              AccessFlags access_flags,
   259                              bool is_anonymous) {
   260   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   262   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   263                                    access_flags.is_interface(), is_anonymous);
   265   set_vtable_length(vtable_len);
   266   set_itable_length(itable_len);
   267   set_static_field_size(static_field_size);
   268   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   269   set_access_flags(access_flags);
   270   _misc_flags = 0;  // initialize to zero
   271   set_is_anonymous(is_anonymous);
   272   assert(size() == iksize, "wrong size for object");
   274   set_array_klasses(NULL);
   275   set_methods(NULL);
   276   set_method_ordering(NULL);
   277   set_default_methods(NULL);
   278   set_default_vtable_indices(NULL);
   279   set_local_interfaces(NULL);
   280   set_transitive_interfaces(NULL);
   281   init_implementor();
   282   set_fields(NULL, 0);
   283   set_constants(NULL);
   284   set_class_loader_data(NULL);
   285   set_source_file_name_index(0);
   286   set_source_debug_extension(NULL, 0);
   287   set_array_name(NULL);
   288   set_inner_classes(NULL);
   289   set_static_oop_field_count(0);
   290   set_nonstatic_field_size(0);
   291   set_is_marked_dependent(false);
   292   set_has_unloaded_dependent(false);
   293   set_init_state(InstanceKlass::allocated);
   294   set_init_thread(NULL);
   295   set_reference_type(rt);
   296   set_oop_map_cache(NULL);
   297   set_jni_ids(NULL);
   298   set_osr_nmethods_head(NULL);
   299   set_breakpoints(NULL);
   300   init_previous_versions();
   301   set_generic_signature_index(0);
   302   release_set_methods_jmethod_ids(NULL);
   303   set_annotations(NULL);
   304   set_jvmti_cached_class_field_map(NULL);
   305   set_initial_method_idnum(0);
   306   _dependencies = NULL;
   307   set_jvmti_cached_class_field_map(NULL);
   308   set_cached_class_file(NULL);
   309   set_initial_method_idnum(0);
   310   set_minor_version(0);
   311   set_major_version(0);
   312   NOT_PRODUCT(_verify_count = 0;)
   314   // initialize the non-header words to zero
   315   intptr_t* p = (intptr_t*)this;
   316   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
   317     p[index] = NULL_WORD;
   318   }
   320   // Set temporary value until parseClassFile updates it with the real instance
   321   // size.
   322   set_layout_helper(Klass::instance_layout_helper(0, true));
   323 }
   326 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
   327                                        Array<Method*>* methods) {
   328   if (methods != NULL && methods != Universe::the_empty_method_array() &&
   329       !methods->is_shared()) {
   330     for (int i = 0; i < methods->length(); i++) {
   331       Method* method = methods->at(i);
   332       if (method == NULL) continue;  // maybe null if error processing
   333       // Only want to delete methods that are not executing for RedefineClasses.
   334       // The previous version will point to them so they're not totally dangling
   335       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   336       MetadataFactory::free_metadata(loader_data, method);
   337     }
   338     MetadataFactory::free_array<Method*>(loader_data, methods);
   339   }
   340 }
   342 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
   343                                           Klass* super_klass,
   344                                           Array<Klass*>* local_interfaces,
   345                                           Array<Klass*>* transitive_interfaces) {
   346   // Only deallocate transitive interfaces if not empty, same as super class
   347   // or same as local interfaces.  See code in parseClassFile.
   348   Array<Klass*>* ti = transitive_interfaces;
   349   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
   350     // check that the interfaces don't come from super class
   351     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
   352                     InstanceKlass::cast(super_klass)->transitive_interfaces();
   353     if (ti != sti && ti != NULL && !ti->is_shared()) {
   354       MetadataFactory::free_array<Klass*>(loader_data, ti);
   355     }
   356   }
   358   // local interfaces can be empty
   359   if (local_interfaces != Universe::the_empty_klass_array() &&
   360       local_interfaces != NULL && !local_interfaces->is_shared()) {
   361     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
   362   }
   363 }
   365 // This function deallocates the metadata and C heap pointers that the
   366 // InstanceKlass points to.
   367 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   369   // Orphan the mirror first, CMS thinks it's still live.
   370   if (java_mirror() != NULL) {
   371     java_lang_Class::set_klass(java_mirror(), NULL);
   372   }
   374   // Need to take this class off the class loader data list.
   375   loader_data->remove_class(this);
   377   // The array_klass for this class is created later, after error handling.
   378   // For class redefinition, we keep the original class so this scratch class
   379   // doesn't have an array class.  Either way, assert that there is nothing
   380   // to deallocate.
   381   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   383   // Release C heap allocated data that this might point to, which includes
   384   // reference counting symbol names.
   385   release_C_heap_structures();
   387   deallocate_methods(loader_data, methods());
   388   set_methods(NULL);
   390   if (method_ordering() != NULL &&
   391       method_ordering() != Universe::the_empty_int_array() &&
   392       !method_ordering()->is_shared()) {
   393     MetadataFactory::free_array<int>(loader_data, method_ordering());
   394   }
   395   set_method_ordering(NULL);
   397   // default methods can be empty
   398   if (default_methods() != NULL &&
   399       default_methods() != Universe::the_empty_method_array() &&
   400       !default_methods()->is_shared()) {
   401     MetadataFactory::free_array<Method*>(loader_data, default_methods());
   402   }
   403   // Do NOT deallocate the default methods, they are owned by superinterfaces.
   404   set_default_methods(NULL);
   406   // default methods vtable indices can be empty
   407   if (default_vtable_indices() != NULL &&
   408       !default_vtable_indices()->is_shared()) {
   409     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
   410   }
   411   set_default_vtable_indices(NULL);
   414   // This array is in Klass, but remove it with the InstanceKlass since
   415   // this place would be the only caller and it can share memory with transitive
   416   // interfaces.
   417   if (secondary_supers() != NULL &&
   418       secondary_supers() != Universe::the_empty_klass_array() &&
   419       secondary_supers() != transitive_interfaces() &&
   420       !secondary_supers()->is_shared()) {
   421     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   422   }
   423   set_secondary_supers(NULL);
   425   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
   426   set_transitive_interfaces(NULL);
   427   set_local_interfaces(NULL);
   429   if (fields() != NULL && !fields()->is_shared()) {
   430     MetadataFactory::free_array<jushort>(loader_data, fields());
   431   }
   432   set_fields(NULL, 0);
   434   // If a method from a redefined class is using this constant pool, don't
   435   // delete it, yet.  The new class's previous version will point to this.
   436   if (constants() != NULL) {
   437     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   438     if (!constants()->is_shared()) {
   439       MetadataFactory::free_metadata(loader_data, constants());
   440     }
   441     set_constants(NULL);
   442   }
   444   if (inner_classes() != NULL &&
   445       inner_classes() != Universe::the_empty_short_array() &&
   446       !inner_classes()->is_shared()) {
   447     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   448   }
   449   set_inner_classes(NULL);
   451   // We should deallocate the Annotations instance if it's not in shared spaces.
   452   if (annotations() != NULL && !annotations()->is_shared()) {
   453     MetadataFactory::free_metadata(loader_data, annotations());
   454   }
   455   set_annotations(NULL);
   456 }
   458 bool InstanceKlass::should_be_initialized() const {
   459   return !is_initialized();
   460 }
   462 klassVtable* InstanceKlass::vtable() const {
   463   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   464 }
   466 klassItable* InstanceKlass::itable() const {
   467   return new klassItable(instanceKlassHandle(this));
   468 }
   470 void InstanceKlass::eager_initialize(Thread *thread) {
   471   if (!EagerInitialization) return;
   473   if (this->is_not_initialized()) {
   474     // abort if the the class has a class initializer
   475     if (this->class_initializer() != NULL) return;
   477     // abort if it is java.lang.Object (initialization is handled in genesis)
   478     Klass* super = this->super();
   479     if (super == NULL) return;
   481     // abort if the super class should be initialized
   482     if (!InstanceKlass::cast(super)->is_initialized()) return;
   484     // call body to expose the this pointer
   485     instanceKlassHandle this_oop(thread, this);
   486     eager_initialize_impl(this_oop);
   487   }
   488 }
   490 // JVMTI spec thinks there are signers and protection domain in the
   491 // instanceKlass.  These accessors pretend these fields are there.
   492 // The hprof specification also thinks these fields are in InstanceKlass.
   493 oop InstanceKlass::protection_domain() const {
   494   // return the protection_domain from the mirror
   495   return java_lang_Class::protection_domain(java_mirror());
   496 }
   498 // To remove these from requires an incompatible change and CCC request.
   499 objArrayOop InstanceKlass::signers() const {
   500   // return the signers from the mirror
   501   return java_lang_Class::signers(java_mirror());
   502 }
   504 oop InstanceKlass::init_lock() const {
   505   // return the init lock from the mirror
   506   oop lock = java_lang_Class::init_lock(java_mirror());
   507   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   508          "only fully initialized state can have a null lock");
   509   return lock;
   510 }
   512 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   513 // threads to get this lock will see a null lock and will not lock.
   514 // That's okay because they all check for initialized state after getting
   515 // the lock and return.
   516 void InstanceKlass::fence_and_clear_init_lock() {
   517   // make sure previous stores are all done, notably the init_state.
   518   OrderAccess::storestore();
   519   java_lang_Class::set_init_lock(java_mirror(), NULL);
   520   assert(!is_not_initialized(), "class must be initialized now");
   521 }
   523 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   524   EXCEPTION_MARK;
   525   oop init_lock = this_oop->init_lock();
   526   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   528   // abort if someone beat us to the initialization
   529   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   531   ClassState old_state = this_oop->init_state();
   532   link_class_impl(this_oop, true, THREAD);
   533   if (HAS_PENDING_EXCEPTION) {
   534     CLEAR_PENDING_EXCEPTION;
   535     // Abort if linking the class throws an exception.
   537     // Use a test to avoid redundantly resetting the state if there's
   538     // no change.  Set_init_state() asserts that state changes make
   539     // progress, whereas here we might just be spinning in place.
   540     if( old_state != this_oop->_init_state )
   541       this_oop->set_init_state (old_state);
   542   } else {
   543     // linking successfull, mark class as initialized
   544     this_oop->set_init_state (fully_initialized);
   545     this_oop->fence_and_clear_init_lock();
   546     // trace
   547     if (TraceClassInitialization) {
   548       ResourceMark rm(THREAD);
   549       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   550     }
   551   }
   552 }
   555 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   556 // process. The step comments refers to the procedure described in that section.
   557 // Note: implementation moved to static method to expose the this pointer.
   558 void InstanceKlass::initialize(TRAPS) {
   559   if (this->should_be_initialized()) {
   560     HandleMark hm(THREAD);
   561     instanceKlassHandle this_oop(THREAD, this);
   562     initialize_impl(this_oop, CHECK);
   563     // Note: at this point the class may be initialized
   564     //       OR it may be in the state of being initialized
   565     //       in case of recursive initialization!
   566   } else {
   567     assert(is_initialized(), "sanity check");
   568   }
   569 }
   572 bool InstanceKlass::verify_code(
   573     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   574   // 1) Verify the bytecodes
   575   Verifier::Mode mode =
   576     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   577   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   578 }
   581 // Used exclusively by the shared spaces dump mechanism to prevent
   582 // classes mapped into the shared regions in new VMs from appearing linked.
   584 void InstanceKlass::unlink_class() {
   585   assert(is_linked(), "must be linked");
   586   _init_state = loaded;
   587 }
   589 void InstanceKlass::link_class(TRAPS) {
   590   assert(is_loaded(), "must be loaded");
   591   if (!is_linked()) {
   592     HandleMark hm(THREAD);
   593     instanceKlassHandle this_oop(THREAD, this);
   594     link_class_impl(this_oop, true, CHECK);
   595   }
   596 }
   598 // Called to verify that a class can link during initialization, without
   599 // throwing a VerifyError.
   600 bool InstanceKlass::link_class_or_fail(TRAPS) {
   601   assert(is_loaded(), "must be loaded");
   602   if (!is_linked()) {
   603     HandleMark hm(THREAD);
   604     instanceKlassHandle this_oop(THREAD, this);
   605     link_class_impl(this_oop, false, CHECK_false);
   606   }
   607   return is_linked();
   608 }
   610 bool InstanceKlass::link_class_impl(
   611     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   612   // check for error state
   613   if (this_oop->is_in_error_state()) {
   614     ResourceMark rm(THREAD);
   615     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   616                this_oop->external_name(), false);
   617   }
   618   // return if already verified
   619   if (this_oop->is_linked()) {
   620     return true;
   621   }
   623   // Timing
   624   // timer handles recursion
   625   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   626   JavaThread* jt = (JavaThread*)THREAD;
   628   // link super class before linking this class
   629   instanceKlassHandle super(THREAD, this_oop->super());
   630   if (super.not_null()) {
   631     if (super->is_interface()) {  // check if super class is an interface
   632       ResourceMark rm(THREAD);
   633       Exceptions::fthrow(
   634         THREAD_AND_LOCATION,
   635         vmSymbols::java_lang_IncompatibleClassChangeError(),
   636         "class %s has interface %s as super class",
   637         this_oop->external_name(),
   638         super->external_name()
   639       );
   640       return false;
   641     }
   643     link_class_impl(super, throw_verifyerror, CHECK_false);
   644   }
   646   // link all interfaces implemented by this class before linking this class
   647   Array<Klass*>* interfaces = this_oop->local_interfaces();
   648   int num_interfaces = interfaces->length();
   649   for (int index = 0; index < num_interfaces; index++) {
   650     HandleMark hm(THREAD);
   651     instanceKlassHandle ih(THREAD, interfaces->at(index));
   652     link_class_impl(ih, throw_verifyerror, CHECK_false);
   653   }
   655   // in case the class is linked in the process of linking its superclasses
   656   if (this_oop->is_linked()) {
   657     return true;
   658   }
   660   // trace only the link time for this klass that includes
   661   // the verification time
   662   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   663                              ClassLoader::perf_class_link_selftime(),
   664                              ClassLoader::perf_classes_linked(),
   665                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   666                              jt->get_thread_stat()->perf_timers_addr(),
   667                              PerfClassTraceTime::CLASS_LINK);
   669   // verification & rewriting
   670   {
   671     oop init_lock = this_oop->init_lock();
   672     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   673     // rewritten will have been set if loader constraint error found
   674     // on an earlier link attempt
   675     // don't verify or rewrite if already rewritten
   677     if (!this_oop->is_linked()) {
   678       if (!this_oop->is_rewritten()) {
   679         {
   680           // Timer includes any side effects of class verification (resolution,
   681           // etc), but not recursive entry into verify_code().
   682           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   683                                    ClassLoader::perf_class_verify_selftime(),
   684                                    ClassLoader::perf_classes_verified(),
   685                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   686                                    jt->get_thread_stat()->perf_timers_addr(),
   687                                    PerfClassTraceTime::CLASS_VERIFY);
   688           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   689           if (!verify_ok) {
   690             return false;
   691           }
   692         }
   694         // Just in case a side-effect of verify linked this class already
   695         // (which can sometimes happen since the verifier loads classes
   696         // using custom class loaders, which are free to initialize things)
   697         if (this_oop->is_linked()) {
   698           return true;
   699         }
   701         // also sets rewritten
   702         this_oop->rewrite_class(CHECK_false);
   703       }
   705       // relocate jsrs and link methods after they are all rewritten
   706       this_oop->link_methods(CHECK_false);
   708       // Initialize the vtable and interface table after
   709       // methods have been rewritten since rewrite may
   710       // fabricate new Method*s.
   711       // also does loader constraint checking
   712       if (!this_oop()->is_shared()) {
   713         ResourceMark rm(THREAD);
   714         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   715         this_oop->itable()->initialize_itable(true, CHECK_false);
   716       }
   717 #ifdef ASSERT
   718       else {
   719         ResourceMark rm(THREAD);
   720         this_oop->vtable()->verify(tty, true);
   721         // In case itable verification is ever added.
   722         // this_oop->itable()->verify(tty, true);
   723       }
   724 #endif
   725       this_oop->set_init_state(linked);
   726       if (JvmtiExport::should_post_class_prepare()) {
   727         Thread *thread = THREAD;
   728         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   729         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   730       }
   731     }
   732   }
   733   return true;
   734 }
   737 // Rewrite the byte codes of all of the methods of a class.
   738 // The rewriter must be called exactly once. Rewriting must happen after
   739 // verification but before the first method of the class is executed.
   740 void InstanceKlass::rewrite_class(TRAPS) {
   741   assert(is_loaded(), "must be loaded");
   742   instanceKlassHandle this_oop(THREAD, this);
   743   if (this_oop->is_rewritten()) {
   744     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   745     return;
   746   }
   747   Rewriter::rewrite(this_oop, CHECK);
   748   this_oop->set_rewritten();
   749 }
   751 // Now relocate and link method entry points after class is rewritten.
   752 // This is outside is_rewritten flag. In case of an exception, it can be
   753 // executed more than once.
   754 void InstanceKlass::link_methods(TRAPS) {
   755   int len = methods()->length();
   756   for (int i = len-1; i >= 0; i--) {
   757     methodHandle m(THREAD, methods()->at(i));
   759     // Set up method entry points for compiler and interpreter    .
   760     m->link_method(m, CHECK);
   762     // This is for JVMTI and unrelated to relocator but the last thing we do
   763 #ifdef ASSERT
   764     if (StressMethodComparator) {
   765       ResourceMark rm(THREAD);
   766       static int nmc = 0;
   767       for (int j = i; j >= 0 && j >= i-4; j--) {
   768         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   769         bool z = MethodComparator::methods_EMCP(m(),
   770                    methods()->at(j));
   771         if (j == i && !z) {
   772           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   773           assert(z, "method must compare equal to itself");
   774         }
   775       }
   776     }
   777 #endif //ASSERT
   778   }
   779 }
   782 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   783   // Make sure klass is linked (verified) before initialization
   784   // A class could already be verified, since it has been reflected upon.
   785   this_oop->link_class(CHECK);
   787   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   789   bool wait = false;
   791   // refer to the JVM book page 47 for description of steps
   792   // Step 1
   793   {
   794     oop init_lock = this_oop->init_lock();
   795     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   797     Thread *self = THREAD; // it's passed the current thread
   799     // Step 2
   800     // If we were to use wait() instead of waitInterruptibly() then
   801     // we might end up throwing IE from link/symbol resolution sites
   802     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   803     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   804         wait = true;
   805       ol.waitUninterruptibly(CHECK);
   806     }
   808     // Step 3
   809     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   810       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   811       return;
   812     }
   814     // Step 4
   815     if (this_oop->is_initialized()) {
   816       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   817       return;
   818     }
   820     // Step 5
   821     if (this_oop->is_in_error_state()) {
   822       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   823       ResourceMark rm(THREAD);
   824       const char* desc = "Could not initialize class ";
   825       const char* className = this_oop->external_name();
   826       size_t msglen = strlen(desc) + strlen(className) + 1;
   827       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   828       if (NULL == message) {
   829         // Out of memory: can't create detailed error message
   830         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   831       } else {
   832         jio_snprintf(message, msglen, "%s%s", desc, className);
   833         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   834       }
   835     }
   837     // Step 6
   838     this_oop->set_init_state(being_initialized);
   839     this_oop->set_init_thread(self);
   840   }
   842   // Step 7
   843   Klass* super_klass = this_oop->super();
   844   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   845     super_klass->initialize(THREAD);
   847     if (HAS_PENDING_EXCEPTION) {
   848       Handle e(THREAD, PENDING_EXCEPTION);
   849       CLEAR_PENDING_EXCEPTION;
   850       {
   851         EXCEPTION_MARK;
   852         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   853         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   854       }
   855       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   856       THROW_OOP(e());
   857     }
   858   }
   860   if (this_oop->has_default_methods()) {
   861     // Step 7.5: initialize any interfaces which have default methods
   862     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   863       Klass* iface = this_oop->local_interfaces()->at(i);
   864       InstanceKlass* ik = InstanceKlass::cast(iface);
   865       if (ik->has_default_methods() && ik->should_be_initialized()) {
   866         ik->initialize(THREAD);
   868         if (HAS_PENDING_EXCEPTION) {
   869           Handle e(THREAD, PENDING_EXCEPTION);
   870           CLEAR_PENDING_EXCEPTION;
   871           {
   872             EXCEPTION_MARK;
   873             // Locks object, set state, and notify all waiting threads
   874             this_oop->set_initialization_state_and_notify(
   875                 initialization_error, THREAD);
   877             // ignore any exception thrown, superclass initialization error is
   878             // thrown below
   879             CLEAR_PENDING_EXCEPTION;
   880           }
   881           DTRACE_CLASSINIT_PROBE_WAIT(
   882               super__failed, InstanceKlass::cast(this_oop()), -1, wait);
   883           THROW_OOP(e());
   884         }
   885       }
   886     }
   887   }
   889   // Step 8
   890   {
   891     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   892     JavaThread* jt = (JavaThread*)THREAD;
   893     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   894     // Timer includes any side effects of class initialization (resolution,
   895     // etc), but not recursive entry into call_class_initializer().
   896     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   897                              ClassLoader::perf_class_init_selftime(),
   898                              ClassLoader::perf_classes_inited(),
   899                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   900                              jt->get_thread_stat()->perf_timers_addr(),
   901                              PerfClassTraceTime::CLASS_CLINIT);
   902     this_oop->call_class_initializer(THREAD);
   903   }
   905   // Step 9
   906   if (!HAS_PENDING_EXCEPTION) {
   907     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   908     { ResourceMark rm(THREAD);
   909       debug_only(this_oop->vtable()->verify(tty, true);)
   910     }
   911   }
   912   else {
   913     // Step 10 and 11
   914     Handle e(THREAD, PENDING_EXCEPTION);
   915     CLEAR_PENDING_EXCEPTION;
   916     {
   917       EXCEPTION_MARK;
   918       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   919       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   920     }
   921     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   922     if (e->is_a(SystemDictionary::Error_klass())) {
   923       THROW_OOP(e());
   924     } else {
   925       JavaCallArguments args(e);
   926       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   927                 vmSymbols::throwable_void_signature(),
   928                 &args);
   929     }
   930   }
   931   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   932 }
   935 // Note: implementation moved to static method to expose the this pointer.
   936 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   937   instanceKlassHandle kh(THREAD, this);
   938   set_initialization_state_and_notify_impl(kh, state, CHECK);
   939 }
   941 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   942   oop init_lock = this_oop->init_lock();
   943   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   944   this_oop->set_init_state(state);
   945   this_oop->fence_and_clear_init_lock();
   946   ol.notify_all(CHECK);
   947 }
   949 // The embedded _implementor field can only record one implementor.
   950 // When there are more than one implementors, the _implementor field
   951 // is set to the interface Klass* itself. Following are the possible
   952 // values for the _implementor field:
   953 //   NULL                  - no implementor
   954 //   implementor Klass*    - one implementor
   955 //   self                  - more than one implementor
   956 //
   957 // The _implementor field only exists for interfaces.
   958 void InstanceKlass::add_implementor(Klass* k) {
   959   assert(Compile_lock->owned_by_self(), "");
   960   assert(is_interface(), "not interface");
   961   // Filter out my subinterfaces.
   962   // (Note: Interfaces are never on the subklass list.)
   963   if (InstanceKlass::cast(k)->is_interface()) return;
   965   // Filter out subclasses whose supers already implement me.
   966   // (Note: CHA must walk subclasses of direct implementors
   967   // in order to locate indirect implementors.)
   968   Klass* sk = InstanceKlass::cast(k)->super();
   969   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   970     // We only need to check one immediate superclass, since the
   971     // implements_interface query looks at transitive_interfaces.
   972     // Any supers of the super have the same (or fewer) transitive_interfaces.
   973     return;
   975   Klass* ik = implementor();
   976   if (ik == NULL) {
   977     set_implementor(k);
   978   } else if (ik != this) {
   979     // There is already an implementor. Use itself as an indicator of
   980     // more than one implementors.
   981     set_implementor(this);
   982   }
   984   // The implementor also implements the transitive_interfaces
   985   for (int index = 0; index < local_interfaces()->length(); index++) {
   986     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
   987   }
   988 }
   990 void InstanceKlass::init_implementor() {
   991   if (is_interface()) {
   992     set_implementor(NULL);
   993   }
   994 }
   997 void InstanceKlass::process_interfaces(Thread *thread) {
   998   // link this class into the implementors list of every interface it implements
   999   Klass* this_as_klass_oop = this;
  1000   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
  1001     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
  1002     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
  1003     assert(interf->is_interface(), "expected interface");
  1004     interf->add_implementor(this_as_klass_oop);
  1008 bool InstanceKlass::can_be_primary_super_slow() const {
  1009   if (is_interface())
  1010     return false;
  1011   else
  1012     return Klass::can_be_primary_super_slow();
  1015 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
  1016   // The secondaries are the implemented interfaces.
  1017   InstanceKlass* ik = InstanceKlass::cast(this);
  1018   Array<Klass*>* interfaces = ik->transitive_interfaces();
  1019   int num_secondaries = num_extra_slots + interfaces->length();
  1020   if (num_secondaries == 0) {
  1021     // Must share this for correct bootstrapping!
  1022     set_secondary_supers(Universe::the_empty_klass_array());
  1023     return NULL;
  1024   } else if (num_extra_slots == 0) {
  1025     // The secondary super list is exactly the same as the transitive interfaces.
  1026     // Redefine classes has to be careful not to delete this!
  1027     set_secondary_supers(interfaces);
  1028     return NULL;
  1029   } else {
  1030     // Copy transitive interfaces to a temporary growable array to be constructed
  1031     // into the secondary super list with extra slots.
  1032     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
  1033     for (int i = 0; i < interfaces->length(); i++) {
  1034       secondaries->push(interfaces->at(i));
  1036     return secondaries;
  1040 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
  1041   if (k->is_interface()) {
  1042     return implements_interface(k);
  1043   } else {
  1044     return Klass::compute_is_subtype_of(k);
  1048 bool InstanceKlass::implements_interface(Klass* k) const {
  1049   if (this == k) return true;
  1050   assert(k->is_interface(), "should be an interface class");
  1051   for (int i = 0; i < transitive_interfaces()->length(); i++) {
  1052     if (transitive_interfaces()->at(i) == k) {
  1053       return true;
  1056   return false;
  1059 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
  1060   // Verify direct super interface
  1061   if (this == k) return true;
  1062   assert(k->is_interface(), "should be an interface class");
  1063   for (int i = 0; i < local_interfaces()->length(); i++) {
  1064     if (local_interfaces()->at(i) == k) {
  1065       return true;
  1068   return false;
  1071 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
  1072   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  1073   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
  1074     report_java_out_of_memory("Requested array size exceeds VM limit");
  1075     JvmtiExport::post_array_size_exhausted();
  1076     THROW_OOP_0(Universe::out_of_memory_error_array_size());
  1078   int size = objArrayOopDesc::object_size(length);
  1079   Klass* ak = array_klass(n, CHECK_NULL);
  1080   KlassHandle h_ak (THREAD, ak);
  1081   objArrayOop o =
  1082     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  1083   return o;
  1086 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
  1087   if (TraceFinalizerRegistration) {
  1088     tty->print("Registered ");
  1089     i->print_value_on(tty);
  1090     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  1092   instanceHandle h_i(THREAD, i);
  1093   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  1094   JavaValue result(T_VOID);
  1095   JavaCallArguments args(h_i);
  1096   methodHandle mh (THREAD, Universe::finalizer_register_method());
  1097   JavaCalls::call(&result, mh, &args, CHECK_NULL);
  1098   return h_i();
  1101 instanceOop InstanceKlass::allocate_instance(TRAPS) {
  1102   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  1103   int size = size_helper();  // Query before forming handle.
  1105   KlassHandle h_k(THREAD, this);
  1107   instanceOop i;
  1109   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1110   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1111     i = register_finalizer(i, CHECK_NULL);
  1113   return i;
  1116 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1117   if (is_interface() || is_abstract()) {
  1118     ResourceMark rm(THREAD);
  1119     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1120               : vmSymbols::java_lang_InstantiationException(), external_name());
  1122   if (this == SystemDictionary::Class_klass()) {
  1123     ResourceMark rm(THREAD);
  1124     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1125               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1129 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1130   instanceKlassHandle this_oop(THREAD, this);
  1131   return array_klass_impl(this_oop, or_null, n, THREAD);
  1134 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1135   if (this_oop->array_klasses() == NULL) {
  1136     if (or_null) return NULL;
  1138     ResourceMark rm;
  1139     JavaThread *jt = (JavaThread *)THREAD;
  1141       // Atomic creation of array_klasses
  1142       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1143       MutexLocker ma(MultiArray_lock, THREAD);
  1145       // Check if update has already taken place
  1146       if (this_oop->array_klasses() == NULL) {
  1147         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1148         this_oop->set_array_klasses(k);
  1152   // _this will always be set at this point
  1153   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1154   if (or_null) {
  1155     return oak->array_klass_or_null(n);
  1157   return oak->array_klass(n, CHECK_NULL);
  1160 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1161   return array_klass_impl(or_null, 1, THREAD);
  1164 void InstanceKlass::call_class_initializer(TRAPS) {
  1165   instanceKlassHandle ik (THREAD, this);
  1166   call_class_initializer_impl(ik, THREAD);
  1169 static int call_class_initializer_impl_counter = 0;   // for debugging
  1171 Method* InstanceKlass::class_initializer() {
  1172   Method* clinit = find_method(
  1173       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1174   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1175     return clinit;
  1177   return NULL;
  1180 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1181   if (ReplayCompiles &&
  1182       (ReplaySuppressInitializers == 1 ||
  1183        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1184     // Hide the existence of the initializer for the purpose of replaying the compile
  1185     return;
  1188   methodHandle h_method(THREAD, this_oop->class_initializer());
  1189   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1190   if (TraceClassInitialization) {
  1191     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1192     this_oop->name()->print_value();
  1193     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1195   if (h_method() != NULL) {
  1196     JavaCallArguments args; // No arguments
  1197     JavaValue result(T_VOID);
  1198     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1203 void InstanceKlass::mask_for(methodHandle method, int bci,
  1204   InterpreterOopMap* entry_for) {
  1205   // Dirty read, then double-check under a lock.
  1206   if (_oop_map_cache == NULL) {
  1207     // Otherwise, allocate a new one.
  1208     MutexLocker x(OopMapCacheAlloc_lock);
  1209     // First time use. Allocate a cache in C heap
  1210     if (_oop_map_cache == NULL) {
  1211       // Release stores from OopMapCache constructor before assignment
  1212       // to _oop_map_cache. C++ compilers on ppc do not emit the
  1213       // required memory barrier only because of the volatile
  1214       // qualifier of _oop_map_cache.
  1215       OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
  1218   // _oop_map_cache is constant after init; lookup below does is own locking.
  1219   _oop_map_cache->lookup(method, bci, entry_for);
  1223 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1224   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1225     Symbol* f_name = fs.name();
  1226     Symbol* f_sig  = fs.signature();
  1227     if (f_name == name && f_sig == sig) {
  1228       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1229       return true;
  1232   return false;
  1236 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1237   const int n = local_interfaces()->length();
  1238   for (int i = 0; i < n; i++) {
  1239     Klass* intf1 = local_interfaces()->at(i);
  1240     assert(intf1->is_interface(), "just checking type");
  1241     // search for field in current interface
  1242     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1243       assert(fd->is_static(), "interface field must be static");
  1244       return intf1;
  1246     // search for field in direct superinterfaces
  1247     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1248     if (intf2 != NULL) return intf2;
  1250   // otherwise field lookup fails
  1251   return NULL;
  1255 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1256   // search order according to newest JVM spec (5.4.3.2, p.167).
  1257   // 1) search for field in current klass
  1258   if (find_local_field(name, sig, fd)) {
  1259     return const_cast<InstanceKlass*>(this);
  1261   // 2) search for field recursively in direct superinterfaces
  1262   { Klass* intf = find_interface_field(name, sig, fd);
  1263     if (intf != NULL) return intf;
  1265   // 3) apply field lookup recursively if superclass exists
  1266   { Klass* supr = super();
  1267     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1269   // 4) otherwise field lookup fails
  1270   return NULL;
  1274 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1275   // search order according to newest JVM spec (5.4.3.2, p.167).
  1276   // 1) search for field in current klass
  1277   if (find_local_field(name, sig, fd)) {
  1278     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1280   // 2) search for field recursively in direct superinterfaces
  1281   if (is_static) {
  1282     Klass* intf = find_interface_field(name, sig, fd);
  1283     if (intf != NULL) return intf;
  1285   // 3) apply field lookup recursively if superclass exists
  1286   { Klass* supr = super();
  1287     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1289   // 4) otherwise field lookup fails
  1290   return NULL;
  1294 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1295   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1296     if (fs.offset() == offset) {
  1297       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1298       if (fd->is_static() == is_static) return true;
  1301   return false;
  1305 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1306   Klass* klass = const_cast<InstanceKlass*>(this);
  1307   while (klass != NULL) {
  1308     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1309       return true;
  1311     klass = klass->super();
  1313   return false;
  1317 void InstanceKlass::methods_do(void f(Method* method)) {
  1318   int len = methods()->length();
  1319   for (int index = 0; index < len; index++) {
  1320     Method* m = methods()->at(index);
  1321     assert(m->is_method(), "must be method");
  1322     f(m);
  1327 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1328   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1329     if (fs.access_flags().is_static()) {
  1330       fieldDescriptor& fd = fs.field_descriptor();
  1331       cl->do_field(&fd);
  1337 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
  1338   instanceKlassHandle h_this(THREAD, this);
  1339   do_local_static_fields_impl(h_this, f, mirror, CHECK);
  1343 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
  1344                              void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {
  1345   for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
  1346     if (fs.access_flags().is_static()) {
  1347       fieldDescriptor& fd = fs.field_descriptor();
  1348       f(&fd, mirror, CHECK);
  1354 static int compare_fields_by_offset(int* a, int* b) {
  1355   return a[0] - b[0];
  1358 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1359   InstanceKlass* super = superklass();
  1360   if (super != NULL) {
  1361     super->do_nonstatic_fields(cl);
  1363   fieldDescriptor fd;
  1364   int length = java_fields_count();
  1365   // In DebugInfo nonstatic fields are sorted by offset.
  1366   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1367   int j = 0;
  1368   for (int i = 0; i < length; i += 1) {
  1369     fd.reinitialize(this, i);
  1370     if (!fd.is_static()) {
  1371       fields_sorted[j + 0] = fd.offset();
  1372       fields_sorted[j + 1] = i;
  1373       j += 2;
  1376   if (j > 0) {
  1377     length = j;
  1378     // _sort_Fn is defined in growableArray.hpp.
  1379     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1380     for (int i = 0; i < length; i += 2) {
  1381       fd.reinitialize(this, fields_sorted[i + 1]);
  1382       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1383       cl->do_field(&fd);
  1386   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1390 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1391   if (array_klasses() != NULL)
  1392     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1395 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1396   if (array_klasses() != NULL)
  1397     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1400 #ifdef ASSERT
  1401 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1402   int len = methods->length();
  1403   for (int index = 0; index < len; index++) {
  1404     Method* m = methods->at(index);
  1405     assert(m->is_method(), "must be method");
  1406     if (m->signature() == signature && m->name() == name) {
  1407        return index;
  1410   return -1;
  1412 #endif
  1414 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1415   int len = methods->length();
  1416   // methods are sorted, so do binary search
  1417   int l = 0;
  1418   int h = len - 1;
  1419   while (l <= h) {
  1420     int mid = (l + h) >> 1;
  1421     Method* m = methods->at(mid);
  1422     assert(m->is_method(), "must be method");
  1423     int res = m->name()->fast_compare(name);
  1424     if (res == 0) {
  1425       return mid;
  1426     } else if (res < 0) {
  1427       l = mid + 1;
  1428     } else {
  1429       h = mid - 1;
  1432   return -1;
  1435 // find_method looks up the name/signature in the local methods array
  1436 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1437   return find_method_impl(name, signature, false);
  1440 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
  1441   return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass);
  1444 // find_instance_method looks up the name/signature in the local methods array
  1445 // and skips over static methods
  1446 Method* InstanceKlass::find_instance_method(
  1447     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1448   Method* meth = InstanceKlass::find_method(methods, name, signature);
  1449   if (meth != NULL && meth->is_static()) {
  1450       meth = NULL;
  1452   return meth;
  1455 // find_method looks up the name/signature in the local methods array
  1456 Method* InstanceKlass::find_method(
  1457     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1458   return InstanceKlass::find_method_impl(methods, name, signature, false);
  1461 Method* InstanceKlass::find_method_impl(
  1462     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
  1463   int hit = find_method_index(methods, name, signature, skipping_overpass);
  1464   return hit >= 0 ? methods->at(hit): NULL;
  1467 // Used directly for default_methods to find the index into the
  1468 // default_vtable_indices, and indirectly by find_method
  1469 // find_method_index looks in the local methods array to return the index
  1470 // of the matching name/signature. If, overpass methods are being ignored,
  1471 // the search continues to find a potential non-overpass match.  This capability
  1472 // is important during method resolution to prefer a static method, for example,
  1473 // over an overpass method.
  1474 int InstanceKlass::find_method_index(
  1475     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
  1476   int hit = binary_search(methods, name);
  1477   if (hit != -1) {
  1478     Method* m = methods->at(hit);
  1479     // Do linear search to find matching signature.  First, quick check
  1480     // for common case, ignoring overpasses if requested.
  1481     if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return hit;
  1483     // search downwards through overloaded methods
  1484     int i;
  1485     for (i = hit - 1; i >= 0; --i) {
  1486         Method* m = methods->at(i);
  1487         assert(m->is_method(), "must be method");
  1488         if (m->name() != name) break;
  1489         if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
  1491     // search upwards
  1492     for (i = hit + 1; i < methods->length(); ++i) {
  1493         Method* m = methods->at(i);
  1494         assert(m->is_method(), "must be method");
  1495         if (m->name() != name) break;
  1496         if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
  1498     // not found
  1499 #ifdef ASSERT
  1500     int index = skipping_overpass ? -1 : linear_search(methods, name, signature);
  1501     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1502 #endif
  1504   return -1;
  1506 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1507   return find_method_by_name(methods(), name, end);
  1510 int InstanceKlass::find_method_by_name(
  1511     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1512   assert(end_ptr != NULL, "just checking");
  1513   int start = binary_search(methods, name);
  1514   int end = start + 1;
  1515   if (start != -1) {
  1516     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1517     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1518     *end_ptr = end;
  1519     return start;
  1521   return -1;
  1524 // uncached_lookup_method searches both the local class methods array and all
  1525 // superclasses methods arrays, skipping any overpass methods in superclasses.
  1526 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
  1527   MethodLookupMode lookup_mode = mode;
  1528   Klass* klass = const_cast<InstanceKlass*>(this);
  1529   while (klass != NULL) {
  1530     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
  1531     if (method != NULL) {
  1532       return method;
  1534     klass = InstanceKlass::cast(klass)->super();
  1535     lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
  1537   return NULL;
  1540 // lookup a method in the default methods list then in all transitive interfaces
  1541 // Do NOT return private or static methods
  1542 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
  1543                                                          Symbol* signature) const {
  1544   Method* m = NULL;
  1545   if (default_methods() != NULL) {
  1546     m = find_method(default_methods(), name, signature);
  1548   // Look up interfaces
  1549   if (m == NULL) {
  1550     m = lookup_method_in_all_interfaces(name, signature, normal);
  1552   return m;
  1555 // lookup a method in all the interfaces that this class implements
  1556 // Do NOT return private or static methods, new in JDK8 which are not externally visible
  1557 // They should only be found in the initial InterfaceMethodRef
  1558 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1559                                                        Symbol* signature,
  1560                                                        MethodLookupMode mode) const {
  1561   Array<Klass*>* all_ifs = transitive_interfaces();
  1562   int num_ifs = all_ifs->length();
  1563   InstanceKlass *ik = NULL;
  1564   for (int i = 0; i < num_ifs; i++) {
  1565     ik = InstanceKlass::cast(all_ifs->at(i));
  1566     Method* m = ik->lookup_method(name, signature);
  1567     if (m != NULL && m->is_public() && !m->is_static() &&
  1568         ((mode != skip_defaults) || !m->is_default_method())) {
  1569       return m;
  1572   return NULL;
  1575 /* jni_id_for_impl for jfieldIds only */
  1576 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1577   MutexLocker ml(JfieldIdCreation_lock);
  1578   // Retry lookup after we got the lock
  1579   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1580   if (probe == NULL) {
  1581     // Slow case, allocate new static field identifier
  1582     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1583     this_oop->set_jni_ids(probe);
  1585   return probe;
  1589 /* jni_id_for for jfieldIds only */
  1590 JNIid* InstanceKlass::jni_id_for(int offset) {
  1591   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1592   if (probe == NULL) {
  1593     probe = jni_id_for_impl(this, offset);
  1595   return probe;
  1598 u2 InstanceKlass::enclosing_method_data(int offset) {
  1599   Array<jushort>* inner_class_list = inner_classes();
  1600   if (inner_class_list == NULL) {
  1601     return 0;
  1603   int length = inner_class_list->length();
  1604   if (length % inner_class_next_offset == 0) {
  1605     return 0;
  1606   } else {
  1607     int index = length - enclosing_method_attribute_size;
  1608     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1609     return inner_class_list->at(index + offset);
  1613 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1614                                                  u2 method_index) {
  1615   Array<jushort>* inner_class_list = inner_classes();
  1616   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1617   int length = inner_class_list->length();
  1618   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1619     int index = length - enclosing_method_attribute_size;
  1620     inner_class_list->at_put(
  1621       index + enclosing_method_class_index_offset, class_index);
  1622     inner_class_list->at_put(
  1623       index + enclosing_method_method_index_offset, method_index);
  1627 // Lookup or create a jmethodID.
  1628 // This code is called by the VMThread and JavaThreads so the
  1629 // locking has to be done very carefully to avoid deadlocks
  1630 // and/or other cache consistency problems.
  1631 //
  1632 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1633   size_t idnum = (size_t)method_h->method_idnum();
  1634   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1635   size_t length = 0;
  1636   jmethodID id = NULL;
  1638   // We use a double-check locking idiom here because this cache is
  1639   // performance sensitive. In the normal system, this cache only
  1640   // transitions from NULL to non-NULL which is safe because we use
  1641   // release_set_methods_jmethod_ids() to advertise the new cache.
  1642   // A partially constructed cache should never be seen by a racing
  1643   // thread. We also use release_store_ptr() to save a new jmethodID
  1644   // in the cache so a partially constructed jmethodID should never be
  1645   // seen either. Cache reads of existing jmethodIDs proceed without a
  1646   // lock, but cache writes of a new jmethodID requires uniqueness and
  1647   // creation of the cache itself requires no leaks so a lock is
  1648   // generally acquired in those two cases.
  1649   //
  1650   // If the RedefineClasses() API has been used, then this cache can
  1651   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1652   // Cache creation requires no leaks and we require safety between all
  1653   // cache accesses and freeing of the old cache so a lock is generally
  1654   // acquired when the RedefineClasses() API has been used.
  1656   if (jmeths != NULL) {
  1657     // the cache already exists
  1658     if (!ik_h->idnum_can_increment()) {
  1659       // the cache can't grow so we can just get the current values
  1660       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1661     } else {
  1662       // cache can grow so we have to be more careful
  1663       if (Threads::number_of_threads() == 0 ||
  1664           SafepointSynchronize::is_at_safepoint()) {
  1665         // we're single threaded or at a safepoint - no locking needed
  1666         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1667       } else {
  1668         MutexLocker ml(JmethodIdCreation_lock);
  1669         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1673   // implied else:
  1674   // we need to allocate a cache so default length and id values are good
  1676   if (jmeths == NULL ||   // no cache yet
  1677       length <= idnum ||  // cache is too short
  1678       id == NULL) {       // cache doesn't contain entry
  1680     // This function can be called by the VMThread so we have to do all
  1681     // things that might block on a safepoint before grabbing the lock.
  1682     // Otherwise, we can deadlock with the VMThread or have a cache
  1683     // consistency issue. These vars keep track of what we might have
  1684     // to free after the lock is dropped.
  1685     jmethodID  to_dealloc_id     = NULL;
  1686     jmethodID* to_dealloc_jmeths = NULL;
  1688     // may not allocate new_jmeths or use it if we allocate it
  1689     jmethodID* new_jmeths = NULL;
  1690     if (length <= idnum) {
  1691       // allocate a new cache that might be used
  1692       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1693       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1694       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1695       // cache size is stored in element[0], other elements offset by one
  1696       new_jmeths[0] = (jmethodID)size;
  1699     // allocate a new jmethodID that might be used
  1700     jmethodID new_id = NULL;
  1701     if (method_h->is_old() && !method_h->is_obsolete()) {
  1702       // The method passed in is old (but not obsolete), we need to use the current version
  1703       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1704       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1705       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1706     } else {
  1707       // It is the current version of the method or an obsolete method,
  1708       // use the version passed in
  1709       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1712     if (Threads::number_of_threads() == 0 ||
  1713         SafepointSynchronize::is_at_safepoint()) {
  1714       // we're single threaded or at a safepoint - no locking needed
  1715       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1716                                           &to_dealloc_id, &to_dealloc_jmeths);
  1717     } else {
  1718       MutexLocker ml(JmethodIdCreation_lock);
  1719       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1720                                           &to_dealloc_id, &to_dealloc_jmeths);
  1723     // The lock has been dropped so we can free resources.
  1724     // Free up either the old cache or the new cache if we allocated one.
  1725     if (to_dealloc_jmeths != NULL) {
  1726       FreeHeap(to_dealloc_jmeths);
  1728     // free up the new ID since it wasn't needed
  1729     if (to_dealloc_id != NULL) {
  1730       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1733   return id;
  1737 // Common code to fetch the jmethodID from the cache or update the
  1738 // cache with the new jmethodID. This function should never do anything
  1739 // that causes the caller to go to a safepoint or we can deadlock with
  1740 // the VMThread or have cache consistency issues.
  1741 //
  1742 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1743             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1744             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1745             jmethodID** to_dealloc_jmeths_p) {
  1746   assert(new_id != NULL, "sanity check");
  1747   assert(to_dealloc_id_p != NULL, "sanity check");
  1748   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1749   assert(Threads::number_of_threads() == 0 ||
  1750          SafepointSynchronize::is_at_safepoint() ||
  1751          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1753   // reacquire the cache - we are locked, single threaded or at a safepoint
  1754   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1755   jmethodID  id     = NULL;
  1756   size_t     length = 0;
  1758   if (jmeths == NULL ||                         // no cache yet
  1759       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1760     if (jmeths != NULL) {
  1761       // copy any existing entries from the old cache
  1762       for (size_t index = 0; index < length; index++) {
  1763         new_jmeths[index+1] = jmeths[index+1];
  1765       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1767     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1768   } else {
  1769     // fetch jmethodID (if any) from the existing cache
  1770     id = jmeths[idnum+1];
  1771     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1773   if (id == NULL) {
  1774     // No matching jmethodID in the existing cache or we have a new
  1775     // cache or we just grew the cache. This cache write is done here
  1776     // by the first thread to win the foot race because a jmethodID
  1777     // needs to be unique once it is generally available.
  1778     id = new_id;
  1780     // The jmethodID cache can be read while unlocked so we have to
  1781     // make sure the new jmethodID is complete before installing it
  1782     // in the cache.
  1783     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1784   } else {
  1785     *to_dealloc_id_p = new_id; // save new id for later delete
  1787   return id;
  1791 // Common code to get the jmethodID cache length and the jmethodID
  1792 // value at index idnum if there is one.
  1793 //
  1794 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1795        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1796   assert(cache != NULL, "sanity check");
  1797   assert(length_p != NULL, "sanity check");
  1798   assert(id_p != NULL, "sanity check");
  1800   // cache size is stored in element[0], other elements offset by one
  1801   *length_p = (size_t)cache[0];
  1802   if (*length_p <= idnum) {  // cache is too short
  1803     *id_p = NULL;
  1804   } else {
  1805     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1810 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1811 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1812   size_t idnum = (size_t)method->method_idnum();
  1813   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1814   size_t length;                                // length assigned as debugging crumb
  1815   jmethodID id = NULL;
  1816   if (jmeths != NULL &&                         // If there is a cache
  1817       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1818     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1820   return id;
  1823 int nmethodBucket::decrement() {
  1824   return Atomic::add(-1, (volatile int *)&_count);
  1827 //
  1828 // Walk the list of dependent nmethods searching for nmethods which
  1829 // are dependent on the changes that were passed in and mark them for
  1830 // deoptimization.  Returns the number of nmethods found.
  1831 //
  1832 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1833   assert_locked_or_safepoint(CodeCache_lock);
  1834   int found = 0;
  1835   nmethodBucket* b = _dependencies;
  1836   while (b != NULL) {
  1837     nmethod* nm = b->get_nmethod();
  1838     // since dependencies aren't removed until an nmethod becomes a zombie,
  1839     // the dependency list may contain nmethods which aren't alive.
  1840     if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1841       if (TraceDependencies) {
  1842         ResourceMark rm;
  1843         tty->print_cr("Marked for deoptimization");
  1844         tty->print_cr("  context = %s", this->external_name());
  1845         changes.print();
  1846         nm->print();
  1847         nm->print_dependencies();
  1849       nm->mark_for_deoptimization();
  1850       found++;
  1852     b = b->next();
  1854   return found;
  1857 void InstanceKlass::clean_dependent_nmethods() {
  1858   assert_locked_or_safepoint(CodeCache_lock);
  1860   if (has_unloaded_dependent()) {
  1861     nmethodBucket* b = _dependencies;
  1862     nmethodBucket* last = NULL;
  1863     while (b != NULL) {
  1864       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
  1866       nmethodBucket* next = b->next();
  1868       if (b->count() == 0) {
  1869         if (last == NULL) {
  1870           _dependencies = next;
  1871         } else {
  1872           last->set_next(next);
  1874         delete b;
  1875         // last stays the same.
  1876       } else {
  1877         last = b;
  1880       b = next;
  1882     set_has_unloaded_dependent(false);
  1884 #ifdef ASSERT
  1885   else {
  1886     // Verification
  1887     for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
  1888       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
  1889       assert(b->count() != 0, "empty buckets need to be cleaned");
  1892 #endif
  1895 //
  1896 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1897 // It's possible that an nmethod has multiple dependencies on this klass
  1898 // so a count is kept for each bucket to guarantee that creation and
  1899 // deletion of dependencies is consistent.
  1900 //
  1901 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1902   assert_locked_or_safepoint(CodeCache_lock);
  1903   nmethodBucket* b = _dependencies;
  1904   nmethodBucket* last = NULL;
  1905   while (b != NULL) {
  1906     if (nm == b->get_nmethod()) {
  1907       b->increment();
  1908       return;
  1910     b = b->next();
  1912   _dependencies = new nmethodBucket(nm, _dependencies);
  1916 //
  1917 // Decrement count of the nmethod in the dependency list and remove
  1918 // the bucket competely when the count goes to 0.  This method must
  1919 // find a corresponding bucket otherwise there's a bug in the
  1920 // recording of dependecies.
  1921 //
  1922 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1923   assert_locked_or_safepoint(CodeCache_lock);
  1924   nmethodBucket* b = _dependencies;
  1925   nmethodBucket* last = NULL;
  1926   while (b != NULL) {
  1927     if (nm == b->get_nmethod()) {
  1928       int val = b->decrement();
  1929       guarantee(val >= 0, err_msg("Underflow: %d", val));
  1930       if (val == 0) {
  1931         set_has_unloaded_dependent(true);
  1933       return;
  1935     last = b;
  1936     b = b->next();
  1938 #ifdef ASSERT
  1939   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1940   nm->print();
  1941 #endif // ASSERT
  1942   ShouldNotReachHere();
  1946 #ifndef PRODUCT
  1947 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1948   nmethodBucket* b = _dependencies;
  1949   int idx = 0;
  1950   while (b != NULL) {
  1951     nmethod* nm = b->get_nmethod();
  1952     tty->print("[%d] count=%d { ", idx++, b->count());
  1953     if (!verbose) {
  1954       nm->print_on(tty, "nmethod");
  1955       tty->print_cr(" } ");
  1956     } else {
  1957       nm->print();
  1958       nm->print_dependencies();
  1959       tty->print_cr("--- } ");
  1961     b = b->next();
  1966 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  1967   nmethodBucket* b = _dependencies;
  1968   while (b != NULL) {
  1969     if (nm == b->get_nmethod()) {
  1970 #ifdef ASSERT
  1971       int count = b->count();
  1972       assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
  1973 #endif
  1974       return true;
  1976     b = b->next();
  1978   return false;
  1980 #endif //PRODUCT
  1983 // Garbage collection
  1985 #ifdef ASSERT
  1986 template <class T> void assert_is_in(T *p) {
  1987   T heap_oop = oopDesc::load_heap_oop(p);
  1988   if (!oopDesc::is_null(heap_oop)) {
  1989     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1990     assert(Universe::heap()->is_in(o), "should be in heap");
  1993 template <class T> void assert_is_in_closed_subset(T *p) {
  1994   T heap_oop = oopDesc::load_heap_oop(p);
  1995   if (!oopDesc::is_null(heap_oop)) {
  1996     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  1997     assert(Universe::heap()->is_in_closed_subset(o),
  1998            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  2001 template <class T> void assert_is_in_reserved(T *p) {
  2002   T heap_oop = oopDesc::load_heap_oop(p);
  2003   if (!oopDesc::is_null(heap_oop)) {
  2004     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2005     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  2008 template <class T> void assert_nothing(T *p) {}
  2010 #else
  2011 template <class T> void assert_is_in(T *p) {}
  2012 template <class T> void assert_is_in_closed_subset(T *p) {}
  2013 template <class T> void assert_is_in_reserved(T *p) {}
  2014 template <class T> void assert_nothing(T *p) {}
  2015 #endif // ASSERT
  2017 //
  2018 // Macros that iterate over areas of oops which are specialized on type of
  2019 // oop pointer either narrow or wide, depending on UseCompressedOops
  2020 //
  2021 // Parameters are:
  2022 //   T         - type of oop to point to (either oop or narrowOop)
  2023 //   start_p   - starting pointer for region to iterate over
  2024 //   count     - number of oops or narrowOops to iterate over
  2025 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  2026 //               makes it more efficient to put in a macro rather than making
  2027 //               it a template function)
  2028 //   assert_fn - assert function which is template function because performance
  2029 //               doesn't matter when enabled.
  2030 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  2031   T, start_p, count, do_oop,                \
  2032   assert_fn)                                \
  2033 {                                           \
  2034   T* p         = (T*)(start_p);             \
  2035   T* const end = p + (count);               \
  2036   while (p < end) {                         \
  2037     (assert_fn)(p);                         \
  2038     do_oop;                                 \
  2039     ++p;                                    \
  2040   }                                         \
  2043 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  2044   T, start_p, count, do_oop,                \
  2045   assert_fn)                                \
  2046 {                                           \
  2047   T* const start = (T*)(start_p);           \
  2048   T*       p     = start + (count);         \
  2049   while (start < p) {                       \
  2050     --p;                                    \
  2051     (assert_fn)(p);                         \
  2052     do_oop;                                 \
  2053   }                                         \
  2056 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  2057   T, start_p, count, low, high,             \
  2058   do_oop, assert_fn)                        \
  2059 {                                           \
  2060   T* const l = (T*)(low);                   \
  2061   T* const h = (T*)(high);                  \
  2062   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  2063          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  2064          "bounded region must be properly aligned"); \
  2065   T* p       = (T*)(start_p);               \
  2066   T* end     = p + (count);                 \
  2067   if (p < l) p = l;                         \
  2068   if (end > h) end = h;                     \
  2069   while (p < end) {                         \
  2070     (assert_fn)(p);                         \
  2071     do_oop;                                 \
  2072     ++p;                                    \
  2073   }                                         \
  2077 // The following macros call specialized macros, passing either oop or
  2078 // narrowOop as the specialization type.  These test the UseCompressedOops
  2079 // flag.
  2080 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  2081 {                                                                        \
  2082   /* Compute oopmap block range. The common case                         \
  2083      is nonstatic_oop_map_size == 1. */                                  \
  2084   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2085   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2086   if (UseCompressedOops) {                                               \
  2087     while (map < end_map) {                                              \
  2088       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  2089         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2090         do_oop, assert_fn)                                               \
  2091       ++map;                                                             \
  2092     }                                                                    \
  2093   } else {                                                               \
  2094     while (map < end_map) {                                              \
  2095       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  2096         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2097         do_oop, assert_fn)                                               \
  2098       ++map;                                                             \
  2099     }                                                                    \
  2100   }                                                                      \
  2103 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  2104 {                                                                        \
  2105   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  2106   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  2107   if (UseCompressedOops) {                                               \
  2108     while (start_map < map) {                                            \
  2109       --map;                                                             \
  2110       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  2111         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2112         do_oop, assert_fn)                                               \
  2113     }                                                                    \
  2114   } else {                                                               \
  2115     while (start_map < map) {                                            \
  2116       --map;                                                             \
  2117       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  2118         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2119         do_oop, assert_fn)                                               \
  2120     }                                                                    \
  2121   }                                                                      \
  2124 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  2125                                               assert_fn)                 \
  2126 {                                                                        \
  2127   /* Compute oopmap block range. The common case is                      \
  2128      nonstatic_oop_map_size == 1, so we accept the                       \
  2129      usually non-existent extra overhead of examining                    \
  2130      all the maps. */                                                    \
  2131   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2132   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2133   if (UseCompressedOops) {                                               \
  2134     while (map < end_map) {                                              \
  2135       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  2136         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2137         low, high,                                                       \
  2138         do_oop, assert_fn)                                               \
  2139       ++map;                                                             \
  2140     }                                                                    \
  2141   } else {                                                               \
  2142     while (map < end_map) {                                              \
  2143       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2144         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2145         low, high,                                                       \
  2146         do_oop, assert_fn)                                               \
  2147       ++map;                                                             \
  2148     }                                                                    \
  2149   }                                                                      \
  2152 void InstanceKlass::oop_follow_contents(oop obj) {
  2153   assert(obj != NULL, "can't follow the content of NULL object");
  2154   MarkSweep::follow_klass(obj->klass());
  2155   InstanceKlass_OOP_MAP_ITERATE( \
  2156     obj, \
  2157     MarkSweep::mark_and_push(p), \
  2158     assert_is_in_closed_subset)
  2161 #if INCLUDE_ALL_GCS
  2162 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2163                                         oop obj) {
  2164   assert(obj != NULL, "can't follow the content of NULL object");
  2165   PSParallelCompact::follow_klass(cm, obj->klass());
  2166   // Only mark the header and let the scan of the meta-data mark
  2167   // everything else.
  2168   InstanceKlass_OOP_MAP_ITERATE( \
  2169     obj, \
  2170     PSParallelCompact::mark_and_push(cm, p), \
  2171     assert_is_in)
  2173 #endif // INCLUDE_ALL_GCS
  2175 // closure's do_metadata() method dictates whether the given closure should be
  2176 // applied to the klass ptr in the object header.
  2178 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2180 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2181   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2182   /* header */                                                          \
  2183   if_do_metadata_checked(closure, nv_suffix) {                          \
  2184     closure->do_klass##nv_suffix(obj->klass());                         \
  2185   }                                                                     \
  2186   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2187     obj,                                                                \
  2188     SpecializationStats::                                               \
  2189       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2190     (closure)->do_oop##nv_suffix(p),                                    \
  2191     assert_is_in_closed_subset)                                         \
  2192   return size_helper();                                                 \
  2195 #if INCLUDE_ALL_GCS
  2196 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2198 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2199                                               OopClosureType* closure) {        \
  2200   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2202   assert_should_ignore_metadata(closure, nv_suffix);                            \
  2204   /* instance variables */                                                      \
  2205   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2206     obj,                                                                        \
  2207     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2208     (closure)->do_oop##nv_suffix(p),                                            \
  2209     assert_is_in_closed_subset)                                                 \
  2210    return size_helper();                                                        \
  2212 #endif // INCLUDE_ALL_GCS
  2214 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2216 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2217                                                   OopClosureType* closure, \
  2218                                                   MemRegion mr) {          \
  2219   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2220   if_do_metadata_checked(closure, nv_suffix) {                           \
  2221     if (mr.contains(obj)) {                                              \
  2222       closure->do_klass##nv_suffix(obj->klass());                        \
  2223     }                                                                    \
  2224   }                                                                      \
  2225   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2226     obj, mr.start(), mr.end(),                                           \
  2227     (closure)->do_oop##nv_suffix(p),                                     \
  2228     assert_is_in_closed_subset)                                          \
  2229   return size_helper();                                                  \
  2232 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2233 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2234 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2235 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2236 #if INCLUDE_ALL_GCS
  2237 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2238 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2239 #endif // INCLUDE_ALL_GCS
  2241 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2242   int size = size_helper();
  2243   InstanceKlass_OOP_MAP_ITERATE( \
  2244     obj, \
  2245     MarkSweep::adjust_pointer(p), \
  2246     assert_is_in)
  2247   return size;
  2250 #if INCLUDE_ALL_GCS
  2251 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2252   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2253     obj, \
  2254     if (PSScavenge::should_scavenge(p)) { \
  2255       pm->claim_or_forward_depth(p); \
  2256     }, \
  2257     assert_nothing )
  2260 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2261   int size = size_helper();
  2262   InstanceKlass_OOP_MAP_ITERATE( \
  2263     obj, \
  2264     PSParallelCompact::adjust_pointer(p), \
  2265     assert_is_in)
  2266   return size;
  2269 #endif // INCLUDE_ALL_GCS
  2271 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2272   assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
  2273   if (is_interface()) {
  2274     if (ClassUnloading) {
  2275       Klass* impl = implementor();
  2276       if (impl != NULL) {
  2277         if (!impl->is_loader_alive(is_alive)) {
  2278           // remove this guy
  2279           Klass** klass = adr_implementor();
  2280           assert(klass != NULL, "null klass");
  2281           if (klass != NULL) {
  2282             *klass = NULL;
  2290 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2291   for (int m = 0; m < methods()->length(); m++) {
  2292     MethodData* mdo = methods()->at(m)->method_data();
  2293     if (mdo != NULL) {
  2294       mdo->clean_method_data(is_alive);
  2300 static void remove_unshareable_in_class(Klass* k) {
  2301   // remove klass's unshareable info
  2302   k->remove_unshareable_info();
  2305 void InstanceKlass::remove_unshareable_info() {
  2306   Klass::remove_unshareable_info();
  2307   // Unlink the class
  2308   if (is_linked()) {
  2309     unlink_class();
  2311   init_implementor();
  2313   constants()->remove_unshareable_info();
  2315   for (int i = 0; i < methods()->length(); i++) {
  2316     Method* m = methods()->at(i);
  2317     m->remove_unshareable_info();
  2320   // do array classes also.
  2321   array_klasses_do(remove_unshareable_in_class);
  2324 static void restore_unshareable_in_class(Klass* k, TRAPS) {
  2325   // Array classes have null protection domain.
  2326   // --> see ArrayKlass::complete_create_array_klass()
  2327   k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
  2330 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
  2331   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
  2332   instanceKlassHandle ik(THREAD, this);
  2334   Array<Method*>* methods = ik->methods();
  2335   int num_methods = methods->length();
  2336   for (int index2 = 0; index2 < num_methods; ++index2) {
  2337     methodHandle m(THREAD, methods->at(index2));
  2338     m->restore_unshareable_info(CHECK);
  2340   if (JvmtiExport::has_redefined_a_class()) {
  2341     // Reinitialize vtable because RedefineClasses may have changed some
  2342     // entries in this vtable for super classes so the CDS vtable might
  2343     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2344     // vtables in the shared system dictionary, only the main one.
  2345     // It also redefines the itable too so fix that too.
  2346     ResourceMark rm(THREAD);
  2347     ik->vtable()->initialize_vtable(false, CHECK);
  2348     ik->itable()->initialize_itable(false, CHECK);
  2351   // restore constant pool resolved references
  2352   ik->constants()->restore_unshareable_info(CHECK);
  2354   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2357 // returns true IFF is_in_error_state() has been changed as a result of this call.
  2358 bool InstanceKlass::check_sharing_error_state() {
  2359   assert(DumpSharedSpaces, "should only be called during dumping");
  2360   bool old_state = is_in_error_state();
  2362   if (!is_in_error_state()) {
  2363     bool bad = false;
  2364     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
  2365       if (sup->is_in_error_state()) {
  2366         bad = true;
  2367         break;
  2370     if (!bad) {
  2371       Array<Klass*>* interfaces = transitive_interfaces();
  2372       for (int i = 0; i < interfaces->length(); i++) {
  2373         Klass* iface = interfaces->at(i);
  2374         if (InstanceKlass::cast(iface)->is_in_error_state()) {
  2375           bad = true;
  2376           break;
  2381     if (bad) {
  2382       set_in_error_state();
  2386   return (old_state != is_in_error_state());
  2389 static void clear_all_breakpoints(Method* m) {
  2390   m->clear_all_breakpoints();
  2394 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
  2395   // notify the debugger
  2396   if (JvmtiExport::should_post_class_unload()) {
  2397     JvmtiExport::post_class_unload(ik);
  2400   // notify ClassLoadingService of class unload
  2401   ClassLoadingService::notify_class_unloaded(ik);
  2404 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
  2405   // Clean up C heap
  2406   ik->release_C_heap_structures();
  2407   ik->constants()->release_C_heap_structures();
  2410 void InstanceKlass::release_C_heap_structures() {
  2412   // Can't release the constant pool here because the constant pool can be
  2413   // deallocated separately from the InstanceKlass for default methods and
  2414   // redefine classes.
  2416   // Deallocate oop map cache
  2417   if (_oop_map_cache != NULL) {
  2418     delete _oop_map_cache;
  2419     _oop_map_cache = NULL;
  2422   // Deallocate JNI identifiers for jfieldIDs
  2423   JNIid::deallocate(jni_ids());
  2424   set_jni_ids(NULL);
  2426   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2427   if (jmeths != (jmethodID*)NULL) {
  2428     release_set_methods_jmethod_ids(NULL);
  2429     FreeHeap(jmeths);
  2432   // Deallocate MemberNameTable
  2434     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
  2435     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
  2436     MemberNameTable* mnt = member_names();
  2437     if (mnt != NULL) {
  2438       delete mnt;
  2439       set_member_names(NULL);
  2443   // release dependencies
  2444   nmethodBucket* b = _dependencies;
  2445   _dependencies = NULL;
  2446   while (b != NULL) {
  2447     nmethodBucket* next = b->next();
  2448     delete b;
  2449     b = next;
  2452   // Deallocate breakpoint records
  2453   if (breakpoints() != 0x0) {
  2454     methods_do(clear_all_breakpoints);
  2455     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2458   // deallocate information about previous versions
  2459   if (_previous_versions != NULL) {
  2460     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2461       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2462       delete pv_node;
  2464     delete _previous_versions;
  2465     _previous_versions = NULL;
  2468   // deallocate the cached class file
  2469   if (_cached_class_file != NULL) {
  2470     os::free(_cached_class_file, mtClass);
  2471     _cached_class_file = NULL;
  2474   // Decrement symbol reference counts associated with the unloaded class.
  2475   if (_name != NULL) _name->decrement_refcount();
  2476   // unreference array name derived from this class name (arrays of an unloaded
  2477   // class can't be referenced anymore).
  2478   if (_array_name != NULL)  _array_name->decrement_refcount();
  2479   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2481   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2482   Atomic::dec(&_total_instanceKlass_count);
  2485 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2486   if (array == NULL) {
  2487     _source_debug_extension = NULL;
  2488   } else {
  2489     // Adding one to the attribute length in order to store a null terminator
  2490     // character could cause an overflow because the attribute length is
  2491     // already coded with an u4 in the classfile, but in practice, it's
  2492     // unlikely to happen.
  2493     assert((length+1) > length, "Overflow checking");
  2494     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2495     for (int i = 0; i < length; i++) {
  2496       sde[i] = array[i];
  2498     sde[length] = '\0';
  2499     _source_debug_extension = sde;
  2503 address InstanceKlass::static_field_addr(int offset) {
  2504   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
  2508 const char* InstanceKlass::signature_name() const {
  2509   int hash_len = 0;
  2510   char hash_buf[40];
  2512   // If this is an anonymous class, append a hash to make the name unique
  2513   if (is_anonymous()) {
  2514     assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
  2515     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
  2516     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
  2517     hash_len = (int)strlen(hash_buf);
  2520   // Get the internal name as a c string
  2521   const char* src = (const char*) (name()->as_C_string());
  2522   const int src_length = (int)strlen(src);
  2524   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
  2526   // Add L as type indicator
  2527   int dest_index = 0;
  2528   dest[dest_index++] = 'L';
  2530   // Add the actual class name
  2531   for (int src_index = 0; src_index < src_length; ) {
  2532     dest[dest_index++] = src[src_index++];
  2535   // If we have a hash, append it
  2536   for (int hash_index = 0; hash_index < hash_len; ) {
  2537     dest[dest_index++] = hash_buf[hash_index++];
  2540   // Add the semicolon and the NULL
  2541   dest[dest_index++] = ';';
  2542   dest[dest_index] = '\0';
  2543   return dest;
  2546 // different verisons of is_same_class_package
  2547 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2548   Klass* class1 = this;
  2549   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2550   Symbol* classname1 = class1->name();
  2552   if (class2->oop_is_objArray()) {
  2553     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2555   oop classloader2;
  2556   if (class2->oop_is_instance()) {
  2557     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2558   } else {
  2559     assert(class2->oop_is_typeArray(), "should be type array");
  2560     classloader2 = NULL;
  2562   Symbol* classname2 = class2->name();
  2564   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2565                                               classloader2, classname2);
  2568 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2569   Klass* class1 = this;
  2570   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2571   Symbol* classname1 = class1->name();
  2573   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2574                                               classloader2, classname2);
  2577 // return true if two classes are in the same package, classloader
  2578 // and classname information is enough to determine a class's package
  2579 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2580                                           oop class_loader2, Symbol* class_name2) {
  2581   if (class_loader1 != class_loader2) {
  2582     return false;
  2583   } else if (class_name1 == class_name2) {
  2584     return true;                // skip painful bytewise comparison
  2585   } else {
  2586     ResourceMark rm;
  2588     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2589     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2590     // Otherwise, we just compare jbyte values between the strings.
  2591     const jbyte *name1 = class_name1->base();
  2592     const jbyte *name2 = class_name2->base();
  2594     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2595     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2597     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2598       // One of the two doesn't have a package.  Only return true
  2599       // if the other one also doesn't have a package.
  2600       return last_slash1 == last_slash2;
  2601     } else {
  2602       // Skip over '['s
  2603       if (*name1 == '[') {
  2604         do {
  2605           name1++;
  2606         } while (*name1 == '[');
  2607         if (*name1 != 'L') {
  2608           // Something is terribly wrong.  Shouldn't be here.
  2609           return false;
  2612       if (*name2 == '[') {
  2613         do {
  2614           name2++;
  2615         } while (*name2 == '[');
  2616         if (*name2 != 'L') {
  2617           // Something is terribly wrong.  Shouldn't be here.
  2618           return false;
  2622       // Check that package part is identical
  2623       int length1 = last_slash1 - name1;
  2624       int length2 = last_slash2 - name2;
  2626       return UTF8::equal(name1, length1, name2, length2);
  2631 // Returns true iff super_method can be overridden by a method in targetclassname
  2632 // See JSL 3rd edition 8.4.6.1
  2633 // Assumes name-signature match
  2634 // "this" is InstanceKlass of super_method which must exist
  2635 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2636 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2637    // Private methods can not be overridden
  2638    if (super_method->is_private()) {
  2639      return false;
  2641    // If super method is accessible, then override
  2642    if ((super_method->is_protected()) ||
  2643        (super_method->is_public())) {
  2644      return true;
  2646    // Package-private methods are not inherited outside of package
  2647    assert(super_method->is_package_private(), "must be package private");
  2648    return(is_same_class_package(targetclassloader(), targetclassname));
  2651 /* defined for now in jvm.cpp, for historical reasons *--
  2652 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2653                                                      Symbol*& simple_name_result, TRAPS) {
  2654   ...
  2656 */
  2658 // tell if two classes have the same enclosing class (at package level)
  2659 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2660                                                 Klass* class2_oop, TRAPS) {
  2661   if (class2_oop == class1())                       return true;
  2662   if (!class2_oop->oop_is_instance())  return false;
  2663   instanceKlassHandle class2(THREAD, class2_oop);
  2665   // must be in same package before we try anything else
  2666   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2667     return false;
  2669   // As long as there is an outer1.getEnclosingClass,
  2670   // shift the search outward.
  2671   instanceKlassHandle outer1 = class1;
  2672   for (;;) {
  2673     // As we walk along, look for equalities between outer1 and class2.
  2674     // Eventually, the walks will terminate as outer1 stops
  2675     // at the top-level class around the original class.
  2676     bool ignore_inner_is_member;
  2677     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2678                                                     CHECK_false);
  2679     if (next == NULL)  break;
  2680     if (next == class2())  return true;
  2681     outer1 = instanceKlassHandle(THREAD, next);
  2684   // Now do the same for class2.
  2685   instanceKlassHandle outer2 = class2;
  2686   for (;;) {
  2687     bool ignore_inner_is_member;
  2688     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2689                                                     CHECK_false);
  2690     if (next == NULL)  break;
  2691     // Might as well check the new outer against all available values.
  2692     if (next == class1())  return true;
  2693     if (next == outer1())  return true;
  2694     outer2 = instanceKlassHandle(THREAD, next);
  2697   // If by this point we have not found an equality between the
  2698   // two classes, we know they are in separate package members.
  2699   return false;
  2703 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2704   jint access = access_flags().as_int();
  2706   // But check if it happens to be member class.
  2707   instanceKlassHandle ik(THREAD, this);
  2708   InnerClassesIterator iter(ik);
  2709   for (; !iter.done(); iter.next()) {
  2710     int ioff = iter.inner_class_info_index();
  2711     // Inner class attribute can be zero, skip it.
  2712     // Strange but true:  JVM spec. allows null inner class refs.
  2713     if (ioff == 0) continue;
  2715     // only look at classes that are already loaded
  2716     // since we are looking for the flags for our self.
  2717     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2718     if ((ik->name() == inner_name)) {
  2719       // This is really a member class.
  2720       access = iter.inner_access_flags();
  2721       break;
  2724   // Remember to strip ACC_SUPER bit
  2725   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2728 jint InstanceKlass::jvmti_class_status() const {
  2729   jint result = 0;
  2731   if (is_linked()) {
  2732     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2735   if (is_initialized()) {
  2736     assert(is_linked(), "Class status is not consistent");
  2737     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2739   if (is_in_error_state()) {
  2740     result |= JVMTI_CLASS_STATUS_ERROR;
  2742   return result;
  2745 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2746   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2747   int method_table_offset_in_words = ioe->offset()/wordSize;
  2748   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2749                        / itableOffsetEntry::size();
  2751   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2752     // If the interface isn't implemented by the receiver class,
  2753     // the VM should throw IncompatibleClassChangeError.
  2754     if (cnt >= nof_interfaces) {
  2755       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2758     Klass* ik = ioe->interface_klass();
  2759     if (ik == holder) break;
  2762   itableMethodEntry* ime = ioe->first_method_entry(this);
  2763   Method* m = ime[index].method();
  2764   if (m == NULL) {
  2765     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2767   return m;
  2771 #if INCLUDE_JVMTI
  2772 // update default_methods for redefineclasses for methods that are
  2773 // not yet in the vtable due to concurrent subclass define and superinterface
  2774 // redefinition
  2775 // Note: those in the vtable, should have been updated via adjust_method_entries
  2776 void InstanceKlass::adjust_default_methods(Method** old_methods, Method** new_methods,
  2777                                            int methods_length, bool* trace_name_printed) {
  2778   // search the default_methods for uses of either obsolete or EMCP methods
  2779   if (default_methods() != NULL) {
  2780     for (int j = 0; j < methods_length; j++) {
  2781       Method* old_method = old_methods[j];
  2782       Method* new_method = new_methods[j];
  2784       for (int index = 0; index < default_methods()->length(); index ++) {
  2785         if (default_methods()->at(index) == old_method) {
  2786           default_methods()->at_put(index, new_method);
  2787           if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
  2788             if (!(*trace_name_printed)) {
  2789               // RC_TRACE_MESG macro has an embedded ResourceMark
  2790               RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
  2791                              external_name(),
  2792                              old_method->method_holder()->external_name()));
  2793               *trace_name_printed = true;
  2795             RC_TRACE(0x00100000, ("default method update: %s(%s) ",
  2796                                   new_method->name()->as_C_string(),
  2797                                   new_method->signature()->as_C_string()));
  2804 #endif // INCLUDE_JVMTI
  2806 // On-stack replacement stuff
  2807 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2808   // only one compilation can be active
  2809   NEEDS_CLEANUP
  2810   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2811   OsrList_lock->lock_without_safepoint_check();
  2812   assert(n->is_osr_method(), "wrong kind of nmethod");
  2813   n->set_osr_link(osr_nmethods_head());
  2814   set_osr_nmethods_head(n);
  2815   // Raise the highest osr level if necessary
  2816   if (TieredCompilation) {
  2817     Method* m = n->method();
  2818     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2820   // Remember to unlock again
  2821   OsrList_lock->unlock();
  2823   // Get rid of the osr methods for the same bci that have lower levels.
  2824   if (TieredCompilation) {
  2825     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2826       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2827       if (inv != NULL && inv->is_in_use()) {
  2828         inv->make_not_entrant();
  2835 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2836   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2837   OsrList_lock->lock_without_safepoint_check();
  2838   assert(n->is_osr_method(), "wrong kind of nmethod");
  2839   nmethod* last = NULL;
  2840   nmethod* cur  = osr_nmethods_head();
  2841   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2842   Method* m = n->method();
  2843   // Search for match
  2844   while(cur != NULL && cur != n) {
  2845     if (TieredCompilation && m == cur->method()) {
  2846       // Find max level before n
  2847       max_level = MAX2(max_level, cur->comp_level());
  2849     last = cur;
  2850     cur = cur->osr_link();
  2852   nmethod* next = NULL;
  2853   if (cur == n) {
  2854     next = cur->osr_link();
  2855     if (last == NULL) {
  2856       // Remove first element
  2857       set_osr_nmethods_head(next);
  2858     } else {
  2859       last->set_osr_link(next);
  2862   n->set_osr_link(NULL);
  2863   if (TieredCompilation) {
  2864     cur = next;
  2865     while (cur != NULL) {
  2866       // Find max level after n
  2867       if (m == cur->method()) {
  2868         max_level = MAX2(max_level, cur->comp_level());
  2870       cur = cur->osr_link();
  2872     m->set_highest_osr_comp_level(max_level);
  2874   // Remember to unlock again
  2875   OsrList_lock->unlock();
  2878 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
  2879   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2880   OsrList_lock->lock_without_safepoint_check();
  2881   nmethod* osr = osr_nmethods_head();
  2882   nmethod* best = NULL;
  2883   while (osr != NULL) {
  2884     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2885     // There can be a time when a c1 osr method exists but we are waiting
  2886     // for a c2 version. When c2 completes its osr nmethod we will trash
  2887     // the c1 version and only be able to find the c2 version. However
  2888     // while we overflow in the c1 code at back branches we don't want to
  2889     // try and switch to the same code as we are already running
  2891     if (osr->method() == m &&
  2892         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2893       if (match_level) {
  2894         if (osr->comp_level() == comp_level) {
  2895           // Found a match - return it.
  2896           OsrList_lock->unlock();
  2897           return osr;
  2899       } else {
  2900         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2901           if (osr->comp_level() == CompLevel_highest_tier) {
  2902             // Found the best possible - return it.
  2903             OsrList_lock->unlock();
  2904             return osr;
  2906           best = osr;
  2910     osr = osr->osr_link();
  2912   OsrList_lock->unlock();
  2913   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2914     return best;
  2916   return NULL;
  2919 void InstanceKlass::add_member_name(int index, Handle mem_name) {
  2920   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  2921   MutexLocker ml(MemberNameTable_lock);
  2922   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  2923   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2925   if (_member_names == NULL) {
  2926     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
  2928   _member_names->add_member_name(index, mem_name_wref);
  2931 oop InstanceKlass::get_member_name(int index) {
  2932   MutexLocker ml(MemberNameTable_lock);
  2933   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  2934   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2936   if (_member_names == NULL) {
  2937     return NULL;
  2939   oop mem_name =_member_names->get_member_name(index);
  2940   return mem_name;
  2943 // -----------------------------------------------------------------------------------------------------
  2944 // Printing
  2946 #ifndef PRODUCT
  2948 #define BULLET  " - "
  2950 static const char* state_names[] = {
  2951   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  2952 };
  2954 static void print_vtable(intptr_t* start, int len, outputStream* st) {
  2955   for (int i = 0; i < len; i++) {
  2956     intptr_t e = start[i];
  2957     st->print("%d : " INTPTR_FORMAT, i, e);
  2958     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
  2959       st->print(" ");
  2960       ((Metadata*)e)->print_value_on(st);
  2962     st->cr();
  2966 void InstanceKlass::print_on(outputStream* st) const {
  2967   assert(is_klass(), "must be klass");
  2968   Klass::print_on(st);
  2970   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  2971   st->print(BULLET"klass size:        %d", size());                               st->cr();
  2972   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  2973   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
  2974   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  2975   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  2976   st->print(BULLET"sub:               ");
  2977   Klass* sub = subklass();
  2978   int n;
  2979   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  2980     if (n < MaxSubklassPrintSize) {
  2981       sub->print_value_on(st);
  2982       st->print("   ");
  2985   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  2986   st->cr();
  2988   if (is_interface()) {
  2989     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  2990     if (nof_implementors() == 1) {
  2991       st->print_cr(BULLET"implementor:    ");
  2992       st->print("   ");
  2993       implementor()->print_value_on(st);
  2994       st->cr();
  2998   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  2999   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  3000   if (Verbose || WizardMode) {
  3001     Array<Method*>* method_array = methods();
  3002     for (int i = 0; i < method_array->length(); i++) {
  3003       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  3006   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
  3007   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
  3008   if (Verbose && default_methods() != NULL) {
  3009     Array<Method*>* method_array = default_methods();
  3010     for (int i = 0; i < method_array->length(); i++) {
  3011       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  3014   if (default_vtable_indices() != NULL) {
  3015     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
  3017   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  3018   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  3019   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  3020   if (class_loader_data() != NULL) {
  3021     st->print(BULLET"class loader data:  ");
  3022     class_loader_data()->print_value_on(st);
  3023     st->cr();
  3025   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  3026   if (source_file_name() != NULL) {
  3027     st->print(BULLET"source file:       ");
  3028     source_file_name()->print_value_on(st);
  3029     st->cr();
  3031   if (source_debug_extension() != NULL) {
  3032     st->print(BULLET"source debug extension:       ");
  3033     st->print("%s", source_debug_extension());
  3034     st->cr();
  3036   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  3037   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  3038   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  3039   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  3041     bool have_pv = false;
  3042     PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  3043     for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  3044          pv_node != NULL; pv_node = pvw.next_previous_version()) {
  3045       if (!have_pv)
  3046         st->print(BULLET"previous version:  ");
  3047       have_pv = true;
  3048       pv_node->prev_constant_pool()->print_value_on(st);
  3050     if (have_pv) st->cr();
  3051   } // pvw is cleaned up
  3053   if (generic_signature() != NULL) {
  3054     st->print(BULLET"generic signature: ");
  3055     generic_signature()->print_value_on(st);
  3056     st->cr();
  3058   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  3059   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  3060   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  3061   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
  3062   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  3063   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
  3064   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  3065   FieldPrinter print_static_field(st);
  3066   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  3067   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  3068   FieldPrinter print_nonstatic_field(st);
  3069   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  3071   st->print(BULLET"non-static oop maps: ");
  3072   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  3073   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  3074   while (map < end_map) {
  3075     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  3076     map++;
  3078   st->cr();
  3081 #endif //PRODUCT
  3083 void InstanceKlass::print_value_on(outputStream* st) const {
  3084   assert(is_klass(), "must be klass");
  3085   if (Verbose || WizardMode)  access_flags().print_on(st);
  3086   name()->print_value_on(st);
  3089 #ifndef PRODUCT
  3091 void FieldPrinter::do_field(fieldDescriptor* fd) {
  3092   _st->print(BULLET);
  3093    if (_obj == NULL) {
  3094      fd->print_on(_st);
  3095      _st->cr();
  3096    } else {
  3097      fd->print_on_for(_st, _obj);
  3098      _st->cr();
  3103 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  3104   Klass::oop_print_on(obj, st);
  3106   if (this == SystemDictionary::String_klass()) {
  3107     typeArrayOop value  = java_lang_String::value(obj);
  3108     juint        offset = java_lang_String::offset(obj);
  3109     juint        length = java_lang_String::length(obj);
  3110     if (value != NULL &&
  3111         value->is_typeArray() &&
  3112         offset          <= (juint) value->length() &&
  3113         offset + length <= (juint) value->length()) {
  3114       st->print(BULLET"string: ");
  3115       java_lang_String::print(obj, st);
  3116       st->cr();
  3117       if (!WizardMode)  return;  // that is enough
  3121   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  3122   FieldPrinter print_field(st, obj);
  3123   do_nonstatic_fields(&print_field);
  3125   if (this == SystemDictionary::Class_klass()) {
  3126     st->print(BULLET"signature: ");
  3127     java_lang_Class::print_signature(obj, st);
  3128     st->cr();
  3129     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  3130     st->print(BULLET"fake entry for mirror: ");
  3131     mirrored_klass->print_value_on_maybe_null(st);
  3132     st->cr();
  3133     Klass* array_klass = java_lang_Class::array_klass(obj);
  3134     st->print(BULLET"fake entry for array: ");
  3135     array_klass->print_value_on_maybe_null(st);
  3136     st->cr();
  3137     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  3138     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  3139     Klass* real_klass = java_lang_Class::as_Klass(obj);
  3140     if (real_klass != NULL && real_klass->oop_is_instance()) {
  3141       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  3143   } else if (this == SystemDictionary::MethodType_klass()) {
  3144     st->print(BULLET"signature: ");
  3145     java_lang_invoke_MethodType::print_signature(obj, st);
  3146     st->cr();
  3150 #endif //PRODUCT
  3152 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  3153   st->print("a ");
  3154   name()->print_value_on(st);
  3155   obj->print_address_on(st);
  3156   if (this == SystemDictionary::String_klass()
  3157       && java_lang_String::value(obj) != NULL) {
  3158     ResourceMark rm;
  3159     int len = java_lang_String::length(obj);
  3160     int plen = (len < 24 ? len : 12);
  3161     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  3162     st->print(" = \"%s\"", str);
  3163     if (len > plen)
  3164       st->print("...[%d]", len);
  3165   } else if (this == SystemDictionary::Class_klass()) {
  3166     Klass* k = java_lang_Class::as_Klass(obj);
  3167     st->print(" = ");
  3168     if (k != NULL) {
  3169       k->print_value_on(st);
  3170     } else {
  3171       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  3172       st->print("%s", tname ? tname : "type?");
  3174   } else if (this == SystemDictionary::MethodType_klass()) {
  3175     st->print(" = ");
  3176     java_lang_invoke_MethodType::print_signature(obj, st);
  3177   } else if (java_lang_boxing_object::is_instance(obj)) {
  3178     st->print(" = ");
  3179     java_lang_boxing_object::print(obj, st);
  3180   } else if (this == SystemDictionary::LambdaForm_klass()) {
  3181     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  3182     if (vmentry != NULL) {
  3183       st->print(" => ");
  3184       vmentry->print_value_on(st);
  3186   } else if (this == SystemDictionary::MemberName_klass()) {
  3187     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  3188     if (vmtarget != NULL) {
  3189       st->print(" = ");
  3190       vmtarget->print_value_on(st);
  3191     } else {
  3192       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  3193       st->print(".");
  3194       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  3199 const char* InstanceKlass::internal_name() const {
  3200   return external_name();
  3203 #if INCLUDE_SERVICES
  3204 // Size Statistics
  3205 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  3206   Klass::collect_statistics(sz);
  3208   sz->_inst_size  = HeapWordSize * size_helper();
  3209   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  3210   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  3211   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  3212         ((is_interface() || is_anonymous()) ?
  3213          align_object_offset(nonstatic_oop_map_size()) :
  3214          nonstatic_oop_map_size());
  3216   int n = 0;
  3217   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  3218   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  3219   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  3220   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  3221   n += (sz->_fields_bytes                = sz->count_array(fields()));
  3222   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  3223   sz->_ro_bytes += n;
  3225   const ConstantPool* cp = constants();
  3226   if (cp) {
  3227     cp->collect_statistics(sz);
  3230   const Annotations* anno = annotations();
  3231   if (anno) {
  3232     anno->collect_statistics(sz);
  3235   const Array<Method*>* methods_array = methods();
  3236   if (methods()) {
  3237     for (int i = 0; i < methods_array->length(); i++) {
  3238       Method* method = methods_array->at(i);
  3239       if (method) {
  3240         sz->_method_count ++;
  3241         method->collect_statistics(sz);
  3246 #endif // INCLUDE_SERVICES
  3248 // Verification
  3250 class VerifyFieldClosure: public OopClosure {
  3251  protected:
  3252   template <class T> void do_oop_work(T* p) {
  3253     oop obj = oopDesc::load_decode_heap_oop(p);
  3254     if (!obj->is_oop_or_null()) {
  3255       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  3256       Universe::print();
  3257       guarantee(false, "boom");
  3260  public:
  3261   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  3262   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  3263 };
  3265 void InstanceKlass::verify_on(outputStream* st) {
  3266 #ifndef PRODUCT
  3267   // Avoid redundant verifies, this really should be in product.
  3268   if (_verify_count == Universe::verify_count()) return;
  3269   _verify_count = Universe::verify_count();
  3270 #endif
  3272   // Verify Klass
  3273   Klass::verify_on(st);
  3275   // Verify that klass is present in ClassLoaderData
  3276   guarantee(class_loader_data()->contains_klass(this),
  3277             "this class isn't found in class loader data");
  3279   // Verify vtables
  3280   if (is_linked()) {
  3281     ResourceMark rm;
  3282     // $$$ This used to be done only for m/s collections.  Doing it
  3283     // always seemed a valid generalization.  (DLD -- 6/00)
  3284     vtable()->verify(st);
  3287   // Verify first subklass
  3288   if (subklass_oop() != NULL) {
  3289     guarantee(subklass_oop()->is_klass(), "should be klass");
  3292   // Verify siblings
  3293   Klass* super = this->super();
  3294   Klass* sib = next_sibling();
  3295   if (sib != NULL) {
  3296     if (sib == this) {
  3297       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3300     guarantee(sib->is_klass(), "should be klass");
  3301     guarantee(sib->super() == super, "siblings should have same superklass");
  3304   // Verify implementor fields
  3305   Klass* im = implementor();
  3306   if (im != NULL) {
  3307     guarantee(is_interface(), "only interfaces should have implementor set");
  3308     guarantee(im->is_klass(), "should be klass");
  3309     guarantee(!im->is_interface() || im == this,
  3310       "implementors cannot be interfaces");
  3313   // Verify local interfaces
  3314   if (local_interfaces()) {
  3315     Array<Klass*>* local_interfaces = this->local_interfaces();
  3316     for (int j = 0; j < local_interfaces->length(); j++) {
  3317       Klass* e = local_interfaces->at(j);
  3318       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3322   // Verify transitive interfaces
  3323   if (transitive_interfaces() != NULL) {
  3324     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3325     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3326       Klass* e = transitive_interfaces->at(j);
  3327       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3331   // Verify methods
  3332   if (methods() != NULL) {
  3333     Array<Method*>* methods = this->methods();
  3334     for (int j = 0; j < methods->length(); j++) {
  3335       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3337     for (int j = 0; j < methods->length() - 1; j++) {
  3338       Method* m1 = methods->at(j);
  3339       Method* m2 = methods->at(j + 1);
  3340       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3344   // Verify method ordering
  3345   if (method_ordering() != NULL) {
  3346     Array<int>* method_ordering = this->method_ordering();
  3347     int length = method_ordering->length();
  3348     if (JvmtiExport::can_maintain_original_method_order() ||
  3349         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
  3350       guarantee(length == methods()->length(), "invalid method ordering length");
  3351       jlong sum = 0;
  3352       for (int j = 0; j < length; j++) {
  3353         int original_index = method_ordering->at(j);
  3354         guarantee(original_index >= 0, "invalid method ordering index");
  3355         guarantee(original_index < length, "invalid method ordering index");
  3356         sum += original_index;
  3358       // Verify sum of indices 0,1,...,length-1
  3359       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3360     } else {
  3361       guarantee(length == 0, "invalid method ordering length");
  3365   // Verify default methods
  3366   if (default_methods() != NULL) {
  3367     Array<Method*>* methods = this->default_methods();
  3368     for (int j = 0; j < methods->length(); j++) {
  3369       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3371     for (int j = 0; j < methods->length() - 1; j++) {
  3372       Method* m1 = methods->at(j);
  3373       Method* m2 = methods->at(j + 1);
  3374       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3378   // Verify JNI static field identifiers
  3379   if (jni_ids() != NULL) {
  3380     jni_ids()->verify(this);
  3383   // Verify other fields
  3384   if (array_klasses() != NULL) {
  3385     guarantee(array_klasses()->is_klass(), "should be klass");
  3387   if (constants() != NULL) {
  3388     guarantee(constants()->is_constantPool(), "should be constant pool");
  3390   const Klass* host = host_klass();
  3391   if (host != NULL) {
  3392     guarantee(host->is_klass(), "should be klass");
  3396 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3397   Klass::oop_verify_on(obj, st);
  3398   VerifyFieldClosure blk;
  3399   obj->oop_iterate_no_header(&blk);
  3403 // JNIid class for jfieldIDs only
  3404 // Note to reviewers:
  3405 // These JNI functions are just moved over to column 1 and not changed
  3406 // in the compressed oops workspace.
  3407 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3408   _holder = holder;
  3409   _offset = offset;
  3410   _next = next;
  3411   debug_only(_is_static_field_id = false;)
  3415 JNIid* JNIid::find(int offset) {
  3416   JNIid* current = this;
  3417   while (current != NULL) {
  3418     if (current->offset() == offset) return current;
  3419     current = current->next();
  3421   return NULL;
  3424 void JNIid::deallocate(JNIid* current) {
  3425   while (current != NULL) {
  3426     JNIid* next = current->next();
  3427     delete current;
  3428     current = next;
  3433 void JNIid::verify(Klass* holder) {
  3434   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3435   int end_field_offset;
  3436   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3438   JNIid* current = this;
  3439   while (current != NULL) {
  3440     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3441 #ifdef ASSERT
  3442     int o = current->offset();
  3443     if (current->is_static_field_id()) {
  3444       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3446 #endif
  3447     current = current->next();
  3452 #ifdef ASSERT
  3453 void InstanceKlass::set_init_state(ClassState state) {
  3454   bool good_state = is_shared() ? (_init_state <= state)
  3455                                                : (_init_state < state);
  3456   assert(good_state || state == allocated, "illegal state transition");
  3457   _init_state = (u1)state;
  3459 #endif
  3462 // RedefineClasses() support for previous versions:
  3464 // Purge previous versions
  3465 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3466   if (ik->previous_versions() != NULL) {
  3467     // This klass has previous versions so see what we can cleanup
  3468     // while it is safe to do so.
  3470     int deleted_count = 0;    // leave debugging breadcrumbs
  3471     int live_count = 0;
  3472     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3473                        ClassLoaderData::the_null_class_loader_data() :
  3474                        ik->class_loader_data();
  3476     // RC_TRACE macro has an embedded ResourceMark
  3477     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3478       ik->external_name(), ik->previous_versions()->length()));
  3480     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3481       // check the previous versions array
  3482       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3483       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3484       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3486       ConstantPool* pvcp = cp_ref;
  3487       if (!pvcp->on_stack()) {
  3488         // If the constant pool isn't on stack, none of the methods
  3489         // are executing.  Delete all the methods, the constant pool and
  3490         // and this previous version node.
  3491         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3492         if (method_refs != NULL) {
  3493           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3494             Method* method = method_refs->at(j);
  3495             assert(method != NULL, "method ref was unexpectedly cleared");
  3496             method_refs->remove_at(j);
  3497             // method will be freed with associated class.
  3500         // Remove the constant pool
  3501         delete pv_node;
  3502         // Since we are traversing the array backwards, we don't have to
  3503         // do anything special with the index.
  3504         ik->previous_versions()->remove_at(i);
  3505         deleted_count++;
  3506         continue;
  3507       } else {
  3508         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3509         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3510         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3511         live_count++;
  3514       // At least one method is live in this previous version, clean out
  3515       // the others or mark them as obsolete.
  3516       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3517       if (method_refs != NULL) {
  3518         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3519           method_refs->length()));
  3520         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3521           Method* method = method_refs->at(j);
  3522           assert(method != NULL, "method ref was unexpectedly cleared");
  3524           // Remove the emcp method if it's not executing
  3525           // If it's been made obsolete by a redefinition of a non-emcp
  3526           // method, mark it as obsolete but leave it to clean up later.
  3527           if (!method->on_stack()) {
  3528             method_refs->remove_at(j);
  3529           } else if (emcp_method_count == 0) {
  3530             method->set_is_obsolete();
  3531           } else {
  3532             // RC_TRACE macro has an embedded ResourceMark
  3533             RC_TRACE(0x00000200,
  3534               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3535               method->name()->as_C_string(),
  3536               method->signature()->as_C_string(), j, i));
  3541     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3542     RC_TRACE(0x00000200,
  3543       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3544       deleted_count));
  3548 // External interface for use during class unloading.
  3549 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3550   // Call with >0 emcp methods since they are not currently being redefined.
  3551   purge_previous_versions_internal(ik, 1);
  3555 // Potentially add an information node that contains pointers to the
  3556 // interesting parts of the previous version of the_class.
  3557 // This is also where we clean out any unused references.
  3558 // Note that while we delete nodes from the _previous_versions
  3559 // array, we never delete the array itself until the klass is
  3560 // unloaded. The has_been_redefined() query depends on that fact.
  3561 //
  3562 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3563        BitMap* emcp_methods, int emcp_method_count) {
  3564   assert(Thread::current()->is_VM_thread(),
  3565          "only VMThread can add previous versions");
  3567   if (_previous_versions == NULL) {
  3568     // This is the first previous version so make some space.
  3569     // Start with 2 elements under the assumption that the class
  3570     // won't be redefined much.
  3571     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3572                             GrowableArray<PreviousVersionNode *>(2, true);
  3575   ConstantPool* cp_ref = ikh->constants();
  3577   // RC_TRACE macro has an embedded ResourceMark
  3578   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3579                         "on_stack=%d",
  3580     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3581     cp_ref->on_stack()));
  3583   // If the constant pool for this previous version of the class
  3584   // is not marked as being on the stack, then none of the methods
  3585   // in this previous version of the class are on the stack so
  3586   // we don't need to create a new PreviousVersionNode. However,
  3587   // we still need to examine older previous versions below.
  3588   Array<Method*>* old_methods = ikh->methods();
  3590   if (cp_ref->on_stack()) {
  3591     PreviousVersionNode * pv_node = NULL;
  3592     if (emcp_method_count == 0) {
  3593       // non-shared ConstantPool gets a reference
  3594       pv_node = new PreviousVersionNode(cp_ref, NULL);
  3595       RC_TRACE(0x00000400,
  3596           ("add: all methods are obsolete; flushing any EMCP refs"));
  3597     } else {
  3598       int local_count = 0;
  3599       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3600           GrowableArray<Method*>(emcp_method_count, true);
  3601       for (int i = 0; i < old_methods->length(); i++) {
  3602         if (emcp_methods->at(i)) {
  3603             // this old method is EMCP. Save it only if it's on the stack
  3604             Method* old_method = old_methods->at(i);
  3605             if (old_method->on_stack()) {
  3606               method_refs->append(old_method);
  3608           if (++local_count >= emcp_method_count) {
  3609             // no more EMCP methods so bail out now
  3610             break;
  3614       // non-shared ConstantPool gets a reference
  3615       pv_node = new PreviousVersionNode(cp_ref, method_refs);
  3617     // append new previous version.
  3618     _previous_versions->append(pv_node);
  3621   // Since the caller is the VMThread and we are at a safepoint, this
  3622   // is a good time to clear out unused references.
  3624   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3625     _previous_versions->length()));
  3627   // Purge previous versions not executing on the stack
  3628   purge_previous_versions_internal(this, emcp_method_count);
  3630   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3632   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3633       _previous_versions->length() > 0) {
  3634     // We have a mix of obsolete and EMCP methods so we have to
  3635     // clear out any matching EMCP method entries the hard way.
  3636     int local_count = 0;
  3637     for (int i = 0; i < old_methods->length(); i++) {
  3638       if (!emcp_methods->at(i)) {
  3639         // only obsolete methods are interesting
  3640         Method* old_method = old_methods->at(i);
  3641         Symbol* m_name = old_method->name();
  3642         Symbol* m_signature = old_method->signature();
  3644         // we might not have added the last entry
  3645         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3646           // check the previous versions array for non executing obsolete methods
  3647           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3649           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3650           if (method_refs == NULL) {
  3651             // We have run into a PreviousVersion generation where
  3652             // all methods were made obsolete during that generation's
  3653             // RedefineClasses() operation. At the time of that
  3654             // operation, all EMCP methods were flushed so we don't
  3655             // have to go back any further.
  3656             //
  3657             // A NULL method_refs is different than an empty method_refs.
  3658             // We cannot infer any optimizations about older generations
  3659             // from an empty method_refs for the current generation.
  3660             break;
  3663           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3664             Method* method = method_refs->at(k);
  3666             if (!method->is_obsolete() &&
  3667                 method->name() == m_name &&
  3668                 method->signature() == m_signature) {
  3669               // The current RedefineClasses() call has made all EMCP
  3670               // versions of this method obsolete so mark it as obsolete
  3671               // and remove the reference.
  3672               RC_TRACE(0x00000400,
  3673                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3674                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3676               method->set_is_obsolete();
  3677               // Leave obsolete methods on the previous version list to
  3678               // clean up later.
  3679               break;
  3683           // The previous loop may not find a matching EMCP method, but
  3684           // that doesn't mean that we can optimize and not go any
  3685           // further back in the PreviousVersion generations. The EMCP
  3686           // method for this generation could have already been deleted,
  3687           // but there still may be an older EMCP method that has not
  3688           // been deleted.
  3691         if (++local_count >= obsolete_method_count) {
  3692           // no more obsolete methods so bail out now
  3693           break;
  3698 } // end add_previous_version()
  3701 // Determine if InstanceKlass has a previous version.
  3702 bool InstanceKlass::has_previous_version() const {
  3703   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3704 } // end has_previous_version()
  3707 Method* InstanceKlass::method_with_idnum(int idnum) {
  3708   Method* m = NULL;
  3709   if (idnum < methods()->length()) {
  3710     m = methods()->at(idnum);
  3712   if (m == NULL || m->method_idnum() != idnum) {
  3713     for (int index = 0; index < methods()->length(); ++index) {
  3714       m = methods()->at(index);
  3715       if (m->method_idnum() == idnum) {
  3716         return m;
  3719     // None found, return null for the caller to handle.
  3720     return NULL;
  3722   return m;
  3725 jint InstanceKlass::get_cached_class_file_len() {
  3726   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
  3729 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
  3730   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
  3734 // Construct a PreviousVersionNode entry for the array hung off
  3735 // the InstanceKlass.
  3736 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3737   GrowableArray<Method*>* prev_EMCP_methods) {
  3739   _prev_constant_pool = prev_constant_pool;
  3740   _prev_EMCP_methods = prev_EMCP_methods;
  3744 // Destroy a PreviousVersionNode
  3745 PreviousVersionNode::~PreviousVersionNode() {
  3746   if (_prev_constant_pool != NULL) {
  3747     _prev_constant_pool = NULL;
  3750   if (_prev_EMCP_methods != NULL) {
  3751     delete _prev_EMCP_methods;
  3755 // Construct a helper for walking the previous versions array
  3756 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
  3757   _thread = thread;
  3758   _previous_versions = ik->previous_versions();
  3759   _current_index = 0;
  3760   _current_p = NULL;
  3761   _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
  3765 // Return the interesting information for the next previous version
  3766 // of the klass. Returns NULL if there are no more previous versions.
  3767 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
  3768   if (_previous_versions == NULL) {
  3769     // no previous versions so nothing to return
  3770     return NULL;
  3773   _current_p = NULL;  // reset to NULL
  3774   _current_constant_pool_handle = NULL;
  3776   int length = _previous_versions->length();
  3778   while (_current_index < length) {
  3779     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3781     // Save a handle to the constant pool for this previous version,
  3782     // which keeps all the methods from being deallocated.
  3783     _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
  3784     _current_p = pv_node;
  3785     return pv_node;
  3788   return NULL;
  3789 } // end next_previous_version()

mercurial