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