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