src/share/vm/oops/instanceKlass.cpp

Fri, 24 Feb 2017 06:48:48 -0800

author
kevinw
date
Fri, 24 Feb 2017 06:48:48 -0800
changeset 8951
0612a789929b
parent 8509
cb4af293fe70
child 8982
8f1acbb637e3
permissions
-rw-r--r--

8162795: [REDO] MemberNameTable doesn't purge stale entries
Summary: Re-application of the change in JDK-8152271.
Reviewed-by: coleenp, sspitsyn

     1 /*
     2  * Copyright (c) 1997, 2016, 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/systemDictionaryShared.hpp"
    29 #include "classfile/verifier.hpp"
    30 #include "classfile/vmSymbols.hpp"
    31 #include "compiler/compileBroker.hpp"
    32 #include "gc_implementation/shared/markSweep.inline.hpp"
    33 #include "gc_interface/collectedHeap.inline.hpp"
    34 #include "interpreter/oopMapCache.hpp"
    35 #include "interpreter/rewriter.hpp"
    36 #include "jvmtifiles/jvmti.h"
    37 #include "memory/genOopClosures.inline.hpp"
    38 #include "memory/heapInspection.hpp"
    39 #include "memory/iterator.inline.hpp"
    40 #include "memory/metadataFactory.hpp"
    41 #include "memory/oopFactory.hpp"
    42 #include "oops/fieldStreams.hpp"
    43 #include "oops/instanceClassLoaderKlass.hpp"
    44 #include "oops/instanceKlass.hpp"
    45 #include "oops/instanceMirrorKlass.hpp"
    46 #include "oops/instanceOop.hpp"
    47 #include "oops/klass.inline.hpp"
    48 #include "oops/method.hpp"
    49 #include "oops/oop.inline.hpp"
    50 #include "oops/symbol.hpp"
    51 #include "prims/jvmtiExport.hpp"
    52 #include "prims/jvmtiRedefineClassesTrace.hpp"
    53 #include "prims/jvmtiRedefineClasses.hpp"
    54 #include "prims/jvmtiThreadState.hpp"
    55 #include "prims/methodComparator.hpp"
    56 #include "runtime/fieldDescriptor.hpp"
    57 #include "runtime/handles.inline.hpp"
    58 #include "runtime/javaCalls.hpp"
    59 #include "runtime/mutexLocker.hpp"
    60 #include "runtime/orderAccess.inline.hpp"
    61 #include "runtime/thread.inline.hpp"
    62 #include "services/classLoadingService.hpp"
    63 #include "services/threadService.hpp"
    64 #include "utilities/dtrace.hpp"
    65 #include "utilities/macros.hpp"
    66 #if INCLUDE_ALL_GCS
    67 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    68 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    69 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    70 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    71 #include "gc_implementation/g1/heapRegionManager.inline.hpp"
    72 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
    73 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
    74 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
    75 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
    76 #include "oops/oop.pcgc.inline.hpp"
    77 #endif // INCLUDE_ALL_GCS
    78 #ifdef COMPILER1
    79 #include "c1/c1_Compiler.hpp"
    80 #endif
    82 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    84 #ifdef DTRACE_ENABLED
    86 #ifndef USDT2
    88 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
    89   char*, intptr_t, oop, intptr_t);
    90 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
    91   char*, intptr_t, oop, intptr_t, int);
    92 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
    93   char*, intptr_t, oop, intptr_t, int);
    94 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
    95   char*, intptr_t, oop, intptr_t, int);
    96 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
    97   char*, intptr_t, oop, intptr_t, int);
    98 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
    99   char*, intptr_t, oop, intptr_t, int);
   100 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
   101   char*, intptr_t, oop, intptr_t, int);
   102 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
   103   char*, intptr_t, oop, intptr_t, int);
   105 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   106   {                                                              \
   107     char* data = NULL;                                           \
   108     int len = 0;                                                 \
   109     Symbol* name = (clss)->name();                               \
   110     if (name != NULL) {                                          \
   111       data = (char*)name->bytes();                               \
   112       len = name->utf8_length();                                 \
   113     }                                                            \
   114     HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
   115       data, len, (void *)(clss)->class_loader(), thread_type);           \
   116   }
   118 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   119   {                                                              \
   120     char* data = NULL;                                           \
   121     int len = 0;                                                 \
   122     Symbol* name = (clss)->name();                               \
   123     if (name != NULL) {                                          \
   124       data = (char*)name->bytes();                               \
   125       len = name->utf8_length();                                 \
   126     }                                                            \
   127     HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
   128       data, len, (void *)(clss)->class_loader(), thread_type, wait);     \
   129   }
   130 #else /* USDT2 */
   132 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
   133 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
   134 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
   135 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
   136 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
   137 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
   138 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
   139 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
   140 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
   141   {                                                              \
   142     char* data = NULL;                                           \
   143     int len = 0;                                                 \
   144     Symbol* name = (clss)->name();                               \
   145     if (name != NULL) {                                          \
   146       data = (char*)name->bytes();                               \
   147       len = name->utf8_length();                                 \
   148     }                                                            \
   149     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   150       data, len, (clss)->class_loader(), thread_type);           \
   151   }
   153 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
   154   {                                                              \
   155     char* data = NULL;                                           \
   156     int len = 0;                                                 \
   157     Symbol* name = (clss)->name();                               \
   158     if (name != NULL) {                                          \
   159       data = (char*)name->bytes();                               \
   160       len = name->utf8_length();                                 \
   161     }                                                            \
   162     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
   163       data, len, (clss)->class_loader(), thread_type, wait);     \
   164   }
   165 #endif /* USDT2 */
   167 #else //  ndef DTRACE_ENABLED
   169 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
   170 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
   172 #endif //  ndef DTRACE_ENABLED
   174 volatile int InstanceKlass::_total_instanceKlass_count = 0;
   176 InstanceKlass* InstanceKlass::allocate_instance_klass(
   177                                               ClassLoaderData* loader_data,
   178                                               int vtable_len,
   179                                               int itable_len,
   180                                               int static_field_size,
   181                                               int nonstatic_oop_map_size,
   182                                               ReferenceType rt,
   183                                               AccessFlags access_flags,
   184                                               Symbol* name,
   185                                               Klass* super_klass,
   186                                               bool is_anonymous,
   187                                               TRAPS) {
   189   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   190                                  access_flags.is_interface(), is_anonymous);
   192   // Allocation
   193   InstanceKlass* ik;
   194   if (rt == REF_NONE) {
   195     if (name == vmSymbols::java_lang_Class()) {
   196       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
   197         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   198         access_flags, is_anonymous);
   199     } else if (name == vmSymbols::java_lang_ClassLoader() ||
   200           (SystemDictionary::ClassLoader_klass_loaded() &&
   201           super_klass != NULL &&
   202           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
   203       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
   204         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   205         access_flags, is_anonymous);
   206     } else {
   207       // normal class
   208       ik = new (loader_data, size, THREAD) InstanceKlass(
   209         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   210         access_flags, is_anonymous);
   211     }
   212   } else {
   213     // reference klass
   214     ik = new (loader_data, size, THREAD) InstanceRefKlass(
   215         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
   216         access_flags, is_anonymous);
   217   }
   219   // Check for pending exception before adding to the loader data and incrementing
   220   // class count.  Can get OOM here.
   221   if (HAS_PENDING_EXCEPTION) {
   222     return NULL;
   223   }
   225   // Add all classes to our internal class loader list here,
   226   // including classes in the bootstrap (NULL) class loader.
   227   loader_data->add_class(ik);
   229   Atomic::inc(&_total_instanceKlass_count);
   230   return ik;
   231 }
   234 // copy method ordering from resource area to Metaspace
   235 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
   236   if (m != NULL) {
   237     // allocate a new array and copy contents (memcpy?)
   238     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
   239     for (int i = 0; i < m->length(); i++) {
   240       _method_ordering->at_put(i, m->at(i));
   241     }
   242   } else {
   243     _method_ordering = Universe::the_empty_int_array();
   244   }
   245 }
   247 // create a new array of vtable_indices for default methods
   248 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
   249   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
   250   assert(default_vtable_indices() == NULL, "only create once");
   251   set_default_vtable_indices(vtable_indices);
   252   return vtable_indices;
   253 }
   255 InstanceKlass::InstanceKlass(int vtable_len,
   256                              int itable_len,
   257                              int static_field_size,
   258                              int nonstatic_oop_map_size,
   259                              ReferenceType rt,
   260                              AccessFlags access_flags,
   261                              bool is_anonymous) {
   262   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
   264   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
   265                                    access_flags.is_interface(), is_anonymous);
   267   set_vtable_length(vtable_len);
   268   set_itable_length(itable_len);
   269   set_static_field_size(static_field_size);
   270   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
   271   set_access_flags(access_flags);
   272   _misc_flags = 0;  // initialize to zero
   273   set_is_anonymous(is_anonymous);
   274   assert(size() == iksize, "wrong size for object");
   276   set_array_klasses(NULL);
   277   set_methods(NULL);
   278   set_method_ordering(NULL);
   279   set_default_methods(NULL);
   280   set_default_vtable_indices(NULL);
   281   set_local_interfaces(NULL);
   282   set_transitive_interfaces(NULL);
   283   init_implementor();
   284   set_fields(NULL, 0);
   285   set_constants(NULL);
   286   set_class_loader_data(NULL);
   287   set_source_file_name_index(0);
   288   set_source_debug_extension(NULL, 0);
   289   set_array_name(NULL);
   290   set_inner_classes(NULL);
   291   set_static_oop_field_count(0);
   292   set_nonstatic_field_size(0);
   293   set_is_marked_dependent(false);
   294   set_has_unloaded_dependent(false);
   295   set_init_state(InstanceKlass::allocated);
   296   set_init_thread(NULL);
   297   set_reference_type(rt);
   298   set_oop_map_cache(NULL);
   299   set_jni_ids(NULL);
   300   set_osr_nmethods_head(NULL);
   301   set_breakpoints(NULL);
   302   init_previous_versions();
   303   set_generic_signature_index(0);
   304   release_set_methods_jmethod_ids(NULL);
   305   set_annotations(NULL);
   306   set_jvmti_cached_class_field_map(NULL);
   307   set_initial_method_idnum(0);
   308   _dependencies = NULL;
   309   set_jvmti_cached_class_field_map(NULL);
   310   set_cached_class_file(NULL);
   311   set_initial_method_idnum(0);
   312   set_minor_version(0);
   313   set_major_version(0);
   314   NOT_PRODUCT(_verify_count = 0;)
   316   // initialize the non-header words to zero
   317   intptr_t* p = (intptr_t*)this;
   318   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
   319     p[index] = NULL_WORD;
   320   }
   322   // Set temporary value until parseClassFile updates it with the real instance
   323   // size.
   324   set_layout_helper(Klass::instance_layout_helper(0, true));
   325 }
   328 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
   329                                        Array<Method*>* methods) {
   330   if (methods != NULL && methods != Universe::the_empty_method_array() &&
   331       !methods->is_shared()) {
   332     for (int i = 0; i < methods->length(); i++) {
   333       Method* method = methods->at(i);
   334       if (method == NULL) continue;  // maybe null if error processing
   335       // Only want to delete methods that are not executing for RedefineClasses.
   336       // The previous version will point to them so they're not totally dangling
   337       assert (!method->on_stack(), "shouldn't be called with methods on stack");
   338       MetadataFactory::free_metadata(loader_data, method);
   339     }
   340     MetadataFactory::free_array<Method*>(loader_data, methods);
   341   }
   342 }
   344 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
   345                                           Klass* super_klass,
   346                                           Array<Klass*>* local_interfaces,
   347                                           Array<Klass*>* transitive_interfaces) {
   348   // Only deallocate transitive interfaces if not empty, same as super class
   349   // or same as local interfaces.  See code in parseClassFile.
   350   Array<Klass*>* ti = transitive_interfaces;
   351   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
   352     // check that the interfaces don't come from super class
   353     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
   354                     InstanceKlass::cast(super_klass)->transitive_interfaces();
   355     if (ti != sti && ti != NULL && !ti->is_shared()) {
   356       MetadataFactory::free_array<Klass*>(loader_data, ti);
   357     }
   358   }
   360   // local interfaces can be empty
   361   if (local_interfaces != Universe::the_empty_klass_array() &&
   362       local_interfaces != NULL && !local_interfaces->is_shared()) {
   363     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
   364   }
   365 }
   367 // This function deallocates the metadata and C heap pointers that the
   368 // InstanceKlass points to.
   369 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
   371   // Orphan the mirror first, CMS thinks it's still live.
   372   if (java_mirror() != NULL) {
   373     java_lang_Class::set_klass(java_mirror(), NULL);
   374   }
   376   // Need to take this class off the class loader data list.
   377   loader_data->remove_class(this);
   379   // The array_klass for this class is created later, after error handling.
   380   // For class redefinition, we keep the original class so this scratch class
   381   // doesn't have an array class.  Either way, assert that there is nothing
   382   // to deallocate.
   383   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
   385   // Release C heap allocated data that this might point to, which includes
   386   // reference counting symbol names.
   387   release_C_heap_structures();
   389   deallocate_methods(loader_data, methods());
   390   set_methods(NULL);
   392   if (method_ordering() != NULL &&
   393       method_ordering() != Universe::the_empty_int_array() &&
   394       !method_ordering()->is_shared()) {
   395     MetadataFactory::free_array<int>(loader_data, method_ordering());
   396   }
   397   set_method_ordering(NULL);
   399   // default methods can be empty
   400   if (default_methods() != NULL &&
   401       default_methods() != Universe::the_empty_method_array() &&
   402       !default_methods()->is_shared()) {
   403     MetadataFactory::free_array<Method*>(loader_data, default_methods());
   404   }
   405   // Do NOT deallocate the default methods, they are owned by superinterfaces.
   406   set_default_methods(NULL);
   408   // default methods vtable indices can be empty
   409   if (default_vtable_indices() != NULL &&
   410       !default_vtable_indices()->is_shared()) {
   411     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
   412   }
   413   set_default_vtable_indices(NULL);
   416   // This array is in Klass, but remove it with the InstanceKlass since
   417   // this place would be the only caller and it can share memory with transitive
   418   // interfaces.
   419   if (secondary_supers() != NULL &&
   420       secondary_supers() != Universe::the_empty_klass_array() &&
   421       secondary_supers() != transitive_interfaces() &&
   422       !secondary_supers()->is_shared()) {
   423     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
   424   }
   425   set_secondary_supers(NULL);
   427   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
   428   set_transitive_interfaces(NULL);
   429   set_local_interfaces(NULL);
   431   if (fields() != NULL && !fields()->is_shared()) {
   432     MetadataFactory::free_array<jushort>(loader_data, fields());
   433   }
   434   set_fields(NULL, 0);
   436   // If a method from a redefined class is using this constant pool, don't
   437   // delete it, yet.  The new class's previous version will point to this.
   438   if (constants() != NULL) {
   439     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
   440     if (!constants()->is_shared()) {
   441       MetadataFactory::free_metadata(loader_data, constants());
   442     }
   443     // Delete any cached resolution errors for the constant pool
   444     SystemDictionary::delete_resolution_error(constants());
   446     set_constants(NULL);
   447   }
   449   if (inner_classes() != NULL &&
   450       inner_classes() != Universe::the_empty_short_array() &&
   451       !inner_classes()->is_shared()) {
   452     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
   453   }
   454   set_inner_classes(NULL);
   456   // We should deallocate the Annotations instance if it's not in shared spaces.
   457   if (annotations() != NULL && !annotations()->is_shared()) {
   458     MetadataFactory::free_metadata(loader_data, annotations());
   459   }
   460   set_annotations(NULL);
   461 }
   463 bool InstanceKlass::should_be_initialized() const {
   464   return !is_initialized();
   465 }
   467 klassVtable* InstanceKlass::vtable() const {
   468   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
   469 }
   471 klassItable* InstanceKlass::itable() const {
   472   return new klassItable(instanceKlassHandle(this));
   473 }
   475 void InstanceKlass::eager_initialize(Thread *thread) {
   476   if (!EagerInitialization) return;
   478   if (this->is_not_initialized()) {
   479     // abort if the the class has a class initializer
   480     if (this->class_initializer() != NULL) return;
   482     // abort if it is java.lang.Object (initialization is handled in genesis)
   483     Klass* super = this->super();
   484     if (super == NULL) return;
   486     // abort if the super class should be initialized
   487     if (!InstanceKlass::cast(super)->is_initialized()) return;
   489     // call body to expose the this pointer
   490     instanceKlassHandle this_oop(thread, this);
   491     eager_initialize_impl(this_oop);
   492   }
   493 }
   495 // JVMTI spec thinks there are signers and protection domain in the
   496 // instanceKlass.  These accessors pretend these fields are there.
   497 // The hprof specification also thinks these fields are in InstanceKlass.
   498 oop InstanceKlass::protection_domain() const {
   499   // return the protection_domain from the mirror
   500   return java_lang_Class::protection_domain(java_mirror());
   501 }
   503 // To remove these from requires an incompatible change and CCC request.
   504 objArrayOop InstanceKlass::signers() const {
   505   // return the signers from the mirror
   506   return java_lang_Class::signers(java_mirror());
   507 }
   509 oop InstanceKlass::init_lock() const {
   510   // return the init lock from the mirror
   511   oop lock = java_lang_Class::init_lock(java_mirror());
   512   // Prevent reordering with any access of initialization state
   513   OrderAccess::loadload();
   514   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
   515          "only fully initialized state can have a null lock");
   516   return lock;
   517 }
   519 // Set the initialization lock to null so the object can be GC'ed.  Any racing
   520 // threads to get this lock will see a null lock and will not lock.
   521 // That's okay because they all check for initialized state after getting
   522 // the lock and return.
   523 void InstanceKlass::fence_and_clear_init_lock() {
   524   // make sure previous stores are all done, notably the init_state.
   525   OrderAccess::storestore();
   526   java_lang_Class::set_init_lock(java_mirror(), NULL);
   527   assert(!is_not_initialized(), "class must be initialized now");
   528 }
   530 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
   531   EXCEPTION_MARK;
   532   oop init_lock = this_oop->init_lock();
   533   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   535   // abort if someone beat us to the initialization
   536   if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()
   538   ClassState old_state = this_oop->init_state();
   539   link_class_impl(this_oop, true, THREAD);
   540   if (HAS_PENDING_EXCEPTION) {
   541     CLEAR_PENDING_EXCEPTION;
   542     // Abort if linking the class throws an exception.
   544     // Use a test to avoid redundantly resetting the state if there's
   545     // no change.  Set_init_state() asserts that state changes make
   546     // progress, whereas here we might just be spinning in place.
   547     if( old_state != this_oop->_init_state )
   548       this_oop->set_init_state (old_state);
   549   } else {
   550     // linking successfull, mark class as initialized
   551     this_oop->set_init_state (fully_initialized);
   552     this_oop->fence_and_clear_init_lock();
   553     // trace
   554     if (TraceClassInitialization) {
   555       ResourceMark rm(THREAD);
   556       tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
   557     }
   558   }
   559 }
   562 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
   563 // process. The step comments refers to the procedure described in that section.
   564 // Note: implementation moved to static method to expose the this pointer.
   565 void InstanceKlass::initialize(TRAPS) {
   566   if (this->should_be_initialized()) {
   567     HandleMark hm(THREAD);
   568     instanceKlassHandle this_oop(THREAD, this);
   569     initialize_impl(this_oop, CHECK);
   570     // Note: at this point the class may be initialized
   571     //       OR it may be in the state of being initialized
   572     //       in case of recursive initialization!
   573   } else {
   574     assert(is_initialized(), "sanity check");
   575   }
   576 }
   579 bool InstanceKlass::verify_code(
   580     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   581   // 1) Verify the bytecodes
   582   Verifier::Mode mode =
   583     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
   584   return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
   585 }
   588 // Used exclusively by the shared spaces dump mechanism to prevent
   589 // classes mapped into the shared regions in new VMs from appearing linked.
   591 void InstanceKlass::unlink_class() {
   592   assert(is_linked(), "must be linked");
   593   _init_state = loaded;
   594 }
   596 void InstanceKlass::link_class(TRAPS) {
   597   assert(is_loaded(), "must be loaded");
   598   if (!is_linked()) {
   599     HandleMark hm(THREAD);
   600     instanceKlassHandle this_oop(THREAD, this);
   601     link_class_impl(this_oop, true, CHECK);
   602   }
   603 }
   605 // Called to verify that a class can link during initialization, without
   606 // throwing a VerifyError.
   607 bool InstanceKlass::link_class_or_fail(TRAPS) {
   608   assert(is_loaded(), "must be loaded");
   609   if (!is_linked()) {
   610     HandleMark hm(THREAD);
   611     instanceKlassHandle this_oop(THREAD, this);
   612     link_class_impl(this_oop, false, CHECK_false);
   613   }
   614   return is_linked();
   615 }
   617 bool InstanceKlass::link_class_impl(
   618     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
   619   // check for error state
   620   if (this_oop->is_in_error_state()) {
   621     ResourceMark rm(THREAD);
   622     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
   623                this_oop->external_name(), false);
   624   }
   625   // return if already verified
   626   if (this_oop->is_linked()) {
   627     return true;
   628   }
   630   // Timing
   631   // timer handles recursion
   632   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
   633   JavaThread* jt = (JavaThread*)THREAD;
   635   // link super class before linking this class
   636   instanceKlassHandle super(THREAD, this_oop->super());
   637   if (super.not_null()) {
   638     if (super->is_interface()) {  // check if super class is an interface
   639       ResourceMark rm(THREAD);
   640       Exceptions::fthrow(
   641         THREAD_AND_LOCATION,
   642         vmSymbols::java_lang_IncompatibleClassChangeError(),
   643         "class %s has interface %s as super class",
   644         this_oop->external_name(),
   645         super->external_name()
   646       );
   647       return false;
   648     }
   650     link_class_impl(super, throw_verifyerror, CHECK_false);
   651   }
   653   // link all interfaces implemented by this class before linking this class
   654   Array<Klass*>* interfaces = this_oop->local_interfaces();
   655   int num_interfaces = interfaces->length();
   656   for (int index = 0; index < num_interfaces; index++) {
   657     HandleMark hm(THREAD);
   658     instanceKlassHandle ih(THREAD, interfaces->at(index));
   659     link_class_impl(ih, throw_verifyerror, CHECK_false);
   660   }
   662   // in case the class is linked in the process of linking its superclasses
   663   if (this_oop->is_linked()) {
   664     return true;
   665   }
   667   // trace only the link time for this klass that includes
   668   // the verification time
   669   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
   670                              ClassLoader::perf_class_link_selftime(),
   671                              ClassLoader::perf_classes_linked(),
   672                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   673                              jt->get_thread_stat()->perf_timers_addr(),
   674                              PerfClassTraceTime::CLASS_LINK);
   676   // verification & rewriting
   677   {
   678     oop init_lock = this_oop->init_lock();
   679     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   680     // rewritten will have been set if loader constraint error found
   681     // on an earlier link attempt
   682     // don't verify or rewrite if already rewritten
   684     if (!this_oop->is_linked()) {
   685       if (!this_oop->is_rewritten()) {
   686         {
   687           // Timer includes any side effects of class verification (resolution,
   688           // etc), but not recursive entry into verify_code().
   689           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
   690                                    ClassLoader::perf_class_verify_selftime(),
   691                                    ClassLoader::perf_classes_verified(),
   692                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
   693                                    jt->get_thread_stat()->perf_timers_addr(),
   694                                    PerfClassTraceTime::CLASS_VERIFY);
   695           bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
   696           if (!verify_ok) {
   697             return false;
   698           }
   699         }
   701         // Just in case a side-effect of verify linked this class already
   702         // (which can sometimes happen since the verifier loads classes
   703         // using custom class loaders, which are free to initialize things)
   704         if (this_oop->is_linked()) {
   705           return true;
   706         }
   708         // also sets rewritten
   709         this_oop->rewrite_class(CHECK_false);
   710       } else if (this_oop()->is_shared()) {
   711         ResourceMark rm(THREAD);
   712         char* message_buffer; // res-allocated by check_verification_dependencies
   713         Handle loader = this_oop()->class_loader();
   714         Handle pd     = this_oop()->protection_domain();
   715         bool verified = SystemDictionaryShared::check_verification_dependencies(this_oop(),
   716                         loader, pd, &message_buffer, THREAD);
   717         if (!verified) {
   718           THROW_MSG_(vmSymbols::java_lang_VerifyError(), message_buffer, false);
   719         }
   720       }
   722       // relocate jsrs and link methods after they are all rewritten
   723       this_oop->link_methods(CHECK_false);
   725       // Initialize the vtable and interface table after
   726       // methods have been rewritten since rewrite may
   727       // fabricate new Method*s.
   728       // also does loader constraint checking
   729       //
   730       // Initialize_vtable and initialize_itable need to be rerun for
   731       // a shared class if the class is not loaded by the NULL classloader.
   732       ClassLoaderData * loader_data = this_oop->class_loader_data();
   733       if (!(this_oop()->is_shared() &&
   734             loader_data->is_the_null_class_loader_data())) {
   735         ResourceMark rm(THREAD);
   736         this_oop->vtable()->initialize_vtable(true, CHECK_false);
   737         this_oop->itable()->initialize_itable(true, CHECK_false);
   738       }
   739 #ifdef ASSERT
   740       else {
   741         ResourceMark rm(THREAD);
   742         this_oop->vtable()->verify(tty, true);
   743         // In case itable verification is ever added.
   744         // this_oop->itable()->verify(tty, true);
   745       }
   746 #endif
   747       this_oop->set_init_state(linked);
   748       if (JvmtiExport::should_post_class_prepare()) {
   749         Thread *thread = THREAD;
   750         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
   751         JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
   752       }
   753     }
   754   }
   755   return true;
   756 }
   759 // Rewrite the byte codes of all of the methods of a class.
   760 // The rewriter must be called exactly once. Rewriting must happen after
   761 // verification but before the first method of the class is executed.
   762 void InstanceKlass::rewrite_class(TRAPS) {
   763   assert(is_loaded(), "must be loaded");
   764   instanceKlassHandle this_oop(THREAD, this);
   765   if (this_oop->is_rewritten()) {
   766     assert(this_oop()->is_shared(), "rewriting an unshared class?");
   767     return;
   768   }
   769   Rewriter::rewrite(this_oop, CHECK);
   770   this_oop->set_rewritten();
   771 }
   773 // Now relocate and link method entry points after class is rewritten.
   774 // This is outside is_rewritten flag. In case of an exception, it can be
   775 // executed more than once.
   776 void InstanceKlass::link_methods(TRAPS) {
   777   int len = methods()->length();
   778   for (int i = len-1; i >= 0; i--) {
   779     methodHandle m(THREAD, methods()->at(i));
   781     // Set up method entry points for compiler and interpreter    .
   782     m->link_method(m, CHECK);
   784     // This is for JVMTI and unrelated to relocator but the last thing we do
   785 #ifdef ASSERT
   786     if (StressMethodComparator) {
   787       ResourceMark rm(THREAD);
   788       static int nmc = 0;
   789       for (int j = i; j >= 0 && j >= i-4; j--) {
   790         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
   791         bool z = MethodComparator::methods_EMCP(m(),
   792                    methods()->at(j));
   793         if (j == i && !z) {
   794           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
   795           assert(z, "method must compare equal to itself");
   796         }
   797       }
   798     }
   799 #endif //ASSERT
   800   }
   801 }
   803 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
   804 void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_oop, TRAPS) {
   805   if (this_oop->has_default_methods()) {
   806     for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
   807       Klass* iface = this_oop->local_interfaces()->at(i);
   808       InstanceKlass* ik = InstanceKlass::cast(iface);
   809       if (ik->should_be_initialized()) {
   810         if (ik->has_default_methods()) {
   811           ik->initialize_super_interfaces(ik, THREAD);
   812         }
   813         // Only initialize() interfaces that "declare" concrete methods.
   814         // has_default_methods drives searching superinterfaces since it
   815         // means has_default_methods in its superinterface hierarchy
   816         if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
   817           ik->initialize(THREAD);
   818         }
   819         if (HAS_PENDING_EXCEPTION) {
   820           Handle e(THREAD, PENDING_EXCEPTION);
   821           CLEAR_PENDING_EXCEPTION;
   822           {
   823             EXCEPTION_MARK;
   824             // Locks object, set state, and notify all waiting threads
   825             this_oop->set_initialization_state_and_notify(
   826                 initialization_error, THREAD);
   828             // ignore any exception thrown, superclass initialization error is
   829             // thrown below
   830             CLEAR_PENDING_EXCEPTION;
   831           }
   832           THROW_OOP(e());
   833         }
   834       }
   835     }
   836   }
   837 }
   839 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
   840   // Make sure klass is linked (verified) before initialization
   841   // A class could already be verified, since it has been reflected upon.
   842   this_oop->link_class(CHECK);
   844   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
   846   bool wait = false;
   848   // refer to the JVM book page 47 for description of steps
   849   // Step 1
   850   {
   851     oop init_lock = this_oop->init_lock();
   852     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   854     Thread *self = THREAD; // it's passed the current thread
   856     // Step 2
   857     // If we were to use wait() instead of waitInterruptibly() then
   858     // we might end up throwing IE from link/symbol resolution sites
   859     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
   860     while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
   861         wait = true;
   862       ol.waitUninterruptibly(CHECK);
   863     }
   865     // Step 3
   866     if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
   867       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
   868       return;
   869     }
   871     // Step 4
   872     if (this_oop->is_initialized()) {
   873       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
   874       return;
   875     }
   877     // Step 5
   878     if (this_oop->is_in_error_state()) {
   879       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
   880       ResourceMark rm(THREAD);
   881       const char* desc = "Could not initialize class ";
   882       const char* className = this_oop->external_name();
   883       size_t msglen = strlen(desc) + strlen(className) + 1;
   884       char* message = NEW_RESOURCE_ARRAY(char, msglen);
   885       if (NULL == message) {
   886         // Out of memory: can't create detailed error message
   887         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
   888       } else {
   889         jio_snprintf(message, msglen, "%s%s", desc, className);
   890         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
   891       }
   892     }
   894     // Step 6
   895     this_oop->set_init_state(being_initialized);
   896     this_oop->set_init_thread(self);
   897   }
   899   // Step 7
   900   Klass* super_klass = this_oop->super();
   901   if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
   902     super_klass->initialize(THREAD);
   904     if (HAS_PENDING_EXCEPTION) {
   905       Handle e(THREAD, PENDING_EXCEPTION);
   906       CLEAR_PENDING_EXCEPTION;
   907       {
   908         EXCEPTION_MARK;
   909         this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
   910         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
   911       }
   912       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
   913       THROW_OOP(e());
   914     }
   915   }
   917   // Recursively initialize any superinterfaces that declare default methods
   918   // Only need to recurse if has_default_methods which includes declaring and
   919   // inheriting default methods
   920   if (this_oop->has_default_methods()) {
   921     this_oop->initialize_super_interfaces(this_oop, CHECK);
   922   }
   924   // Step 8
   925   {
   926     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
   927     JavaThread* jt = (JavaThread*)THREAD;
   928     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
   929     // Timer includes any side effects of class initialization (resolution,
   930     // etc), but not recursive entry into call_class_initializer().
   931     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
   932                              ClassLoader::perf_class_init_selftime(),
   933                              ClassLoader::perf_classes_inited(),
   934                              jt->get_thread_stat()->perf_recursion_counts_addr(),
   935                              jt->get_thread_stat()->perf_timers_addr(),
   936                              PerfClassTraceTime::CLASS_CLINIT);
   937     this_oop->call_class_initializer(THREAD);
   938   }
   940   // Step 9
   941   if (!HAS_PENDING_EXCEPTION) {
   942     this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
   943     { ResourceMark rm(THREAD);
   944       debug_only(this_oop->vtable()->verify(tty, true);)
   945     }
   946   }
   947   else {
   948     // Step 10 and 11
   949     Handle e(THREAD, PENDING_EXCEPTION);
   950     CLEAR_PENDING_EXCEPTION;
   951     // JVMTI has already reported the pending exception
   952     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
   953     JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
   954     {
   955       EXCEPTION_MARK;
   956       this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
   957       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
   958       // JVMTI has already reported the pending exception
   959       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
   960       JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
   961     }
   962     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
   963     if (e->is_a(SystemDictionary::Error_klass())) {
   964       THROW_OOP(e());
   965     } else {
   966       JavaCallArguments args(e);
   967       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
   968                 vmSymbols::throwable_void_signature(),
   969                 &args);
   970     }
   971   }
   972   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
   973 }
   976 // Note: implementation moved to static method to expose the this pointer.
   977 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
   978   instanceKlassHandle kh(THREAD, this);
   979   set_initialization_state_and_notify_impl(kh, state, CHECK);
   980 }
   982 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   983   oop init_lock = this_oop->init_lock();
   984   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
   985   this_oop->set_init_state(state);
   986   this_oop->fence_and_clear_init_lock();
   987   ol.notify_all(CHECK);
   988 }
   990 // The embedded _implementor field can only record one implementor.
   991 // When there are more than one implementors, the _implementor field
   992 // is set to the interface Klass* itself. Following are the possible
   993 // values for the _implementor field:
   994 //   NULL                  - no implementor
   995 //   implementor Klass*    - one implementor
   996 //   self                  - more than one implementor
   997 //
   998 // The _implementor field only exists for interfaces.
   999 void InstanceKlass::add_implementor(Klass* k) {
  1000   assert(Compile_lock->owned_by_self(), "");
  1001   assert(is_interface(), "not interface");
  1002   // Filter out my subinterfaces.
  1003   // (Note: Interfaces are never on the subklass list.)
  1004   if (InstanceKlass::cast(k)->is_interface()) return;
  1006   // Filter out subclasses whose supers already implement me.
  1007   // (Note: CHA must walk subclasses of direct implementors
  1008   // in order to locate indirect implementors.)
  1009   Klass* sk = InstanceKlass::cast(k)->super();
  1010   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
  1011     // We only need to check one immediate superclass, since the
  1012     // implements_interface query looks at transitive_interfaces.
  1013     // Any supers of the super have the same (or fewer) transitive_interfaces.
  1014     return;
  1016   Klass* ik = implementor();
  1017   if (ik == NULL) {
  1018     set_implementor(k);
  1019   } else if (ik != this) {
  1020     // There is already an implementor. Use itself as an indicator of
  1021     // more than one implementors.
  1022     set_implementor(this);
  1025   // The implementor also implements the transitive_interfaces
  1026   for (int index = 0; index < local_interfaces()->length(); index++) {
  1027     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
  1031 void InstanceKlass::init_implementor() {
  1032   if (is_interface()) {
  1033     set_implementor(NULL);
  1038 void InstanceKlass::process_interfaces(Thread *thread) {
  1039   // link this class into the implementors list of every interface it implements
  1040   Klass* this_as_klass_oop = this;
  1041   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
  1042     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
  1043     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
  1044     assert(interf->is_interface(), "expected interface");
  1045     interf->add_implementor(this_as_klass_oop);
  1049 bool InstanceKlass::can_be_primary_super_slow() const {
  1050   if (is_interface())
  1051     return false;
  1052   else
  1053     return Klass::can_be_primary_super_slow();
  1056 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
  1057   // The secondaries are the implemented interfaces.
  1058   InstanceKlass* ik = InstanceKlass::cast(this);
  1059   Array<Klass*>* interfaces = ik->transitive_interfaces();
  1060   int num_secondaries = num_extra_slots + interfaces->length();
  1061   if (num_secondaries == 0) {
  1062     // Must share this for correct bootstrapping!
  1063     set_secondary_supers(Universe::the_empty_klass_array());
  1064     return NULL;
  1065   } else if (num_extra_slots == 0) {
  1066     // The secondary super list is exactly the same as the transitive interfaces.
  1067     // Redefine classes has to be careful not to delete this!
  1068     set_secondary_supers(interfaces);
  1069     return NULL;
  1070   } else {
  1071     // Copy transitive interfaces to a temporary growable array to be constructed
  1072     // into the secondary super list with extra slots.
  1073     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
  1074     for (int i = 0; i < interfaces->length(); i++) {
  1075       secondaries->push(interfaces->at(i));
  1077     return secondaries;
  1081 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
  1082   if (k->is_interface()) {
  1083     return implements_interface(k);
  1084   } else {
  1085     return Klass::compute_is_subtype_of(k);
  1089 bool InstanceKlass::implements_interface(Klass* k) const {
  1090   if (this == k) return true;
  1091   assert(k->is_interface(), "should be an interface class");
  1092   for (int i = 0; i < transitive_interfaces()->length(); i++) {
  1093     if (transitive_interfaces()->at(i) == k) {
  1094       return true;
  1097   return false;
  1100 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
  1101   // Verify direct super interface
  1102   if (this == k) return true;
  1103   assert(k->is_interface(), "should be an interface class");
  1104   for (int i = 0; i < local_interfaces()->length(); i++) {
  1105     if (local_interfaces()->at(i) == k) {
  1106       return true;
  1109   return false;
  1112 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
  1113   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  1114   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
  1115     report_java_out_of_memory("Requested array size exceeds VM limit");
  1116     JvmtiExport::post_array_size_exhausted();
  1117     THROW_OOP_0(Universe::out_of_memory_error_array_size());
  1119   int size = objArrayOopDesc::object_size(length);
  1120   Klass* ak = array_klass(n, CHECK_NULL);
  1121   KlassHandle h_ak (THREAD, ak);
  1122   objArrayOop o =
  1123     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  1124   return o;
  1127 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
  1128   if (TraceFinalizerRegistration) {
  1129     tty->print("Registered ");
  1130     i->print_value_on(tty);
  1131     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  1133   instanceHandle h_i(THREAD, i);
  1134   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  1135   JavaValue result(T_VOID);
  1136   JavaCallArguments args(h_i);
  1137   methodHandle mh (THREAD, Universe::finalizer_register_method());
  1138   JavaCalls::call(&result, mh, &args, CHECK_NULL);
  1139   return h_i();
  1142 instanceOop InstanceKlass::allocate_instance(TRAPS) {
  1143   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  1144   int size = size_helper();  // Query before forming handle.
  1146   KlassHandle h_k(THREAD, this);
  1148   instanceOop i;
  1150   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  1151   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
  1152     i = register_finalizer(i, CHECK_NULL);
  1154   return i;
  1157 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  1158   if (is_interface() || is_abstract()) {
  1159     ResourceMark rm(THREAD);
  1160     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  1161               : vmSymbols::java_lang_InstantiationException(), external_name());
  1163   if (this == SystemDictionary::Class_klass()) {
  1164     ResourceMark rm(THREAD);
  1165     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
  1166               : vmSymbols::java_lang_IllegalAccessException(), external_name());
  1170 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  1171   instanceKlassHandle this_oop(THREAD, this);
  1172   return array_klass_impl(this_oop, or_null, n, THREAD);
  1175 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
  1176   if (this_oop->array_klasses() == NULL) {
  1177     if (or_null) return NULL;
  1179     ResourceMark rm;
  1180     JavaThread *jt = (JavaThread *)THREAD;
  1182       // Atomic creation of array_klasses
  1183       MutexLocker mc(Compile_lock, THREAD);   // for vtables
  1184       MutexLocker ma(MultiArray_lock, THREAD);
  1186       // Check if update has already taken place
  1187       if (this_oop->array_klasses() == NULL) {
  1188         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
  1189         this_oop->set_array_klasses(k);
  1193   // _this will always be set at this point
  1194   ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
  1195   if (or_null) {
  1196     return oak->array_klass_or_null(n);
  1198   return oak->array_klass(n, CHECK_NULL);
  1201 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
  1202   return array_klass_impl(or_null, 1, THREAD);
  1205 void InstanceKlass::call_class_initializer(TRAPS) {
  1206   instanceKlassHandle ik (THREAD, this);
  1207   call_class_initializer_impl(ik, THREAD);
  1210 static int call_class_initializer_impl_counter = 0;   // for debugging
  1212 Method* InstanceKlass::class_initializer() {
  1213   Method* clinit = find_method(
  1214       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  1215   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
  1216     return clinit;
  1218   return NULL;
  1221 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
  1222   if (ReplayCompiles &&
  1223       (ReplaySuppressInitializers == 1 ||
  1224        ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
  1225     // Hide the existence of the initializer for the purpose of replaying the compile
  1226     return;
  1229   methodHandle h_method(THREAD, this_oop->class_initializer());
  1230   assert(!this_oop->is_initialized(), "we cannot initialize twice");
  1231   if (TraceClassInitialization) {
  1232     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
  1233     this_oop->name()->print_value();
  1234     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  1236   if (h_method() != NULL) {
  1237     JavaCallArguments args; // No arguments
  1238     JavaValue result(T_VOID);
  1239     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  1244 void InstanceKlass::mask_for(methodHandle method, int bci,
  1245   InterpreterOopMap* entry_for) {
  1246   // Dirty read, then double-check under a lock.
  1247   if (_oop_map_cache == NULL) {
  1248     // Otherwise, allocate a new one.
  1249     MutexLocker x(OopMapCacheAlloc_lock);
  1250     // First time use. Allocate a cache in C heap
  1251     if (_oop_map_cache == NULL) {
  1252       // Release stores from OopMapCache constructor before assignment
  1253       // to _oop_map_cache. C++ compilers on ppc do not emit the
  1254       // required memory barrier only because of the volatile
  1255       // qualifier of _oop_map_cache.
  1256       OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
  1259   // _oop_map_cache is constant after init; lookup below does is own locking.
  1260   _oop_map_cache->lookup(method, bci, entry_for);
  1264 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1265   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1266     Symbol* f_name = fs.name();
  1267     Symbol* f_sig  = fs.signature();
  1268     if (f_name == name && f_sig == sig) {
  1269       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1270       return true;
  1273   return false;
  1277 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1278   const int n = local_interfaces()->length();
  1279   for (int i = 0; i < n; i++) {
  1280     Klass* intf1 = local_interfaces()->at(i);
  1281     assert(intf1->is_interface(), "just checking type");
  1282     // search for field in current interface
  1283     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
  1284       assert(fd->is_static(), "interface field must be static");
  1285       return intf1;
  1287     // search for field in direct superinterfaces
  1288     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
  1289     if (intf2 != NULL) return intf2;
  1291   // otherwise field lookup fails
  1292   return NULL;
  1296 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  1297   // search order according to newest JVM spec (5.4.3.2, p.167).
  1298   // 1) search for field in current klass
  1299   if (find_local_field(name, sig, fd)) {
  1300     return const_cast<InstanceKlass*>(this);
  1302   // 2) search for field recursively in direct superinterfaces
  1303   { Klass* intf = find_interface_field(name, sig, fd);
  1304     if (intf != NULL) return intf;
  1306   // 3) apply field lookup recursively if superclass exists
  1307   { Klass* supr = super();
  1308     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
  1310   // 4) otherwise field lookup fails
  1311   return NULL;
  1315 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
  1316   // search order according to newest JVM spec (5.4.3.2, p.167).
  1317   // 1) search for field in current klass
  1318   if (find_local_field(name, sig, fd)) {
  1319     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
  1321   // 2) search for field recursively in direct superinterfaces
  1322   if (is_static) {
  1323     Klass* intf = find_interface_field(name, sig, fd);
  1324     if (intf != NULL) return intf;
  1326   // 3) apply field lookup recursively if superclass exists
  1327   { Klass* supr = super();
  1328     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
  1330   // 4) otherwise field lookup fails
  1331   return NULL;
  1335 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1336   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1337     if (fs.offset() == offset) {
  1338       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
  1339       if (fd->is_static() == is_static) return true;
  1342   return false;
  1346 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  1347   Klass* klass = const_cast<InstanceKlass*>(this);
  1348   while (klass != NULL) {
  1349     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
  1350       return true;
  1352     klass = klass->super();
  1354   return false;
  1358 void InstanceKlass::methods_do(void f(Method* method)) {
  1359   int len = methods()->length();
  1360   for (int index = 0; index < len; index++) {
  1361     Method* m = methods()->at(index);
  1362     assert(m->is_method(), "must be method");
  1363     f(m);
  1368 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
  1369   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
  1370     if (fs.access_flags().is_static()) {
  1371       fieldDescriptor& fd = fs.field_descriptor();
  1372       cl->do_field(&fd);
  1378 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
  1379   instanceKlassHandle h_this(THREAD, this);
  1380   do_local_static_fields_impl(h_this, f, mirror, CHECK);
  1384 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
  1385                              void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {
  1386   for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
  1387     if (fs.access_flags().is_static()) {
  1388       fieldDescriptor& fd = fs.field_descriptor();
  1389       f(&fd, mirror, CHECK);
  1395 static int compare_fields_by_offset(int* a, int* b) {
  1396   return a[0] - b[0];
  1399 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  1400   InstanceKlass* super = superklass();
  1401   if (super != NULL) {
  1402     super->do_nonstatic_fields(cl);
  1404   fieldDescriptor fd;
  1405   int length = java_fields_count();
  1406   // In DebugInfo nonstatic fields are sorted by offset.
  1407   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
  1408   int j = 0;
  1409   for (int i = 0; i < length; i += 1) {
  1410     fd.reinitialize(this, i);
  1411     if (!fd.is_static()) {
  1412       fields_sorted[j + 0] = fd.offset();
  1413       fields_sorted[j + 1] = i;
  1414       j += 2;
  1417   if (j > 0) {
  1418     length = j;
  1419     // _sort_Fn is defined in growableArray.hpp.
  1420     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
  1421     for (int i = 0; i < length; i += 2) {
  1422       fd.reinitialize(this, fields_sorted[i + 1]);
  1423       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
  1424       cl->do_field(&fd);
  1427   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
  1431 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  1432   if (array_klasses() != NULL)
  1433     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
  1436 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
  1437   if (array_klasses() != NULL)
  1438     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
  1441 #ifdef ASSERT
  1442 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1443   int len = methods->length();
  1444   for (int index = 0; index < len; index++) {
  1445     Method* m = methods->at(index);
  1446     assert(m->is_method(), "must be method");
  1447     if (m->signature() == signature && m->name() == name) {
  1448        return index;
  1451   return -1;
  1453 #endif
  1455 static int binary_search(Array<Method*>* methods, Symbol* name) {
  1456   int len = methods->length();
  1457   // methods are sorted, so do binary search
  1458   int l = 0;
  1459   int h = len - 1;
  1460   while (l <= h) {
  1461     int mid = (l + h) >> 1;
  1462     Method* m = methods->at(mid);
  1463     assert(m->is_method(), "must be method");
  1464     int res = m->name()->fast_compare(name);
  1465     if (res == 0) {
  1466       return mid;
  1467     } else if (res < 0) {
  1468       l = mid + 1;
  1469     } else {
  1470       h = mid - 1;
  1473   return -1;
  1476 // find_method looks up the name/signature in the local methods array
  1477 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  1478   return find_method_impl(name, signature, false);
  1481 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
  1482   return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass, false);
  1485 // find_instance_method looks up the name/signature in the local methods array
  1486 // and skips over static methods
  1487 Method* InstanceKlass::find_instance_method(
  1488     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1489   Method* meth = InstanceKlass::find_method_impl(methods, name, signature, false, true);
  1490   return meth;
  1493 // find_instance_method looks up the name/signature in the local methods array
  1494 // and skips over static methods
  1495 Method* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) {
  1496     return InstanceKlass::find_instance_method(methods(), name, signature);
  1499 // find_method looks up the name/signature in the local methods array
  1500 Method* InstanceKlass::find_method(
  1501     Array<Method*>* methods, Symbol* name, Symbol* signature) {
  1502   return InstanceKlass::find_method_impl(methods, name, signature, false, false);
  1505 Method* InstanceKlass::find_method_impl(
  1506     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
  1507   int hit = find_method_index(methods, name, signature, skipping_overpass, skipping_static);
  1508   return hit >= 0 ? methods->at(hit): NULL;
  1511 bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static) {
  1512     return (m->signature() == signature) &&
  1513             (!skipping_overpass || !m->is_overpass()) &&
  1514             (!skipping_static || !m->is_static());
  1517 // Used directly for default_methods to find the index into the
  1518 // default_vtable_indices, and indirectly by find_method
  1519 // find_method_index looks in the local methods array to return the index
  1520 // of the matching name/signature. If, overpass methods are being ignored,
  1521 // the search continues to find a potential non-overpass match.  This capability
  1522 // is important during method resolution to prefer a static method, for example,
  1523 // over an overpass method.
  1524 int InstanceKlass::find_method_index(
  1525     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
  1526   int hit = binary_search(methods, name);
  1527   if (hit != -1) {
  1528     Method* m = methods->at(hit);
  1530     // Do linear search to find matching signature.  First, quick check
  1531     // for common case, ignoring overpasses if requested.
  1532     if (method_matches(m, signature, skipping_overpass, skipping_static)) return hit;
  1534     // search downwards through overloaded methods
  1535     int i;
  1536     for (i = hit - 1; i >= 0; --i) {
  1537         Method* m = methods->at(i);
  1538         assert(m->is_method(), "must be method");
  1539         if (m->name() != name) break;
  1540         if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
  1542     // search upwards
  1543     for (i = hit + 1; i < methods->length(); ++i) {
  1544         Method* m = methods->at(i);
  1545         assert(m->is_method(), "must be method");
  1546         if (m->name() != name) break;
  1547         if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
  1549     // not found
  1550 #ifdef ASSERT
  1551     int index = skipping_overpass || skipping_static ? -1 : linear_search(methods, name, signature);
  1552     assert(index == -1, err_msg("binary search should have found entry %d", index));
  1553 #endif
  1555   return -1;
  1557 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  1558   return find_method_by_name(methods(), name, end);
  1561 int InstanceKlass::find_method_by_name(
  1562     Array<Method*>* methods, Symbol* name, int* end_ptr) {
  1563   assert(end_ptr != NULL, "just checking");
  1564   int start = binary_search(methods, name);
  1565   int end = start + 1;
  1566   if (start != -1) {
  1567     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
  1568     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
  1569     *end_ptr = end;
  1570     return start;
  1572   return -1;
  1575 // uncached_lookup_method searches both the local class methods array and all
  1576 // superclasses methods arrays, skipping any overpass methods in superclasses.
  1577 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
  1578   MethodLookupMode lookup_mode = mode;
  1579   Klass* klass = const_cast<InstanceKlass*>(this);
  1580   while (klass != NULL) {
  1581     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
  1582     if (method != NULL) {
  1583       return method;
  1585     klass = InstanceKlass::cast(klass)->super();
  1586     lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
  1588   return NULL;
  1591 #ifdef ASSERT
  1592 // search through class hierarchy and return true if this class or
  1593 // one of the superclasses was redefined
  1594 bool InstanceKlass::has_redefined_this_or_super() const {
  1595   const InstanceKlass* klass = this;
  1596   while (klass != NULL) {
  1597     if (klass->has_been_redefined()) {
  1598       return true;
  1600     klass = InstanceKlass::cast(klass->super());
  1602   return false;
  1604 #endif
  1606 // lookup a method in the default methods list then in all transitive interfaces
  1607 // Do NOT return private or static methods
  1608 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
  1609                                                          Symbol* signature) const {
  1610   Method* m = NULL;
  1611   if (default_methods() != NULL) {
  1612     m = find_method(default_methods(), name, signature);
  1614   // Look up interfaces
  1615   if (m == NULL) {
  1616     m = lookup_method_in_all_interfaces(name, signature, normal);
  1618   return m;
  1621 // lookup a method in all the interfaces that this class implements
  1622 // Do NOT return private or static methods, new in JDK8 which are not externally visible
  1623 // They should only be found in the initial InterfaceMethodRef
  1624 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
  1625                                                        Symbol* signature,
  1626                                                        MethodLookupMode mode) const {
  1627   Array<Klass*>* all_ifs = transitive_interfaces();
  1628   int num_ifs = all_ifs->length();
  1629   InstanceKlass *ik = NULL;
  1630   for (int i = 0; i < num_ifs; i++) {
  1631     ik = InstanceKlass::cast(all_ifs->at(i));
  1632     Method* m = ik->lookup_method(name, signature);
  1633     if (m != NULL && m->is_public() && !m->is_static() &&
  1634         ((mode != skip_defaults) || !m->is_default_method())) {
  1635       return m;
  1638   return NULL;
  1641 /* jni_id_for_impl for jfieldIds only */
  1642 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
  1643   MutexLocker ml(JfieldIdCreation_lock);
  1644   // Retry lookup after we got the lock
  1645   JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  1646   if (probe == NULL) {
  1647     // Slow case, allocate new static field identifier
  1648     probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
  1649     this_oop->set_jni_ids(probe);
  1651   return probe;
  1655 /* jni_id_for for jfieldIds only */
  1656 JNIid* InstanceKlass::jni_id_for(int offset) {
  1657   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  1658   if (probe == NULL) {
  1659     probe = jni_id_for_impl(this, offset);
  1661   return probe;
  1664 u2 InstanceKlass::enclosing_method_data(int offset) {
  1665   Array<jushort>* inner_class_list = inner_classes();
  1666   if (inner_class_list == NULL) {
  1667     return 0;
  1669   int length = inner_class_list->length();
  1670   if (length % inner_class_next_offset == 0) {
  1671     return 0;
  1672   } else {
  1673     int index = length - enclosing_method_attribute_size;
  1674     assert(offset < enclosing_method_attribute_size, "invalid offset");
  1675     return inner_class_list->at(index + offset);
  1679 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
  1680                                                  u2 method_index) {
  1681   Array<jushort>* inner_class_list = inner_classes();
  1682   assert (inner_class_list != NULL, "_inner_classes list is not set up");
  1683   int length = inner_class_list->length();
  1684   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
  1685     int index = length - enclosing_method_attribute_size;
  1686     inner_class_list->at_put(
  1687       index + enclosing_method_class_index_offset, class_index);
  1688     inner_class_list->at_put(
  1689       index + enclosing_method_method_index_offset, method_index);
  1693 // Lookup or create a jmethodID.
  1694 // This code is called by the VMThread and JavaThreads so the
  1695 // locking has to be done very carefully to avoid deadlocks
  1696 // and/or other cache consistency problems.
  1697 //
  1698 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
  1699   size_t idnum = (size_t)method_h->method_idnum();
  1700   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1701   size_t length = 0;
  1702   jmethodID id = NULL;
  1704   // We use a double-check locking idiom here because this cache is
  1705   // performance sensitive. In the normal system, this cache only
  1706   // transitions from NULL to non-NULL which is safe because we use
  1707   // release_set_methods_jmethod_ids() to advertise the new cache.
  1708   // A partially constructed cache should never be seen by a racing
  1709   // thread. We also use release_store_ptr() to save a new jmethodID
  1710   // in the cache so a partially constructed jmethodID should never be
  1711   // seen either. Cache reads of existing jmethodIDs proceed without a
  1712   // lock, but cache writes of a new jmethodID requires uniqueness and
  1713   // creation of the cache itself requires no leaks so a lock is
  1714   // generally acquired in those two cases.
  1715   //
  1716   // If the RedefineClasses() API has been used, then this cache can
  1717   // grow and we'll have transitions from non-NULL to bigger non-NULL.
  1718   // Cache creation requires no leaks and we require safety between all
  1719   // cache accesses and freeing of the old cache so a lock is generally
  1720   // acquired when the RedefineClasses() API has been used.
  1722   if (jmeths != NULL) {
  1723     // the cache already exists
  1724     if (!ik_h->idnum_can_increment()) {
  1725       // the cache can't grow so we can just get the current values
  1726       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1727     } else {
  1728       // cache can grow so we have to be more careful
  1729       if (Threads::number_of_threads() == 0 ||
  1730           SafepointSynchronize::is_at_safepoint()) {
  1731         // we're single threaded or at a safepoint - no locking needed
  1732         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1733       } else {
  1734         MutexLocker ml(JmethodIdCreation_lock);
  1735         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
  1739   // implied else:
  1740   // we need to allocate a cache so default length and id values are good
  1742   if (jmeths == NULL ||   // no cache yet
  1743       length <= idnum ||  // cache is too short
  1744       id == NULL) {       // cache doesn't contain entry
  1746     // This function can be called by the VMThread so we have to do all
  1747     // things that might block on a safepoint before grabbing the lock.
  1748     // Otherwise, we can deadlock with the VMThread or have a cache
  1749     // consistency issue. These vars keep track of what we might have
  1750     // to free after the lock is dropped.
  1751     jmethodID  to_dealloc_id     = NULL;
  1752     jmethodID* to_dealloc_jmeths = NULL;
  1754     // may not allocate new_jmeths or use it if we allocate it
  1755     jmethodID* new_jmeths = NULL;
  1756     if (length <= idnum) {
  1757       // allocate a new cache that might be used
  1758       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
  1759       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
  1760       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
  1761       // cache size is stored in element[0], other elements offset by one
  1762       new_jmeths[0] = (jmethodID)size;
  1765     // allocate a new jmethodID that might be used
  1766     jmethodID new_id = NULL;
  1767     if (method_h->is_old() && !method_h->is_obsolete()) {
  1768       // The method passed in is old (but not obsolete), we need to use the current version
  1769       Method* current_method = ik_h->method_with_idnum((int)idnum);
  1770       assert(current_method != NULL, "old and but not obsolete, so should exist");
  1771       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
  1772     } else {
  1773       // It is the current version of the method or an obsolete method,
  1774       // use the version passed in
  1775       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
  1778     if (Threads::number_of_threads() == 0 ||
  1779         SafepointSynchronize::is_at_safepoint()) {
  1780       // we're single threaded or at a safepoint - no locking needed
  1781       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1782                                           &to_dealloc_id, &to_dealloc_jmeths);
  1783     } else {
  1784       MutexLocker ml(JmethodIdCreation_lock);
  1785       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
  1786                                           &to_dealloc_id, &to_dealloc_jmeths);
  1789     // The lock has been dropped so we can free resources.
  1790     // Free up either the old cache or the new cache if we allocated one.
  1791     if (to_dealloc_jmeths != NULL) {
  1792       FreeHeap(to_dealloc_jmeths);
  1794     // free up the new ID since it wasn't needed
  1795     if (to_dealloc_id != NULL) {
  1796       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
  1799   return id;
  1803 // Common code to fetch the jmethodID from the cache or update the
  1804 // cache with the new jmethodID. This function should never do anything
  1805 // that causes the caller to go to a safepoint or we can deadlock with
  1806 // the VMThread or have cache consistency issues.
  1807 //
  1808 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
  1809             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
  1810             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
  1811             jmethodID** to_dealloc_jmeths_p) {
  1812   assert(new_id != NULL, "sanity check");
  1813   assert(to_dealloc_id_p != NULL, "sanity check");
  1814   assert(to_dealloc_jmeths_p != NULL, "sanity check");
  1815   assert(Threads::number_of_threads() == 0 ||
  1816          SafepointSynchronize::is_at_safepoint() ||
  1817          JmethodIdCreation_lock->owned_by_self(), "sanity check");
  1819   // reacquire the cache - we are locked, single threaded or at a safepoint
  1820   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  1821   jmethodID  id     = NULL;
  1822   size_t     length = 0;
  1824   if (jmeths == NULL ||                         // no cache yet
  1825       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
  1826     if (jmeths != NULL) {
  1827       // copy any existing entries from the old cache
  1828       for (size_t index = 0; index < length; index++) {
  1829         new_jmeths[index+1] = jmeths[index+1];
  1831       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
  1833     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  1834   } else {
  1835     // fetch jmethodID (if any) from the existing cache
  1836     id = jmeths[idnum+1];
  1837     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
  1839   if (id == NULL) {
  1840     // No matching jmethodID in the existing cache or we have a new
  1841     // cache or we just grew the cache. This cache write is done here
  1842     // by the first thread to win the foot race because a jmethodID
  1843     // needs to be unique once it is generally available.
  1844     id = new_id;
  1846     // The jmethodID cache can be read while unlocked so we have to
  1847     // make sure the new jmethodID is complete before installing it
  1848     // in the cache.
  1849     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
  1850   } else {
  1851     *to_dealloc_id_p = new_id; // save new id for later delete
  1853   return id;
  1857 // Common code to get the jmethodID cache length and the jmethodID
  1858 // value at index idnum if there is one.
  1859 //
  1860 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
  1861        size_t idnum, size_t *length_p, jmethodID* id_p) {
  1862   assert(cache != NULL, "sanity check");
  1863   assert(length_p != NULL, "sanity check");
  1864   assert(id_p != NULL, "sanity check");
  1866   // cache size is stored in element[0], other elements offset by one
  1867   *length_p = (size_t)cache[0];
  1868   if (*length_p <= idnum) {  // cache is too short
  1869     *id_p = NULL;
  1870   } else {
  1871     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
  1876 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
  1877 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
  1878   size_t idnum = (size_t)method->method_idnum();
  1879   jmethodID* jmeths = methods_jmethod_ids_acquire();
  1880   size_t length;                                // length assigned as debugging crumb
  1881   jmethodID id = NULL;
  1882   if (jmeths != NULL &&                         // If there is a cache
  1883       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
  1884     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  1886   return id;
  1889 int nmethodBucket::decrement() {
  1890   return Atomic::add(-1, (volatile int *)&_count);
  1893 //
  1894 // Walk the list of dependent nmethods searching for nmethods which
  1895 // are dependent on the changes that were passed in and mark them for
  1896 // deoptimization.  Returns the number of nmethods found.
  1897 //
  1898 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
  1899   assert_locked_or_safepoint(CodeCache_lock);
  1900   int found = 0;
  1901   nmethodBucket* b = _dependencies;
  1902   while (b != NULL) {
  1903     nmethod* nm = b->get_nmethod();
  1904     // since dependencies aren't removed until an nmethod becomes a zombie,
  1905     // the dependency list may contain nmethods which aren't alive.
  1906     if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
  1907       if (TraceDependencies) {
  1908         ResourceMark rm;
  1909         tty->print_cr("Marked for deoptimization");
  1910         tty->print_cr("  context = %s", this->external_name());
  1911         changes.print();
  1912         nm->print();
  1913         nm->print_dependencies();
  1915       nm->mark_for_deoptimization();
  1916       found++;
  1918     b = b->next();
  1920   return found;
  1923 void InstanceKlass::clean_dependent_nmethods() {
  1924   assert_locked_or_safepoint(CodeCache_lock);
  1926   if (has_unloaded_dependent()) {
  1927     nmethodBucket* b = _dependencies;
  1928     nmethodBucket* last = NULL;
  1929     while (b != NULL) {
  1930       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
  1932       nmethodBucket* next = b->next();
  1934       if (b->count() == 0) {
  1935         if (last == NULL) {
  1936           _dependencies = next;
  1937         } else {
  1938           last->set_next(next);
  1940         delete b;
  1941         // last stays the same.
  1942       } else {
  1943         last = b;
  1946       b = next;
  1948     set_has_unloaded_dependent(false);
  1950 #ifdef ASSERT
  1951   else {
  1952     // Verification
  1953     for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
  1954       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
  1955       assert(b->count() != 0, "empty buckets need to be cleaned");
  1958 #endif
  1961 //
  1962 // Add an nmethodBucket to the list of dependencies for this nmethod.
  1963 // It's possible that an nmethod has multiple dependencies on this klass
  1964 // so a count is kept for each bucket to guarantee that creation and
  1965 // deletion of dependencies is consistent.
  1966 //
  1967 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
  1968   assert_locked_or_safepoint(CodeCache_lock);
  1969   nmethodBucket* b = _dependencies;
  1970   nmethodBucket* last = NULL;
  1971   while (b != NULL) {
  1972     if (nm == b->get_nmethod()) {
  1973       b->increment();
  1974       return;
  1976     b = b->next();
  1978   _dependencies = new nmethodBucket(nm, _dependencies);
  1982 //
  1983 // Decrement count of the nmethod in the dependency list and remove
  1984 // the bucket competely when the count goes to 0.  This method must
  1985 // find a corresponding bucket otherwise there's a bug in the
  1986 // recording of dependecies.
  1987 //
  1988 void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {
  1989   assert_locked_or_safepoint(CodeCache_lock);
  1990   nmethodBucket* b = _dependencies;
  1991   nmethodBucket* last = NULL;
  1992   while (b != NULL) {
  1993     if (nm == b->get_nmethod()) {
  1994       int val = b->decrement();
  1995       guarantee(val >= 0, err_msg("Underflow: %d", val));
  1996       if (val == 0) {
  1997         if (delete_immediately) {
  1998           if (last == NULL) {
  1999             _dependencies = b->next();
  2000           } else {
  2001             last->set_next(b->next());
  2003           delete b;
  2004         } else {
  2005           // The deletion of this entry is deferred until a later, potentially parallel GC phase.
  2006           set_has_unloaded_dependent(true);
  2009       return;
  2011     last = b;
  2012     b = b->next();
  2014 #ifdef ASSERT
  2015   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  2016   nm->print();
  2017 #endif // ASSERT
  2018   ShouldNotReachHere();
  2022 #ifndef PRODUCT
  2023 void InstanceKlass::print_dependent_nmethods(bool verbose) {
  2024   nmethodBucket* b = _dependencies;
  2025   int idx = 0;
  2026   while (b != NULL) {
  2027     nmethod* nm = b->get_nmethod();
  2028     tty->print("[%d] count=%d { ", idx++, b->count());
  2029     if (!verbose) {
  2030       nm->print_on(tty, "nmethod");
  2031       tty->print_cr(" } ");
  2032     } else {
  2033       nm->print();
  2034       nm->print_dependencies();
  2035       tty->print_cr("--- } ");
  2037     b = b->next();
  2042 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
  2043   nmethodBucket* b = _dependencies;
  2044   while (b != NULL) {
  2045     if (nm == b->get_nmethod()) {
  2046 #ifdef ASSERT
  2047       int count = b->count();
  2048       assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
  2049 #endif
  2050       return true;
  2052     b = b->next();
  2054   return false;
  2056 #endif //PRODUCT
  2059 // Garbage collection
  2061 #ifdef ASSERT
  2062 template <class T> void assert_is_in(T *p) {
  2063   T heap_oop = oopDesc::load_heap_oop(p);
  2064   if (!oopDesc::is_null(heap_oop)) {
  2065     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2066     assert(Universe::heap()->is_in(o), "should be in heap");
  2069 template <class T> void assert_is_in_closed_subset(T *p) {
  2070   T heap_oop = oopDesc::load_heap_oop(p);
  2071   if (!oopDesc::is_null(heap_oop)) {
  2072     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2073     assert(Universe::heap()->is_in_closed_subset(o),
  2074            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
  2077 template <class T> void assert_is_in_reserved(T *p) {
  2078   T heap_oop = oopDesc::load_heap_oop(p);
  2079   if (!oopDesc::is_null(heap_oop)) {
  2080     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
  2081     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  2084 template <class T> void assert_nothing(T *p) {}
  2086 #else
  2087 template <class T> void assert_is_in(T *p) {}
  2088 template <class T> void assert_is_in_closed_subset(T *p) {}
  2089 template <class T> void assert_is_in_reserved(T *p) {}
  2090 template <class T> void assert_nothing(T *p) {}
  2091 #endif // ASSERT
  2093 //
  2094 // Macros that iterate over areas of oops which are specialized on type of
  2095 // oop pointer either narrow or wide, depending on UseCompressedOops
  2096 //
  2097 // Parameters are:
  2098 //   T         - type of oop to point to (either oop or narrowOop)
  2099 //   start_p   - starting pointer for region to iterate over
  2100 //   count     - number of oops or narrowOops to iterate over
  2101 //   do_oop    - action to perform on each oop (it's arbitrary C code which
  2102 //               makes it more efficient to put in a macro rather than making
  2103 //               it a template function)
  2104 //   assert_fn - assert function which is template function because performance
  2105 //               doesn't matter when enabled.
  2106 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  2107   T, start_p, count, do_oop,                \
  2108   assert_fn)                                \
  2109 {                                           \
  2110   T* p         = (T*)(start_p);             \
  2111   T* const end = p + (count);               \
  2112   while (p < end) {                         \
  2113     (assert_fn)(p);                         \
  2114     do_oop;                                 \
  2115     ++p;                                    \
  2116   }                                         \
  2119 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  2120   T, start_p, count, do_oop,                \
  2121   assert_fn)                                \
  2122 {                                           \
  2123   T* const start = (T*)(start_p);           \
  2124   T*       p     = start + (count);         \
  2125   while (start < p) {                       \
  2126     --p;                                    \
  2127     (assert_fn)(p);                         \
  2128     do_oop;                                 \
  2129   }                                         \
  2132 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  2133   T, start_p, count, low, high,             \
  2134   do_oop, assert_fn)                        \
  2135 {                                           \
  2136   T* const l = (T*)(low);                   \
  2137   T* const h = (T*)(high);                  \
  2138   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
  2139          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
  2140          "bounded region must be properly aligned"); \
  2141   T* p       = (T*)(start_p);               \
  2142   T* end     = p + (count);                 \
  2143   if (p < l) p = l;                         \
  2144   if (end > h) end = h;                     \
  2145   while (p < end) {                         \
  2146     (assert_fn)(p);                         \
  2147     do_oop;                                 \
  2148     ++p;                                    \
  2149   }                                         \
  2153 // The following macros call specialized macros, passing either oop or
  2154 // narrowOop as the specialization type.  These test the UseCompressedOops
  2155 // flag.
  2156 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
  2157 {                                                                        \
  2158   /* Compute oopmap block range. The common case                         \
  2159      is nonstatic_oop_map_size == 1. */                                  \
  2160   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2161   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2162   if (UseCompressedOops) {                                               \
  2163     while (map < end_map) {                                              \
  2164       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
  2165         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2166         do_oop, assert_fn)                                               \
  2167       ++map;                                                             \
  2168     }                                                                    \
  2169   } else {                                                               \
  2170     while (map < end_map) {                                              \
  2171       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
  2172         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2173         do_oop, assert_fn)                                               \
  2174       ++map;                                                             \
  2175     }                                                                    \
  2176   }                                                                      \
  2179 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
  2180 {                                                                        \
  2181   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
  2182   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
  2183   if (UseCompressedOops) {                                               \
  2184     while (start_map < map) {                                            \
  2185       --map;                                                             \
  2186       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
  2187         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2188         do_oop, assert_fn)                                               \
  2189     }                                                                    \
  2190   } else {                                                               \
  2191     while (start_map < map) {                                            \
  2192       --map;                                                             \
  2193       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
  2194         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2195         do_oop, assert_fn)                                               \
  2196     }                                                                    \
  2197   }                                                                      \
  2200 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
  2201                                               assert_fn)                 \
  2202 {                                                                        \
  2203   /* Compute oopmap block range. The common case is                      \
  2204      nonstatic_oop_map_size == 1, so we accept the                       \
  2205      usually non-existent extra overhead of examining                    \
  2206      all the maps. */                                                    \
  2207   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
  2208   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
  2209   if (UseCompressedOops) {                                               \
  2210     while (map < end_map) {                                              \
  2211       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
  2212         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
  2213         low, high,                                                       \
  2214         do_oop, assert_fn)                                               \
  2215       ++map;                                                             \
  2216     }                                                                    \
  2217   } else {                                                               \
  2218     while (map < end_map) {                                              \
  2219       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
  2220         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
  2221         low, high,                                                       \
  2222         do_oop, assert_fn)                                               \
  2223       ++map;                                                             \
  2224     }                                                                    \
  2225   }                                                                      \
  2228 void InstanceKlass::oop_follow_contents(oop obj) {
  2229   assert(obj != NULL, "can't follow the content of NULL object");
  2230   MarkSweep::follow_klass(obj->klass());
  2231   InstanceKlass_OOP_MAP_ITERATE( \
  2232     obj, \
  2233     MarkSweep::mark_and_push(p), \
  2234     assert_is_in_closed_subset)
  2237 #if INCLUDE_ALL_GCS
  2238 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
  2239                                         oop obj) {
  2240   assert(obj != NULL, "can't follow the content of NULL object");
  2241   PSParallelCompact::follow_klass(cm, obj->klass());
  2242   // Only mark the header and let the scan of the meta-data mark
  2243   // everything else.
  2244   InstanceKlass_OOP_MAP_ITERATE( \
  2245     obj, \
  2246     PSParallelCompact::mark_and_push(cm, p), \
  2247     assert_is_in)
  2249 #endif // INCLUDE_ALL_GCS
  2251 // closure's do_metadata() method dictates whether the given closure should be
  2252 // applied to the klass ptr in the object header.
  2254 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
  2256 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
  2257   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2258   /* header */                                                          \
  2259   if_do_metadata_checked(closure, nv_suffix) {                          \
  2260     closure->do_klass##nv_suffix(obj->klass());                         \
  2261   }                                                                     \
  2262   InstanceKlass_OOP_MAP_ITERATE(                                        \
  2263     obj,                                                                \
  2264     SpecializationStats::                                               \
  2265       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
  2266     (closure)->do_oop##nv_suffix(p),                                    \
  2267     assert_is_in_closed_subset)                                         \
  2268   return size_helper();                                                 \
  2271 #if INCLUDE_ALL_GCS
  2272 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
  2274 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
  2275                                               OopClosureType* closure) {        \
  2276   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  2278   assert_should_ignore_metadata(closure, nv_suffix);                            \
  2280   /* instance variables */                                                      \
  2281   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
  2282     obj,                                                                        \
  2283     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
  2284     (closure)->do_oop##nv_suffix(p),                                            \
  2285     assert_is_in_closed_subset)                                                 \
  2286    return size_helper();                                                        \
  2288 #endif // INCLUDE_ALL_GCS
  2290 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
  2292 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
  2293                                                   OopClosureType* closure, \
  2294                                                   MemRegion mr) {          \
  2295   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  2296   if_do_metadata_checked(closure, nv_suffix) {                           \
  2297     if (mr.contains(obj)) {                                              \
  2298       closure->do_klass##nv_suffix(obj->klass());                        \
  2299     }                                                                    \
  2300   }                                                                      \
  2301   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
  2302     obj, mr.start(), mr.end(),                                           \
  2303     (closure)->do_oop##nv_suffix(p),                                     \
  2304     assert_is_in_closed_subset)                                          \
  2305   return size_helper();                                                  \
  2308 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2309 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
  2310 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2311 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
  2312 #if INCLUDE_ALL_GCS
  2313 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2314 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
  2315 #endif // INCLUDE_ALL_GCS
  2317 int InstanceKlass::oop_adjust_pointers(oop obj) {
  2318   int size = size_helper();
  2319   InstanceKlass_OOP_MAP_ITERATE( \
  2320     obj, \
  2321     MarkSweep::adjust_pointer(p), \
  2322     assert_is_in)
  2323   return size;
  2326 #if INCLUDE_ALL_GCS
  2327 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
  2328   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
  2329     obj, \
  2330     if (PSScavenge::should_scavenge(p)) { \
  2331       pm->claim_or_forward_depth(p); \
  2332     }, \
  2333     assert_nothing )
  2336 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  2337   int size = size_helper();
  2338   InstanceKlass_OOP_MAP_ITERATE( \
  2339     obj, \
  2340     PSParallelCompact::adjust_pointer(p), \
  2341     assert_is_in)
  2342   return size;
  2345 #endif // INCLUDE_ALL_GCS
  2347 void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {
  2348   clean_implementors_list(is_alive);
  2349   clean_method_data(is_alive);
  2351   clean_dependent_nmethods();
  2354 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  2355   assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
  2356   if (is_interface()) {
  2357     if (ClassUnloading) {
  2358       Klass* impl = implementor();
  2359       if (impl != NULL) {
  2360         if (!impl->is_loader_alive(is_alive)) {
  2361           // remove this guy
  2362           Klass** klass = adr_implementor();
  2363           assert(klass != NULL, "null klass");
  2364           if (klass != NULL) {
  2365             *klass = NULL;
  2373 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  2374   for (int m = 0; m < methods()->length(); m++) {
  2375     MethodData* mdo = methods()->at(m)->method_data();
  2376     if (mdo != NULL) {
  2377       mdo->clean_method_data(is_alive);
  2383 static void remove_unshareable_in_class(Klass* k) {
  2384   // remove klass's unshareable info
  2385   k->remove_unshareable_info();
  2388 void InstanceKlass::remove_unshareable_info() {
  2389   Klass::remove_unshareable_info();
  2390   // Unlink the class
  2391   if (is_linked()) {
  2392     unlink_class();
  2394   init_implementor();
  2396   constants()->remove_unshareable_info();
  2398   for (int i = 0; i < methods()->length(); i++) {
  2399     Method* m = methods()->at(i);
  2400     m->remove_unshareable_info();
  2403   // do array classes also.
  2404   array_klasses_do(remove_unshareable_in_class);
  2407 static void restore_unshareable_in_class(Klass* k, TRAPS) {
  2408   // Array classes have null protection domain.
  2409   // --> see ArrayKlass::complete_create_array_klass()
  2410   k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
  2413 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
  2414   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
  2415   instanceKlassHandle ik(THREAD, this);
  2417   Array<Method*>* methods = ik->methods();
  2418   int num_methods = methods->length();
  2419   for (int index2 = 0; index2 < num_methods; ++index2) {
  2420     methodHandle m(THREAD, methods->at(index2));
  2421     m->restore_unshareable_info(CHECK);
  2423   if (JvmtiExport::has_redefined_a_class()) {
  2424     // Reinitialize vtable because RedefineClasses may have changed some
  2425     // entries in this vtable for super classes so the CDS vtable might
  2426     // point to old or obsolete entries.  RedefineClasses doesn't fix up
  2427     // vtables in the shared system dictionary, only the main one.
  2428     // It also redefines the itable too so fix that too.
  2429     ResourceMark rm(THREAD);
  2430     ik->vtable()->initialize_vtable(false, CHECK);
  2431     ik->itable()->initialize_itable(false, CHECK);
  2434   // restore constant pool resolved references
  2435   ik->constants()->restore_unshareable_info(CHECK);
  2437   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
  2440 // returns true IFF is_in_error_state() has been changed as a result of this call.
  2441 bool InstanceKlass::check_sharing_error_state() {
  2442   assert(DumpSharedSpaces, "should only be called during dumping");
  2443   bool old_state = is_in_error_state();
  2445   if (!is_in_error_state()) {
  2446     bool bad = false;
  2447     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
  2448       if (sup->is_in_error_state()) {
  2449         bad = true;
  2450         break;
  2453     if (!bad) {
  2454       Array<Klass*>* interfaces = transitive_interfaces();
  2455       for (int i = 0; i < interfaces->length(); i++) {
  2456         Klass* iface = interfaces->at(i);
  2457         if (InstanceKlass::cast(iface)->is_in_error_state()) {
  2458           bad = true;
  2459           break;
  2464     if (bad) {
  2465       set_in_error_state();
  2469   return (old_state != is_in_error_state());
  2472 static void clear_all_breakpoints(Method* m) {
  2473   m->clear_all_breakpoints();
  2477 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
  2478   // notify the debugger
  2479   if (JvmtiExport::should_post_class_unload()) {
  2480     JvmtiExport::post_class_unload(ik);
  2483   // notify ClassLoadingService of class unload
  2484   ClassLoadingService::notify_class_unloaded(ik);
  2487 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
  2488   // Clean up C heap
  2489   ik->release_C_heap_structures();
  2490   ik->constants()->release_C_heap_structures();
  2493 void InstanceKlass::release_C_heap_structures() {
  2495   // Can't release the constant pool here because the constant pool can be
  2496   // deallocated separately from the InstanceKlass for default methods and
  2497   // redefine classes.
  2499   // Deallocate oop map cache
  2500   if (_oop_map_cache != NULL) {
  2501     delete _oop_map_cache;
  2502     _oop_map_cache = NULL;
  2505   // Deallocate JNI identifiers for jfieldIDs
  2506   JNIid::deallocate(jni_ids());
  2507   set_jni_ids(NULL);
  2509   jmethodID* jmeths = methods_jmethod_ids_acquire();
  2510   if (jmeths != (jmethodID*)NULL) {
  2511     release_set_methods_jmethod_ids(NULL);
  2512     FreeHeap(jmeths);
  2515   // Deallocate MemberNameTable
  2517     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
  2518     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
  2519     MemberNameTable* mnt = member_names();
  2520     if (mnt != NULL) {
  2521       delete mnt;
  2522       set_member_names(NULL);
  2526   // release dependencies
  2527   nmethodBucket* b = _dependencies;
  2528   _dependencies = NULL;
  2529   while (b != NULL) {
  2530     nmethodBucket* next = b->next();
  2531     delete b;
  2532     b = next;
  2535   // Deallocate breakpoint records
  2536   if (breakpoints() != 0x0) {
  2537     methods_do(clear_all_breakpoints);
  2538     assert(breakpoints() == 0x0, "should have cleared breakpoints");
  2541   // deallocate information about previous versions
  2542   if (_previous_versions != NULL) {
  2543     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
  2544       PreviousVersionNode * pv_node = _previous_versions->at(i);
  2545       delete pv_node;
  2547     delete _previous_versions;
  2548     _previous_versions = NULL;
  2551   // deallocate the cached class file
  2552   if (_cached_class_file != NULL) {
  2553     os::free(_cached_class_file, mtClass);
  2554     _cached_class_file = NULL;
  2557   // Decrement symbol reference counts associated with the unloaded class.
  2558   if (_name != NULL) _name->decrement_refcount();
  2559   // unreference array name derived from this class name (arrays of an unloaded
  2560   // class can't be referenced anymore).
  2561   if (_array_name != NULL)  _array_name->decrement_refcount();
  2562   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
  2564   assert(_total_instanceKlass_count >= 1, "Sanity check");
  2565   Atomic::dec(&_total_instanceKlass_count);
  2568 void InstanceKlass::set_source_debug_extension(char* array, int length) {
  2569   if (array == NULL) {
  2570     _source_debug_extension = NULL;
  2571   } else {
  2572     // Adding one to the attribute length in order to store a null terminator
  2573     // character could cause an overflow because the attribute length is
  2574     // already coded with an u4 in the classfile, but in practice, it's
  2575     // unlikely to happen.
  2576     assert((length+1) > length, "Overflow checking");
  2577     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
  2578     for (int i = 0; i < length; i++) {
  2579       sde[i] = array[i];
  2581     sde[length] = '\0';
  2582     _source_debug_extension = sde;
  2586 address InstanceKlass::static_field_addr(int offset) {
  2587   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
  2591 const char* InstanceKlass::signature_name() const {
  2592   int hash_len = 0;
  2593   char hash_buf[40];
  2595   // If this is an anonymous class, append a hash to make the name unique
  2596   if (is_anonymous()) {
  2597     assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
  2598     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
  2599     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
  2600     hash_len = (int)strlen(hash_buf);
  2603   // Get the internal name as a c string
  2604   const char* src = (const char*) (name()->as_C_string());
  2605   const int src_length = (int)strlen(src);
  2607   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
  2609   // Add L as type indicator
  2610   int dest_index = 0;
  2611   dest[dest_index++] = 'L';
  2613   // Add the actual class name
  2614   for (int src_index = 0; src_index < src_length; ) {
  2615     dest[dest_index++] = src[src_index++];
  2618   // If we have a hash, append it
  2619   for (int hash_index = 0; hash_index < hash_len; ) {
  2620     dest[dest_index++] = hash_buf[hash_index++];
  2623   // Add the semicolon and the NULL
  2624   dest[dest_index++] = ';';
  2625   dest[dest_index] = '\0';
  2626   return dest;
  2629 // different verisons of is_same_class_package
  2630 bool InstanceKlass::is_same_class_package(Klass* class2) {
  2631   Klass* class1 = this;
  2632   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2633   Symbol* classname1 = class1->name();
  2635   if (class2->oop_is_objArray()) {
  2636     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
  2638   oop classloader2;
  2639   if (class2->oop_is_instance()) {
  2640     classloader2 = InstanceKlass::cast(class2)->class_loader();
  2641   } else {
  2642     assert(class2->oop_is_typeArray(), "should be type array");
  2643     classloader2 = NULL;
  2645   Symbol* classname2 = class2->name();
  2647   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2648                                               classloader2, classname2);
  2651 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  2652   Klass* class1 = this;
  2653   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
  2654   Symbol* classname1 = class1->name();
  2656   return InstanceKlass::is_same_class_package(classloader1, classname1,
  2657                                               classloader2, classname2);
  2660 // return true if two classes are in the same package, classloader
  2661 // and classname information is enough to determine a class's package
  2662 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
  2663                                           oop class_loader2, Symbol* class_name2) {
  2664   if (class_loader1 != class_loader2) {
  2665     return false;
  2666   } else if (class_name1 == class_name2) {
  2667     return true;                // skip painful bytewise comparison
  2668   } else {
  2669     ResourceMark rm;
  2671     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
  2672     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
  2673     // Otherwise, we just compare jbyte values between the strings.
  2674     const jbyte *name1 = class_name1->base();
  2675     const jbyte *name2 = class_name2->base();
  2677     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
  2678     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
  2680     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
  2681       // One of the two doesn't have a package.  Only return true
  2682       // if the other one also doesn't have a package.
  2683       return last_slash1 == last_slash2;
  2684     } else {
  2685       // Skip over '['s
  2686       if (*name1 == '[') {
  2687         do {
  2688           name1++;
  2689         } while (*name1 == '[');
  2690         if (*name1 != 'L') {
  2691           // Something is terribly wrong.  Shouldn't be here.
  2692           return false;
  2695       if (*name2 == '[') {
  2696         do {
  2697           name2++;
  2698         } while (*name2 == '[');
  2699         if (*name2 != 'L') {
  2700           // Something is terribly wrong.  Shouldn't be here.
  2701           return false;
  2705       // Check that package part is identical
  2706       int length1 = last_slash1 - name1;
  2707       int length2 = last_slash2 - name2;
  2709       return UTF8::equal(name1, length1, name2, length2);
  2714 // Returns true iff super_method can be overridden by a method in targetclassname
  2715 // See JSL 3rd edition 8.4.6.1
  2716 // Assumes name-signature match
  2717 // "this" is InstanceKlass of super_method which must exist
  2718 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
  2719 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
  2720    // Private methods can not be overridden
  2721    if (super_method->is_private()) {
  2722      return false;
  2724    // If super method is accessible, then override
  2725    if ((super_method->is_protected()) ||
  2726        (super_method->is_public())) {
  2727      return true;
  2729    // Package-private methods are not inherited outside of package
  2730    assert(super_method->is_package_private(), "must be package private");
  2731    return(is_same_class_package(targetclassloader(), targetclassname));
  2734 /* defined for now in jvm.cpp, for historical reasons *--
  2735 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
  2736                                                      Symbol*& simple_name_result, TRAPS) {
  2737   ...
  2739 */
  2741 // tell if two classes have the same enclosing class (at package level)
  2742 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
  2743                                                 Klass* class2_oop, TRAPS) {
  2744   if (class2_oop == class1())                       return true;
  2745   if (!class2_oop->oop_is_instance())  return false;
  2746   instanceKlassHandle class2(THREAD, class2_oop);
  2748   // must be in same package before we try anything else
  2749   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
  2750     return false;
  2752   // As long as there is an outer1.getEnclosingClass,
  2753   // shift the search outward.
  2754   instanceKlassHandle outer1 = class1;
  2755   for (;;) {
  2756     // As we walk along, look for equalities between outer1 and class2.
  2757     // Eventually, the walks will terminate as outer1 stops
  2758     // at the top-level class around the original class.
  2759     bool ignore_inner_is_member;
  2760     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
  2761                                                     CHECK_false);
  2762     if (next == NULL)  break;
  2763     if (next == class2())  return true;
  2764     outer1 = instanceKlassHandle(THREAD, next);
  2767   // Now do the same for class2.
  2768   instanceKlassHandle outer2 = class2;
  2769   for (;;) {
  2770     bool ignore_inner_is_member;
  2771     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
  2772                                                     CHECK_false);
  2773     if (next == NULL)  break;
  2774     // Might as well check the new outer against all available values.
  2775     if (next == class1())  return true;
  2776     if (next == outer1())  return true;
  2777     outer2 = instanceKlassHandle(THREAD, next);
  2780   // If by this point we have not found an equality between the
  2781   // two classes, we know they are in separate package members.
  2782   return false;
  2786 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
  2787   jint access = access_flags().as_int();
  2789   // But check if it happens to be member class.
  2790   instanceKlassHandle ik(THREAD, this);
  2791   InnerClassesIterator iter(ik);
  2792   for (; !iter.done(); iter.next()) {
  2793     int ioff = iter.inner_class_info_index();
  2794     // Inner class attribute can be zero, skip it.
  2795     // Strange but true:  JVM spec. allows null inner class refs.
  2796     if (ioff == 0) continue;
  2798     // only look at classes that are already loaded
  2799     // since we are looking for the flags for our self.
  2800     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
  2801     if ((ik->name() == inner_name)) {
  2802       // This is really a member class.
  2803       access = iter.inner_access_flags();
  2804       break;
  2807   // Remember to strip ACC_SUPER bit
  2808   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
  2811 jint InstanceKlass::jvmti_class_status() const {
  2812   jint result = 0;
  2814   if (is_linked()) {
  2815     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  2818   if (is_initialized()) {
  2819     assert(is_linked(), "Class status is not consistent");
  2820     result |= JVMTI_CLASS_STATUS_INITIALIZED;
  2822   if (is_in_error_state()) {
  2823     result |= JVMTI_CLASS_STATUS_ERROR;
  2825   return result;
  2828 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
  2829   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  2830   int method_table_offset_in_words = ioe->offset()/wordSize;
  2831   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
  2832                        / itableOffsetEntry::size();
  2834   for (int cnt = 0 ; ; cnt ++, ioe ++) {
  2835     // If the interface isn't implemented by the receiver class,
  2836     // the VM should throw IncompatibleClassChangeError.
  2837     if (cnt >= nof_interfaces) {
  2838       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
  2841     Klass* ik = ioe->interface_klass();
  2842     if (ik == holder) break;
  2845   itableMethodEntry* ime = ioe->first_method_entry(this);
  2846   Method* m = ime[index].method();
  2847   if (m == NULL) {
  2848     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
  2850   return m;
  2854 #if INCLUDE_JVMTI
  2855 // update default_methods for redefineclasses for methods that are
  2856 // not yet in the vtable due to concurrent subclass define and superinterface
  2857 // redefinition
  2858 // Note: those in the vtable, should have been updated via adjust_method_entries
  2859 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
  2860   // search the default_methods for uses of either obsolete or EMCP methods
  2861   if (default_methods() != NULL) {
  2862     for (int index = 0; index < default_methods()->length(); index ++) {
  2863       Method* old_method = default_methods()->at(index);
  2864       if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
  2865         continue; // skip uninteresting entries
  2867       assert(!old_method->is_deleted(), "default methods may not be deleted");
  2869       Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
  2871       assert(new_method != NULL, "method_with_idnum() should not be NULL");
  2872       assert(old_method != new_method, "sanity check");
  2874       default_methods()->at_put(index, new_method);
  2875       if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
  2876         if (!(*trace_name_printed)) {
  2877           // RC_TRACE_MESG macro has an embedded ResourceMark
  2878           RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
  2879                          external_name(),
  2880                          old_method->method_holder()->external_name()));
  2881           *trace_name_printed = true;
  2883         RC_TRACE(0x00100000, ("default method update: %s(%s) ",
  2884                               new_method->name()->as_C_string(),
  2885                               new_method->signature()->as_C_string()));
  2890 #endif // INCLUDE_JVMTI
  2892 // On-stack replacement stuff
  2893 void InstanceKlass::add_osr_nmethod(nmethod* n) {
  2894   // only one compilation can be active
  2895   NEEDS_CLEANUP
  2896   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2897   OsrList_lock->lock_without_safepoint_check();
  2898   assert(n->is_osr_method(), "wrong kind of nmethod");
  2899   n->set_osr_link(osr_nmethods_head());
  2900   set_osr_nmethods_head(n);
  2901   // Raise the highest osr level if necessary
  2902   if (TieredCompilation) {
  2903     Method* m = n->method();
  2904     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  2906   // Remember to unlock again
  2907   OsrList_lock->unlock();
  2909   // Get rid of the osr methods for the same bci that have lower levels.
  2910   if (TieredCompilation) {
  2911     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
  2912       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
  2913       if (inv != NULL && inv->is_in_use()) {
  2914         inv->make_not_entrant();
  2921 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
  2922   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2923   OsrList_lock->lock_without_safepoint_check();
  2924   assert(n->is_osr_method(), "wrong kind of nmethod");
  2925   nmethod* last = NULL;
  2926   nmethod* cur  = osr_nmethods_head();
  2927   int max_level = CompLevel_none;  // Find the max comp level excluding n
  2928   Method* m = n->method();
  2929   // Search for match
  2930   while(cur != NULL && cur != n) {
  2931     if (TieredCompilation && m == cur->method()) {
  2932       // Find max level before n
  2933       max_level = MAX2(max_level, cur->comp_level());
  2935     last = cur;
  2936     cur = cur->osr_link();
  2938   nmethod* next = NULL;
  2939   if (cur == n) {
  2940     next = cur->osr_link();
  2941     if (last == NULL) {
  2942       // Remove first element
  2943       set_osr_nmethods_head(next);
  2944     } else {
  2945       last->set_osr_link(next);
  2948   n->set_osr_link(NULL);
  2949   if (TieredCompilation) {
  2950     cur = next;
  2951     while (cur != NULL) {
  2952       // Find max level after n
  2953       if (m == cur->method()) {
  2954         max_level = MAX2(max_level, cur->comp_level());
  2956       cur = cur->osr_link();
  2958     m->set_highest_osr_comp_level(max_level);
  2960   // Remember to unlock again
  2961   OsrList_lock->unlock();
  2964 int InstanceKlass::mark_osr_nmethods(const Method* m) {
  2965   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2966   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
  2967   nmethod* osr = osr_nmethods_head();
  2968   int found = 0;
  2969   while (osr != NULL) {
  2970     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2971     if (osr->method() == m) {
  2972       osr->mark_for_deoptimization();
  2973       found++;
  2975     osr = osr->osr_link();
  2977   return found;
  2980 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
  2981   // This is a short non-blocking critical region, so the no safepoint check is ok.
  2982   OsrList_lock->lock_without_safepoint_check();
  2983   nmethod* osr = osr_nmethods_head();
  2984   nmethod* best = NULL;
  2985   while (osr != NULL) {
  2986     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
  2987     // There can be a time when a c1 osr method exists but we are waiting
  2988     // for a c2 version. When c2 completes its osr nmethod we will trash
  2989     // the c1 version and only be able to find the c2 version. However
  2990     // while we overflow in the c1 code at back branches we don't want to
  2991     // try and switch to the same code as we are already running
  2993     if (osr->method() == m &&
  2994         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
  2995       if (match_level) {
  2996         if (osr->comp_level() == comp_level) {
  2997           // Found a match - return it.
  2998           OsrList_lock->unlock();
  2999           return osr;
  3001       } else {
  3002         if (best == NULL || (osr->comp_level() > best->comp_level())) {
  3003           if (osr->comp_level() == CompLevel_highest_tier) {
  3004             // Found the best possible - return it.
  3005             OsrList_lock->unlock();
  3006             return osr;
  3008           best = osr;
  3012     osr = osr->osr_link();
  3014   OsrList_lock->unlock();
  3015   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
  3016     return best;
  3018   return NULL;
  3021 oop InstanceKlass::add_member_name(Handle mem_name, bool intern) {
  3022   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  3023   MutexLocker ml(MemberNameTable_lock);
  3024   DEBUG_ONLY(No_Safepoint_Verifier nsv);
  3026   // Check if method has been redefined while taking out MemberNameTable_lock, if so
  3027   // return false.  We cannot cache obsolete methods. They will crash when the function
  3028   // is called!
  3029   Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
  3030   if (method->is_obsolete()) {
  3031     return NULL;
  3032   } else if (method->is_old()) {
  3033     // Replace method with redefined version
  3034     java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
  3037   if (_member_names == NULL) {
  3038     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
  3040   if (intern) {
  3041     return _member_names->find_or_add_member_name(mem_name_wref);
  3042   } else {
  3043     return _member_names->add_member_name(mem_name_wref);
  3047 // -----------------------------------------------------------------------------------------------------
  3048 // Printing
  3050 #ifndef PRODUCT
  3052 #define BULLET  " - "
  3054 static const char* state_names[] = {
  3055   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
  3056 };
  3058 static void print_vtable(intptr_t* start, int len, outputStream* st) {
  3059   for (int i = 0; i < len; i++) {
  3060     intptr_t e = start[i];
  3061     st->print("%d : " INTPTR_FORMAT, i, e);
  3062     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
  3063       st->print(" ");
  3064       ((Metadata*)e)->print_value_on(st);
  3066     st->cr();
  3070 void InstanceKlass::print_on(outputStream* st) const {
  3071   assert(is_klass(), "must be klass");
  3072   Klass::print_on(st);
  3074   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  3075   st->print(BULLET"klass size:        %d", size());                               st->cr();
  3076   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  3077   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
  3078   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  3079   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  3080   st->print(BULLET"sub:               ");
  3081   Klass* sub = subklass();
  3082   int n;
  3083   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
  3084     if (n < MaxSubklassPrintSize) {
  3085       sub->print_value_on(st);
  3086       st->print("   ");
  3089   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  3090   st->cr();
  3092   if (is_interface()) {
  3093     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
  3094     if (nof_implementors() == 1) {
  3095       st->print_cr(BULLET"implementor:    ");
  3096       st->print("   ");
  3097       implementor()->print_value_on(st);
  3098       st->cr();
  3102   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  3103   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  3104   if (Verbose || WizardMode) {
  3105     Array<Method*>* method_array = methods();
  3106     for (int i = 0; i < method_array->length(); i++) {
  3107       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  3110   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
  3111   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
  3112   if (Verbose && default_methods() != NULL) {
  3113     Array<Method*>* method_array = default_methods();
  3114     for (int i = 0; i < method_array->length(); i++) {
  3115       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
  3118   if (default_vtable_indices() != NULL) {
  3119     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
  3121   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  3122   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  3123   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  3124   if (class_loader_data() != NULL) {
  3125     st->print(BULLET"class loader data:  ");
  3126     class_loader_data()->print_value_on(st);
  3127     st->cr();
  3129   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  3130   if (source_file_name() != NULL) {
  3131     st->print(BULLET"source file:       ");
  3132     source_file_name()->print_value_on(st);
  3133     st->cr();
  3135   if (source_debug_extension() != NULL) {
  3136     st->print(BULLET"source debug extension:       ");
  3137     st->print("%s", source_debug_extension());
  3138     st->cr();
  3140   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  3141   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  3142   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  3143   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
  3145     bool have_pv = false;
  3146     PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  3147     for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  3148          pv_node != NULL; pv_node = pvw.next_previous_version()) {
  3149       if (!have_pv)
  3150         st->print(BULLET"previous version:  ");
  3151       have_pv = true;
  3152       pv_node->prev_constant_pool()->print_value_on(st);
  3154     if (have_pv) st->cr();
  3155   } // pvw is cleaned up
  3157   if (generic_signature() != NULL) {
  3158     st->print(BULLET"generic signature: ");
  3159     generic_signature()->print_value_on(st);
  3160     st->cr();
  3162   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  3163   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  3164   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  3165   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
  3166   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  3167   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
  3168   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  3169   FieldPrinter print_static_field(st);
  3170   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  3171   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  3172   FieldPrinter print_nonstatic_field(st);
  3173   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
  3175   st->print(BULLET"non-static oop maps: ");
  3176   OopMapBlock* map     = start_of_nonstatic_oop_maps();
  3177   OopMapBlock* end_map = map + nonstatic_oop_map_count();
  3178   while (map < end_map) {
  3179     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
  3180     map++;
  3182   st->cr();
  3185 #endif //PRODUCT
  3187 void InstanceKlass::print_value_on(outputStream* st) const {
  3188   assert(is_klass(), "must be klass");
  3189   if (Verbose || WizardMode)  access_flags().print_on(st);
  3190   name()->print_value_on(st);
  3193 #ifndef PRODUCT
  3195 void FieldPrinter::do_field(fieldDescriptor* fd) {
  3196   _st->print(BULLET);
  3197    if (_obj == NULL) {
  3198      fd->print_on(_st);
  3199      _st->cr();
  3200    } else {
  3201      fd->print_on_for(_st, _obj);
  3202      _st->cr();
  3207 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
  3208   Klass::oop_print_on(obj, st);
  3210   if (this == SystemDictionary::String_klass()) {
  3211     typeArrayOop value  = java_lang_String::value(obj);
  3212     juint        offset = java_lang_String::offset(obj);
  3213     juint        length = java_lang_String::length(obj);
  3214     if (value != NULL &&
  3215         value->is_typeArray() &&
  3216         offset          <= (juint) value->length() &&
  3217         offset + length <= (juint) value->length()) {
  3218       st->print(BULLET"string: ");
  3219       java_lang_String::print(obj, st);
  3220       st->cr();
  3221       if (!WizardMode)  return;  // that is enough
  3225   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
  3226   FieldPrinter print_field(st, obj);
  3227   do_nonstatic_fields(&print_field);
  3229   if (this == SystemDictionary::Class_klass()) {
  3230     st->print(BULLET"signature: ");
  3231     java_lang_Class::print_signature(obj, st);
  3232     st->cr();
  3233     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
  3234     st->print(BULLET"fake entry for mirror: ");
  3235     mirrored_klass->print_value_on_maybe_null(st);
  3236     st->cr();
  3237     Klass* array_klass = java_lang_Class::array_klass(obj);
  3238     st->print(BULLET"fake entry for array: ");
  3239     array_klass->print_value_on_maybe_null(st);
  3240     st->cr();
  3241     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
  3242     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
  3243     Klass* real_klass = java_lang_Class::as_Klass(obj);
  3244     if (real_klass != NULL && real_klass->oop_is_instance()) {
  3245       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
  3247   } else if (this == SystemDictionary::MethodType_klass()) {
  3248     st->print(BULLET"signature: ");
  3249     java_lang_invoke_MethodType::print_signature(obj, st);
  3250     st->cr();
  3254 #endif //PRODUCT
  3256 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
  3257   st->print("a ");
  3258   name()->print_value_on(st);
  3259   obj->print_address_on(st);
  3260   if (this == SystemDictionary::String_klass()
  3261       && java_lang_String::value(obj) != NULL) {
  3262     ResourceMark rm;
  3263     int len = java_lang_String::length(obj);
  3264     int plen = (len < 24 ? len : 12);
  3265     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
  3266     st->print(" = \"%s\"", str);
  3267     if (len > plen)
  3268       st->print("...[%d]", len);
  3269   } else if (this == SystemDictionary::Class_klass()) {
  3270     Klass* k = java_lang_Class::as_Klass(obj);
  3271     st->print(" = ");
  3272     if (k != NULL) {
  3273       k->print_value_on(st);
  3274     } else {
  3275       const char* tname = type2name(java_lang_Class::primitive_type(obj));
  3276       st->print("%s", tname ? tname : "type?");
  3278   } else if (this == SystemDictionary::MethodType_klass()) {
  3279     st->print(" = ");
  3280     java_lang_invoke_MethodType::print_signature(obj, st);
  3281   } else if (java_lang_boxing_object::is_instance(obj)) {
  3282     st->print(" = ");
  3283     java_lang_boxing_object::print(obj, st);
  3284   } else if (this == SystemDictionary::LambdaForm_klass()) {
  3285     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
  3286     if (vmentry != NULL) {
  3287       st->print(" => ");
  3288       vmentry->print_value_on(st);
  3290   } else if (this == SystemDictionary::MemberName_klass()) {
  3291     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
  3292     if (vmtarget != NULL) {
  3293       st->print(" = ");
  3294       vmtarget->print_value_on(st);
  3295     } else {
  3296       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
  3297       st->print(".");
  3298       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
  3303 const char* InstanceKlass::internal_name() const {
  3304   return external_name();
  3307 #if INCLUDE_SERVICES
  3308 // Size Statistics
  3309 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  3310   Klass::collect_statistics(sz);
  3312   sz->_inst_size  = HeapWordSize * size_helper();
  3313   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  3314   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  3315   sz->_nonstatic_oopmap_bytes = HeapWordSize *
  3316         ((is_interface() || is_anonymous()) ?
  3317          align_object_offset(nonstatic_oop_map_size()) :
  3318          nonstatic_oop_map_size());
  3320   int n = 0;
  3321   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  3322   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  3323   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  3324   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  3325   n += (sz->_fields_bytes                = sz->count_array(fields()));
  3326   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  3327   sz->_ro_bytes += n;
  3329   const ConstantPool* cp = constants();
  3330   if (cp) {
  3331     cp->collect_statistics(sz);
  3334   const Annotations* anno = annotations();
  3335   if (anno) {
  3336     anno->collect_statistics(sz);
  3339   const Array<Method*>* methods_array = methods();
  3340   if (methods()) {
  3341     for (int i = 0; i < methods_array->length(); i++) {
  3342       Method* method = methods_array->at(i);
  3343       if (method) {
  3344         sz->_method_count ++;
  3345         method->collect_statistics(sz);
  3350 #endif // INCLUDE_SERVICES
  3352 // Verification
  3354 class VerifyFieldClosure: public OopClosure {
  3355  protected:
  3356   template <class T> void do_oop_work(T* p) {
  3357     oop obj = oopDesc::load_decode_heap_oop(p);
  3358     if (!obj->is_oop_or_null()) {
  3359       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
  3360       Universe::print();
  3361       guarantee(false, "boom");
  3364  public:
  3365   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  3366   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
  3367 };
  3369 void InstanceKlass::verify_on(outputStream* st) {
  3370 #ifndef PRODUCT
  3371   // Avoid redundant verifies, this really should be in product.
  3372   if (_verify_count == Universe::verify_count()) return;
  3373   _verify_count = Universe::verify_count();
  3374 #endif
  3376   // Verify Klass
  3377   Klass::verify_on(st);
  3379   // Verify that klass is present in ClassLoaderData
  3380   guarantee(class_loader_data()->contains_klass(this),
  3381             "this class isn't found in class loader data");
  3383   // Verify vtables
  3384   if (is_linked()) {
  3385     ResourceMark rm;
  3386     // $$$ This used to be done only for m/s collections.  Doing it
  3387     // always seemed a valid generalization.  (DLD -- 6/00)
  3388     vtable()->verify(st);
  3391   // Verify first subklass
  3392   if (subklass_oop() != NULL) {
  3393     guarantee(subklass_oop()->is_klass(), "should be klass");
  3396   // Verify siblings
  3397   Klass* super = this->super();
  3398   Klass* sib = next_sibling();
  3399   if (sib != NULL) {
  3400     if (sib == this) {
  3401       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
  3404     guarantee(sib->is_klass(), "should be klass");
  3405     guarantee(sib->super() == super, "siblings should have same superklass");
  3408   // Verify implementor fields
  3409   Klass* im = implementor();
  3410   if (im != NULL) {
  3411     guarantee(is_interface(), "only interfaces should have implementor set");
  3412     guarantee(im->is_klass(), "should be klass");
  3413     guarantee(!im->is_interface() || im == this,
  3414       "implementors cannot be interfaces");
  3417   // Verify local interfaces
  3418   if (local_interfaces()) {
  3419     Array<Klass*>* local_interfaces = this->local_interfaces();
  3420     for (int j = 0; j < local_interfaces->length(); j++) {
  3421       Klass* e = local_interfaces->at(j);
  3422       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
  3426   // Verify transitive interfaces
  3427   if (transitive_interfaces() != NULL) {
  3428     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
  3429     for (int j = 0; j < transitive_interfaces->length(); j++) {
  3430       Klass* e = transitive_interfaces->at(j);
  3431       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
  3435   // Verify methods
  3436   if (methods() != NULL) {
  3437     Array<Method*>* methods = this->methods();
  3438     for (int j = 0; j < methods->length(); j++) {
  3439       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3441     for (int j = 0; j < methods->length() - 1; j++) {
  3442       Method* m1 = methods->at(j);
  3443       Method* m2 = methods->at(j + 1);
  3444       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3448   // Verify method ordering
  3449   if (method_ordering() != NULL) {
  3450     Array<int>* method_ordering = this->method_ordering();
  3451     int length = method_ordering->length();
  3452     if (JvmtiExport::can_maintain_original_method_order() ||
  3453         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
  3454       guarantee(length == methods()->length(), "invalid method ordering length");
  3455       jlong sum = 0;
  3456       for (int j = 0; j < length; j++) {
  3457         int original_index = method_ordering->at(j);
  3458         guarantee(original_index >= 0, "invalid method ordering index");
  3459         guarantee(original_index < length, "invalid method ordering index");
  3460         sum += original_index;
  3462       // Verify sum of indices 0,1,...,length-1
  3463       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
  3464     } else {
  3465       guarantee(length == 0, "invalid method ordering length");
  3469   // Verify default methods
  3470   if (default_methods() != NULL) {
  3471     Array<Method*>* methods = this->default_methods();
  3472     for (int j = 0; j < methods->length(); j++) {
  3473       guarantee(methods->at(j)->is_method(), "non-method in methods array");
  3475     for (int j = 0; j < methods->length() - 1; j++) {
  3476       Method* m1 = methods->at(j);
  3477       Method* m2 = methods->at(j + 1);
  3478       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
  3482   // Verify JNI static field identifiers
  3483   if (jni_ids() != NULL) {
  3484     jni_ids()->verify(this);
  3487   // Verify other fields
  3488   if (array_klasses() != NULL) {
  3489     guarantee(array_klasses()->is_klass(), "should be klass");
  3491   if (constants() != NULL) {
  3492     guarantee(constants()->is_constantPool(), "should be constant pool");
  3494   const Klass* host = host_klass();
  3495   if (host != NULL) {
  3496     guarantee(host->is_klass(), "should be klass");
  3500 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
  3501   Klass::oop_verify_on(obj, st);
  3502   VerifyFieldClosure blk;
  3503   obj->oop_iterate_no_header(&blk);
  3507 // JNIid class for jfieldIDs only
  3508 // Note to reviewers:
  3509 // These JNI functions are just moved over to column 1 and not changed
  3510 // in the compressed oops workspace.
  3511 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
  3512   _holder = holder;
  3513   _offset = offset;
  3514   _next = next;
  3515   debug_only(_is_static_field_id = false;)
  3519 JNIid* JNIid::find(int offset) {
  3520   JNIid* current = this;
  3521   while (current != NULL) {
  3522     if (current->offset() == offset) return current;
  3523     current = current->next();
  3525   return NULL;
  3528 void JNIid::deallocate(JNIid* current) {
  3529   while (current != NULL) {
  3530     JNIid* next = current->next();
  3531     delete current;
  3532     current = next;
  3537 void JNIid::verify(Klass* holder) {
  3538   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
  3539   int end_field_offset;
  3540   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
  3542   JNIid* current = this;
  3543   while (current != NULL) {
  3544     guarantee(current->holder() == holder, "Invalid klass in JNIid");
  3545 #ifdef ASSERT
  3546     int o = current->offset();
  3547     if (current->is_static_field_id()) {
  3548       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
  3550 #endif
  3551     current = current->next();
  3556 #ifdef ASSERT
  3557 void InstanceKlass::set_init_state(ClassState state) {
  3558   bool good_state = is_shared() ? (_init_state <= state)
  3559                                                : (_init_state < state);
  3560   assert(good_state || state == allocated, "illegal state transition");
  3561   _init_state = (u1)state;
  3563 #endif
  3566 // RedefineClasses() support for previous versions:
  3568 // Purge previous versions
  3569 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  3570   if (ik->previous_versions() != NULL) {
  3571     // This klass has previous versions so see what we can cleanup
  3572     // while it is safe to do so.
  3574     int deleted_count = 0;    // leave debugging breadcrumbs
  3575     int live_count = 0;
  3576     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
  3577                        ClassLoaderData::the_null_class_loader_data() :
  3578                        ik->class_loader_data();
  3580     // RC_TRACE macro has an embedded ResourceMark
  3581     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
  3582       ik->external_name(), ik->previous_versions()->length()));
  3584     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
  3585       // check the previous versions array
  3586       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
  3587       ConstantPool* cp_ref = pv_node->prev_constant_pool();
  3588       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
  3590       ConstantPool* pvcp = cp_ref;
  3591       if (!pvcp->on_stack()) {
  3592         // If the constant pool isn't on stack, none of the methods
  3593         // are executing.  Delete all the methods, the constant pool and
  3594         // and this previous version node.
  3595         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3596         if (method_refs != NULL) {
  3597           for (int j = method_refs->length() - 1; j >= 0; j--) {
  3598             Method* method = method_refs->at(j);
  3599             assert(method != NULL, "method ref was unexpectedly cleared");
  3600             method_refs->remove_at(j);
  3601             // method will be freed with associated class.
  3604         // Remove the constant pool
  3605         delete pv_node;
  3606         // Since we are traversing the array backwards, we don't have to
  3607         // do anything special with the index.
  3608         ik->previous_versions()->remove_at(i);
  3609         deleted_count++;
  3610         continue;
  3611       } else {
  3612         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
  3613         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
  3614         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
  3615         live_count++;
  3618       // At least one method is live in this previous version, clean out
  3619       // the others or mark them as obsolete.
  3620       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3621       if (method_refs != NULL) {
  3622         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
  3623           method_refs->length()));
  3624         for (int j = method_refs->length() - 1; j >= 0; j--) {
  3625           Method* method = method_refs->at(j);
  3626           assert(method != NULL, "method ref was unexpectedly cleared");
  3628           // Remove the emcp method if it's not executing
  3629           // If it's been made obsolete by a redefinition of a non-emcp
  3630           // method, mark it as obsolete but leave it to clean up later.
  3631           if (!method->on_stack()) {
  3632             method_refs->remove_at(j);
  3633           } else if (emcp_method_count == 0) {
  3634             method->set_is_obsolete();
  3635           } else {
  3636             // RC_TRACE macro has an embedded ResourceMark
  3637             RC_TRACE(0x00000200,
  3638               ("purge: %s(%s): prev method @%d in version @%d is alive",
  3639               method->name()->as_C_string(),
  3640               method->signature()->as_C_string(), j, i));
  3645     assert(ik->previous_versions()->length() == live_count, "sanity check");
  3646     RC_TRACE(0x00000200,
  3647       ("purge: previous version stats: live=%d, deleted=%d", live_count,
  3648       deleted_count));
  3652 // External interface for use during class unloading.
  3653 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  3654   // Call with >0 emcp methods since they are not currently being redefined.
  3655   purge_previous_versions_internal(ik, 1);
  3659 // Potentially add an information node that contains pointers to the
  3660 // interesting parts of the previous version of the_class.
  3661 // This is also where we clean out any unused references.
  3662 // Note that while we delete nodes from the _previous_versions
  3663 // array, we never delete the array itself until the klass is
  3664 // unloaded. The has_been_redefined() query depends on that fact.
  3665 //
  3666 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
  3667        BitMap* emcp_methods, int emcp_method_count) {
  3668   assert(Thread::current()->is_VM_thread(),
  3669          "only VMThread can add previous versions");
  3671   if (_previous_versions == NULL) {
  3672     // This is the first previous version so make some space.
  3673     // Start with 2 elements under the assumption that the class
  3674     // won't be redefined much.
  3675     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
  3676                             GrowableArray<PreviousVersionNode *>(2, true);
  3679   ConstantPool* cp_ref = ikh->constants();
  3681   // RC_TRACE macro has an embedded ResourceMark
  3682   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
  3683                         "on_stack=%d",
  3684     ikh->external_name(), _previous_versions->length(), emcp_method_count,
  3685     cp_ref->on_stack()));
  3687   // If the constant pool for this previous version of the class
  3688   // is not marked as being on the stack, then none of the methods
  3689   // in this previous version of the class are on the stack so
  3690   // we don't need to create a new PreviousVersionNode. However,
  3691   // we still need to examine older previous versions below.
  3692   Array<Method*>* old_methods = ikh->methods();
  3694   if (cp_ref->on_stack()) {
  3695     PreviousVersionNode * pv_node = NULL;
  3696     if (emcp_method_count == 0) {
  3697       // non-shared ConstantPool gets a reference
  3698       pv_node = new PreviousVersionNode(cp_ref, NULL);
  3699       RC_TRACE(0x00000400,
  3700           ("add: all methods are obsolete; flushing any EMCP refs"));
  3701     } else {
  3702       int local_count = 0;
  3703       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
  3704           GrowableArray<Method*>(emcp_method_count, true);
  3705       for (int i = 0; i < old_methods->length(); i++) {
  3706         if (emcp_methods->at(i)) {
  3707             // this old method is EMCP. Save it only if it's on the stack
  3708             Method* old_method = old_methods->at(i);
  3709             if (old_method->on_stack()) {
  3710               method_refs->append(old_method);
  3712           if (++local_count >= emcp_method_count) {
  3713             // no more EMCP methods so bail out now
  3714             break;
  3718       // non-shared ConstantPool gets a reference
  3719       pv_node = new PreviousVersionNode(cp_ref, method_refs);
  3721     // append new previous version.
  3722     _previous_versions->append(pv_node);
  3725   // Since the caller is the VMThread and we are at a safepoint, this
  3726   // is a good time to clear out unused references.
  3728   RC_TRACE(0x00000400, ("add: previous version length=%d",
  3729     _previous_versions->length()));
  3731   // Purge previous versions not executing on the stack
  3732   purge_previous_versions_internal(this, emcp_method_count);
  3734   int obsolete_method_count = old_methods->length() - emcp_method_count;
  3736   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
  3737       _previous_versions->length() > 0) {
  3738     // We have a mix of obsolete and EMCP methods so we have to
  3739     // clear out any matching EMCP method entries the hard way.
  3740     int local_count = 0;
  3741     for (int i = 0; i < old_methods->length(); i++) {
  3742       if (!emcp_methods->at(i)) {
  3743         // only obsolete methods are interesting
  3744         Method* old_method = old_methods->at(i);
  3745         Symbol* m_name = old_method->name();
  3746         Symbol* m_signature = old_method->signature();
  3748         // we might not have added the last entry
  3749         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
  3750           // check the previous versions array for non executing obsolete methods
  3751           PreviousVersionNode * pv_node = _previous_versions->at(j);
  3753           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
  3754           if (method_refs == NULL) {
  3755             // We have run into a PreviousVersion generation where
  3756             // all methods were made obsolete during that generation's
  3757             // RedefineClasses() operation. At the time of that
  3758             // operation, all EMCP methods were flushed so we don't
  3759             // have to go back any further.
  3760             //
  3761             // A NULL method_refs is different than an empty method_refs.
  3762             // We cannot infer any optimizations about older generations
  3763             // from an empty method_refs for the current generation.
  3764             break;
  3767           for (int k = method_refs->length() - 1; k >= 0; k--) {
  3768             Method* method = method_refs->at(k);
  3770             if (!method->is_obsolete() &&
  3771                 method->name() == m_name &&
  3772                 method->signature() == m_signature) {
  3773               // The current RedefineClasses() call has made all EMCP
  3774               // versions of this method obsolete so mark it as obsolete
  3775               // and remove the reference.
  3776               RC_TRACE(0x00000400,
  3777                 ("add: %s(%s): flush obsolete method @%d in version @%d",
  3778                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
  3780               method->set_is_obsolete();
  3781               // Leave obsolete methods on the previous version list to
  3782               // clean up later.
  3783               break;
  3787           // The previous loop may not find a matching EMCP method, but
  3788           // that doesn't mean that we can optimize and not go any
  3789           // further back in the PreviousVersion generations. The EMCP
  3790           // method for this generation could have already been deleted,
  3791           // but there still may be an older EMCP method that has not
  3792           // been deleted.
  3795         if (++local_count >= obsolete_method_count) {
  3796           // no more obsolete methods so bail out now
  3797           break;
  3802 } // end add_previous_version()
  3805 // Determine if InstanceKlass has a previous version.
  3806 bool InstanceKlass::has_previous_version() const {
  3807   return (_previous_versions != NULL && _previous_versions->length() > 0);
  3808 } // end has_previous_version()
  3811 InstanceKlass* InstanceKlass::get_klass_version(int version) {
  3812   if (constants()->version() == version) {
  3813     return this;
  3815   PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
  3816   for (PreviousVersionNode * pv_node = pvw.next_previous_version();
  3817        pv_node != NULL; pv_node = pvw.next_previous_version()) {
  3818     ConstantPool* prev_cp = pv_node->prev_constant_pool();
  3819     if (prev_cp->version() == version) {
  3820       return prev_cp->pool_holder();
  3823   return NULL; // None found
  3827 Method* InstanceKlass::method_with_idnum(int idnum) {
  3828   Method* m = NULL;
  3829   if (idnum < methods()->length()) {
  3830     m = methods()->at(idnum);
  3832   if (m == NULL || m->method_idnum() != idnum) {
  3833     for (int index = 0; index < methods()->length(); ++index) {
  3834       m = methods()->at(index);
  3835       if (m->method_idnum() == idnum) {
  3836         return m;
  3839     // None found, return null for the caller to handle.
  3840     return NULL;
  3842   return m;
  3846 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
  3847   if (idnum >= methods()->length()) {
  3848     return NULL;
  3850   Method* m = methods()->at(idnum);
  3851   if (m != NULL && m->orig_method_idnum() == idnum) {
  3852     return m;
  3854   // Obsolete method idnum does not match the original idnum
  3855   for (int index = 0; index < methods()->length(); ++index) {
  3856     m = methods()->at(index);
  3857     if (m->orig_method_idnum() == idnum) {
  3858       return m;
  3861   // None found, return null for the caller to handle.
  3862   return NULL;
  3866 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
  3867   InstanceKlass* holder = get_klass_version(version);
  3868   if (holder == NULL) {
  3869     return NULL; // The version of klass is gone, no method is found
  3871   Method* method = holder->method_with_orig_idnum(idnum);
  3872   return method;
  3876 jint InstanceKlass::get_cached_class_file_len() {
  3877   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
  3880 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
  3881   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
  3885 // Construct a PreviousVersionNode entry for the array hung off
  3886 // the InstanceKlass.
  3887 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  3888   GrowableArray<Method*>* prev_EMCP_methods) {
  3890   _prev_constant_pool = prev_constant_pool;
  3891   _prev_EMCP_methods = prev_EMCP_methods;
  3895 // Destroy a PreviousVersionNode
  3896 PreviousVersionNode::~PreviousVersionNode() {
  3897   if (_prev_constant_pool != NULL) {
  3898     _prev_constant_pool = NULL;
  3901   if (_prev_EMCP_methods != NULL) {
  3902     delete _prev_EMCP_methods;
  3906 // Construct a helper for walking the previous versions array
  3907 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
  3908   _thread = thread;
  3909   _previous_versions = ik->previous_versions();
  3910   _current_index = 0;
  3911   _current_p = NULL;
  3912   _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
  3916 // Return the interesting information for the next previous version
  3917 // of the klass. Returns NULL if there are no more previous versions.
  3918 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
  3919   if (_previous_versions == NULL) {
  3920     // no previous versions so nothing to return
  3921     return NULL;
  3924   _current_p = NULL;  // reset to NULL
  3925   _current_constant_pool_handle = NULL;
  3927   int length = _previous_versions->length();
  3929   while (_current_index < length) {
  3930     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
  3932     // Save a handle to the constant pool for this previous version,
  3933     // which keeps all the methods from being deallocated.
  3934     _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
  3935     _current_p = pv_node;
  3936     return pv_node;
  3939   return NULL;
  3940 } // end next_previous_version()

mercurial