src/share/vm/oops/instanceKlass.cpp

Tue, 16 Jun 2015 15:59:57 +0200

author
aeriksso
date
Tue, 16 Jun 2015 15:59:57 +0200
changeset 8042
b3217f8fd2a1
parent 7812
3c8b53552a43
child 8049
c2c7fed86a5e
permissions
-rw-r--r--

8076110: VM crash when class is redefined with Instrumentation.redefineClasses
Reviewed-by: coleenp, sspitsyn

     1 /*
     2  * Copyright (c) 1997, 2015, 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/jvmtiThreadState.hpp"
    54 #include "prims/methodComparator.hpp"
    55 #include "runtime/fieldDescriptor.hpp"
    56 #include "runtime/handles.inline.hpp"
    57 #include "runtime/javaCalls.hpp"
    58 #include "runtime/mutexLocker.hpp"
    59 #include "runtime/orderAccess.inline.hpp"
    60 #include "runtime/thread.inline.hpp"
    61 #include "services/classLoadingService.hpp"
    62 #include "services/threadService.hpp"
    63 #include "utilities/dtrace.hpp"
    64 #include "utilities/macros.hpp"
    65 #if INCLUDE_ALL_GCS
    66 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    67 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    68 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    69 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    70 #include "gc_implementation/g1/heapRegionManager.inline.hpp"
    71 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    72 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    73 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    74 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    75 #include "oops/oop.pcgc.inline.hpp"
    76 #endif // INCLUDE_ALL_GCS
    77 #ifdef COMPILER1
    78 #include "c1/c1_Compiler.hpp"
    79 #endif
    81 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    83 #ifdef DTRACE_ENABLED
    85 #ifndef USDT2
    87 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    88   char*, intptr_t, oop, intptr_t);
    89 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    90   char*, intptr_t, oop, intptr_t, int);
    91 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    92   char*, intptr_t, oop, intptr_t, int);
    93 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    94   char*, intptr_t, oop, intptr_t, int);
    95 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    96   char*, intptr_t, oop, intptr_t, int);
    97 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    98   char*, intptr_t, oop, intptr_t, int);
    99 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
   100   char*, intptr_t, oop, intptr_t, int);
   101 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
   102   char*, intptr_t, oop, intptr_t, int);
   104 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   105   {                                                              \
   106     char* data = NULL;                                           \
   107     int len = 0;                                                 \
   108     Symbol* name = (clss)->name();                               \
   109     if (name != NULL) {                                          \
   110       data = (char*)name->bytes();                               \
   111       len = name->utf8_length();                                 \
   112     }                                                            \
   113     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   114       data, len, (void *)(clss)->class_loader(), thread_type);           \
   115   }
   117 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   118   {                                                              \
   119     char* data = NULL;                                           \
   120     int len = 0;                                                 \
   121     Symbol* name = (clss)->name();                               \
   122     if (name != NULL) {                                          \
   123       data = (char*)name->bytes();                               \
   124       len = name->utf8_length();                                 \
   125     }                                                            \
   126     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   127       data, len, (void *)(clss)->class_loader(), thread_type, wait);     \
   128   }
   129 #else /* USDT2 */
   131 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   132 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   133 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   134 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   135 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   136 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   137 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   138 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   139 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   140   {                                                              \
   141     char* data = NULL;                                           \
   142     int len = 0;                                                 \
   143     Symbol* name = (clss)->name();                               \
   144     if (name != NULL) {                                          \
   145       data = (char*)name->bytes();                               \
   146       len = name->utf8_length();                                 \
   147     }                                                            \
   148     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   149       data, len, (clss)->class_loader(), thread_type);           \
   150   }
   152 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   153   {                                                              \
   154     char* data = NULL;                                           \
   155     int len = 0;                                                 \
   156     Symbol* name = (clss)->name();                               \
   157     if (name != NULL) {                                          \
   158       data = (char*)name->bytes();                               \
   159       len = name->utf8_length();                                 \
   160     }                                                            \
   161     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   162       data, len, (clss)->class_loader(), thread_type, wait);     \
   163   }
   164 #endif /* USDT2 */
   166 #else //  ndef DTRACE_ENABLED
   168 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   169 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   171 #endif //  ndef DTRACE_ENABLED
   173 volatile int InstanceKlass::_total_instanceKlass_count = 0;
   175 InstanceKlass* InstanceKlass::allocate_instance_klass(
   176                                               ClassLoaderData* loader_data,
   177                                               int vtable_len,
   178                                               int itable_len,
   179                                               int static_field_size,
   180                                               int nonstatic_oop_map_size,
   181                                               ReferenceType rt,
   182                                               AccessFlags access_flags,
   183                                               Symbol* name,
   184                                               Klass* super_klass,
   185                                               bool is_anonymous,
   186                                               TRAPS) {
   188   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   189                                  access_flags.is_interface(), is_anonymous);
   191   // Allocation
   192   InstanceKlass* ik;
   193   if (rt == REF_NONE) {
   194     if (name == vmSymbols::java_lang_Class()) {
   195       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   196         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   197         access_flags, is_anonymous);
   198     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   199           (SystemDictionary::ClassLoader_klass_loaded() &&
   200           super_klass != NULL &&
   201           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   202       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   203         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   204         access_flags, is_anonymous);
   205     } else {
   206       // normal class
   207       ik = new (loader_data, size, THREAD) InstanceKlass(
   208         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   209         access_flags, is_anonymous);
   210     }
   211   } else {
   212     // reference klass
   213     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   214         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   215         access_flags, is_anonymous);
   216   }
   218   // Check for pending exception before adding to the loader data and incrementing
   219   // class count.  Can get OOM here.
   220   if (HAS_PENDING_EXCEPTION) {
   221     return NULL;
   222   }
   224   // Add all classes to our internal class loader list here,
   225   // including classes in the bootstrap (NULL) class loader.
   226   loader_data->add_class(ik);
   228   Atomic::inc(&_total_instanceKlass_count);
   229   return ik;
   230 }
   233 // copy method ordering from resource area to Metaspace
   234 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
   235   if (m != NULL) {
   236     // allocate a new array and copy contents (memcpy?)
   237     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
   238     for (int i = 0; i < m->length(); i++) {
   239       _method_ordering->at_put(i, m->at(i));
   240     }
   241   } else {
   242     _method_ordering = Universe::the_empty_int_array();
   243   }
   244 }
   246 // create a new array of vtable_indices for default methods
   247 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
   248   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
   249   assert(default_vtable_indices() == NULL, "only create once");
   250   set_default_vtable_indices(vtable_indices);
   251   return vtable_indices;
   252 }
   254 InstanceKlass::InstanceKlass(int vtable_len,
   255                              int itable_len,
   256                              int static_field_size,
   257                              int nonstatic_oop_map_size,
   258                              ReferenceType rt,
   259                              AccessFlags access_flags,
   260                              bool is_anonymous) {
   261   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   263   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   264                                    access_flags.is_interface(), is_anonymous);
   266   set_vtable_length(vtable_len);
   267   set_itable_length(itable_len);
   268   set_static_field_size(static_field_size);
   269   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   270   set_access_flags(access_flags);
   271   _misc_flags = 0;  // initialize to zero
   272   set_is_anonymous(is_anonymous);
   273   assert(size() == iksize, "wrong size for object");
   275   set_array_klasses(NULL);
   276   set_methods(NULL);
   277   set_method_ordering(NULL);
   278   set_default_methods(NULL);
   279   set_default_vtable_indices(NULL);
   280   set_local_interfaces(NULL);
   281   set_transitive_interfaces(NULL);
   282   init_implementor();
   283   set_fields(NULL, 0);
   284   set_constants(NULL);
   285   set_class_loader_data(NULL);
   286   set_source_file_name_index(0);
   287   set_source_debug_extension(NULL, 0);
   288   set_array_name(NULL);
   289   set_inner_classes(NULL);
   290   set_static_oop_field_count(0);
   291   set_nonstatic_field_size(0);
   292   set_is_marked_dependent(false);
   293   set_has_unloaded_dependent(false);
   294   set_init_state(InstanceKlass::allocated);
   295   set_init_thread(NULL);
   296   set_reference_type(rt);
   297   set_oop_map_cache(NULL);
   298   set_jni_ids(NULL);
   299   set_osr_nmethods_head(NULL);
   300   set_breakpoints(NULL);
   301   init_previous_versions();
   302   set_generic_signature_index(0);
   303   release_set_methods_jmethod_ids(NULL);
   304   set_annotations(NULL);
   305   set_jvmti_cached_class_field_map(NULL);
   306   set_initial_method_idnum(0);
   307   _dependencies = NULL;
   308   set_jvmti_cached_class_field_map(NULL);
   309   set_cached_class_file(NULL);
   310   set_initial_method_idnum(0);
   311   set_minor_version(0);
   312   set_major_version(0);
   313   NOT_PRODUCT(_verify_count = 0;)
   315   // initialize the non-header words to zero
   316   intptr_t* p = (intptr_t*)this;
   317   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
   318     p[index] = NULL_WORD;
   319   }
   321   // Set temporary value until parseClassFile updates it with the real instance
   322   // size.
   323   set_layout_helper(Klass::instance_layout_helper(0, true));
   324 }
   327 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
   328                                        Array<Method*>* methods) {
   329   if (methods != NULL && methods != Universe::the_empty_method_array() &&
   330       !methods->is_shared()) {
   331     for (int i = 0; i < methods->length(); i++) {
   332       Method* method = methods->at(i);
   333       if (method == NULL) continue;  // maybe null if error processing
   334       // Only want to delete methods that are not executing for RedefineClasses.
   335       // The previous version will point to them so they're not totally dangling
   336       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   337       MetadataFactory::free_metadata(loader_data, method);
   338     }
   339     MetadataFactory::free_array<Method*>(loader_data, methods);
   340   }
   341 }
   343 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
   344                                           Klass* super_klass,
   345                                           Array<Klass*>* local_interfaces,
   346                                           Array<Klass*>* transitive_interfaces) {
   347   // Only deallocate transitive interfaces if not empty, same as super class
   348   // or same as local interfaces.  See code in parseClassFile.
   349   Array<Klass*>* ti = transitive_interfaces;
   350   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
   351     // check that the interfaces don't come from super class
   352     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
   353                     InstanceKlass::cast(super_klass)->transitive_interfaces();
   354     if (ti != sti && ti != NULL && !ti->is_shared()) {
   355       MetadataFactory::free_array<Klass*>(loader_data, ti);
   356     }
   357   }
   359   // local interfaces can be empty
   360   if (local_interfaces != Universe::the_empty_klass_array() &&
   361       local_interfaces != NULL && !local_interfaces->is_shared()) {
   362     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
   363   }
   364 }
   366 // This function deallocates the metadata and C heap pointers that the
   367 // InstanceKlass points to.
   368 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   370   // Orphan the mirror first, CMS thinks it's still live.
   371   if (java_mirror() != NULL) {
   372     java_lang_Class::set_klass(java_mirror(), NULL);
   373   }
   375   // Need to take this class off the class loader data list.
   376   loader_data->remove_class(this);
   378   // The array_klass for this class is created later, after error handling.
   379   // For class redefinition, we keep the original class so this scratch class
   380   // doesn't have an array class.  Either way, assert that there is nothing
   381   // to deallocate.
   382   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   384   // Release C heap allocated data that this might point to, which includes
   385   // reference counting symbol names.
   386   release_C_heap_structures();
   388   deallocate_methods(loader_data, methods());
   389   set_methods(NULL);
   391   if (method_ordering() != NULL &&
   392       method_ordering() != Universe::the_empty_int_array() &&
   393       !method_ordering()->is_shared()) {
   394     MetadataFactory::free_array<int>(loader_data, method_ordering());
   395   }
   396   set_method_ordering(NULL);
   398   // default methods can be empty
   399   if (default_methods() != NULL &&
   400       default_methods() != Universe::the_empty_method_array() &&
   401       !default_methods()->is_shared()) {
   402     MetadataFactory::free_array<Method*>(loader_data, default_methods());
   403   }
   404   // Do NOT deallocate the default methods, they are owned by superinterfaces.
   405   set_default_methods(NULL);
   407   // default methods vtable indices can be empty
   408   if (default_vtable_indices() != NULL &&
   409       !default_vtable_indices()->is_shared()) {
   410     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
   411   }
   412   set_default_vtable_indices(NULL);
   415   // This array is in Klass, but remove it with the InstanceKlass since
   416   // this place would be the only caller and it can share memory with transitive
   417   // interfaces.
   418   if (secondary_supers() != NULL &&
   419       secondary_supers() != Universe::the_empty_klass_array() &&
   420       secondary_supers() != transitive_interfaces() &&
   421       !secondary_supers()->is_shared()) {
   422     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   423   }
   424   set_secondary_supers(NULL);
   426   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
   427   set_transitive_interfaces(NULL);
   428   set_local_interfaces(NULL);
   430   if (fields() != NULL && !fields()->is_shared()) {
   431     MetadataFactory::free_array<jushort>(loader_data, fields());
   432   }
   433   set_fields(NULL, 0);
   435   // If a method from a redefined class is using this constant pool, don't
   436   // delete it, yet.  The new class's previous version will point to this.
   437   if (constants() != NULL) {
   438     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   439     if (!constants()->is_shared()) {
   440       MetadataFactory::free_metadata(loader_data, constants());
   441     }
   442     // Delete any cached resolution errors for the constant pool
   443     SystemDictionary::delete_resolution_error(constants());
   445     set_constants(NULL);
   446   }
   448   if (inner_classes() != NULL &&
   449       inner_classes() != Universe::the_empty_short_array() &&
   450       !inner_classes()->is_shared()) {
   451     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   452   }
   453   set_inner_classes(NULL);
   455   // We should deallocate the Annotations instance if it's not in shared spaces.
   456   if (annotations() != NULL && !annotations()->is_shared()) {
   457     MetadataFactory::free_metadata(loader_data, annotations());
   458   }
   459   set_annotations(NULL);
   460 }
   462 bool InstanceKlass::should_be_initialized() const {
   463   return !is_initialized();
   464 }
   466 klassVtable* InstanceKlass::vtable() const {
   467   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   468 }
   470 klassItable* InstanceKlass::itable() const {
   471   return new klassItable(instanceKlassHandle(this));
   472 }
   474 void InstanceKlass::eager_initialize(Thread *thread) {
   475   if (!EagerInitialization) return;
   477   if (this->is_not_initialized()) {
   478     // abort if the the class has a class initializer
   479     if (this->class_initializer() != NULL) return;
   481     // abort if it is java.lang.Object (initialization is handled in genesis)
   482     Klass* super = this->super();
   483     if (super == NULL) return;
   485     // abort if the super class should be initialized
   486     if (!InstanceKlass::cast(super)->is_initialized()) return;
   488     // call body to expose the this pointer
   489     instanceKlassHandle this_oop(thread, this);
   490     eager_initialize_impl(this_oop);
   491   }
   492 }
   494 // JVMTI spec thinks there are signers and protection domain in the
   495 // instanceKlass.  These accessors pretend these fields are there.
   496 // The hprof specification also thinks these fields are in InstanceKlass.
   497 oop InstanceKlass::protection_domain() const {
   498   // return the protection_domain from the mirror
   499   return java_lang_Class::protection_domain(java_mirror());
   500 }
   502 // To remove these from requires an incompatible change and CCC request.
   503 objArrayOop InstanceKlass::signers() const {
   504   // return the signers from the mirror
   505   return java_lang_Class::signers(java_mirror());
   506 }
   508 oop InstanceKlass::init_lock() const {
   509   // return the init lock from the mirror
   510   oop lock = java_lang_Class::init_lock(java_mirror());
   511   // Prevent reordering with any access of initialization state
   512   OrderAccess::loadload();
   513   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   514          "only fully initialized state can have a null lock");
   515   return lock;
   516 }
   518 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   519 // threads to get this lock will see a null lock and will not lock.
   520 // That's okay because they all check for initialized state after getting
   521 // the lock and return.
   522 void InstanceKlass::fence_and_clear_init_lock() {
   523   // make sure previous stores are all done, notably the init_state.
   524   OrderAccess::storestore();
   525   java_lang_Class::set_init_lock(java_mirror(), NULL);
   526   assert(!is_not_initialized(), "class must be initialized now");
   527 }
   529 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   530   EXCEPTION_MARK;
   531   oop init_lock = this_oop->init_lock();
   532   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   534   // abort if someone beat us to the initialization
   535   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   537   ClassState old_state = this_oop->init_state();
   538   link_class_impl(this_oop, true, THREAD);
   539   if (HAS_PENDING_EXCEPTION) {
   540     CLEAR_PENDING_EXCEPTION;
   541     // Abort if linking the class throws an exception.
   543     // Use a test to avoid redundantly resetting the state if there's
   544     // no change.  Set_init_state() asserts that state changes make
   545     // progress, whereas here we might just be spinning in place.
   546     if( old_state != this_oop->_init_state )
   547       this_oop->set_init_state (old_state);
   548   } else {
   549     // linking successfull, mark class as initialized
   550     this_oop->set_init_state (fully_initialized);
   551     this_oop->fence_and_clear_init_lock();
   552     // trace
   553     if (TraceClassInitialization) {
   554       ResourceMark rm(THREAD);
   555       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   556     }
   557   }
   558 }
   561 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   562 // process. The step comments refers to the procedure described in that section.
   563 // Note: implementation moved to static method to expose the this pointer.
   564 void InstanceKlass::initialize(TRAPS) {
   565   if (this->should_be_initialized()) {
   566     HandleMark hm(THREAD);
   567     instanceKlassHandle this_oop(THREAD, this);
   568     initialize_impl(this_oop, CHECK);
   569     // Note: at this point the class may be initialized
   570     //       OR it may be in the state of being initialized
   571     //       in case of recursive initialization!
   572   } else {
   573     assert(is_initialized(), "sanity check");
   574   }
   575 }
   578 bool InstanceKlass::verify_code(
   579     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   580   // 1) Verify the bytecodes
   581   Verifier::Mode mode =
   582     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   583   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   584 }
   587 // Used exclusively by the shared spaces dump mechanism to prevent
   588 // classes mapped into the shared regions in new VMs from appearing linked.
   590 void InstanceKlass::unlink_class() {
   591   assert(is_linked(), "must be linked");
   592   _init_state = loaded;
   593 }
   595 void InstanceKlass::link_class(TRAPS) {
   596   assert(is_loaded(), "must be loaded");
   597   if (!is_linked()) {
   598     HandleMark hm(THREAD);
   599     instanceKlassHandle this_oop(THREAD, this);
   600     link_class_impl(this_oop, true, CHECK);
   601   }
   602 }
   604 // Called to verify that a class can link during initialization, without
   605 // throwing a VerifyError.
   606 bool InstanceKlass::link_class_or_fail(TRAPS) {
   607   assert(is_loaded(), "must be loaded");
   608   if (!is_linked()) {
   609     HandleMark hm(THREAD);
   610     instanceKlassHandle this_oop(THREAD, this);
   611     link_class_impl(this_oop, false, CHECK_false);
   612   }
   613   return is_linked();
   614 }
   616 bool InstanceKlass::link_class_impl(
   617     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   618   // check for error state
   619   if (this_oop->is_in_error_state()) {
   620     ResourceMark rm(THREAD);
   621     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   622                this_oop->external_name(), false);
   623   }
   624   // return if already verified
   625   if (this_oop->is_linked()) {
   626     return true;
   627   }
   629   // Timing
   630   // timer handles recursion
   631   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   632   JavaThread* jt = (JavaThread*)THREAD;
   634   // link super class before linking this class
   635   instanceKlassHandle super(THREAD, this_oop->super());
   636   if (super.not_null()) {
   637     if (super->is_interface()) {  // check if super class is an interface
   638       ResourceMark rm(THREAD);
   639       Exceptions::fthrow(
   640         THREAD_AND_LOCATION,
   641         vmSymbols::java_lang_IncompatibleClassChangeError(),
   642         "class %s has interface %s as super class",
   643         this_oop->external_name(),
   644         super->external_name()
   645       );
   646       return false;
   647     }
   649     link_class_impl(super, throw_verifyerror, CHECK_false);
   650   }
   652   // link all interfaces implemented by this class before linking this class
   653   Array<Klass*>* interfaces = this_oop->local_interfaces();
   654   int num_interfaces = interfaces->length();
   655   for (int index = 0; index < num_interfaces; index++) {
   656     HandleMark hm(THREAD);
   657     instanceKlassHandle ih(THREAD, interfaces->at(index));
   658     link_class_impl(ih, throw_verifyerror, CHECK_false);
   659   }
   661   // in case the class is linked in the process of linking its superclasses
   662   if (this_oop->is_linked()) {
   663     return true;
   664   }
   666   // trace only the link time for this klass that includes
   667   // the verification time
   668   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   669                              ClassLoader::perf_class_link_selftime(),
   670                              ClassLoader::perf_classes_linked(),
   671                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   672                              jt->get_thread_stat()->perf_timers_addr(),
   673                              PerfClassTraceTime::CLASS_LINK);
   675   // verification & rewriting
   676   {
   677     oop init_lock = this_oop->init_lock();
   678     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   679     // rewritten will have been set if loader constraint error found
   680     // on an earlier link attempt
   681     // don't verify or rewrite if already rewritten
   683     if (!this_oop->is_linked()) {
   684       if (!this_oop->is_rewritten()) {
   685         {
   686           // Timer includes any side effects of class verification (resolution,
   687           // etc), but not recursive entry into verify_code().
   688           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   689                                    ClassLoader::perf_class_verify_selftime(),
   690                                    ClassLoader::perf_classes_verified(),
   691                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   692                                    jt->get_thread_stat()->perf_timers_addr(),
   693                                    PerfClassTraceTime::CLASS_VERIFY);
   694           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   695           if (!verify_ok) {
   696             return false;
   697           }
   698         }
   700         // Just in case a side-effect of verify linked this class already
   701         // (which can sometimes happen since the verifier loads classes
   702         // using custom class loaders, which are free to initialize things)
   703         if (this_oop->is_linked()) {
   704           return true;
   705         }
   707         // also sets rewritten
   708         this_oop->rewrite_class(CHECK_false);
   709       }
   711       // relocate jsrs and link methods after they are all rewritten
   712       this_oop->link_methods(CHECK_false);
   714       // Initialize the vtable and interface table after
   715       // methods have been rewritten since rewrite may
   716       // fabricate new Method*s.
   717       // also does loader constraint checking
   718       if (!this_oop()->is_shared()) {
   719         ResourceMark rm(THREAD);
   720         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   721         this_oop->itable()->initialize_itable(true, CHECK_false);
   722       }
   723 #ifdef ASSERT
   724       else {
   725         ResourceMark rm(THREAD);
   726         this_oop->vtable()->verify(tty, true);
   727         // In case itable verification is ever added.
   728         // this_oop->itable()->verify(tty, true);
   729       }
   730 #endif
   731       this_oop->set_init_state(linked);
   732       if (JvmtiExport::should_post_class_prepare()) {
   733         Thread *thread = THREAD;
   734         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   735         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   736       }
   737     }
   738   }
   739   return true;
   740 }
   743 // Rewrite the byte codes of all of the methods of a class.
   744 // The rewriter must be called exactly once. Rewriting must happen after
   745 // verification but before the first method of the class is executed.
   746 void InstanceKlass::rewrite_class(TRAPS) {
   747   assert(is_loaded(), "must be loaded");
   748   instanceKlassHandle this_oop(THREAD, this);
   749   if (this_oop->is_rewritten()) {
   750     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   751     return;
   752   }
   753   Rewriter::rewrite(this_oop, CHECK);
   754   this_oop->set_rewritten();
   755 }
   757 // Now relocate and link method entry points after class is rewritten.
   758 // This is outside is_rewritten flag. In case of an exception, it can be
   759 // executed more than once.
   760 void InstanceKlass::link_methods(TRAPS) {
   761   int len = methods()->length();
   762   for (int i = len-1; i >= 0; i--) {
   763     methodHandle m(THREAD, methods()->at(i));
   765     // Set up method entry points for compiler and interpreter    .
   766     m->link_method(m, CHECK);
   768     // This is for JVMTI and unrelated to relocator but the last thing we do
   769 #ifdef ASSERT
   770     if (StressMethodComparator) {
   771       ResourceMark rm(THREAD);
   772       static int nmc = 0;
   773       for (int j = i; j >= 0 && j >= i-4; j--) {
   774         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   775         bool z = MethodComparator::methods_EMCP(m(),
   776                    methods()->at(j));
   777         if (j == i && !z) {
   778           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   779           assert(z, "method must compare equal to itself");
   780         }
   781       }
   782     }
   783 #endif //ASSERT
   784   }
   785 }
   787 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
   788 void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_oop, TRAPS) {
   789   if (this_oop->has_default_methods()) {
   790     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   791       Klass* iface = this_oop->local_interfaces()->at(i);
   792       InstanceKlass* ik = InstanceKlass::cast(iface);
   793       if (ik->should_be_initialized()) {
   794         if (ik->has_default_methods()) {
   795           ik->initialize_super_interfaces(ik, THREAD);
   796         }
   797         // Only initialize() interfaces that "declare" concrete methods.
   798         // has_default_methods drives searching superinterfaces since it
   799         // means has_default_methods in its superinterface hierarchy
   800         if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
   801           ik->initialize(THREAD);
   802         }
   803         if (HAS_PENDING_EXCEPTION) {
   804           Handle e(THREAD, PENDING_EXCEPTION);
   805           CLEAR_PENDING_EXCEPTION;
   806           {
   807             EXCEPTION_MARK;
   808             // Locks object, set state, and notify all waiting threads
   809             this_oop->set_initialization_state_and_notify(
   810                 initialization_error, THREAD);
   812             // ignore any exception thrown, superclass initialization error is
   813             // thrown below
   814             CLEAR_PENDING_EXCEPTION;
   815           }
   816           THROW_OOP(e());
   817         }
   818       }
   819     }
   820   }
   821 }
   823 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   824   // Make sure klass is linked (verified) before initialization
   825   // A class could already be verified, since it has been reflected upon.
   826   this_oop->link_class(CHECK);
   828   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   830   bool wait = false;
   832   // refer to the JVM book page 47 for description of steps
   833   // Step 1
   834   {
   835     oop init_lock = this_oop->init_lock();
   836     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   838     Thread *self = THREAD; // it's passed the current thread
   840     // Step 2
   841     // If we were to use wait() instead of waitInterruptibly() then
   842     // we might end up throwing IE from link/symbol resolution sites
   843     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   844     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   845         wait = true;
   846       ol.waitUninterruptibly(CHECK);
   847     }
   849     // Step 3
   850     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   851       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   852       return;
   853     }
   855     // Step 4
   856     if (this_oop->is_initialized()) {
   857       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   858       return;
   859     }
   861     // Step 5
   862     if (this_oop->is_in_error_state()) {
   863       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   864       ResourceMark rm(THREAD);
   865       const char* desc = "Could not initialize class ";
   866       const char* className = this_oop->external_name();
   867       size_t msglen = strlen(desc) + strlen(className) + 1;
   868       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   869       if (NULL == message) {
   870         // Out of memory: can't create detailed error message
   871         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   872       } else {
   873         jio_snprintf(message, msglen, "%s%s", desc, className);
   874         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   875       }
   876     }
   878     // Step 6
   879     this_oop->set_init_state(being_initialized);
   880     this_oop->set_init_thread(self);
   881   }
   883   // Step 7
   884   Klass* super_klass = this_oop->super();
   885   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   886     super_klass->initialize(THREAD);
   888     if (HAS_PENDING_EXCEPTION) {
   889       Handle e(THREAD, PENDING_EXCEPTION);
   890       CLEAR_PENDING_EXCEPTION;
   891       {
   892         EXCEPTION_MARK;
   893         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   894         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   895       }
   896       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   897       THROW_OOP(e());
   898     }
   899   }
   901   // Recursively initialize any superinterfaces that declare default methods
   902   // Only need to recurse if has_default_methods which includes declaring and
   903   // inheriting default methods
   904   if (this_oop->has_default_methods()) {
   905     this_oop->initialize_super_interfaces(this_oop, CHECK);
   906   }
   908   // Step 8
   909   {
   910     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   911     JavaThread* jt = (JavaThread*)THREAD;
   912     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   913     // Timer includes any side effects of class initialization (resolution,
   914     // etc), but not recursive entry into call_class_initializer().
   915     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   916                              ClassLoader::perf_class_init_selftime(),
   917                              ClassLoader::perf_classes_inited(),
   918                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   919                              jt->get_thread_stat()->perf_timers_addr(),
   920                              PerfClassTraceTime::CLASS_CLINIT);
   921     this_oop->call_class_initializer(THREAD);
   922   }
   924   // Step 9
   925   if (!HAS_PENDING_EXCEPTION) {
   926     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   927     { ResourceMark rm(THREAD);
   928       debug_only(this_oop->vtable()->verify(tty, true);)
   929     }
   930   }
   931   else {
   932     // Step 10 and 11
   933     Handle e(THREAD, PENDING_EXCEPTION);
   934     CLEAR_PENDING_EXCEPTION;
   935     // JVMTI has already reported the pending exception
   936     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
   937     JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
   938     {
   939       EXCEPTION_MARK;
   940       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   941       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   942       // JVMTI has already reported the pending exception
   943       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
   944       JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
   945     }
   946     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   947     if (e->is_a(SystemDictionary::Error_klass())) {
   948       THROW_OOP(e());
   949     } else {
   950       JavaCallArguments args(e);
   951       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   952                 vmSymbols::throwable_void_signature(),
   953                 &args);
   954     }
   955   }
   956   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   957 }
   960 // Note: implementation moved to static method to expose the this pointer.
   961 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   962   instanceKlassHandle kh(THREAD, this);
   963   set_initialization_state_and_notify_impl(kh, state, CHECK);
   964 }
   966 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   967   oop init_lock = this_oop->init_lock();
   968   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   969   this_oop->set_init_state(state);
   970   this_oop->fence_and_clear_init_lock();
   971   ol.notify_all(CHECK);
   972 }
   974 // The embedded _implementor field can only record one implementor.
   975 // When there are more than one implementors, the _implementor field
   976 // is set to the interface Klass* itself. Following are the possible
   977 // values for the _implementor field:
   978 //   NULL                  - no implementor
   979 //   implementor Klass*    - one implementor
   980 //   self                  - more than one implementor
   981 //
   982 // The _implementor field only exists for interfaces.
   983 void InstanceKlass::add_implementor(Klass* k) {
   984   assert(Compile_lock->owned_by_self(), "");
   985   assert(is_interface(), "not interface");
   986   // Filter out my subinterfaces.
   987   // (Note: Interfaces are never on the subklass list.)
   988   if (InstanceKlass::cast(k)->is_interface()) return;
   990   // Filter out subclasses whose supers already implement me.
   991   // (Note: CHA must walk subclasses of direct implementors
   992   // in order to locate indirect implementors.)
   993   Klass* sk = InstanceKlass::cast(k)->super();
   994   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
   995     // We only need to check one immediate superclass, since the
   996     // implements_interface query looks at transitive_interfaces.
   997     // Any supers of the super have the same (or fewer) transitive_interfaces.
   998     return;
  1000   Klass* ik = implementor();
  1001   if (ik == NULL) {
  1002     set_implementor(k);
  1003   } else if (ik != this) {
  1004     // There is already an implementor. Use itself as an indicator of
  1005     // more than one implementors.
  1006     set_implementor(this);
  1009   // The implementor also implements the transitive_interfaces
  1010   for (int index = 0; index < local_interfaces()->length(); index++) {
  1011     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
  1015 void InstanceKlass::init_implementor() {
  1016   if (is_interface()) {
  1017     set_implementor(NULL);
  1022 void InstanceKlass::process_interfaces(Thread *thread) {
  1023   // link this class into the implementors list of every interface it implements
  1024   Klass* this_as_klass_oop = this;
  1025   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
  1026     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
  1027     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
  1028     assert(interf->is_interface(), "expected interface");
  1029     interf->add_implementor(this_as_klass_oop);
  1033 bool InstanceKlass::can_be_primary_super_slow() const {
  1034   if (is_interface())
  1035     return false;
  1036   else
  1037     return Klass::can_be_primary_super_slow();
  1040 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
  1041   // The secondaries are the implemented interfaces.
  1042   InstanceKlass* ik = InstanceKlass::cast(this);
  1043   Array<Klass*>* interfaces = ik->transitive_interfaces();
  1044   int num_secondaries = num_extra_slots + interfaces->length();
  1045   if (num_secondaries == 0) {
  1046     // Must share this for correct bootstrapping!
  1047     set_secondary_supers(Universe::the_empty_klass_array());
  1048     return NULL;
  1049   } else if (num_extra_slots == 0) {
  1050     // The secondary super list is exactly the same as the transitive interfaces.
  1051     // Redefine classes has to be careful not to delete this!
  1052     set_secondary_supers(interfaces);
  1053     return NULL;
  1054   } else {
  1055     // Copy transitive interfaces to a temporary growable array to be constructed
  1056     // into the secondary super list with extra slots.
  1057     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
  1058     for (int i = 0; i < interfaces->length(); i++) {
  1059       secondaries->push(interfaces->at(i));
  1061     return secondaries;
  1065 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
  1066   if (k->is_interface()) {
  1067     return implements_interface(k);
  1068   } else {
  1069     return Klass::compute_is_subtype_of(k);
  1073 bool InstanceKlass::implements_interface(Klass* k) const {
  1074   if (this == k) return true;
  1075   assert(k->is_interface(), "should be an interface class");
  1076   for (int i = 0; i < transitive_interfaces()->length(); i++) {
  1077     if (transitive_interfaces()->at(i) == k) {
  1078       return true;
  1081   return false;
  1084 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
  1085   // Verify direct super interface
  1086   if (this == k) return true;
  1087   assert(k->is_interface(), "should be an interface class");
  1088   for (int i = 0; i < local_interfaces()->length(); i++) {
  1089     if (local_interfaces()->at(i) == k) {
  1090       return true;
  1093   return false;
  1096 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
  1097   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  1098   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
  1099     report_java_out_of_memory("Requested array size exceeds VM limit");
  1100     JvmtiExport::post_array_size_exhausted();
  1101     THROW_OOP_0(Universe::out_of_memory_error_array_size());
  1103   int size = objArrayOopDesc::object_size(length);
  1104   Klass* ak = array_klass(n, CHECK_NULL);
  1105   KlassHandle h_ak (THREAD, ak);
  1106   objArrayOop o =
  1107     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  1108   return o;
  1111 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
  1112   if (TraceFinalizerRegistration) {
  1113     tty->print("Registered ");
  1114     i->print_value_on(tty);
  1115     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  1117   instanceHandle h_i(THREAD, i);
  1118   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  1119   JavaValue result(T_VOID);
  1120   JavaCallArguments args(h_i);
  1121   methodHandle mh (THREAD, Universe::finalizer_register_method());
  1122   JavaCalls::call(&result, mh, &args, CHECK_NULL);
  1123   return h_i();
  1126 instanceOop InstanceKlass::allocate_instance(TRAPS) {
  1127   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  1128   int size = size_helper();  // Query before forming handle.
  1130   KlassHandle h_k(THREAD, this);
  1132   instanceOop i;
  1134   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1135   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1136     i = register_finalizer(i, CHECK_NULL);
  1138   return i;
  1141 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1142   if (is_interface() || is_abstract()) {
  1143     ResourceMark rm(THREAD);
  1144     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1145               : vmSymbols::java_lang_InstantiationException(), external_name());
  1147   if (this == SystemDictionary::Class_klass()) {
  1148     ResourceMark rm(THREAD);
  1149     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1150               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1154 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1155   instanceKlassHandle this_oop(THREAD, this);
  1156   return array_klass_impl(this_oop, or_null, n, THREAD);
  1159 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1160   if (this_oop->array_klasses() == NULL) {
  1161     if (or_null) return NULL;
  1163     ResourceMark rm;
  1164     JavaThread *jt = (JavaThread *)THREAD;
  1166       // Atomic creation of array_klasses
  1167       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1168       MutexLocker ma(MultiArray_lock, THREAD);
  1170       // Check if update has already taken place
  1171       if (this_oop->array_klasses() == NULL) {
  1172         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1173         this_oop->set_array_klasses(k);
  1177   // _this will always be set at this point
  1178   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1179   if (or_null) {
  1180     return oak->array_klass_or_null(n);
  1182   return oak->array_klass(n, CHECK_NULL);
  1185 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1186   return array_klass_impl(or_null, 1, THREAD);
  1189 void InstanceKlass::call_class_initializer(TRAPS) {
  1190   instanceKlassHandle ik (THREAD, this);
  1191   call_class_initializer_impl(ik, THREAD);
  1194 static int call_class_initializer_impl_counter = 0;   // for debugging
  1196 Method* InstanceKlass::class_initializer() {
  1197   Method* clinit = find_method(
  1198       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1199   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1200     return clinit;
  1202   return NULL;
  1205 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1206   if (ReplayCompiles &&
  1207       (ReplaySuppressInitializers == 1 ||
  1208        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1209     // Hide the existence of the initializer for the purpose of replaying the compile
  1210     return;
  1213   methodHandle h_method(THREAD, this_oop->class_initializer());
  1214   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1215   if (TraceClassInitialization) {
  1216     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1217     this_oop->name()->print_value();
  1218     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1220   if (h_method() != NULL) {
  1221     JavaCallArguments args; // No arguments
  1222     JavaValue result(T_VOID);
  1223     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1228 void InstanceKlass::mask_for(methodHandle method, int bci,
  1229   InterpreterOopMap* entry_for) {
  1230   // Dirty read, then double-check under a lock.
  1231   if (_oop_map_cache == NULL) {
  1232     // Otherwise, allocate a new one.
  1233     MutexLocker x(OopMapCacheAlloc_lock);
  1234     // First time use. Allocate a cache in C heap
  1235     if (_oop_map_cache == NULL) {
  1236       // Release stores from OopMapCache constructor before assignment
  1237       // to _oop_map_cache. C++ compilers on ppc do not emit the
  1238       // required memory barrier only because of the volatile
  1239       // qualifier of _oop_map_cache.
  1240       OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
  1243   // _oop_map_cache is constant after init; lookup below does is own locking.
  1244   _oop_map_cache->lookup(method, bci, entry_for);
  1248 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1249   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1250     Symbol* f_name = fs.name();
  1251     Symbol* f_sig  = fs.signature();
  1252     if (f_name == name && f_sig == sig) {
  1253       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1254       return true;
  1257   return false;
  1261 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1262   const int n = local_interfaces()->length();
  1263   for (int i = 0; i < n; i++) {
  1264     Klass* intf1 = local_interfaces()->at(i);
  1265     assert(intf1->is_interface(), "just checking type");
  1266     // search for field in current interface
  1267     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1268       assert(fd->is_static(), "interface field must be static");
  1269       return intf1;
  1271     // search for field in direct superinterfaces
  1272     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1273     if (intf2 != NULL) return intf2;
  1275   // otherwise field lookup fails
  1276   return NULL;
  1280 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1281   // search order according to newest JVM spec (5.4.3.2, p.167).
  1282   // 1) search for field in current klass
  1283   if (find_local_field(name, sig, fd)) {
  1284     return const_cast<InstanceKlass*>(this);
  1286   // 2) search for field recursively in direct superinterfaces
  1287   { Klass* intf = find_interface_field(name, sig, fd);
  1288     if (intf != NULL) return intf;
  1290   // 3) apply field lookup recursively if superclass exists
  1291   { Klass* supr = super();
  1292     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1294   // 4) otherwise field lookup fails
  1295   return NULL;
  1299 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1300   // search order according to newest JVM spec (5.4.3.2, p.167).
  1301   // 1) search for field in current klass
  1302   if (find_local_field(name, sig, fd)) {
  1303     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1305   // 2) search for field recursively in direct superinterfaces
  1306   if (is_static) {
  1307     Klass* intf = find_interface_field(name, sig, fd);
  1308     if (intf != NULL) return intf;
  1310   // 3) apply field lookup recursively if superclass exists
  1311   { Klass* supr = super();
  1312     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1314   // 4) otherwise field lookup fails
  1315   return NULL;
  1319 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1320   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1321     if (fs.offset() == offset) {
  1322       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1323       if (fd->is_static() == is_static) return true;
  1326   return false;
  1330 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1331   Klass* klass = const_cast<InstanceKlass*>(this);
  1332   while (klass != NULL) {
  1333     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1334       return true;
  1336     klass = klass->super();
  1338   return false;
  1342 void InstanceKlass::methods_do(void f(Method* method)) {
  1343   int len = methods()->length();
  1344   for (int index = 0; index < len; index++) {
  1345     Method* m = methods()->at(index);
  1346     assert(m->is_method(), "must be method");
  1347     f(m);
  1352 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1353   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1354     if (fs.access_flags().is_static()) {
  1355       fieldDescriptor& fd = fs.field_descriptor();
  1356       cl->do_field(&fd);
  1362 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
  1363   instanceKlassHandle h_this(THREAD, this);
  1364   do_local_static_fields_impl(h_this, f, mirror, CHECK);
  1368 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
  1369                              void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {
  1370   for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
  1371     if (fs.access_flags().is_static()) {
  1372       fieldDescriptor& fd = fs.field_descriptor();
  1373       f(&fd, mirror, CHECK);
  1379 static int compare_fields_by_offset(int* a, int* b) {
  1380   return a[0] - b[0];
  1383 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1384   InstanceKlass* super = superklass();
  1385   if (super != NULL) {
  1386     super->do_nonstatic_fields(cl);
  1388   fieldDescriptor fd;
  1389   int length = java_fields_count();
  1390   // In DebugInfo nonstatic fields are sorted by offset.
  1391   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1392   int j = 0;
  1393   for (int i = 0; i < length; i += 1) {
  1394     fd.reinitialize(this, i);
  1395     if (!fd.is_static()) {
  1396       fields_sorted[j + 0] = fd.offset();
  1397       fields_sorted[j + 1] = i;
  1398       j += 2;
  1401   if (j > 0) {
  1402     length = j;
  1403     // _sort_Fn is defined in growableArray.hpp.
  1404     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1405     for (int i = 0; i < length; i += 2) {
  1406       fd.reinitialize(this, fields_sorted[i + 1]);
  1407       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1408       cl->do_field(&fd);
  1411   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1415 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1416   if (array_klasses() != NULL)
  1417     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1420 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1421   if (array_klasses() != NULL)
  1422     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1425 #ifdef ASSERT
  1426 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1427   int len = methods->length();
  1428   for (int index = 0; index < len; index++) {
  1429     Method* m = methods->at(index);
  1430     assert(m->is_method(), "must be method");
  1431     if (m->signature() == signature && m->name() == name) {
  1432        return index;
  1435   return -1;
  1437 #endif
  1439 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1440   int len = methods->length();
  1441   // methods are sorted, so do binary search
  1442   int l = 0;
  1443   int h = len - 1;
  1444   while (l <= h) {
  1445     int mid = (l + h) >> 1;
  1446     Method* m = methods->at(mid);
  1447     assert(m->is_method(), "must be method");
  1448     int res = m->name()->fast_compare(name);
  1449     if (res == 0) {
  1450       return mid;
  1451     } else if (res < 0) {
  1452       l = mid + 1;
  1453     } else {
  1454       h = mid - 1;
  1457   return -1;
  1460 // find_method looks up the name/signature in the local methods array
  1461 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1462   return find_method_impl(name, signature, false);
  1465 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
  1466   return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass, false);
  1469 // find_instance_method looks up the name/signature in the local methods array
  1470 // and skips over static methods
  1471 Method* InstanceKlass::find_instance_method(
  1472     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1473   Method* meth = InstanceKlass::find_method_impl(methods, name, signature, false, true);
  1474   return meth;
  1477 // find_instance_method looks up the name/signature in the local methods array
  1478 // and skips over static methods
  1479 Method* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) {
  1480     return InstanceKlass::find_instance_method(methods(), name, signature);
  1483 // find_method looks up the name/signature in the local methods array
  1484 Method* InstanceKlass::find_method(
  1485     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1486   return InstanceKlass::find_method_impl(methods, name, signature, false, false);
  1489 Method* InstanceKlass::find_method_impl(
  1490     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
  1491   int hit = find_method_index(methods, name, signature, skipping_overpass, skipping_static);
  1492   return hit >= 0 ? methods->at(hit): NULL;
  1495 bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static) {
  1496     return (m->signature() == signature) &&
  1497             (!skipping_overpass || !m->is_overpass()) &&
  1498             (!skipping_static || !m->is_static());
  1501 // Used directly for default_methods to find the index into the
  1502 // default_vtable_indices, and indirectly by find_method
  1503 // find_method_index looks in the local methods array to return the index
  1504 // of the matching name/signature. If, overpass methods are being ignored,
  1505 // the search continues to find a potential non-overpass match.  This capability
  1506 // is important during method resolution to prefer a static method, for example,
  1507 // over an overpass method.
  1508 int InstanceKlass::find_method_index(
  1509     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
  1510   int hit = binary_search(methods, name);
  1511   if (hit != -1) {
  1512     Method* m = methods->at(hit);
  1514     // Do linear search to find matching signature.  First, quick check
  1515     // for common case, ignoring overpasses if requested.
  1516     if (method_matches(m, signature, skipping_overpass, skipping_static)) return hit;
  1518     // search downwards through overloaded methods
  1519     int i;
  1520     for (i = hit - 1; i >= 0; --i) {
  1521         Method* m = methods->at(i);
  1522         assert(m->is_method(), "must be method");
  1523         if (m->name() != name) break;
  1524         if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
  1526     // search upwards
  1527     for (i = hit + 1; i < methods->length(); ++i) {
  1528         Method* m = methods->at(i);
  1529         assert(m->is_method(), "must be method");
  1530         if (m->name() != name) break;
  1531         if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
  1533     // not found
  1534 #ifdef ASSERT
  1535     int index = skipping_overpass || skipping_static ? -1 : linear_search(methods, name, signature);
  1536     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1537 #endif
  1539   return -1;
  1541 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1542   return find_method_by_name(methods(), name, end);
  1545 int InstanceKlass::find_method_by_name(
  1546     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1547   assert(end_ptr != NULL, "just checking");
  1548   int start = binary_search(methods, name);
  1549   int end = start + 1;
  1550   if (start != -1) {
  1551     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1552     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1553     *end_ptr = end;
  1554     return start;
  1556   return -1;
  1559 // uncached_lookup_method searches both the local class methods array and all
  1560 // superclasses methods arrays, skipping any overpass methods in superclasses.
  1561 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
  1562   MethodLookupMode lookup_mode = mode;
  1563   Klass* klass = const_cast<InstanceKlass*>(this);
  1564   while (klass != NULL) {
  1565     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
  1566     if (method != NULL) {
  1567       return method;
  1569     klass = InstanceKlass::cast(klass)->super();
  1570     lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
  1572   return NULL;
  1575 // lookup a method in the default methods list then in all transitive interfaces
  1576 // Do NOT return private or static methods
  1577 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
  1578                                                          Symbol* signature) const {
  1579   Method* m = NULL;
  1580   if (default_methods() != NULL) {
  1581     m = find_method(default_methods(), name, signature);
  1583   // Look up interfaces
  1584   if (m == NULL) {
  1585     m = lookup_method_in_all_interfaces(name, signature, normal);
  1587   return m;
  1590 // lookup a method in all the interfaces that this class implements
  1591 // Do NOT return private or static methods, new in JDK8 which are not externally visible
  1592 // They should only be found in the initial InterfaceMethodRef
  1593 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1594                                                        Symbol* signature,
  1595                                                        MethodLookupMode mode) const {
  1596   Array<Klass*>* all_ifs = transitive_interfaces();
  1597   int num_ifs = all_ifs->length();
  1598   InstanceKlass *ik = NULL;
  1599   for (int i = 0; i < num_ifs; i++) {
  1600     ik = InstanceKlass::cast(all_ifs->at(i));
  1601     Method* m = ik->lookup_method(name, signature);
  1602     if (m != NULL && m->is_public() && !m->is_static() &&
  1603         ((mode != skip_defaults) || !m->is_default_method())) {
  1604       return m;
  1607   return NULL;
  1610 /* jni_id_for_impl for jfieldIds only */
  1611 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1612   MutexLocker ml(JfieldIdCreation_lock);
  1613   // Retry lookup after we got the lock
  1614   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1615   if (probe == NULL) {
  1616     // Slow case, allocate new static field identifier
  1617     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1618     this_oop->set_jni_ids(probe);
  1620   return probe;
  1624 /* jni_id_for for jfieldIds only */
  1625 JNIid* InstanceKlass::jni_id_for(int offset) {
  1626   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1627   if (probe == NULL) {
  1628     probe = jni_id_for_impl(this, offset);
  1630   return probe;
  1633 u2 InstanceKlass::enclosing_method_data(int offset) {
  1634   Array<jushort>* inner_class_list = inner_classes();
  1635   if (inner_class_list == NULL) {
  1636     return 0;
  1638   int length = inner_class_list->length();
  1639   if (length % inner_class_next_offset == 0) {
  1640     return 0;
  1641   } else {
  1642     int index = length - enclosing_method_attribute_size;
  1643     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1644     return inner_class_list->at(index + offset);
  1648 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1649                                                  u2 method_index) {
  1650   Array<jushort>* inner_class_list = inner_classes();
  1651   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1652   int length = inner_class_list->length();
  1653   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1654     int index = length - enclosing_method_attribute_size;
  1655     inner_class_list->at_put(
  1656       index + enclosing_method_class_index_offset, class_index);
  1657     inner_class_list->at_put(
  1658       index + enclosing_method_method_index_offset, method_index);
  1662 // Lookup or create a jmethodID.
  1663 // This code is called by the VMThread and JavaThreads so the
  1664 // locking has to be done very carefully to avoid deadlocks
  1665 // and/or other cache consistency problems.
  1666 //
  1667 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1668   size_t idnum = (size_t)method_h->method_idnum();
  1669   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1670   size_t length = 0;
  1671   jmethodID id = NULL;
  1673   // We use a double-check locking idiom here because this cache is
  1674   // performance sensitive. In the normal system, this cache only
  1675   // transitions from NULL to non-NULL which is safe because we use
  1676   // release_set_methods_jmethod_ids() to advertise the new cache.
  1677   // A partially constructed cache should never be seen by a racing
  1678   // thread. We also use release_store_ptr() to save a new jmethodID
  1679   // in the cache so a partially constructed jmethodID should never be
  1680   // seen either. Cache reads of existing jmethodIDs proceed without a
  1681   // lock, but cache writes of a new jmethodID requires uniqueness and
  1682   // creation of the cache itself requires no leaks so a lock is
  1683   // generally acquired in those two cases.
  1684   //
  1685   // If the RedefineClasses() API has been used, then this cache can
  1686   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1687   // Cache creation requires no leaks and we require safety between all
  1688   // cache accesses and freeing of the old cache so a lock is generally
  1689   // acquired when the RedefineClasses() API has been used.
  1691   if (jmeths != NULL) {
  1692     // the cache already exists
  1693     if (!ik_h->idnum_can_increment()) {
  1694       // the cache can't grow so we can just get the current values
  1695       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1696     } else {
  1697       // cache can grow so we have to be more careful
  1698       if (Threads::number_of_threads() == 0 ||
  1699           SafepointSynchronize::is_at_safepoint()) {
  1700         // we're single threaded or at a safepoint - no locking needed
  1701         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1702       } else {
  1703         MutexLocker ml(JmethodIdCreation_lock);
  1704         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1708   // implied else:
  1709   // we need to allocate a cache so default length and id values are good
  1711   if (jmeths == NULL ||   // no cache yet
  1712       length <= idnum ||  // cache is too short
  1713       id == NULL) {       // cache doesn't contain entry
  1715     // This function can be called by the VMThread so we have to do all
  1716     // things that might block on a safepoint before grabbing the lock.
  1717     // Otherwise, we can deadlock with the VMThread or have a cache
  1718     // consistency issue. These vars keep track of what we might have
  1719     // to free after the lock is dropped.
  1720     jmethodID  to_dealloc_id     = NULL;
  1721     jmethodID* to_dealloc_jmeths = NULL;
  1723     // may not allocate new_jmeths or use it if we allocate it
  1724     jmethodID* new_jmeths = NULL;
  1725     if (length <= idnum) {
  1726       // allocate a new cache that might be used
  1727       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1728       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1729       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1730       // cache size is stored in element[0], other elements offset by one
  1731       new_jmeths[0] = (jmethodID)size;
  1734     // allocate a new jmethodID that might be used
  1735     jmethodID new_id = NULL;
  1736     if (method_h->is_old() && !method_h->is_obsolete()) {
  1737       // The method passed in is old (but not obsolete), we need to use the current version
  1738       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1739       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1740       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1741     } else {
  1742       // It is the current version of the method or an obsolete method,
  1743       // use the version passed in
  1744       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1747     if (Threads::number_of_threads() == 0 ||
  1748         SafepointSynchronize::is_at_safepoint()) {
  1749       // we're single threaded or at a safepoint - no locking needed
  1750       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1751                                           &to_dealloc_id, &to_dealloc_jmeths);
  1752     } else {
  1753       MutexLocker ml(JmethodIdCreation_lock);
  1754       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1755                                           &to_dealloc_id, &to_dealloc_jmeths);
  1758     // The lock has been dropped so we can free resources.
  1759     // Free up either the old cache or the new cache if we allocated one.
  1760     if (to_dealloc_jmeths != NULL) {
  1761       FreeHeap(to_dealloc_jmeths);
  1763     // free up the new ID since it wasn't needed
  1764     if (to_dealloc_id != NULL) {
  1765       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1768   return id;
  1772 // Common code to fetch the jmethodID from the cache or update the
  1773 // cache with the new jmethodID. This function should never do anything
  1774 // that causes the caller to go to a safepoint or we can deadlock with
  1775 // the VMThread or have cache consistency issues.
  1776 //
  1777 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1778             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1779             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1780             jmethodID** to_dealloc_jmeths_p) {
  1781   assert(new_id != NULL, "sanity check");
  1782   assert(to_dealloc_id_p != NULL, "sanity check");
  1783   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1784   assert(Threads::number_of_threads() == 0 ||
  1785          SafepointSynchronize::is_at_safepoint() ||
  1786          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1788   // reacquire the cache - we are locked, single threaded or at a safepoint
  1789   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1790   jmethodID  id     = NULL;
  1791   size_t     length = 0;
  1793   if (jmeths == NULL ||                         // no cache yet
  1794       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1795     if (jmeths != NULL) {
  1796       // copy any existing entries from the old cache
  1797       for (size_t index = 0; index < length; index++) {
  1798         new_jmeths[index+1] = jmeths[index+1];
  1800       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1802     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1803   } else {
  1804     // fetch jmethodID (if any) from the existing cache
  1805     id = jmeths[idnum+1];
  1806     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1808   if (id == NULL) {
  1809     // No matching jmethodID in the existing cache or we have a new
  1810     // cache or we just grew the cache. This cache write is done here
  1811     // by the first thread to win the foot race because a jmethodID
  1812     // needs to be unique once it is generally available.
  1813     id = new_id;
  1815     // The jmethodID cache can be read while unlocked so we have to
  1816     // make sure the new jmethodID is complete before installing it
  1817     // in the cache.
  1818     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1819   } else {
  1820     *to_dealloc_id_p = new_id; // save new id for later delete
  1822   return id;
  1826 // Common code to get the jmethodID cache length and the jmethodID
  1827 // value at index idnum if there is one.
  1828 //
  1829 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1830        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1831   assert(cache != NULL, "sanity check");
  1832   assert(length_p != NULL, "sanity check");
  1833   assert(id_p != NULL, "sanity check");
  1835   // cache size is stored in element[0], other elements offset by one
  1836   *length_p = (size_t)cache[0];
  1837   if (*length_p <= idnum) {  // cache is too short
  1838     *id_p = NULL;
  1839   } else {
  1840     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1845 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1846 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1847   size_t idnum = (size_t)method->method_idnum();
  1848   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1849   size_t length;                                // length assigned as debugging crumb
  1850   jmethodID id = NULL;
  1851   if (jmeths != NULL &&                         // If there is a cache
  1852       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1853     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1855   return id;
  1858 int nmethodBucket::decrement() {
  1859   return Atomic::add(-1, (volatile int *)&_count);
  1862 //
  1863 // Walk the list of dependent nmethods searching for nmethods which
  1864 // are dependent on the changes that were passed in and mark them for
  1865 // deoptimization.  Returns the number of nmethods found.
  1866 //
  1867 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1868   assert_locked_or_safepoint(CodeCache_lock);
  1869   int found = 0;
  1870   nmethodBucket* b = _dependencies;
  1871   while (b != NULL) {
  1872     nmethod* nm = b->get_nmethod();
  1873     // since dependencies aren't removed until an nmethod becomes a zombie,
  1874     // the dependency list may contain nmethods which aren't alive.
  1875     if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1876       if (TraceDependencies) {
  1877         ResourceMark rm;
  1878         tty->print_cr("Marked for deoptimization");
  1879         tty->print_cr("  context = %s", this->external_name());
  1880         changes.print();
  1881         nm->print();
  1882         nm->print_dependencies();
  1884       nm->mark_for_deoptimization();
  1885       found++;
  1887     b = b->next();
  1889   return found;
  1892 void InstanceKlass::clean_dependent_nmethods() {
  1893   assert_locked_or_safepoint(CodeCache_lock);
  1895   if (has_unloaded_dependent()) {
  1896     nmethodBucket* b = _dependencies;
  1897     nmethodBucket* last = NULL;
  1898     while (b != NULL) {
  1899       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
  1901       nmethodBucket* next = b->next();
  1903       if (b->count() == 0) {
  1904         if (last == NULL) {
  1905           _dependencies = next;
  1906         } else {
  1907           last->set_next(next);
  1909         delete b;
  1910         // last stays the same.
  1911       } else {
  1912         last = b;
  1915       b = next;
  1917     set_has_unloaded_dependent(false);
  1919 #ifdef ASSERT
  1920   else {
  1921     // Verification
  1922     for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
  1923       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
  1924       assert(b->count() != 0, "empty buckets need to be cleaned");
  1927 #endif
  1930 //
  1931 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1932 // It's possible that an nmethod has multiple dependencies on this klass
  1933 // so a count is kept for each bucket to guarantee that creation and
  1934 // deletion of dependencies is consistent.
  1935 //
  1936 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1937   assert_locked_or_safepoint(CodeCache_lock);
  1938   nmethodBucket* b = _dependencies;
  1939   nmethodBucket* last = NULL;
  1940   while (b != NULL) {
  1941     if (nm == b->get_nmethod()) {
  1942       b->increment();
  1943       return;
  1945     b = b->next();
  1947   _dependencies = new nmethodBucket(nm, _dependencies);
  1951 //
  1952 // Decrement count of the nmethod in the dependency list and remove
  1953 // the bucket competely when the count goes to 0.  This method must
  1954 // find a corresponding bucket otherwise there's a bug in the
  1955 // recording of dependecies.
  1956 //
  1957 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
  1958   assert_locked_or_safepoint(CodeCache_lock);
  1959   nmethodBucket* b = _dependencies;
  1960   nmethodBucket* last = NULL;
  1961   while (b != NULL) {
  1962     if (nm == b->get_nmethod()) {
  1963       int val = b->decrement();
  1964       guarantee(val >= 0, err_msg("Underflow: %d", val));
  1965       if (val == 0) {
  1966         set_has_unloaded_dependent(true);
  1968       return;
  1970     last = b;
  1971     b = b->next();
  1973 #ifdef ASSERT
  1974   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  1975   nm->print();
  1976 #endif // ASSERT
  1977   ShouldNotReachHere();
  1981 #ifndef PRODUCT
  1982 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  1983   nmethodBucket* b = _dependencies;
  1984   int idx = 0;
  1985   while (b != NULL) {
  1986     nmethod* nm = b->get_nmethod();
  1987     tty->print("[%d] count=%d { ", idx++, b->count());
  1988     if (!verbose) {
  1989       nm->print_on(tty, "nmethod");
  1990       tty->print_cr(" } ");
  1991     } else {
  1992       nm->print();
  1993       nm->print_dependencies();
  1994       tty->print_cr("--- } ");
  1996     b = b->next();
  2001 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  2002   nmethodBucket* b = _dependencies;
  2003   while (b != NULL) {
  2004     if (nm == b->get_nmethod()) {
  2005 #ifdef ASSERT
  2006       int count = b->count();
  2007       assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
  2008 #endif
  2009       return true;
  2011     b = b->next();
  2013   return false;
  2015 #endif //PRODUCT
  2018 // Garbage collection
  2020 #ifdef ASSERT
  2021 template <class T> void assert_is_in(T *p) {
  2022   T heap_oop = oopDesc::load_heap_oop(p);
  2023   if (!oopDesc::is_null(heap_oop)) {
  2024     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2025     assert(Universe::heap()->is_in(o), "should be in heap");
  2028 template <class T> void assert_is_in_closed_subset(T *p) {
  2029   T heap_oop = oopDesc::load_heap_oop(p);
  2030   if (!oopDesc::is_null(heap_oop)) {
  2031     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2032     assert(Universe::heap()->is_in_closed_subset(o),
  2033            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  2036 template <class T> void assert_is_in_reserved(T *p) {
  2037   T heap_oop = oopDesc::load_heap_oop(p);
  2038   if (!oopDesc::is_null(heap_oop)) {
  2039     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2040     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  2043 template <class T> void assert_nothing(T *p) {}
  2045 #else
  2046 template <class T> void assert_is_in(T *p) {}
  2047 template <class T> void assert_is_in_closed_subset(T *p) {}
  2048 template <class T> void assert_is_in_reserved(T *p) {}
  2049 template <class T> void assert_nothing(T *p) {}
  2050 #endif // ASSERT
  2052 //
  2053 // Macros that iterate over areas of oops which are specialized on type of
  2054 // oop pointer either narrow or wide, depending on UseCompressedOops
  2055 //
  2056 // Parameters are:
  2057 //   T         - type of oop to point to (either oop or narrowOop)
  2058 //   start_p   - starting pointer for region to iterate over
  2059 //   count     - number of oops or narrowOops to iterate over
  2060 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  2061 //               makes it more efficient to put in a macro rather than making
  2062 //               it a template function)
  2063 //   assert_fn - assert function which is template function because performance
  2064 //               doesn't matter when enabled.
  2065 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  2066   T, start_p, count, do_oop,                \
  2067   assert_fn)                                \
  2068 {                                           \
  2069   T* p         = (T*)(start_p);             \
  2070   T* const end = p + (count);               \
  2071   while (p < end) {                         \
  2072     (assert_fn)(p);                         \
  2073     do_oop;                                 \
  2074     ++p;                                    \
  2075   }                                         \
  2078 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  2079   T, start_p, count, do_oop,                \
  2080   assert_fn)                                \
  2081 {                                           \
  2082   T* const start = (T*)(start_p);           \
  2083   T*       p     = start + (count);         \
  2084   while (start < p) {                       \
  2085     --p;                                    \
  2086     (assert_fn)(p);                         \
  2087     do_oop;                                 \
  2088   }                                         \
  2091 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  2092   T, start_p, count, low, high,             \
  2093   do_oop, assert_fn)                        \
  2094 {                                           \
  2095   T* const l = (T*)(low);                   \
  2096   T* const h = (T*)(high);                  \
  2097   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  2098          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  2099          "bounded region must be properly aligned"); \
  2100   T* p       = (T*)(start_p);               \
  2101   T* end     = p + (count);                 \
  2102   if (p < l) p = l;                         \
  2103   if (end > h) end = h;                     \
  2104   while (p < end) {                         \
  2105     (assert_fn)(p);                         \
  2106     do_oop;                                 \
  2107     ++p;                                    \
  2108   }                                         \
  2112 // The following macros call specialized macros, passing either oop or
  2113 // narrowOop as the specialization type.  These test the UseCompressedOops
  2114 // flag.
  2115 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  2116 {                                                                        \
  2117   /* Compute oopmap block range. The common case                         \
  2118      is nonstatic_oop_map_size == 1. */                                  \
  2119   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2120   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2121   if (UseCompressedOops) {                                               \
  2122     while (map < end_map) {                                              \
  2123       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  2124         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2125         do_oop, assert_fn)                                               \
  2126       ++map;                                                             \
  2127     }                                                                    \
  2128   } else {                                                               \
  2129     while (map < end_map) {                                              \
  2130       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  2131         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2132         do_oop, assert_fn)                                               \
  2133       ++map;                                                             \
  2134     }                                                                    \
  2135   }                                                                      \
  2138 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  2139 {                                                                        \
  2140   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  2141   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  2142   if (UseCompressedOops) {                                               \
  2143     while (start_map < map) {                                            \
  2144       --map;                                                             \
  2145       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  2146         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2147         do_oop, assert_fn)                                               \
  2148     }                                                                    \
  2149   } else {                                                               \
  2150     while (start_map < map) {                                            \
  2151       --map;                                                             \
  2152       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  2153         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2154         do_oop, assert_fn)                                               \
  2155     }                                                                    \
  2156   }                                                                      \
  2159 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  2160                                               assert_fn)                 \
  2161 {                                                                        \
  2162   /* Compute oopmap block range. The common case is                      \
  2163      nonstatic_oop_map_size == 1, so we accept the                       \
  2164      usually non-existent extra overhead of examining                    \
  2165      all the maps. */                                                    \
  2166   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2167   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2168   if (UseCompressedOops) {                                               \
  2169     while (map < end_map) {                                              \
  2170       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  2171         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2172         low, high,                                                       \
  2173         do_oop, assert_fn)                                               \
  2174       ++map;                                                             \
  2175     }                                                                    \
  2176   } else {                                                               \
  2177     while (map < end_map) {                                              \
  2178       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2179         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2180         low, high,                                                       \
  2181         do_oop, assert_fn)                                               \
  2182       ++map;                                                             \
  2183     }                                                                    \
  2184   }                                                                      \
  2187 void InstanceKlass::oop_follow_contents(oop obj) {
  2188   assert(obj != NULL, "can't follow the content of NULL object");
  2189   MarkSweep::follow_klass(obj->klass());
  2190   InstanceKlass_OOP_MAP_ITERATE( \
  2191     obj, \
  2192     MarkSweep::mark_and_push(p), \
  2193     assert_is_in_closed_subset)
  2196 #if INCLUDE_ALL_GCS
  2197 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2198                                         oop obj) {
  2199   assert(obj != NULL, "can't follow the content of NULL object");
  2200   PSParallelCompact::follow_klass(cm, obj->klass());
  2201   // Only mark the header and let the scan of the meta-data mark
  2202   // everything else.
  2203   InstanceKlass_OOP_MAP_ITERATE( \
  2204     obj, \
  2205     PSParallelCompact::mark_and_push(cm, p), \
  2206     assert_is_in)
  2208 #endif // INCLUDE_ALL_GCS
  2210 // closure's do_metadata() method dictates whether the given closure should be
  2211 // applied to the klass ptr in the object header.
  2213 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2215 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2216   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2217   /* header */                                                          \
  2218   if_do_metadata_checked(closure, nv_suffix) {                          \
  2219     closure->do_klass##nv_suffix(obj->klass());                         \
  2220   }                                                                     \
  2221   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2222     obj,                                                                \
  2223     SpecializationStats::                                               \
  2224       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2225     (closure)->do_oop##nv_suffix(p),                                    \
  2226     assert_is_in_closed_subset)                                         \
  2227   return size_helper();                                                 \
  2230 #if INCLUDE_ALL_GCS
  2231 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2233 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2234                                               OopClosureType* closure) {        \
  2235   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2237   assert_should_ignore_metadata(closure, nv_suffix);                            \
  2239   /* instance variables */                                                      \
  2240   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2241     obj,                                                                        \
  2242     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2243     (closure)->do_oop##nv_suffix(p),                                            \
  2244     assert_is_in_closed_subset)                                                 \
  2245    return size_helper();                                                        \
  2247 #endif // INCLUDE_ALL_GCS
  2249 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2251 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2252                                                   OopClosureType* closure, \
  2253                                                   MemRegion mr) {          \
  2254   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2255   if_do_metadata_checked(closure, nv_suffix) {                           \
  2256     if (mr.contains(obj)) {                                              \
  2257       closure->do_klass##nv_suffix(obj->klass());                        \
  2258     }                                                                    \
  2259   }                                                                      \
  2260   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2261     obj, mr.start(), mr.end(),                                           \
  2262     (closure)->do_oop##nv_suffix(p),                                     \
  2263     assert_is_in_closed_subset)                                          \
  2264   return size_helper();                                                  \
  2267 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2268 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2269 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2270 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2271 #if INCLUDE_ALL_GCS
  2272 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2273 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2274 #endif // INCLUDE_ALL_GCS
  2276 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2277   int size = size_helper();
  2278   InstanceKlass_OOP_MAP_ITERATE( \
  2279     obj, \
  2280     MarkSweep::adjust_pointer(p), \
  2281     assert_is_in)
  2282   return size;
  2285 #if INCLUDE_ALL_GCS
  2286 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2287   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2288     obj, \
  2289     if (PSScavenge::should_scavenge(p)) { \
  2290       pm->claim_or_forward_depth(p); \
  2291     }, \
  2292     assert_nothing )
  2295 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2296   int size = size_helper();
  2297   InstanceKlass_OOP_MAP_ITERATE( \
  2298     obj, \
  2299     PSParallelCompact::adjust_pointer(p), \
  2300     assert_is_in)
  2301   return size;
  2304 #endif // INCLUDE_ALL_GCS
  2306 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2307   assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
  2308   if (is_interface()) {
  2309     if (ClassUnloading) {
  2310       Klass* impl = implementor();
  2311       if (impl != NULL) {
  2312         if (!impl->is_loader_alive(is_alive)) {
  2313           // remove this guy
  2314           Klass** klass = adr_implementor();
  2315           assert(klass != NULL, "null klass");
  2316           if (klass != NULL) {
  2317             *klass = NULL;
  2325 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2326   for (int m = 0; m < methods()->length(); m++) {
  2327     MethodData* mdo = methods()->at(m)->method_data();
  2328     if (mdo != NULL) {
  2329       mdo->clean_method_data(is_alive);
  2335 static void remove_unshareable_in_class(Klass* k) {
  2336   // remove klass's unshareable info
  2337   k->remove_unshareable_info();
  2340 void InstanceKlass::remove_unshareable_info() {
  2341   Klass::remove_unshareable_info();
  2342   // Unlink the class
  2343   if (is_linked()) {
  2344     unlink_class();
  2346   init_implementor();
  2348   constants()->remove_unshareable_info();
  2350   for (int i = 0; i < methods()->length(); i++) {
  2351     Method* m = methods()->at(i);
  2352     m->remove_unshareable_info();
  2355   // do array classes also.
  2356   array_klasses_do(remove_unshareable_in_class);
  2359 static void restore_unshareable_in_class(Klass* k, TRAPS) {
  2360   // Array classes have null protection domain.
  2361   // --> see ArrayKlass::complete_create_array_klass()
  2362   k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
  2365 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
  2366   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
  2367   instanceKlassHandle ik(THREAD, this);
  2369   Array<Method*>* methods = ik->methods();
  2370   int num_methods = methods->length();
  2371   for (int index2 = 0; index2 < num_methods; ++index2) {
  2372     methodHandle m(THREAD, methods->at(index2));
  2373     m->restore_unshareable_info(CHECK);
  2375   if (JvmtiExport::has_redefined_a_class()) {
  2376     // Reinitialize vtable because RedefineClasses may have changed some
  2377     // entries in this vtable for super classes so the CDS vtable might
  2378     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2379     // vtables in the shared system dictionary, only the main one.
  2380     // It also redefines the itable too so fix that too.
  2381     ResourceMark rm(THREAD);
  2382     ik->vtable()->initialize_vtable(false, CHECK);
  2383     ik->itable()->initialize_itable(false, CHECK);
  2386   // restore constant pool resolved references
  2387   ik->constants()->restore_unshareable_info(CHECK);
  2389   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2392 // returns true IFF is_in_error_state() has been changed as a result of this call.
  2393 bool InstanceKlass::check_sharing_error_state() {
  2394   assert(DumpSharedSpaces, "should only be called during dumping");
  2395   bool old_state = is_in_error_state();
  2397   if (!is_in_error_state()) {
  2398     bool bad = false;
  2399     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
  2400       if (sup->is_in_error_state()) {
  2401         bad = true;
  2402         break;
  2405     if (!bad) {
  2406       Array<Klass*>* interfaces = transitive_interfaces();
  2407       for (int i = 0; i < interfaces->length(); i++) {
  2408         Klass* iface = interfaces->at(i);
  2409         if (InstanceKlass::cast(iface)->is_in_error_state()) {
  2410           bad = true;
  2411           break;
  2416     if (bad) {
  2417       set_in_error_state();
  2421   return (old_state != is_in_error_state());
  2424 static void clear_all_breakpoints(Method* m) {
  2425   m->clear_all_breakpoints();
  2429 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
  2430   // notify the debugger
  2431   if (JvmtiExport::should_post_class_unload()) {
  2432     JvmtiExport::post_class_unload(ik);
  2435   // notify ClassLoadingService of class unload
  2436   ClassLoadingService::notify_class_unloaded(ik);
  2439 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
  2440   // Clean up C heap
  2441   ik->release_C_heap_structures();
  2442   ik->constants()->release_C_heap_structures();
  2445 void InstanceKlass::release_C_heap_structures() {
  2447   // Can't release the constant pool here because the constant pool can be
  2448   // deallocated separately from the InstanceKlass for default methods and
  2449   // redefine classes.
  2451   // Deallocate oop map cache
  2452   if (_oop_map_cache != NULL) {
  2453     delete _oop_map_cache;
  2454     _oop_map_cache = NULL;
  2457   // Deallocate JNI identifiers for jfieldIDs
  2458   JNIid::deallocate(jni_ids());
  2459   set_jni_ids(NULL);
  2461   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2462   if (jmeths != (jmethodID*)NULL) {
  2463     release_set_methods_jmethod_ids(NULL);
  2464     FreeHeap(jmeths);
  2467   // Deallocate MemberNameTable
  2469     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
  2470     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
  2471     MemberNameTable* mnt = member_names();
  2472     if (mnt != NULL) {
  2473       delete mnt;
  2474       set_member_names(NULL);
  2478   // release dependencies
  2479   nmethodBucket* b = _dependencies;
  2480   _dependencies = NULL;
  2481   while (b != NULL) {
  2482     nmethodBucket* next = b->next();
  2483     delete b;
  2484     b = next;
  2487   // Deallocate breakpoint records
  2488   if (breakpoints() != 0x0) {
  2489     methods_do(clear_all_breakpoints);
  2490     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2493   // deallocate information about previous versions
  2494   if (_previous_versions != NULL) {
  2495     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2496       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2497       delete pv_node;
  2499     delete _previous_versions;
  2500     _previous_versions = NULL;
  2503   // deallocate the cached class file
  2504   if (_cached_class_file != NULL) {
  2505     os::free(_cached_class_file, mtClass);
  2506     _cached_class_file = NULL;
  2509   // Decrement symbol reference counts associated with the unloaded class.
  2510   if (_name != NULL) _name->decrement_refcount();
  2511   // unreference array name derived from this class name (arrays of an unloaded
  2512   // class can't be referenced anymore).
  2513   if (_array_name != NULL)  _array_name->decrement_refcount();
  2514   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2516   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2517   Atomic::dec(&_total_instanceKlass_count);
  2520 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2521   if (array == NULL) {
  2522     _source_debug_extension = NULL;
  2523   } else {
  2524     // Adding one to the attribute length in order to store a null terminator
  2525     // character could cause an overflow because the attribute length is
  2526     // already coded with an u4 in the classfile, but in practice, it's
  2527     // unlikely to happen.
  2528     assert((length+1) > length, "Overflow checking");
  2529     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2530     for (int i = 0; i < length; i++) {
  2531       sde[i] = array[i];
  2533     sde[length] = '\0';
  2534     _source_debug_extension = sde;
  2538 address InstanceKlass::static_field_addr(int offset) {
  2539   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
  2543 const char* InstanceKlass::signature_name() const {
  2544   int hash_len = 0;
  2545   char hash_buf[40];
  2547   // If this is an anonymous class, append a hash to make the name unique
  2548   if (is_anonymous()) {
  2549     assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
  2550     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
  2551     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
  2552     hash_len = (int)strlen(hash_buf);
  2555   // Get the internal name as a c string
  2556   const char* src = (const char*) (name()->as_C_string());
  2557   const int src_length = (int)strlen(src);
  2559   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
  2561   // Add L as type indicator
  2562   int dest_index = 0;
  2563   dest[dest_index++] = 'L';
  2565   // Add the actual class name
  2566   for (int src_index = 0; src_index < src_length; ) {
  2567     dest[dest_index++] = src[src_index++];
  2570   // If we have a hash, append it
  2571   for (int hash_index = 0; hash_index < hash_len; ) {
  2572     dest[dest_index++] = hash_buf[hash_index++];
  2575   // Add the semicolon and the NULL
  2576   dest[dest_index++] = ';';
  2577   dest[dest_index] = '\0';
  2578   return dest;
  2581 // different verisons of is_same_class_package
  2582 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2583   Klass* class1 = this;
  2584   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2585   Symbol* classname1 = class1->name();
  2587   if (class2->oop_is_objArray()) {
  2588     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2590   oop classloader2;
  2591   if (class2->oop_is_instance()) {
  2592     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2593   } else {
  2594     assert(class2->oop_is_typeArray(), "should be type array");
  2595     classloader2 = NULL;
  2597   Symbol* classname2 = class2->name();
  2599   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2600                                               classloader2, classname2);
  2603 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2604   Klass* class1 = this;
  2605   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2606   Symbol* classname1 = class1->name();
  2608   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2609                                               classloader2, classname2);
  2612 // return true if two classes are in the same package, classloader
  2613 // and classname information is enough to determine a class's package
  2614 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2615                                           oop class_loader2, Symbol* class_name2) {
  2616   if (class_loader1 != class_loader2) {
  2617     return false;
  2618   } else if (class_name1 == class_name2) {
  2619     return true;                // skip painful bytewise comparison
  2620   } else {
  2621     ResourceMark rm;
  2623     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2624     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2625     // Otherwise, we just compare jbyte values between the strings.
  2626     const jbyte *name1 = class_name1->base();
  2627     const jbyte *name2 = class_name2->base();
  2629     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2630     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2632     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2633       // One of the two doesn't have a package.  Only return true
  2634       // if the other one also doesn't have a package.
  2635       return last_slash1 == last_slash2;
  2636     } else {
  2637       // Skip over '['s
  2638       if (*name1 == '[') {
  2639         do {
  2640           name1++;
  2641         } while (*name1 == '[');
  2642         if (*name1 != 'L') {
  2643           // Something is terribly wrong.  Shouldn't be here.
  2644           return false;
  2647       if (*name2 == '[') {
  2648         do {
  2649           name2++;
  2650         } while (*name2 == '[');
  2651         if (*name2 != 'L') {
  2652           // Something is terribly wrong.  Shouldn't be here.
  2653           return false;
  2657       // Check that package part is identical
  2658       int length1 = last_slash1 - name1;
  2659       int length2 = last_slash2 - name2;
  2661       return UTF8::equal(name1, length1, name2, length2);
  2666 // Returns true iff super_method can be overridden by a method in targetclassname
  2667 // See JSL 3rd edition 8.4.6.1
  2668 // Assumes name-signature match
  2669 // "this" is InstanceKlass of super_method which must exist
  2670 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2671 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2672    // Private methods can not be overridden
  2673    if (super_method->is_private()) {
  2674      return false;
  2676    // If super method is accessible, then override
  2677    if ((super_method->is_protected()) ||
  2678        (super_method->is_public())) {
  2679      return true;
  2681    // Package-private methods are not inherited outside of package
  2682    assert(super_method->is_package_private(), "must be package private");
  2683    return(is_same_class_package(targetclassloader(), targetclassname));
  2686 /* defined for now in jvm.cpp, for historical reasons *--
  2687 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2688                                                      Symbol*& simple_name_result, TRAPS) {
  2689   ...
  2691 */
  2693 // tell if two classes have the same enclosing class (at package level)
  2694 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2695                                                 Klass* class2_oop, TRAPS) {
  2696   if (class2_oop == class1())                       return true;
  2697   if (!class2_oop->oop_is_instance())  return false;
  2698   instanceKlassHandle class2(THREAD, class2_oop);
  2700   // must be in same package before we try anything else
  2701   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2702     return false;
  2704   // As long as there is an outer1.getEnclosingClass,
  2705   // shift the search outward.
  2706   instanceKlassHandle outer1 = class1;
  2707   for (;;) {
  2708     // As we walk along, look for equalities between outer1 and class2.
  2709     // Eventually, the walks will terminate as outer1 stops
  2710     // at the top-level class around the original class.
  2711     bool ignore_inner_is_member;
  2712     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2713                                                     CHECK_false);
  2714     if (next == NULL)  break;
  2715     if (next == class2())  return true;
  2716     outer1 = instanceKlassHandle(THREAD, next);
  2719   // Now do the same for class2.
  2720   instanceKlassHandle outer2 = class2;
  2721   for (;;) {
  2722     bool ignore_inner_is_member;
  2723     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2724                                                     CHECK_false);
  2725     if (next == NULL)  break;
  2726     // Might as well check the new outer against all available values.
  2727     if (next == class1())  return true;
  2728     if (next == outer1())  return true;
  2729     outer2 = instanceKlassHandle(THREAD, next);
  2732   // If by this point we have not found an equality between the
  2733   // two classes, we know they are in separate package members.
  2734   return false;
  2738 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2739   jint access = access_flags().as_int();
  2741   // But check if it happens to be member class.
  2742   instanceKlassHandle ik(THREAD, this);
  2743   InnerClassesIterator iter(ik);
  2744   for (; !iter.done(); iter.next()) {
  2745     int ioff = iter.inner_class_info_index();
  2746     // Inner class attribute can be zero, skip it.
  2747     // Strange but true:  JVM spec. allows null inner class refs.
  2748     if (ioff == 0) continue;
  2750     // only look at classes that are already loaded
  2751     // since we are looking for the flags for our self.
  2752     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2753     if ((ik->name() == inner_name)) {
  2754       // This is really a member class.
  2755       access = iter.inner_access_flags();
  2756       break;
  2759   // Remember to strip ACC_SUPER bit
  2760   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2763 jint InstanceKlass::jvmti_class_status() const {
  2764   jint result = 0;
  2766   if (is_linked()) {
  2767     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2770   if (is_initialized()) {
  2771     assert(is_linked(), "Class status is not consistent");
  2772     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2774   if (is_in_error_state()) {
  2775     result |= JVMTI_CLASS_STATUS_ERROR;
  2777   return result;
  2780 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2781   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2782   int method_table_offset_in_words = ioe->offset()/wordSize;
  2783   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2784                        / itableOffsetEntry::size();
  2786   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2787     // If the interface isn't implemented by the receiver class,
  2788     // the VM should throw IncompatibleClassChangeError.
  2789     if (cnt >= nof_interfaces) {
  2790       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2793     Klass* ik = ioe->interface_klass();
  2794     if (ik == holder) break;
  2797   itableMethodEntry* ime = ioe->first_method_entry(this);
  2798   Method* m = ime[index].method();
  2799   if (m == NULL) {
  2800     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2802   return m;
  2806 #if INCLUDE_JVMTI
  2807 // update default_methods for redefineclasses for methods that are
  2808 // not yet in the vtable due to concurrent subclass define and superinterface
  2809 // redefinition
  2810 // Note: those in the vtable, should have been updated via adjust_method_entries
  2811 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
  2812   // search the default_methods for uses of either obsolete or EMCP methods
  2813   if (default_methods() != NULL) {
  2814     for (int index = 0; index < default_methods()->length(); index ++) {
  2815       Method* old_method = default_methods()->at(index);
  2816       if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
  2817         continue; // skip uninteresting entries
  2819       assert(!old_method->is_deleted(), "default methods may not be deleted");
  2821       Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
  2823       assert(new_method != NULL, "method_with_idnum() should not be NULL");
  2824       assert(old_method != new_method, "sanity check");
  2826       default_methods()->at_put(index, new_method);
  2827       if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
  2828         if (!(*trace_name_printed)) {
  2829           // RC_TRACE_MESG macro has an embedded ResourceMark
  2830           RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
  2831                          external_name(),
  2832                          old_method->method_holder()->external_name()));
  2833           *trace_name_printed = true;
  2835         RC_TRACE(0x00100000, ("default method update: %s(%s) ",
  2836                               new_method->name()->as_C_string(),
  2837                               new_method->signature()->as_C_string()));
  2842 #endif // INCLUDE_JVMTI
  2844 // On-stack replacement stuff
  2845 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2846   // only one compilation can be active
  2847   NEEDS_CLEANUP
  2848   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2849   OsrList_lock->lock_without_safepoint_check();
  2850   assert(n->is_osr_method(), "wrong kind of nmethod");
  2851   n->set_osr_link(osr_nmethods_head());
  2852   set_osr_nmethods_head(n);
  2853   // Raise the highest osr level if necessary
  2854   if (TieredCompilation) {
  2855     Method* m = n->method();
  2856     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2858   // Remember to unlock again
  2859   OsrList_lock->unlock();
  2861   // Get rid of the osr methods for the same bci that have lower levels.
  2862   if (TieredCompilation) {
  2863     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2864       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2865       if (inv != NULL && inv->is_in_use()) {
  2866         inv->make_not_entrant();
  2873 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2874   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2875   OsrList_lock->lock_without_safepoint_check();
  2876   assert(n->is_osr_method(), "wrong kind of nmethod");
  2877   nmethod* last = NULL;
  2878   nmethod* cur  = osr_nmethods_head();
  2879   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2880   Method* m = n->method();
  2881   // Search for match
  2882   while(cur != NULL && cur != n) {
  2883     if (TieredCompilation && m == cur->method()) {
  2884       // Find max level before n
  2885       max_level = MAX2(max_level, cur->comp_level());
  2887     last = cur;
  2888     cur = cur->osr_link();
  2890   nmethod* next = NULL;
  2891   if (cur == n) {
  2892     next = cur->osr_link();
  2893     if (last == NULL) {
  2894       // Remove first element
  2895       set_osr_nmethods_head(next);
  2896     } else {
  2897       last->set_osr_link(next);
  2900   n->set_osr_link(NULL);
  2901   if (TieredCompilation) {
  2902     cur = next;
  2903     while (cur != NULL) {
  2904       // Find max level after n
  2905       if (m == cur->method()) {
  2906         max_level = MAX2(max_level, cur->comp_level());
  2908       cur = cur->osr_link();
  2910     m->set_highest_osr_comp_level(max_level);
  2912   // Remember to unlock again
  2913   OsrList_lock->unlock();
  2916 int InstanceKlass::mark_osr_nmethods(const Method* m) {
  2917   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2918   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
  2919   nmethod* osr = osr_nmethods_head();
  2920   int found = 0;
  2921   while (osr != NULL) {
  2922     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2923     if (osr->method() == m) {
  2924       osr->mark_for_deoptimization();
  2925       found++;
  2927     osr = osr->osr_link();
  2929   return found;
  2932 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
  2933   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2934   OsrList_lock->lock_without_safepoint_check();
  2935   nmethod* osr = osr_nmethods_head();
  2936   nmethod* best = NULL;
  2937   while (osr != NULL) {
  2938     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2939     // There can be a time when a c1 osr method exists but we are waiting
  2940     // for a c2 version. When c2 completes its osr nmethod we will trash
  2941     // the c1 version and only be able to find the c2 version. However
  2942     // while we overflow in the c1 code at back branches we don't want to
  2943     // try and switch to the same code as we are already running
  2945     if (osr->method() == m &&
  2946         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2947       if (match_level) {
  2948         if (osr->comp_level() == comp_level) {
  2949           // Found a match - return it.
  2950           OsrList_lock->unlock();
  2951           return osr;
  2953       } else {
  2954         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  2955           if (osr->comp_level() == CompLevel_highest_tier) {
  2956             // Found the best possible - return it.
  2957             OsrList_lock->unlock();
  2958             return osr;
  2960           best = osr;
  2964     osr = osr->osr_link();
  2966   OsrList_lock->unlock();
  2967   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  2968     return best;
  2970   return NULL;
  2973 bool InstanceKlass::add_member_name(Handle mem_name) {
  2974   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  2975   MutexLocker ml(MemberNameTable_lock);
  2976   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  2978   // Check if method has been redefined while taking out MemberNameTable_lock, if so
  2979   // return false.  We cannot cache obsolete methods. They will crash when the function
  2980   // is called!
  2981   Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
  2982   if (method->is_obsolete()) {
  2983     return false;
  2984   } else if (method->is_old()) {
  2985     // Replace method with redefined version
  2986     java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
  2989   if (_member_names == NULL) {
  2990     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
  2992   _member_names->add_member_name(mem_name_wref);
  2993   return true;
  2996 // -----------------------------------------------------------------------------------------------------
  2997 // Printing
  2999 #ifndef PRODUCT
  3001 #define BULLET  " - "
  3003 static const char* state_names[] = {
  3004   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  3005 };
  3007 static void print_vtable(intptr_t* start, int len, outputStream* st) {
  3008   for (int i = 0; i < len; i++) {
  3009     intptr_t e = start[i];
  3010     st->print("%d : " INTPTR_FORMAT, i, e);
  3011     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
  3012       st->print(" ");
  3013       ((Metadata*)e)->print_value_on(st);
  3015     st->cr();
  3019 void InstanceKlass::print_on(outputStream* st) const {
  3020   assert(is_klass(), "must be klass");
  3021   Klass::print_on(st);
  3023   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  3024   st->print(BULLET"klass size:        %d", size());                               st->cr();
  3025   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  3026   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
  3027   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  3028   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  3029   st->print(BULLET"sub:               ");
  3030   Klass* sub = subklass();
  3031   int n;
  3032   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  3033     if (n < MaxSubklassPrintSize) {
  3034       sub->print_value_on(st);
  3035       st->print("   ");
  3038   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  3039   st->cr();
  3041   if (is_interface()) {
  3042     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  3043     if (nof_implementors() == 1) {
  3044       st->print_cr(BULLET"implementor:    ");
  3045       st->print("   ");
  3046       implementor()->print_value_on(st);
  3047       st->cr();
  3051   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  3052   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  3053   if (Verbose || WizardMode) {
  3054     Array<Method*>* method_array = methods();
  3055     for (int i = 0; i < method_array->length(); i++) {
  3056       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  3059   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
  3060   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
  3061   if (Verbose && default_methods() != NULL) {
  3062     Array<Method*>* method_array = default_methods();
  3063     for (int i = 0; i < method_array->length(); i++) {
  3064       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  3067   if (default_vtable_indices() != NULL) {
  3068     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
  3070   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  3071   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  3072   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  3073   if (class_loader_data() != NULL) {
  3074     st->print(BULLET"class loader data:  ");
  3075     class_loader_data()->print_value_on(st);
  3076     st->cr();
  3078   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  3079   if (source_file_name() != NULL) {
  3080     st->print(BULLET"source file:       ");
  3081     source_file_name()->print_value_on(st);
  3082     st->cr();
  3084   if (source_debug_extension() != NULL) {
  3085     st->print(BULLET"source debug extension:       ");
  3086     st->print("%s", source_debug_extension());
  3087     st->cr();
  3089   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  3090   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  3091   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  3092   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  3094     bool have_pv = false;
  3095     PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  3096     for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  3097          pv_node != NULL; pv_node = pvw.next_previous_version()) {
  3098       if (!have_pv)
  3099         st->print(BULLET"previous version:  ");
  3100       have_pv = true;
  3101       pv_node->prev_constant_pool()->print_value_on(st);
  3103     if (have_pv) st->cr();
  3104   } // pvw is cleaned up
  3106   if (generic_signature() != NULL) {
  3107     st->print(BULLET"generic signature: ");
  3108     generic_signature()->print_value_on(st);
  3109     st->cr();
  3111   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  3112   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  3113   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  3114   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
  3115   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  3116   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
  3117   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  3118   FieldPrinter print_static_field(st);
  3119   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  3120   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  3121   FieldPrinter print_nonstatic_field(st);
  3122   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  3124   st->print(BULLET"non-static oop maps: ");
  3125   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  3126   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  3127   while (map < end_map) {
  3128     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  3129     map++;
  3131   st->cr();
  3134 #endif //PRODUCT
  3136 void InstanceKlass::print_value_on(outputStream* st) const {
  3137   assert(is_klass(), "must be klass");
  3138   if (Verbose || WizardMode)  access_flags().print_on(st);
  3139   name()->print_value_on(st);
  3142 #ifndef PRODUCT
  3144 void FieldPrinter::do_field(fieldDescriptor* fd) {
  3145   _st->print(BULLET);
  3146    if (_obj == NULL) {
  3147      fd->print_on(_st);
  3148      _st->cr();
  3149    } else {
  3150      fd->print_on_for(_st, _obj);
  3151      _st->cr();
  3156 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  3157   Klass::oop_print_on(obj, st);
  3159   if (this == SystemDictionary::String_klass()) {
  3160     typeArrayOop value  = java_lang_String::value(obj);
  3161     juint        offset = java_lang_String::offset(obj);
  3162     juint        length = java_lang_String::length(obj);
  3163     if (value != NULL &&
  3164         value->is_typeArray() &&
  3165         offset          <= (juint) value->length() &&
  3166         offset + length <= (juint) value->length()) {
  3167       st->print(BULLET"string: ");
  3168       java_lang_String::print(obj, st);
  3169       st->cr();
  3170       if (!WizardMode)  return;  // that is enough
  3174   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  3175   FieldPrinter print_field(st, obj);
  3176   do_nonstatic_fields(&print_field);
  3178   if (this == SystemDictionary::Class_klass()) {
  3179     st->print(BULLET"signature: ");
  3180     java_lang_Class::print_signature(obj, st);
  3181     st->cr();
  3182     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  3183     st->print(BULLET"fake entry for mirror: ");
  3184     mirrored_klass->print_value_on_maybe_null(st);
  3185     st->cr();
  3186     Klass* array_klass = java_lang_Class::array_klass(obj);
  3187     st->print(BULLET"fake entry for array: ");
  3188     array_klass->print_value_on_maybe_null(st);
  3189     st->cr();
  3190     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  3191     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  3192     Klass* real_klass = java_lang_Class::as_Klass(obj);
  3193     if (real_klass != NULL && real_klass->oop_is_instance()) {
  3194       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  3196   } else if (this == SystemDictionary::MethodType_klass()) {
  3197     st->print(BULLET"signature: ");
  3198     java_lang_invoke_MethodType::print_signature(obj, st);
  3199     st->cr();
  3203 #endif //PRODUCT
  3205 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  3206   st->print("a ");
  3207   name()->print_value_on(st);
  3208   obj->print_address_on(st);
  3209   if (this == SystemDictionary::String_klass()
  3210       && java_lang_String::value(obj) != NULL) {
  3211     ResourceMark rm;
  3212     int len = java_lang_String::length(obj);
  3213     int plen = (len < 24 ? len : 12);
  3214     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  3215     st->print(" = \"%s\"", str);
  3216     if (len > plen)
  3217       st->print("...[%d]", len);
  3218   } else if (this == SystemDictionary::Class_klass()) {
  3219     Klass* k = java_lang_Class::as_Klass(obj);
  3220     st->print(" = ");
  3221     if (k != NULL) {
  3222       k->print_value_on(st);
  3223     } else {
  3224       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  3225       st->print("%s", tname ? tname : "type?");
  3227   } else if (this == SystemDictionary::MethodType_klass()) {
  3228     st->print(" = ");
  3229     java_lang_invoke_MethodType::print_signature(obj, st);
  3230   } else if (java_lang_boxing_object::is_instance(obj)) {
  3231     st->print(" = ");
  3232     java_lang_boxing_object::print(obj, st);
  3233   } else if (this == SystemDictionary::LambdaForm_klass()) {
  3234     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  3235     if (vmentry != NULL) {
  3236       st->print(" => ");
  3237       vmentry->print_value_on(st);
  3239   } else if (this == SystemDictionary::MemberName_klass()) {
  3240     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  3241     if (vmtarget != NULL) {
  3242       st->print(" = ");
  3243       vmtarget->print_value_on(st);
  3244     } else {
  3245       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  3246       st->print(".");
  3247       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  3252 const char* InstanceKlass::internal_name() const {
  3253   return external_name();
  3256 #if INCLUDE_SERVICES
  3257 // Size Statistics
  3258 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  3259   Klass::collect_statistics(sz);
  3261   sz->_inst_size  = HeapWordSize * size_helper();
  3262   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  3263   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  3264   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  3265         ((is_interface() || is_anonymous()) ?
  3266          align_object_offset(nonstatic_oop_map_size()) :
  3267          nonstatic_oop_map_size());
  3269   int n = 0;
  3270   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  3271   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  3272   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  3273   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  3274   n += (sz->_fields_bytes                = sz->count_array(fields()));
  3275   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  3276   sz->_ro_bytes += n;
  3278   const ConstantPool* cp = constants();
  3279   if (cp) {
  3280     cp->collect_statistics(sz);
  3283   const Annotations* anno = annotations();
  3284   if (anno) {
  3285     anno->collect_statistics(sz);
  3288   const Array<Method*>* methods_array = methods();
  3289   if (methods()) {
  3290     for (int i = 0; i < methods_array->length(); i++) {
  3291       Method* method = methods_array->at(i);
  3292       if (method) {
  3293         sz->_method_count ++;
  3294         method->collect_statistics(sz);
  3299 #endif // INCLUDE_SERVICES
  3301 // Verification
  3303 class VerifyFieldClosure: public OopClosure {
  3304  protected:
  3305   template <class T> void do_oop_work(T* p) {
  3306     oop obj = oopDesc::load_decode_heap_oop(p);
  3307     if (!obj->is_oop_or_null()) {
  3308       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  3309       Universe::print();
  3310       guarantee(false, "boom");
  3313  public:
  3314   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  3315   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  3316 };
  3318 void InstanceKlass::verify_on(outputStream* st) {
  3319 #ifndef PRODUCT
  3320   // Avoid redundant verifies, this really should be in product.
  3321   if (_verify_count == Universe::verify_count()) return;
  3322   _verify_count = Universe::verify_count();
  3323 #endif
  3325   // Verify Klass
  3326   Klass::verify_on(st);
  3328   // Verify that klass is present in ClassLoaderData
  3329   guarantee(class_loader_data()->contains_klass(this),
  3330             "this class isn't found in class loader data");
  3332   // Verify vtables
  3333   if (is_linked()) {
  3334     ResourceMark rm;
  3335     // $$$ This used to be done only for m/s collections.  Doing it
  3336     // always seemed a valid generalization.  (DLD -- 6/00)
  3337     vtable()->verify(st);
  3340   // Verify first subklass
  3341   if (subklass_oop() != NULL) {
  3342     guarantee(subklass_oop()->is_klass(), "should be klass");
  3345   // Verify siblings
  3346   Klass* super = this->super();
  3347   Klass* sib = next_sibling();
  3348   if (sib != NULL) {
  3349     if (sib == this) {
  3350       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3353     guarantee(sib->is_klass(), "should be klass");
  3354     guarantee(sib->super() == super, "siblings should have same superklass");
  3357   // Verify implementor fields
  3358   Klass* im = implementor();
  3359   if (im != NULL) {
  3360     guarantee(is_interface(), "only interfaces should have implementor set");
  3361     guarantee(im->is_klass(), "should be klass");
  3362     guarantee(!im->is_interface() || im == this,
  3363       "implementors cannot be interfaces");
  3366   // Verify local interfaces
  3367   if (local_interfaces()) {
  3368     Array<Klass*>* local_interfaces = this->local_interfaces();
  3369     for (int j = 0; j < local_interfaces->length(); j++) {
  3370       Klass* e = local_interfaces->at(j);
  3371       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3375   // Verify transitive interfaces
  3376   if (transitive_interfaces() != NULL) {
  3377     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3378     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3379       Klass* e = transitive_interfaces->at(j);
  3380       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3384   // Verify methods
  3385   if (methods() != NULL) {
  3386     Array<Method*>* methods = this->methods();
  3387     for (int j = 0; j < methods->length(); j++) {
  3388       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3390     for (int j = 0; j < methods->length() - 1; j++) {
  3391       Method* m1 = methods->at(j);
  3392       Method* m2 = methods->at(j + 1);
  3393       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3397   // Verify method ordering
  3398   if (method_ordering() != NULL) {
  3399     Array<int>* method_ordering = this->method_ordering();
  3400     int length = method_ordering->length();
  3401     if (JvmtiExport::can_maintain_original_method_order() ||
  3402         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
  3403       guarantee(length == methods()->length(), "invalid method ordering length");
  3404       jlong sum = 0;
  3405       for (int j = 0; j < length; j++) {
  3406         int original_index = method_ordering->at(j);
  3407         guarantee(original_index >= 0, "invalid method ordering index");
  3408         guarantee(original_index < length, "invalid method ordering index");
  3409         sum += original_index;
  3411       // Verify sum of indices 0,1,...,length-1
  3412       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3413     } else {
  3414       guarantee(length == 0, "invalid method ordering length");
  3418   // Verify default methods
  3419   if (default_methods() != NULL) {
  3420     Array<Method*>* methods = this->default_methods();
  3421     for (int j = 0; j < methods->length(); j++) {
  3422       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3424     for (int j = 0; j < methods->length() - 1; j++) {
  3425       Method* m1 = methods->at(j);
  3426       Method* m2 = methods->at(j + 1);
  3427       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3431   // Verify JNI static field identifiers
  3432   if (jni_ids() != NULL) {
  3433     jni_ids()->verify(this);
  3436   // Verify other fields
  3437   if (array_klasses() != NULL) {
  3438     guarantee(array_klasses()->is_klass(), "should be klass");
  3440   if (constants() != NULL) {
  3441     guarantee(constants()->is_constantPool(), "should be constant pool");
  3443   const Klass* host = host_klass();
  3444   if (host != NULL) {
  3445     guarantee(host->is_klass(), "should be klass");
  3449 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3450   Klass::oop_verify_on(obj, st);
  3451   VerifyFieldClosure blk;
  3452   obj->oop_iterate_no_header(&blk);
  3456 // JNIid class for jfieldIDs only
  3457 // Note to reviewers:
  3458 // These JNI functions are just moved over to column 1 and not changed
  3459 // in the compressed oops workspace.
  3460 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3461   _holder = holder;
  3462   _offset = offset;
  3463   _next = next;
  3464   debug_only(_is_static_field_id = false;)
  3468 JNIid* JNIid::find(int offset) {
  3469   JNIid* current = this;
  3470   while (current != NULL) {
  3471     if (current->offset() == offset) return current;
  3472     current = current->next();
  3474   return NULL;
  3477 void JNIid::deallocate(JNIid* current) {
  3478   while (current != NULL) {
  3479     JNIid* next = current->next();
  3480     delete current;
  3481     current = next;
  3486 void JNIid::verify(Klass* holder) {
  3487   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3488   int end_field_offset;
  3489   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3491   JNIid* current = this;
  3492   while (current != NULL) {
  3493     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3494 #ifdef ASSERT
  3495     int o = current->offset();
  3496     if (current->is_static_field_id()) {
  3497       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3499 #endif
  3500     current = current->next();
  3505 #ifdef ASSERT
  3506 void InstanceKlass::set_init_state(ClassState state) {
  3507   bool good_state = is_shared() ? (_init_state <= state)
  3508                                                : (_init_state < state);
  3509   assert(good_state || state == allocated, "illegal state transition");
  3510   _init_state = (u1)state;
  3512 #endif
  3515 // RedefineClasses() support for previous versions:
  3517 // Purge previous versions
  3518 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3519   if (ik->previous_versions() != NULL) {
  3520     // This klass has previous versions so see what we can cleanup
  3521     // while it is safe to do so.
  3523     int deleted_count = 0;    // leave debugging breadcrumbs
  3524     int live_count = 0;
  3525     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3526                        ClassLoaderData::the_null_class_loader_data() :
  3527                        ik->class_loader_data();
  3529     // RC_TRACE macro has an embedded ResourceMark
  3530     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3531       ik->external_name(), ik->previous_versions()->length()));
  3533     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3534       // check the previous versions array
  3535       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3536       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3537       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3539       ConstantPool* pvcp = cp_ref;
  3540       if (!pvcp->on_stack()) {
  3541         // If the constant pool isn't on stack, none of the methods
  3542         // are executing.  Delete all the methods, the constant pool and
  3543         // and this previous version node.
  3544         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3545         if (method_refs != NULL) {
  3546           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3547             Method* method = method_refs->at(j);
  3548             assert(method != NULL, "method ref was unexpectedly cleared");
  3549             method_refs->remove_at(j);
  3550             // method will be freed with associated class.
  3553         // Remove the constant pool
  3554         delete pv_node;
  3555         // Since we are traversing the array backwards, we don't have to
  3556         // do anything special with the index.
  3557         ik->previous_versions()->remove_at(i);
  3558         deleted_count++;
  3559         continue;
  3560       } else {
  3561         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3562         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3563         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3564         live_count++;
  3567       // At least one method is live in this previous version, clean out
  3568       // the others or mark them as obsolete.
  3569       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3570       if (method_refs != NULL) {
  3571         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3572           method_refs->length()));
  3573         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3574           Method* method = method_refs->at(j);
  3575           assert(method != NULL, "method ref was unexpectedly cleared");
  3577           // Remove the emcp method if it's not executing
  3578           // If it's been made obsolete by a redefinition of a non-emcp
  3579           // method, mark it as obsolete but leave it to clean up later.
  3580           if (!method->on_stack()) {
  3581             method_refs->remove_at(j);
  3582           } else if (emcp_method_count == 0) {
  3583             method->set_is_obsolete();
  3584           } else {
  3585             // RC_TRACE macro has an embedded ResourceMark
  3586             RC_TRACE(0x00000200,
  3587               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3588               method->name()->as_C_string(),
  3589               method->signature()->as_C_string(), j, i));
  3594     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3595     RC_TRACE(0x00000200,
  3596       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3597       deleted_count));
  3601 // External interface for use during class unloading.
  3602 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3603   // Call with >0 emcp methods since they are not currently being redefined.
  3604   purge_previous_versions_internal(ik, 1);
  3608 // Potentially add an information node that contains pointers to the
  3609 // interesting parts of the previous version of the_class.
  3610 // This is also where we clean out any unused references.
  3611 // Note that while we delete nodes from the _previous_versions
  3612 // array, we never delete the array itself until the klass is
  3613 // unloaded. The has_been_redefined() query depends on that fact.
  3614 //
  3615 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3616        BitMap* emcp_methods, int emcp_method_count) {
  3617   assert(Thread::current()->is_VM_thread(),
  3618          "only VMThread can add previous versions");
  3620   if (_previous_versions == NULL) {
  3621     // This is the first previous version so make some space.
  3622     // Start with 2 elements under the assumption that the class
  3623     // won't be redefined much.
  3624     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3625                             GrowableArray<PreviousVersionNode *>(2, true);
  3628   ConstantPool* cp_ref = ikh->constants();
  3630   // RC_TRACE macro has an embedded ResourceMark
  3631   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3632                         "on_stack=%d",
  3633     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3634     cp_ref->on_stack()));
  3636   // If the constant pool for this previous version of the class
  3637   // is not marked as being on the stack, then none of the methods
  3638   // in this previous version of the class are on the stack so
  3639   // we don't need to create a new PreviousVersionNode. However,
  3640   // we still need to examine older previous versions below.
  3641   Array<Method*>* old_methods = ikh->methods();
  3643   if (cp_ref->on_stack()) {
  3644     PreviousVersionNode * pv_node = NULL;
  3645     if (emcp_method_count == 0) {
  3646       // non-shared ConstantPool gets a reference
  3647       pv_node = new PreviousVersionNode(cp_ref, NULL);
  3648       RC_TRACE(0x00000400,
  3649           ("add: all methods are obsolete; flushing any EMCP refs"));
  3650     } else {
  3651       int local_count = 0;
  3652       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3653           GrowableArray<Method*>(emcp_method_count, true);
  3654       for (int i = 0; i < old_methods->length(); i++) {
  3655         if (emcp_methods->at(i)) {
  3656             // this old method is EMCP. Save it only if it's on the stack
  3657             Method* old_method = old_methods->at(i);
  3658             if (old_method->on_stack()) {
  3659               method_refs->append(old_method);
  3661           if (++local_count >= emcp_method_count) {
  3662             // no more EMCP methods so bail out now
  3663             break;
  3667       // non-shared ConstantPool gets a reference
  3668       pv_node = new PreviousVersionNode(cp_ref, method_refs);
  3670     // append new previous version.
  3671     _previous_versions->append(pv_node);
  3674   // Since the caller is the VMThread and we are at a safepoint, this
  3675   // is a good time to clear out unused references.
  3677   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3678     _previous_versions->length()));
  3680   // Purge previous versions not executing on the stack
  3681   purge_previous_versions_internal(this, emcp_method_count);
  3683   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3685   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3686       _previous_versions->length() > 0) {
  3687     // We have a mix of obsolete and EMCP methods so we have to
  3688     // clear out any matching EMCP method entries the hard way.
  3689     int local_count = 0;
  3690     for (int i = 0; i < old_methods->length(); i++) {
  3691       if (!emcp_methods->at(i)) {
  3692         // only obsolete methods are interesting
  3693         Method* old_method = old_methods->at(i);
  3694         Symbol* m_name = old_method->name();
  3695         Symbol* m_signature = old_method->signature();
  3697         // we might not have added the last entry
  3698         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3699           // check the previous versions array for non executing obsolete methods
  3700           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3702           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3703           if (method_refs == NULL) {
  3704             // We have run into a PreviousVersion generation where
  3705             // all methods were made obsolete during that generation's
  3706             // RedefineClasses() operation. At the time of that
  3707             // operation, all EMCP methods were flushed so we don't
  3708             // have to go back any further.
  3709             //
  3710             // A NULL method_refs is different than an empty method_refs.
  3711             // We cannot infer any optimizations about older generations
  3712             // from an empty method_refs for the current generation.
  3713             break;
  3716           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3717             Method* method = method_refs->at(k);
  3719             if (!method->is_obsolete() &&
  3720                 method->name() == m_name &&
  3721                 method->signature() == m_signature) {
  3722               // The current RedefineClasses() call has made all EMCP
  3723               // versions of this method obsolete so mark it as obsolete
  3724               // and remove the reference.
  3725               RC_TRACE(0x00000400,
  3726                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3727                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3729               method->set_is_obsolete();
  3730               // Leave obsolete methods on the previous version list to
  3731               // clean up later.
  3732               break;
  3736           // The previous loop may not find a matching EMCP method, but
  3737           // that doesn't mean that we can optimize and not go any
  3738           // further back in the PreviousVersion generations. The EMCP
  3739           // method for this generation could have already been deleted,
  3740           // but there still may be an older EMCP method that has not
  3741           // been deleted.
  3744         if (++local_count >= obsolete_method_count) {
  3745           // no more obsolete methods so bail out now
  3746           break;
  3751 } // end add_previous_version()
  3754 // Determine if InstanceKlass has a previous version.
  3755 bool InstanceKlass::has_previous_version() const {
  3756   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3757 } // end has_previous_version()
  3760 InstanceKlass* InstanceKlass::get_klass_version(int version) {
  3761   if (constants()->version() == version) {
  3762     return this;
  3764   PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  3765   for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  3766        pv_node != NULL; pv_node = pvw.next_previous_version()) {
  3767     ConstantPool* prev_cp = pv_node->prev_constant_pool();
  3768     if (prev_cp->version() == version) {
  3769       return prev_cp->pool_holder();
  3772   return NULL; // None found
  3776 Method* InstanceKlass::method_with_idnum(int idnum) {
  3777   Method* m = NULL;
  3778   if (idnum < methods()->length()) {
  3779     m = methods()->at(idnum);
  3781   if (m == NULL || m->method_idnum() != idnum) {
  3782     for (int index = 0; index < methods()->length(); ++index) {
  3783       m = methods()->at(index);
  3784       if (m->method_idnum() == idnum) {
  3785         return m;
  3788     // None found, return null for the caller to handle.
  3789     return NULL;
  3791   return m;
  3795 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
  3796   if (idnum >= methods()->length()) {
  3797     return NULL;
  3799   Method* m = methods()->at(idnum);
  3800   if (m != NULL && m->orig_method_idnum() == idnum) {
  3801     return m;
  3803   // Obsolete method idnum does not match the original idnum
  3804   for (int index = 0; index < methods()->length(); ++index) {
  3805     m = methods()->at(index);
  3806     if (m->orig_method_idnum() == idnum) {
  3807       return m;
  3810   // None found, return null for the caller to handle.
  3811   return NULL;
  3815 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
  3816   InstanceKlass* holder = get_klass_version(version);
  3817   if (holder == NULL) {
  3818     return NULL; // The version of klass is gone, no method is found
  3820   Method* method = holder->method_with_orig_idnum(idnum);
  3821   return method;
  3825 jint InstanceKlass::get_cached_class_file_len() {
  3826   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
  3829 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
  3830   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
  3834 // Construct a PreviousVersionNode entry for the array hung off
  3835 // the InstanceKlass.
  3836 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3837   GrowableArray<Method*>* prev_EMCP_methods) {
  3839   _prev_constant_pool = prev_constant_pool;
  3840   _prev_EMCP_methods = prev_EMCP_methods;
  3844 // Destroy a PreviousVersionNode
  3845 PreviousVersionNode::~PreviousVersionNode() {
  3846   if (_prev_constant_pool != NULL) {
  3847     _prev_constant_pool = NULL;
  3850   if (_prev_EMCP_methods != NULL) {
  3851     delete _prev_EMCP_methods;
  3855 // Construct a helper for walking the previous versions array
  3856 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
  3857   _thread = thread;
  3858   _previous_versions = ik->previous_versions();
  3859   _current_index = 0;
  3860   _current_p = NULL;
  3861   _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
  3865 // Return the interesting information for the next previous version
  3866 // of the klass. Returns NULL if there are no more previous versions.
  3867 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
  3868   if (_previous_versions == NULL) {
  3869     // no previous versions so nothing to return
  3870     return NULL;
  3873   _current_p = NULL;  // reset to NULL
  3874   _current_constant_pool_handle = NULL;
  3876   int length = _previous_versions->length();
  3878   while (_current_index < length) {
  3879     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3881     // Save a handle to the constant pool for this previous version,
  3882     // which keeps all the methods from being deallocated.
  3883     _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
  3884     _current_p = pv_node;
  3885     return pv_node;
  3888   return NULL;
  3889 } // end next_previous_version()

mercurial